ASR_BASE

Change-Id: Icf3719cc0afe3eeb3edc7fa80a2eb5199ca9dda1
diff --git a/package/base-files/files/lib/functions.sh b/package/base-files/files/lib/functions.sh
new file mode 100644
index 0000000..658eafe
--- /dev/null
+++ b/package/base-files/files/lib/functions.sh
@@ -0,0 +1,562 @@
+# Copyright (C) 2006-2014 OpenWrt.org
+# Copyright (C) 2006 Fokus Fraunhofer <carsten.tittel@fokus.fraunhofer.de>
+# Copyright (C) 2010 Vertical Communications
+
+
+debug () {
+	${DEBUG:-:} "$@"
+}
+
+# newline
+N="
+"
+
+_C=0
+NO_EXPORT=1
+LOAD_STATE=1
+LIST_SEP=" "
+
+# xor multiple hex values of the same length
+xor() {
+	local val
+	local ret="0x$1"
+	local retlen=${#1}
+
+	shift
+	while [ -n "$1" ]; do
+		val="0x$1"
+		ret=$((ret ^ val))
+		shift
+	done
+
+	printf "%0${retlen}x" "$ret"
+}
+
+data_2bin() {
+	local data=$1
+	local len=${#1}
+	local bin_data
+
+	for i in $(seq 0 2 $(($len - 1))); do
+		bin_data="${bin_data}\x${data:i:2}"
+	done
+
+	echo -ne $bin_data
+}
+
+data_2xor_val() {
+	local data=$1
+	local len=${#1}
+	local xor_data
+
+	for i in $(seq 0 4 $(($len - 1))); do
+		xor_data="${xor_data}${data:i:4} "
+	done
+
+	echo -n ${xor_data:0:-1}
+}
+
+append() {
+	local var="$1"
+	local value="$2"
+	local sep="${3:- }"
+
+	eval "export ${NO_EXPORT:+-n} -- \"$var=\${$var:+\${$var}\${value:+\$sep}}\$value\""
+}
+
+prepend() {
+	local var="$1"
+	local value="$2"
+	local sep="${3:- }"
+
+	eval "export ${NO_EXPORT:+-n} -- \"$var=\$value\${$var:+\${sep}\${$var}}\""
+}
+
+list_contains() {
+	local var="$1"
+	local str="$2"
+	local val
+
+	eval "val=\" \${$var} \""
+	[ "${val%% $str *}" != "$val" ]
+}
+
+config_load() {
+	[ -n "$IPKG_INSTROOT" ] && return 0
+	uci_load "$@"
+}
+
+reset_cb() {
+	config_cb() { return 0; }
+	option_cb() { return 0; }
+	list_cb() { return 0; }
+}
+reset_cb
+
+package() {
+	return 0
+}
+
+config () {
+	local cfgtype="$1"
+	local name="$2"
+
+	export ${NO_EXPORT:+-n} CONFIG_NUM_SECTIONS=$((CONFIG_NUM_SECTIONS + 1))
+	name="${name:-cfg$CONFIG_NUM_SECTIONS}"
+	append CONFIG_SECTIONS "$name"
+	export ${NO_EXPORT:+-n} CONFIG_SECTION="$name"
+	config_set "$CONFIG_SECTION" "TYPE" "${cfgtype}"
+	[ -n "$NO_CALLBACK" ] || config_cb "$cfgtype" "$name"
+}
+
+option () {
+	local varname="$1"; shift
+	local value="$*"
+
+	config_set "$CONFIG_SECTION" "${varname}" "${value}"
+	[ -n "$NO_CALLBACK" ] || option_cb "$varname" "$*"
+}
+
+list() {
+	local varname="$1"; shift
+	local value="$*"
+	local len
+
+	config_get len "$CONFIG_SECTION" "${varname}_LENGTH" 0
+	[ $len = 0 ] && append CONFIG_LIST_STATE "${CONFIG_SECTION}_${varname}"
+	len=$((len + 1))
+	config_set "$CONFIG_SECTION" "${varname}_ITEM$len" "$value"
+	config_set "$CONFIG_SECTION" "${varname}_LENGTH" "$len"
+	append "CONFIG_${CONFIG_SECTION}_${varname}" "$value" "$LIST_SEP"
+	[ -n "$NO_CALLBACK" ] || list_cb "$varname" "$*"
+}
+
+config_unset() {
+	config_set "$1" "$2" ""
+}
+
+# config_get <variable> <section> <option> [<default>]
+# config_get <section> <option>
+config_get() {
+	case "$2${3:-$1}" in
+		*[!A-Za-z0-9_]*) : ;;
+		*)
+			case "$3" in
+				"") eval echo "\"\${CONFIG_${1}_${2}:-\${4}}\"";;
+				*)  eval export ${NO_EXPORT:+-n} -- "${1}=\${CONFIG_${2}_${3}:-\${4}}";;
+			esac
+		;;
+	esac
+}
+
+# get_bool <value> [<default>]
+get_bool() {
+	local _tmp="$1"
+	case "$_tmp" in
+		1|on|true|yes|enabled) _tmp=1;;
+		0|off|false|no|disabled) _tmp=0;;
+		*) _tmp="$2";;
+	esac
+	echo -n "$_tmp"
+}
+
+# config_get_bool <variable> <section> <option> [<default>]
+config_get_bool() {
+	local _tmp
+	config_get _tmp "$2" "$3" "$4"
+	_tmp="$(get_bool "$_tmp" "$4")"
+	export ${NO_EXPORT:+-n} "$1=$_tmp"
+}
+
+config_set() {
+	local section="$1"
+	local option="$2"
+	local value="$3"
+
+	export ${NO_EXPORT:+-n} "CONFIG_${section}_${option}=${value}"
+}
+
+config_add_list() {
+	local section="$1"
+	local option="$2"
+	local value="$3"
+	local old_section="$CONFIG_SECTION"
+
+	CONFIG_SECTION="$section"
+	list "$option" "$value"
+	CONFIG_SECTION="$old_section"
+}
+
+config_foreach() {
+	local ___function="$1"
+	[ "$#" -ge 1 ] && shift
+	local ___type="$1"
+	[ "$#" -ge 1 ] && shift
+	local section cfgtype
+
+	[ -z "$CONFIG_SECTIONS" ] && return 0
+	for section in ${CONFIG_SECTIONS}; do
+		config_get cfgtype "$section" TYPE
+		[ -n "$___type" ] && [ "x$cfgtype" != "x$___type" ] && continue
+		eval "$___function \"\$section\" \"\$@\""
+	done
+}
+
+config_list_foreach() {
+	[ "$#" -ge 3 ] || return 0
+	local section="$1"; shift
+	local option="$1"; shift
+	local function="$1"; shift
+	local val
+	local len
+	local c=1
+
+	config_get len "${section}" "${option}_LENGTH"
+	[ -z "$len" ] && return 0
+	while [ $c -le "$len" ]; do
+		config_get val "${section}" "${option}_ITEM$c"
+		eval "$function \"\$val\" \"\$@\""
+		c="$((c + 1))"
+	done
+}
+
+default_prerm() {
+	local root="${IPKG_INSTROOT}"
+	[ -z "$pkgname" ] && local pkgname="$(basename ${1%.*})"
+	local ret=0
+	local filelist="${root}/usr/lib/opkg/info/${pkgname}.list"
+	[ -f "$root/lib/apk/packages/${pkgname}.list" ] && filelist="$root/lib/apk/packages/${pkgname}.list"
+
+	if [ -f "$root/usr/lib/opkg/info/${pkgname}.prerm-pkg" ]; then
+		( . "$root/usr/lib/opkg/info/${pkgname}.prerm-pkg" )
+		ret=$?
+	fi
+
+	local shell="$(command -v bash)"
+	for i in $(grep -s "^/etc/init.d/" "$filelist"); do
+		if [ -n "$root" ]; then
+			${shell:-/bin/sh} "$root/etc/rc.common" "$root$i" disable
+		else
+			if [ "$PKG_UPGRADE" != "1" ]; then
+				"$i" disable
+			fi
+			"$i" stop
+		fi
+	done
+
+	return $ret
+}
+
+add_group_and_user() {
+	[ -z "$pkgname" ] && local pkgname="$(basename ${1%.*})"
+	local rusers="$(sed -ne 's/^Require-User: *//p' $root/usr/lib/opkg/info/${pkgname}.control 2>/dev/null)"
+	if [ -f "$root/lib/apk/packages/${pkgname}.rusers" ]; then
+		local rusers="$(cat $root/lib/apk/packages/${pkgname}.rusers)"
+	fi
+
+	if [ -n "$rusers" ]; then
+		local tuple oIFS="$IFS"
+		for tuple in $rusers; do
+			local uid gid uname gname addngroups addngroup addngname addngid
+
+			IFS=":"
+			set -- $tuple; uname="$1"; gname="$2"; addngroups="$3"
+			IFS="="
+			set -- $uname; uname="$1"; uid="$2"
+			set -- $gname; gname="$1"; gid="$2"
+			IFS="$oIFS"
+
+			if [ -n "$gname" ] && [ -n "$gid" ]; then
+				group_exists "$gname" || group_add "$gname" "$gid"
+			elif [ -n "$gname" ]; then
+				gid="$(group_add_next "$gname")"
+			fi
+
+			if [ -n "$uname" ]; then
+				user_exists "$uname" || user_add "$uname" "$uid" "$gid"
+			fi
+
+			if [ -n "$uname" ] && [ -n "$gname" ]; then
+				group_add_user "$gname" "$uname"
+			fi
+
+			if [ -n "$uname" ] &&  [ -n "$addngroups" ]; then
+				oIFS="$IFS"
+				IFS=","
+				for addngroup in $addngroups ; do
+					IFS="="
+					set -- $addngroup; addngname="$1"; addngid="$2"
+					if [ -n "$addngid" ]; then
+						group_exists "$addngname" || group_add "$addngname" "$addngid"
+					else
+						group_add_next "$addngname"
+					fi
+
+					group_add_user "$addngname" "$uname"
+				done
+				IFS="$oIFS"
+			fi
+
+			unset uid gid uname gname addngroups addngroup addngname addngid
+		done
+	fi
+}
+
+update_alternatives() {
+	local root="${IPKG_INSTROOT}"
+	local action="$1"
+	local pkgname="$2"
+
+	if [ -f "$root/lib/apk/packages/${pkgname}.alternatives" ]; then
+		for pkg_alt in $(cat $root/lib/apk/packages/${pkgname}.alternatives); do
+			local best_prio=0;
+			local best_src="/bin/busybox";
+			pkg_prio=${pkg_alt%%:*};
+			pkg_target=${pkg_alt#*:};
+			pkg_target=${pkg_target%:*};
+			pkg_src=${pkg_alt##*:};
+
+			if [ -e "$root/$target" ]; then
+				for alts in $root/lib/apk/packages/*.alternatives; do
+					for alt in $(cat $alts); do
+						prio=${alt%%:*};
+						target=${alt#*:};
+						target=${target%:*};
+						src=${alt##*:};
+
+						if [ "$target" = "$pkg_target" ] &&
+						   [ "$src" != "$pkg_src" ] &&
+						   [ "$best_prio" -lt "$prio" ]; then
+							best_prio=$prio;
+							best_src=$src;
+						fi
+					done
+				done
+			fi
+			case "$action" in
+				install)
+					if [ "$best_prio" -lt "$pkg_prio" ]; then
+						ln -sf "$pkg_src" "$root/$pkg_target"
+						echo "add alternative: $pkg_target -> $pkg_src"
+					fi
+				;;
+				remove)
+					if [ "$best_prio" -lt "$pkg_prio" ]; then
+						ln -sf "$best_src" "$root/$pkg_target"
+						echo "add alternative: $pkg_target -> $best_src"
+					fi
+				;;
+			esac
+		done
+	fi
+}
+
+default_postinst() {
+	local root="${IPKG_INSTROOT}"
+	[ -z "$pkgname" ] && local pkgname="$(basename ${1%.*})"
+	local filelist="${root}/usr/lib/opkg/info/${pkgname}.list"
+	[ -f "$root/lib/apk/packages/${pkgname}.list" ] && filelist="$root/lib/apk/packages/${pkgname}.list"
+	local ret=0
+
+	if [ -e "${root}/usr/lib/opkg/info/${pkgname}.list" ]; then
+		filelist="${root}/usr/lib/opkg/info/${pkgname}.list"
+		add_group_and_user "${pkgname}"
+	fi
+
+	if [ -e "${root}/lib/apk/packages/${pkgname}.list" ]; then
+		filelist="${root}/lib/apk/packages/${pkgname}.list"
+		update_alternatives install "${pkgname}"
+	fi
+
+	if [ -d "$root/rootfs-overlay" ]; then
+		cp -R $root/rootfs-overlay/. $root/
+		rm -fR $root/rootfs-overlay/
+	fi
+
+	if [ -z "$root" ]; then
+		if grep -m1 -q -s "^/etc/modules.d/" "$filelist"; then
+			kmodloader
+		fi
+
+		if grep -m1 -q -s "^/etc/sysctl.d/" "$filelist"; then
+			/etc/init.d/sysctl restart
+		fi
+
+		if grep -m1 -q -s "^/etc/uci-defaults/" "$filelist"; then
+			[ -d /tmp/.uci ] || mkdir -p /tmp/.uci
+			for i in $(grep -s "^/etc/uci-defaults/" "$filelist"); do
+				( [ -f "$i" ] && cd "$(dirname $i)" && . "$i" ) && rm -f "$i"
+			done
+			uci commit
+		fi
+
+		rm -f /tmp/luci-indexcache
+	fi
+
+	if [ -f "$root/usr/lib/opkg/info/${pkgname}.postinst-pkg" ]; then
+		( . "$root/usr/lib/opkg/info/${pkgname}.postinst-pkg" )
+		ret=$?
+	fi
+
+	local shell="$(command -v bash)"
+	for i in $(grep -s "^/etc/init.d/" "$filelist"); do
+		if [ -n "$root" ]; then
+			${shell:-/bin/sh} "$root/etc/rc.common" "$root$i" enable
+		else
+			if [ "$PKG_UPGRADE" != "1" ]; then
+				"$i" enable
+			fi
+			"$i" start
+		fi
+	done
+
+	return $ret
+}
+
+include() {
+	local file
+
+	for file in $(ls $1/*.sh 2>/dev/null); do
+		. $file
+	done
+}
+
+ipcalc() {
+	set -- $(ipcalc.sh "$@")
+	[ $? -eq 0 ] && export -- "$@"
+}
+
+find_mtd_index() {
+	local PART="$(grep "\"$1\"" /proc/mtd | awk -F: '{print $1}')"
+	local INDEX="${PART##mtd}"
+
+	echo ${INDEX}
+}
+
+find_mtd_part() {
+	local INDEX=$(find_mtd_index "$1")
+	local PREFIX=/dev/mtdblock
+
+	[ -d /dev/mtdblock ] && PREFIX=/dev/mtdblock/
+	echo "${INDEX:+$PREFIX$INDEX}"
+}
+
+find_system_slot() {
+	sys=`cat /proc/cmdline | grep "system=a"`
+	if [ -z "$sys" ]; then
+		sys=`cat /proc/cmdline | grep "system=b"`
+			if [ -z "$sys" ]; then
+				type=""
+			else
+				type="-b"
+	fi
+	else
+		type="-a"
+	fi
+	echo ${type}
+}
+
+find_mmc_part() {
+	local DEVNAME PARTNAME ROOTDEV
+
+	if grep -q "$1" /proc/mtd; then
+		echo "" && return 0
+	fi
+
+	if [ -n "$2" ]; then
+		ROOTDEV="$2"
+	else
+		ROOTDEV="mmcblk*"
+	fi
+
+	for DEVNAME in /sys/block/$ROOTDEV/mmcblk*p*; do
+		PARTNAME="$(grep PARTNAME ${DEVNAME}/uevent | cut -f2 -d'=')"
+		[ "$PARTNAME" = "$1" ] && echo "/dev/$(basename $DEVNAME)" && return 0
+	done
+}
+
+group_add() {
+	local name="$1"
+	local gid="$2"
+	local rc
+	[ -f "${IPKG_INSTROOT}/etc/group" ] || return 1
+	[ -n "$IPKG_INSTROOT" ] || lock /var/lock/group
+	echo "${name}:x:${gid}:" >> ${IPKG_INSTROOT}/etc/group
+	[ -n "$IPKG_INSTROOT" ] || lock -u /var/lock/group
+}
+
+group_exists() {
+	grep -qs "^${1}:" ${IPKG_INSTROOT}/etc/group
+}
+
+group_add_next() {
+	local gid gids
+	gid=$(grep -s "^${1}:" ${IPKG_INSTROOT}/etc/group | cut -d: -f3)
+	if [ -n "$gid" ]; then
+		echo $gid
+		return
+	fi
+	gids=$(cut -d: -f3 ${IPKG_INSTROOT}/etc/group)
+	gid=32768
+	while echo "$gids" | grep -q "^$gid$"; do
+		gid=$((gid + 1))
+	done
+	group_add $1 $gid
+	echo $gid
+}
+
+group_add_user() {
+	local grp delim=","
+	grp=$(grep -s "^${1}:" ${IPKG_INSTROOT}/etc/group)
+	echo "$grp" | cut -d: -f4 | grep -q $2 && return
+	echo "$grp" | grep -q ":$" && delim=""
+	[ -n "$IPKG_INSTROOT" ] || lock /var/lock/passwd
+	sed -i "s/$grp/$grp$delim$2/g" ${IPKG_INSTROOT}/etc/group
+	if [ -z "$IPKG_INSTROOT" ] && [ -x /usr/sbin/selinuxenabled ] && selinuxenabled; then
+		restorecon /etc/group
+	fi
+	[ -n "$IPKG_INSTROOT" ] || lock -u /var/lock/passwd
+}
+
+user_add() {
+	local name="${1}"
+	local uid="${2}"
+	local gid="${3}"
+	local desc="${4:-$1}"
+	local home="${5:-/var/run/$1}"
+	local shell="${6:-/bin/false}"
+	local rc
+	[ -z "$uid" ] && {
+		uids=$(cut -d: -f3 ${IPKG_INSTROOT}/etc/passwd)
+		uid=32768
+		while echo "$uids" | grep -q "^$uid$"; do
+			uid=$((uid + 1))
+		done
+	}
+	[ -z "$gid" ] && gid=$uid
+	[ -f "${IPKG_INSTROOT}/etc/passwd" ] || return 1
+	[ -n "$IPKG_INSTROOT" ] || lock /var/lock/passwd
+	echo "${name}:x:${uid}:${gid}:${desc}:${home}:${shell}" >> ${IPKG_INSTROOT}/etc/passwd
+	echo "${name}:x:0:0:99999:7:::" >> ${IPKG_INSTROOT}/etc/shadow
+	[ -n "$IPKG_INSTROOT" ] || lock -u /var/lock/passwd
+}
+
+user_exists() {
+	grep -qs "^${1}:" ${IPKG_INSTROOT}/etc/passwd
+}
+
+board_name() {
+	[ -e /tmp/sysinfo/board_name ] && cat /tmp/sysinfo/board_name || echo "generic"
+}
+
+cmdline_get_var() {
+	local var=$1
+	local cmdlinevar tmp
+
+	for cmdlinevar in $(cat /proc/cmdline); do
+		tmp=${cmdlinevar##${var}}
+		[ "=" = "${tmp:0:1}" ] && echo ${tmp:1}
+	done
+}
+
+[ -z "$IPKG_INSTROOT" ] && [ -f /lib/config/uci.sh ] && . /lib/config/uci.sh || true
diff --git a/package/base-files/files/lib/functions/caldata.sh b/package/base-files/files/lib/functions/caldata.sh
new file mode 100644
index 0000000..f0fc907
--- /dev/null
+++ b/package/base-files/files/lib/functions/caldata.sh
@@ -0,0 +1,218 @@
+# Copyright (C) 2019 OpenWrt.org
+
+. /lib/functions.sh
+. /lib/functions/system.sh
+
+caldata_dd() {
+	local source=$1
+	local target=$2
+	local count=$(($3))
+	local offset=$(($4))
+
+	dd if=$source of=$target iflag=skip_bytes,fullblock bs=$count skip=$offset count=1 2>/dev/null
+	return $?
+}
+
+caldata_die() {
+	echo "caldata: " "$*"
+	exit 1
+}
+
+caldata_extract() {
+	local part=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local mtd
+
+	mtd=$(find_mtd_chardev $part)
+	[ -n "$mtd" ] || caldata_die "no mtd device found for partition $part"
+
+	caldata_dd $mtd /lib/firmware/$FIRMWARE $count $offset || \
+		caldata_die "failed to extract calibration data from $mtd"
+}
+
+caldata_extract_ubi() {
+	local part=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local ubidev
+	local ubi
+
+	. /lib/upgrade/nand.sh
+
+	ubidev=$(nand_find_ubi $CI_UBIPART)
+	ubi=$(nand_find_volume $ubidev $part)
+	[ -n "$ubi" ] || caldata_die "no UBI volume found for $part"
+
+	caldata_dd /dev/$ubi /lib/firmware/$FIRMWARE $count $offset || \
+		caldata_die "failed to extract calibration data from $ubi"
+}
+
+caldata_extract_mmc() {
+	local part=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local mmc_part
+
+	mmc_part=$(find_mmc_part $part)
+	[ -n "$mmc_part" ] || caldata_die "no mmc partition found for partition $part"
+
+	caldata_dd $mmc_part /lib/firmware/$FIRMWARE $count $offset || \
+		caldata_die "failed to extract calibration data from $mmc_part"
+}
+
+caldata_extract_reverse() {
+	local part=$1
+	local offset=$2
+	local count=$(($3))
+	local mtd
+	local reversed
+	local caldata
+
+	mtd=$(find_mtd_chardev "$part")
+	reversed=$(hexdump -v -s $offset -n $count -e '1/1 "%02x "' $mtd)
+
+	for byte in $reversed; do
+		caldata="\x${byte}${caldata}"
+	done
+
+	printf "%b" "$caldata" > /lib/firmware/$FIRMWARE
+}
+
+caldata_from_file() {
+	local source=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local target=$4
+
+	[ -n "$target" ] || target=/lib/firmware/$FIRMWARE
+
+	caldata_dd $source $target $count $offset || \
+		caldata_die "failed to extract calibration data from $source"
+}
+
+caldata_sysfsload_from_file() {
+	local source=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local target_dir="/sys/$DEVPATH"
+	local target="$target_dir/data"
+
+	[ -d "$target_dir" ] || \
+		caldata_die "no sysfs dir to write: $target"
+
+	echo 1 > "$target_dir/loading"
+	caldata_dd $source $target $count $offset
+	if [ $? != 0 ]; then
+		echo 1 > "$target_dir/loading"
+		caldata_die "failed to extract calibration data from $source"
+	else
+		echo 0 > "$target_dir/loading"
+	fi
+}
+
+caldata_valid() {
+	local expected="$1"
+	local target=$2
+
+	[ -n "$target" ] || target=/lib/firmware/$FIRMWARE
+
+	magic=$(hexdump -v -n 2 -e '1/1 "%02x"' $target)
+	[ "$magic" = "$expected" ]
+	return $?
+}
+
+caldata_patch_data() {
+	local data=$1
+	local data_count=$((${#1} / 2))
+	[ -n "$2" ] && local data_offset=$(($2))
+	[ -n "$3" ] && local chksum_offset=$(($3))
+	local target=$4
+	local fw_data
+	local fw_chksum
+
+	[ -z "$data" -o -z "$data_offset" ] && return
+
+	[ -n "$target" ] || target=/lib/firmware/$FIRMWARE
+
+	fw_data=$(hexdump -v -n $data_count -s $data_offset -e '1/1 "%02x"' $target)
+
+	if [ "$data" != "$fw_data" ]; then
+
+		if [ -n "$chksum_offset" ]; then
+			fw_chksum=$(hexdump -v -n 2 -s $chksum_offset -e '1/1 "%02x"' $target)
+			fw_chksum=$(xor $fw_chksum $(data_2xor_val $fw_data) $(data_2xor_val $data))
+
+			data_2bin $fw_chksum | \
+				dd of=$target conv=notrunc bs=1 seek=$chksum_offset count=2 || \
+				caldata_die "failed to write chksum to eeprom file"
+		fi
+
+		data_2bin $data | \
+			dd of=$target conv=notrunc bs=1 seek=$data_offset count=$data_count || \
+			caldata_die "failed to write data to eeprom file"
+	fi
+}
+
+ath9k_patch_mac() {
+	local mac=$1
+	local target=$2
+
+	caldata_patch_data "${mac//:/}" 0x2 "" "$target"
+}
+
+ath9k_patch_mac_crc() {
+	local mac=$1
+	local mac_offset=$2
+	local chksum_offset=$((mac_offset - 10))
+	local target=$4
+
+	caldata_patch_data "${mac//:/}" "$mac_offset" "$chksum_offset" "$target"
+}
+
+ath10k_patch_mac() {
+	local mac=$1
+	local target=$2
+
+	caldata_patch_data "${mac//:/}" 0x6 0x2 "$target"
+}
+
+ath11k_patch_mac() {
+	local mac=$1
+	# mac_id from 0 to 5
+	local mac_id=$2
+	local target=$3
+
+	[ -z "$mac_id" ] && return
+
+	caldata_patch_data "${mac//:/}" $(printf "0x%x" $(($mac_id * 0x6 + 0xe))) 0xa "$target"
+}
+
+ath10k_remove_regdomain() {
+	local target=$1
+
+	caldata_patch_data "0000" 0xc 0x2 "$target"
+}
+
+ath11k_remove_regdomain() {
+	local target=$1
+	local regdomain
+	local regdomain_data
+
+	regdomain=$(hexdump -v -n 2 -s 0x34 -e '1/1 "%02x"' $target)
+	caldata_patch_data "0000" 0x34 0xa "$target"
+	
+	for offset in 0x450 0x458 0x500 0x5a8; do
+		regdomain_data=$(hexdump -v -n 2 -s $offset -e '1/1 "%02x"' $target)
+
+		if [ "$regdomain" == "$regdomain_data" ]; then
+			caldata_patch_data "0000" $offset 0xa "$target"
+		fi
+	done
+}
+
+ath11k_set_macflag() {
+	local target=$1
+
+	caldata_patch_data "0100" 0x3e 0xa "$target"
+}
diff --git a/package/base-files/files/lib/functions/ipv4.sh b/package/base-files/files/lib/functions/ipv4.sh
new file mode 100644
index 0000000..d0b93db
--- /dev/null
+++ b/package/base-files/files/lib/functions/ipv4.sh
@@ -0,0 +1,268 @@
+uint_max=4294967295
+
+d_10_0_0_0=167772160
+d_10_255_255_255=184549375
+
+d_172_16_0_0=2886729728
+d_172_31_255_255=2887778303
+
+d_192_168_0_0=3232235520
+d_192_168_255_255=3232301055
+
+d_169_254_0_0=2851995648
+d_169_254_255_255=2852061183
+
+d_127_0_0_0=2130706432
+d_127_255_255_255=2147483647
+
+d_224_0_0_0=3758096384
+d_239_255_255_255=4026531839
+
+# check that $1 is only base 10 digits, and that it doesn't
+# exceed 2^32-1
+assert_uint32() {
+    local __n="$1"
+
+    if [ -z "$__n" -o -n "${__n//[0-9]/}" ]; then
+	printf "Not a decimal integer (%s)\n" "$__n ">&2
+	return 1
+    fi
+
+    if [ "$__n" -gt $uint_max ]; then
+	printf "Out of range (%s)\n" "$__n" >&2
+	return 1
+    fi
+
+    if [ "$((__n + 0))" != "$__n" ]; then
+	printf "Not normalized notation (%s)\n" "$__n" >&2
+	return 1
+    fi
+
+    return 0
+}
+
+# return a count of the number of bits set in $1
+bitcount() {
+    local __var="$1" __c="$2"
+    assert_uint32 "$__c" || return 1
+
+    __c=$((((__c >> 1) & 0x55555555) + (__c & 0x55555555)))
+    __c=$((((__c >> 2) & 0x33333333) + (__c & 0x33333333)))
+    __c=$((((__c >> 4) & 0x0f0f0f0f) + (__c & 0x0f0f0f0f)))
+    __c=$((((__c >> 8) & 0x00ff00ff) + (__c & 0x00ff00ff)))
+    __c=$((((__c >> 16) & 0x0000ffff) + (__c & 0x0000ffff)))
+
+    export -- "$__var=$__c"
+}
+
+# tedious but portable with busybox's limited shell
+# we check each octet to be in the range of 0..255,
+# and also make sure there's no extaneous characters.
+str2ip() {
+    local __var="$1" __ip="$2" __n __val=0
+
+    case "$__ip" in
+    [0-9].*)
+	__n="${__ip:0:1}"
+	__ip="${__ip:2}"
+	;;
+    [1-9][0-9].*)
+	__n="${__ip:0:2}"
+	__ip="${__ip:3}"
+	;;
+    1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
+	__n="${__ip:0:3}"
+	__ip="${__ip:4}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__n << 24))
+
+    case "$__ip" in
+    [0-9].*)
+	__n="${__ip:0:1}"
+	__ip="${__ip:2}"
+	;;
+    [1-9][0-9].*)
+	__n="${__ip:0:2}"
+	__ip="${__ip:3}"
+	;;
+    1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
+	__n="${__ip:0:3}"
+	__ip="${__ip:4}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__val + (__n << 16)))
+
+    case "$__ip" in
+    [0-9].*)
+	__n="${__ip:0:1}"
+	__ip="${__ip:2}"
+	;;
+    [1-9][0-9].*)
+	__n="${__ip:0:2}"
+	__ip="${__ip:3}"
+	;;
+    1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
+	__n="${__ip:0:3}"
+	__ip="${__ip:4}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__val + (__n << 8)))
+
+    case "$__ip" in
+    [0-9])
+	__n="${__ip:0:1}"
+	__ip="${__ip:1}"
+	;;
+    [1-9][0-9])
+	__n="${__ip:0:2}"
+	__ip="${__ip:2}"
+	;;
+    1[0-9][0-9]|2[0-4][0-9]|25[0-5])
+	__n="${__ip:0:3}"
+	__ip="${__ip:3}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__val + __n))
+
+    if [ -n "$__ip" ]; then
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+    fi
+
+    export -- "$__var=$__val"
+    return 0
+}
+
+# convert back from an integer to dotted-quad.
+ip2str() {
+    local __var="$1" __n="$2"
+    assert_uint32 "$__n" || return 1
+
+    export -- "$__var=$((__n >> 24)).$(((__n >> 16) & 255)).$(((__n >> 8) & 255)).$((__n & 255))"
+}
+
+# convert prefix into an integer bitmask
+prefix2netmask() {
+    local __var="$1" __n="$2"
+    assert_uint32 "$__n" || return 1
+
+    if [ "$__n" -gt 32 ]; then
+	printf "Prefix out-of-range (%s)" "$__n" >&2
+	return 1
+    fi
+
+    export -- "$__var=$(((~(uint_max >> __n)) & uint_max))"
+}
+
+_is_contiguous() {
+    local __x="$1"	# no checking done
+    local __y=$((~__x & uint_max))
+    local __z=$(((__y + 1) & uint_max))
+
+    [ $((__z & __y)) -eq 0 ]
+}
+
+# check argument as being contiguous upper bits (and yes,
+# 0 doesn't have any discontiguous bits).
+is_contiguous() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    local __y=$((~__x & uint_max))
+    local __z=$(((__y + 1) & uint_max))
+
+    [ $((__z & __y)) -eq 0 ] && __val=1
+
+    export -- "$__var=$__val"
+}
+
+# convert mask to prefix, validating that it's a conventional
+# (contiguous) netmask.
+netmask2prefix() {
+    local __var="$1" __n="$2" __cont __bits
+    assert_uint32 "$__n" || return 1
+
+    is_contiguous __cont "$__n" || return 1
+    if [ $__cont -eq 0 ]; then
+	printf "Not a contiguous netmask (%08x)\n" "$__n" >&2
+	return 1
+    fi
+
+    bitcount __bits "$__n"		# already checked
+
+    export -- "$__var=$__bits"
+}
+
+# check the argument as being an rfc-1918 address
+is_rfc1918() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_10_0_0_0 -le $__x ] && [ $__x -le $d_10_255_255_255 ]; then
+	__val=1
+    elif [ $d_172_16_0_0 -le $__x ] && [ $__x -le $d_172_31_255_255 ]; then
+	__val=1
+    elif [ $d_192_168_0_0 -le $__x ] && [ $__x -le $d_192_168_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
+# check the argument as being an rfc-3927 address
+is_rfc3927() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_169_254_0_0 -le $__x ] && [ $__x -le $d_169_254_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
+# check the argument as being an rfc-1122 loopback address
+is_loopback() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_127_0_0_0 -le $__x ] && [ $__x -le $d_127_255_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
+# check the argument as being a multicast address
+is_multicast() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_224_0_0_0 -le $__x ] && [ $__x -le $d_239_255_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
diff --git a/package/base-files/files/lib/functions/leds.sh b/package/base-files/files/lib/functions/leds.sh
new file mode 100644
index 0000000..333d900
--- /dev/null
+++ b/package/base-files/files/lib/functions/leds.sh
@@ -0,0 +1,125 @@
+# Copyright (C) 2013 OpenWrt.org
+
+get_dt_led_path() {
+	local ledpath
+	local basepath="/proc/device-tree"
+	local nodepath="$basepath/aliases/led-$1"
+
+	[ -f "$nodepath" ] && ledpath=$(cat "$nodepath")
+	[ -n "$ledpath" ] && ledpath="$basepath$ledpath"
+
+	echo "$ledpath"
+}
+
+get_dt_led_color_func() {
+	local enum
+	local func
+	local idx
+	local label
+
+	[ -e "$1/function" ] && func=$(cat "$1/function")
+	[ -e "$1/color" ] && idx=$((0x$(hexdump -n 4 -e '4/1 "%02x"' "$1/color")))
+	[ -e "$1/function-enumerator" ] && \
+		enum=$((0x$(hexdump -n 4 -e '4/1 "%02x"' "$1/function-enumerator")))
+
+	[ -z "$idx" ] && [ -z "$func" ] && return 2
+
+	if [ -n "$idx" ]; then
+		for color in "white" "red" "green" "blue" "amber" \
+			     "violet" "yellow" "ir" "multicolor" "rgb" \
+			     "purple" "orange" "pink" "cyan" "lime"
+		do
+			[ $idx -eq 0 ] && label="$color" && break
+			idx=$((idx-1))
+		done
+	fi
+
+	label="$label:$func"
+	[ -n "$enum" ] && label="$label-$enum"
+	echo "$label"
+
+	return 0
+}
+
+get_dt_led() {
+	local label
+	local ledpath=$(get_dt_led_path $1)
+
+	[ -n "$ledpath" ] && \
+		label=$(cat "$ledpath/label" 2>/dev/null) || \
+		label=$(cat "$ledpath/chan-name" 2>/dev/null) || \
+		label=$(get_dt_led_color_func "$ledpath") || \
+		label=$(basename "$ledpath")
+
+	echo "$label"
+}
+
+led_set_attr() {
+	[ -f "/sys/class/leds/$1/$2" ] && echo "$3" > "/sys/class/leds/$1/$2"
+}
+
+led_timer() {
+	led_set_attr $1 "trigger" "timer"
+	led_set_attr $1 "delay_on" "$2"
+	led_set_attr $1 "delay_off" "$3"
+}
+
+led_on() {
+	led_set_attr $1 "trigger" "none"
+	led_set_attr $1 "brightness" 255
+}
+
+led_off() {
+	led_set_attr $1 "trigger" "none"
+	led_set_attr $1 "brightness" 0
+}
+
+status_led_restore_trigger() {
+	local trigger
+	local ledpath=$(get_dt_led_path $1)
+
+	[ -n "$ledpath" ] && \
+		trigger=$(cat "$ledpath/linux,default-trigger" 2>/dev/null)
+
+	[ -n "$trigger" ] && \
+		led_set_attr "$(get_dt_led $1)" "trigger" "$trigger"
+}
+
+status_led_set_timer() {
+	led_timer $status_led "$1" "$2"
+	[ -n "$status_led2" ] && led_timer $status_led2 "$1" "$2"
+}
+
+status_led_set_heartbeat() {
+	led_set_attr $status_led "trigger" "heartbeat"
+}
+
+status_led_on() {
+	led_on $status_led
+	[ -n "$status_led2" ] && led_on $status_led2
+}
+
+status_led_off() {
+	led_off $status_led
+	[ -n "$status_led2" ] && led_off $status_led2
+}
+
+status_led_blink_slow() {
+	led_timer $status_led 1000 1000
+}
+
+status_led_blink_fast() {
+	led_timer $status_led 100 100
+}
+
+status_led_blink_preinit() {
+	led_timer $status_led 100 100
+}
+
+status_led_blink_failsafe() {
+	led_timer $status_led 50 50
+}
+
+status_led_blink_preinit_regular() {
+	led_timer $status_led 200 200
+}
diff --git a/package/base-files/files/lib/functions/migrations.sh b/package/base-files/files/lib/functions/migrations.sh
new file mode 100644
index 0000000..d43ea35
--- /dev/null
+++ b/package/base-files/files/lib/functions/migrations.sh
@@ -0,0 +1,67 @@
+. /lib/functions.sh
+
+migrate_led_sysfs() {
+	local cfg="$1"; shift
+	local tuples="$@"
+	local sysfs
+	local name
+
+	config_get sysfs ${cfg} sysfs
+	config_get name ${cfg} name
+
+	[ -z "${sysfs}" ] && return
+
+	for tuple in ${tuples}; do
+		local old=${tuple%=*}
+		local new=${tuple#*=}
+		local new_sysfs
+
+		new_sysfs=$(echo ${sysfs} | sed "s/${old}/${new}/")
+
+		[ "${new_sysfs}" = "${sysfs}" ] && continue
+
+		uci set system.${cfg}.sysfs="${new_sysfs}"
+
+		logger -t led-migration "sysfs option of LED \"${name}\" updated to ${new_sysfs}"
+	done;
+}
+
+remove_devicename_led_sysfs() {
+	local cfg="$1"; shift
+	local exceptions="$@"
+	local sysfs
+	local name
+	local new_sysfs
+
+	config_get sysfs ${cfg} sysfs
+	config_get name ${cfg} name
+
+	# only continue if two or more colons are present
+	echo "${sysfs}" | grep -q ":.*:" || return
+
+	for exception in ${exceptions}; do
+		# no change if exceptions provided as argument are found for devicename
+		echo "${sysfs}" | grep -q "^${exception}:" && return
+	done
+
+	new_sysfs=$(echo ${sysfs} | sed "s/^[^:]*://")
+
+	uci set system.${cfg}.sysfs="${new_sysfs}"
+
+	logger -t led-migration "sysfs option of LED \"${name}\" updated to ${new_sysfs}"
+}
+
+migrate_leds() {
+	config_load system
+	config_foreach migrate_led_sysfs led "$@"
+}
+
+remove_devicename_leds() {
+	config_load system
+	config_foreach remove_devicename_led_sysfs led "$@"
+}
+
+migrations_apply() {
+	local realm="$1"
+	[ -n "$(uci changes ${realm})" ] && uci -q commit ${realm}
+}
diff --git a/package/base-files/files/lib/functions/network.sh b/package/base-files/files/lib/functions/network.sh
new file mode 100644
index 0000000..4851a58
--- /dev/null
+++ b/package/base-files/files/lib/functions/network.sh
@@ -0,0 +1,325 @@
+# 1: destination variable
+# 2: interface
+# 3: path
+# 4: separator
+# 5: limit
+__network_ifstatus() {
+	local __tmp
+
+	[ -z "$__NETWORK_CACHE" ] && {
+		__tmp="$(ubus call network.interface dump 2>&1)"
+		case "$?" in
+			4) : ;;
+			0) export __NETWORK_CACHE="$__tmp" ;;
+			*) echo "$__tmp" >&2 ;;
+		esac
+	}
+
+	__tmp="$(jsonfilter ${4:+-F "$4"} ${5:+-l "$5"} -s "${__NETWORK_CACHE:-{}}" -e "$1=@.interface${2:+[@.interface='$2']}$3")"
+
+	[ -z "$__tmp" ] && \
+		unset "$1" && \
+		return 1
+
+	eval "$__tmp"
+}
+
+# determine first IPv4 address of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddr() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][0].address";
+}
+
+# determine first IPv6 address of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddr6() {
+	__network_ifstatus "$1" "$2" "['ipv6-address'][0].address" || \
+		__network_ifstatus "$1" "$2" "['ipv6-prefix-assignment'][0]['local-address'].address" || \
+		return 1
+}
+
+# determine first IPv4 subnet of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnet() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][0]['address','mask']" "/"
+}
+
+# determine first IPv6 subnet of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnet6() {
+	local __nets __addr
+
+	if network_get_subnets6 __nets "$2"; then
+		# Attempt to return first non-fe80::/10, non-fc::/7 range
+		for __addr in $__nets; do
+			case "$__addr" in fe[8ab]?:*|f[cd]??:*)
+				continue
+			esac
+			export "$1=$__addr"
+			return 0
+		done
+
+		# Attempt to return first non-fe80::/10 range
+		for __addr in $__nets; do
+			case "$__addr" in fe[8ab]?:*)
+				continue
+			esac
+			export "$1=$__addr"
+			return 0
+		done
+
+		# Return first item
+		for __addr in $__nets; do
+			export "$1=$__addr"
+			return 0
+		done
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine first IPv6 prefix of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefix6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix'][0]['address','mask']" "/"
+}
+
+# determine first IPv6 prefix assignment of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefix_assignment6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix-assignment'][0]['address','mask']" "/"
+}
+
+# determine all IPv4 addresses of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddrs() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][*].address"
+}
+
+# determine all IPv6 addresses of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddrs6() {
+	local __addr
+	local __list=""
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-address'][*].address"; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}"
+		done
+	fi
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-prefix-assignment'][*]['local-address'].address"; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}"
+		done
+	fi
+
+	if [ -n "$__list" ]; then
+		export "$1=$__list"
+		return 0
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine all IP addresses of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddrs_all() {
+	local __addr __addr6
+
+	network_get_ipaddrs __addr "$2"
+	network_get_ipaddrs6 __addr6 "$2"
+
+	if [ -n "$__addr" -o -n "$__addr6" ]; then
+		export "$1=${__addr:+$__addr }$__addr6"
+		return 0
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine all IPv4 subnets of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnets() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][*]['address','mask']" "/ "
+}
+
+# determine all IPv6 subnets of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnets6() {
+	local __addr __mask
+	local __list=""
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-address'][*]['address','mask']" "/ "; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}"
+		done
+	fi
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-prefix-assignment'][*]['local-address'].address" && \
+	   __network_ifstatus "__mask" "$2" "['ipv6-prefix-assignment'][*].mask"; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}/${__mask%% *}"
+			__mask="${__mask#* }"
+		done
+	fi
+
+	if [ -n "$__list" ]; then
+		export "$1=$__list"
+		return 0
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine all IPv6 prefixes of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefixes6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix'][*]['address','mask']" "/ "
+}
+
+# determine all IPv6 prefix assignments of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefix_assignments6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix-assignment'][*]['address','mask']" "/ "
+}
+
+# determine IPv4 gateway of given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive gateway if "true" (optional)
+network_get_gateway() {
+	__network_ifstatus "$1" "$2" ".route[@.target='0.0.0.0' && !@.table].nexthop" "" 1 && \
+		return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive.route[@.target='0.0.0.0' && !@.table].nexthop" "" 1
+}
+
+# determine IPv6 gateway of given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive gateway if "true" (optional)
+network_get_gateway6() {
+	__network_ifstatus "$1" "$2" ".route[@.target='::' && !@.table].nexthop" "" 1 && \
+		return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive.route[@.target='::' && !@.table].nexthop" "" 1
+}
+
+# determine the DNS servers of the given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive servers if "true" (optional)
+network_get_dnsserver() {
+	__network_ifstatus "$1" "$2" "['dns-server'][*]" && return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive['dns-server'][*]"
+}
+
+# determine the domains of the given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive domains if "true" (optional)
+network_get_dnssearch() {
+	__network_ifstatus "$1" "$2" "['dns-search'][*]" && return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive['dns-search'][*]"
+}
+
+
+# 1: destination variable
+# 2: addr
+# 3: inactive
+__network_wan()
+{
+	__network_ifstatus "$1" "" \
+		"[@.route[@.target='$2' && !@.table]].interface" "" 1 && \
+			return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "" \
+			"[@.inactive.route[@.target='$2' && !@.table]].interface" "" 1
+}
+
+# find the logical interface which holds the current IPv4 default route
+# 1: destination variable
+# 2: consider inactive default routes if "true" (optional)
+network_find_wan() { __network_wan "$1" "0.0.0.0" "$2"; }
+
+# find the logical interface which holds the current IPv6 default route
+# 1: destination variable
+# 2: consider inactive default routes if "true" (optional)
+network_find_wan6() { __network_wan "$1" "::" "$2"; }
+
+# test whether the given logical interface is running
+# 1: interface
+network_is_up()
+{
+	local __up
+	__network_ifstatus "__up" "$1" ".up" && [ "$__up" = 1 ]
+}
+
+# determine the protocol of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_protocol() { __network_ifstatus "$1" "$2" ".proto"; }
+
+# determine the uptime of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_uptime() { __network_ifstatus "$1" "$2" ".uptime"; }
+
+# determine the metric of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_metric() { __network_ifstatus "$1" "$2" ".metric"; }
+
+# determine the layer 3 linux network device of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_device() { __network_ifstatus "$1" "$2" ".l3_device"; }
+
+# determine the layer 2 linux network device of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_physdev() { __network_ifstatus "$1" "$2" ".device"; }
+
+# defer netifd actions on the given linux network device
+# 1: device name
+network_defer_device()
+{
+	ubus call network.device set_state \
+		"$(printf '{ "name": "%s", "defer": true }' "$1")" 2>/dev/null
+}
+
+# continue netifd actions on the given linux network device
+# 1: device name
+network_ready_device()
+{
+	ubus call network.device set_state \
+		"$(printf '{ "name": "%s", "defer": false }' "$1")" 2>/dev/null
+}
+
+# flush the internal value cache to force re-reading values from ubus
+network_flush_cache() { unset __NETWORK_CACHE; }
diff --git a/package/base-files/files/lib/functions/preinit.sh b/package/base-files/files/lib/functions/preinit.sh
new file mode 100644
index 0000000..591e810
--- /dev/null
+++ b/package/base-files/files/lib/functions/preinit.sh
@@ -0,0 +1,87 @@
+# Copyright (C) 2006-2013 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+boot_hook_splice_start() {
+	export -n PI_HOOK_SPLICE=1
+}
+
+boot_hook_splice_finish() {
+	local hook
+	for hook in $PI_STACK_LIST; do
+		local v; eval "v=\${${hook}_splice:+\$${hook}_splice }$hook"
+		export -n "${hook}=${v% }"
+		export -n "${hook}_splice="
+	done
+	export -n PI_HOOK_SPLICE=
+}
+
+boot_hook_init() {
+	local hook="${1}_hook"
+	export -n "PI_STACK_LIST=${PI_STACK_LIST:+$PI_STACK_LIST }$hook"
+	export -n "$hook="
+}
+
+boot_hook_add() {
+	local hook="${1}_hook${PI_HOOK_SPLICE:+_splice}"
+	local func="${2}"
+
+	[ -n "$func" ] && {
+		local v; eval "v=\$$hook"
+		export -n "$hook=${v:+$v }$func"
+	}
+}
+
+boot_hook_shift() {
+	local hook="${1}_hook"
+	local rvar="${2}"
+
+	local v; eval "v=\$$hook"
+	[ -n "$v" ] && {
+		local first="${v%% *}"
+
+		[ "$v" != "${v#* }" ] && \
+			export -n "$hook=${v#* }" || \
+			export -n "$hook="
+
+		export -n "$rvar=$first"
+		return 0
+	}
+
+	return 1
+}
+
+boot_run_hook() {
+	local hook="$1"
+	local func
+
+	while boot_hook_shift "$hook" func; do
+		local ran; eval "ran=\$PI_RAN_$func"
+		[ -n "$ran" ] || {
+			export -n "PI_RAN_$func=1"
+			$func "$1" "$2"
+		}
+	done
+}
+
+pivot() { # <new_root> <old_root>
+	/bin/mount -o noatime,move /proc $1/proc && \
+	pivot_root $1 $1$2 && {
+		/bin/mount -o noatime,move $2/dev /dev
+		/bin/mount -o noatime,move $2/tmp /tmp
+		/bin/mount -o noatime,move $2/sys /sys 2>&-
+		/bin/mount -o noatime,move $2/overlay /overlay 2>&-
+		return 0
+	}
+}
+
+fopivot() { # <rw_root> <work_dir> <ro_root> <dupe?>
+	/bin/mount -o noatime,lowerdir=/,upperdir=$1,workdir=$2 -t overlay "overlayfs:$1" /mnt
+	pivot /mnt $3
+}
+
+ramoverlay() {
+	mkdir -p /tmp/root
+	/bin/mount -t tmpfs -o noatime,mode=0755 root /tmp/root
+	mkdir -p /tmp/root/root /tmp/root/work
+	fopivot /tmp/root/root /tmp/root/work /rom 1
+}
diff --git a/package/base-files/files/lib/functions/service.sh b/package/base-files/files/lib/functions/service.sh
new file mode 100644
index 0000000..3d08e14
--- /dev/null
+++ b/package/base-files/files/lib/functions/service.sh
@@ -0,0 +1,103 @@
+#
+# service: simple wrapper around start-stop-daemon
+#
+# Usage: service ACTION EXEC ARGS...
+#
+# Action:
+#   -C	check if EXEC is alive
+#   -S	start EXEC, passing it ARGS as its arguments
+#   -K	kill EXEC, sending it a TERM signal if not specified otherwise
+#
+# Environment variables exposed:
+#   SERVICE_DAEMONIZE	run EXEC in background
+#   SERVICE_WRITE_PID	create a pid-file and use it for matching
+#   SERVICE_MATCH_EXEC	use EXEC command-line for matching (default)
+#   SERVICE_MATCH_NAME	use EXEC process name for matching
+#   SERVICE_USE_PID	assume EXEC create its own pid-file and use it for matching
+#   SERVICE_NAME	process name to use (default to EXEC file part)
+#   SERVICE_PID_FILE	pid file to use (default to /var/run/$SERVICE_NAME.pid)
+#   SERVICE_SIG		signal to send when using -K
+#   SERVICE_SIG_RELOAD	default signal used when reloading
+#   SERVICE_SIG_STOP	default signal used when stopping
+#   SERVICE_STOP_TIME	time to wait for a process to stop gracefully before killing it
+#   SERVICE_UID		user EXEC should be run as
+#   SERVICE_GID		group EXEC should be run as
+#
+#   SERVICE_DEBUG	don't do anything, but show what would be done
+#   SERVICE_QUIET	don't print anything
+#
+
+SERVICE_QUIET=1
+SERVICE_SIG_RELOAD="HUP"
+SERVICE_SIG_STOP="TERM"
+SERVICE_STOP_TIME=5
+SERVICE_MATCH_EXEC=1
+
+service() {
+	local ssd
+	local exec
+	local name
+	local start
+	ssd="${SERVICE_DEBUG:+echo }start-stop-daemon${SERVICE_QUIET:+ -q}"
+	case "$1" in
+	  -C)
+		ssd="$ssd -K -t"
+		;;
+	  -S)
+		ssd="$ssd -S${SERVICE_DAEMONIZE:+ -b}${SERVICE_WRITE_PID:+ -m}"
+		start=1
+		;;
+	  -K)
+		ssd="$ssd -K${SERVICE_SIG:+ -s $SERVICE_SIG}"
+		;;
+	  *)
+		echo "service: unknown ACTION '$1'" 1>&2
+		return 1
+	esac
+	shift
+	exec="$1"
+	[ -n "$exec" ] || {
+		echo "service: missing argument" 1>&2
+		return 1
+	}
+	[ -x "$exec" ] || {
+		echo "service: file '$exec' is not executable" 1>&2
+		return 1
+	}
+	name="${SERVICE_NAME:-${exec##*/}}"
+	[ -z "$SERVICE_USE_PID$SERVICE_WRITE_PID$SERVICE_PID_FILE" ] \
+		|| ssd="$ssd -p ${SERVICE_PID_FILE:-/var/run/$name.pid}"
+	[ -z "$SERVICE_MATCH_NAME" ] || ssd="$ssd -n $name"
+	ssd="$ssd${SERVICE_UID:+ -c $SERVICE_UID${SERVICE_GID:+:$SERVICE_GID}}"
+	[ -z "$SERVICE_MATCH_EXEC$start" ] || ssd="$ssd -x $exec"
+	shift
+	$ssd${1:+ -- "$@"}
+}
+
+service_check() {
+	service -C "$@"
+}
+
+service_signal() {
+	SERVICE_SIG="${SERVICE_SIG:-USR1}" service -K "$@"
+}
+
+service_start() {
+	service -S "$@"
+}
+
+service_stop() {
+	local try
+	SERVICE_SIG="${SERVICE_SIG:-$SERVICE_SIG_STOP}" service -K "$@" || return 1
+	while [ $((try++)) -lt $SERVICE_STOP_TIME ]; do
+		service -C "$@" || return 0
+		sleep 1
+	done
+	SERVICE_SIG="KILL" service -K "$@"
+	sleep 1
+	! service -C "$@"
+}
+
+service_reload() {
+	SERVICE_SIG="${SERVICE_SIG:-$SERVICE_SIG_RELOAD}" service -K "$@"
+}
diff --git a/package/base-files/files/lib/functions/system.sh b/package/base-files/files/lib/functions/system.sh
new file mode 100644
index 0000000..f43281b
--- /dev/null
+++ b/package/base-files/files/lib/functions/system.sh
@@ -0,0 +1,317 @@
+# Copyright (C) 2006-2013 OpenWrt.org
+
+. /lib/functions.sh
+. /usr/share/libubox/jshn.sh
+
+get_mac_binary() {
+	local path="$1"
+	local offset="$2"
+
+	if ! [ -e "$path" ]; then
+		echo "get_mac_binary: file $path not found!" >&2
+		return
+	fi
+
+	hexdump -v -n 6 -s $offset -e '5/1 "%02x:" 1/1 "%02x"' $path 2>/dev/null
+}
+
+get_mac_label_dt() {
+	local basepath="/proc/device-tree"
+	local macdevice="$(cat "$basepath/aliases/label-mac-device" 2>/dev/null)"
+	local macaddr
+
+	[ -n "$macdevice" ] || return
+
+	macaddr=$(get_mac_binary "$basepath/$macdevice/mac-address" 0 2>/dev/null)
+	[ -n "$macaddr" ] || macaddr=$(get_mac_binary "$basepath/$macdevice/local-mac-address" 0 2>/dev/null)
+
+	echo $macaddr
+}
+
+get_mac_label_json() {
+	local cfg="/etc/board.json"
+	local macaddr
+
+	[ -s "$cfg" ] || return
+
+	json_init
+	json_load "$(cat $cfg)"
+	if json_is_a system object; then
+		json_select system
+			json_get_var macaddr label_macaddr
+		json_select ..
+	fi
+
+	echo $macaddr
+}
+
+get_mac_label() {
+	local macaddr=$(get_mac_label_dt)
+
+	[ -n "$macaddr" ] || macaddr=$(get_mac_label_json)
+
+	echo $macaddr
+}
+
+find_mtd_chardev() {
+	local INDEX=$(find_mtd_index "$1")
+	local PREFIX=/dev/mtd
+
+	[ -d /dev/mtd ] && PREFIX=/dev/mtd/
+	echo "${INDEX:+$PREFIX$INDEX}"
+}
+
+get_mac_ascii() {
+	local part="$1"
+	local key="$2"
+	local mac_dirty
+
+	mac_dirty=$(strings "$part" | tr -d ' \t' | sed -n 's/^'"$key"'=//p' | head -n 1)
+
+	# "canonicalize" mac
+	[ -n "$mac_dirty" ] && macaddr_canonicalize "$mac_dirty"
+}
+
+mtd_get_mac_ascii() {
+	local mtdname="$1"
+	local key="$2"
+	local part
+
+	part=$(find_mtd_part "$mtdname")
+	if [ -z "$part" ]; then
+		echo "mtd_get_mac_ascii: partition $mtdname not found!" >&2
+		return
+	fi
+
+	get_mac_ascii "$part" "$key"
+}
+
+mtd_get_mac_encrypted_arcadyan() {
+	local iv="00000000000000000000000000000000"
+	local key="2A4B303D7644395C3B2B7053553C5200"
+	local mac_dirty
+	local mtdname="$1"
+	local part
+	local size
+
+	part=$(find_mtd_part "$mtdname")
+	if [ -z "$part" ]; then
+		echo "mtd_get_mac_encrypted_arcadyan: partition $mtdname not found!" >&2
+		return
+	fi
+
+	# Config decryption and getting mac. Trying uencrypt and openssl utils.
+	size=$((0x$(dd if=$part skip=9 bs=1 count=4 2>/dev/null | hexdump -v -e '1/4 "%08x"')))
+	if [[ -f  "/usr/bin/uencrypt" ]]; then
+		mac_dirty=$(dd if=$part bs=1 count=$size skip=$((0x100)) 2>/dev/null | \
+			uencrypt -d -n -k $key -i $iv | grep mac | cut -c 5-)
+	elif [[ -f  "/usr/bin/openssl" ]]; then
+		mac_dirty=$(dd if=$part bs=1 count=$size skip=$((0x100)) 2>/dev/null | \
+			openssl aes-128-cbc -d -nopad -K $key -iv $iv | grep mac | cut -c 5-)
+	else
+		echo "mtd_get_mac_encrypted_arcadyan: Neither uencrypt nor openssl was found!" >&2
+		return
+	fi
+
+	# "canonicalize" mac
+	[ -n "$mac_dirty" ] && macaddr_canonicalize "$mac_dirty"
+}
+
+mtd_get_mac_encrypted_deco() {
+	local mtdname="$1"
+
+	if ! [ -e "$mtdname" ]; then
+		echo "mtd_get_mac_encrypted_deco: file $mtdname not found!" >&2
+		return
+	fi
+
+	tplink_key="3336303032384339"
+
+	key=$(dd if=$mtdname bs=1 skip=16 count=8 2>/dev/null | \
+		uencrypt -n -d -k $tplink_key -c des-ecb | hexdump -v -n 8 -e '1/1 "%02x"')
+
+	macaddr=$(dd if=$mtdname bs=1 skip=32 count=8 2>/dev/null | \
+		uencrypt -n -d -k $key -c des-ecb | hexdump -v -n 6 -e '5/1 "%02x:" 1/1 "%02x"')
+
+	echo $macaddr
+}
+
+mtd_get_mac_uci_config_ubi() {
+	local volumename="$1"
+
+	. /lib/upgrade/nand.sh
+
+	local ubidev=$(nand_attach_ubi $CI_UBIPART)
+	local part=$(nand_find_volume $ubidev $volumename)
+
+	cat "/dev/$part" | sed -n 's/^\s*option macaddr\s*'"'"'\?\([0-9A-F:]\+\)'"'"'\?/\1/Ip'
+}
+
+mtd_get_mac_text() {
+	local mtdname="$1"
+	local offset=$((${2:-0}))
+	local length="${3:-17}"
+	local part
+
+	part=$(find_mtd_part "$mtdname")
+	if [ -z "$part" ]; then
+		echo "mtd_get_mac_text: partition $mtdname not found!" >&2
+		return
+	fi
+
+	[ $((offset + length)) -le $(mtd_get_part_size "$mtdname") ] || return
+
+	macaddr_canonicalize $(dd bs=1 if="$part" skip="$offset" count="$length" 2>/dev/null)
+}
+
+mtd_get_mac_binary() {
+	local mtdname="$1"
+	local offset="$2"
+	local part
+
+	part=$(find_mtd_part "$mtdname")
+	get_mac_binary "$part" "$offset"
+}
+
+mtd_get_mac_binary_ubi() {
+	local mtdname="$1"
+	local offset="$2"
+
+	. /lib/upgrade/nand.sh
+
+	local ubidev=$(nand_find_ubi $CI_UBIPART)
+	local part=$(nand_find_volume $ubidev $1)
+
+	get_mac_binary "/dev/$part" "$offset"
+}
+
+mtd_get_part_size() {
+	local part_name=$1
+	local first dev size erasesize name
+	while read dev size erasesize name; do
+		name=${name#'"'}; name=${name%'"'}
+		if [ "$name" = "$part_name" ]; then
+			echo $((0x$size))
+			break
+		fi
+	done < /proc/mtd
+}
+
+mmc_get_mac_ascii() {
+	local part_name="$1"
+	local key="$2"
+	local part
+
+	part=$(find_mmc_part "$part_name")
+	if [ -z "$part" ]; then
+		echo "mmc_get_mac_ascii: partition $part_name not found!" >&2
+		return
+	fi
+
+	get_mac_ascii "$part" "$key"
+}
+
+mmc_get_mac_binary() {
+	local part_name="$1"
+	local offset="$2"
+	local part
+
+	part=$(find_mmc_part "$part_name")
+	get_mac_binary "$part" "$offset"
+}
+
+macaddr_add() {
+	local mac=$1
+	local val=$2
+	local oui=${mac%:*:*:*}
+	local nic=${mac#*:*:*:}
+
+	nic=$(printf "%06x" $((0x${nic//:/} + val & 0xffffff)) | sed 's/^\(.\{2\}\)\(.\{2\}\)\(.\{2\}\)/\1:\2:\3/')
+	echo $oui:$nic
+}
+
+macaddr_generate_from_mmc_cid() {
+	local mmc_dev=$1
+
+	local sd_hash=$(sha256sum /sys/class/block/$mmc_dev/device/cid)
+	local mac_base=$(macaddr_canonicalize "$(echo "${sd_hash}" | dd bs=1 count=12 2>/dev/null)")
+	echo "$(macaddr_unsetbit_mc "$(macaddr_setbit_la "${mac_base}")")"
+}
+
+macaddr_geteui() {
+	local mac=$1
+	local sep=$2
+
+	echo ${mac:9:2}$sep${mac:12:2}$sep${mac:15:2}
+}
+
+macaddr_setbit() {
+	local mac=$1
+	local bit=${2:-0}
+
+	[ $bit -gt 0 -a $bit -le 48 ] || return
+
+	printf "%012x" $(( 0x${mac//:/} | 2**(48-bit) )) | sed -e 's/\(.\{2\}\)/\1:/g' -e 's/:$//'
+}
+
+macaddr_unsetbit() {
+	local mac=$1
+	local bit=${2:-0}
+
+	[ $bit -gt 0 -a $bit -le 48 ] || return
+
+	printf "%012x" $(( 0x${mac//:/} & ~(2**(48-bit)) )) | sed -e 's/\(.\{2\}\)/\1:/g' -e 's/:$//'
+}
+
+macaddr_setbit_la() {
+	macaddr_setbit $1 7
+}
+
+macaddr_unsetbit_mc() {
+	local mac=$1
+
+	printf "%02x:%s" $((0x${mac%%:*} & ~0x01)) ${mac#*:}
+}
+
+macaddr_random() {
+	local randsrc=$(get_mac_binary /dev/urandom 0)
+	
+	echo "$(macaddr_unsetbit_mc "$(macaddr_setbit_la "${randsrc}")")"
+}
+
+macaddr_canonicalize() {
+	local mac="$1"
+	local canon=""
+
+	mac=$(echo -n $mac | tr -d \")
+	[ ${#mac} -gt 17 ] && return
+	[ -n "${mac//[a-fA-F0-9\.: -]/}" ] && return
+
+	for octet in ${mac//[\.:-]/ }; do
+		case "${#octet}" in
+		1)
+			octet="0${octet}"
+			;;
+		2)
+			;;
+		4)
+			octet="${octet:0:2} ${octet:2:2}"
+			;;
+		12)
+			octet="${octet:0:2} ${octet:2:2} ${octet:4:2} ${octet:6:2} ${octet:8:2} ${octet:10:2}"
+			;;
+		*)
+			return
+			;;
+		esac
+		canon=${canon}${canon:+ }${octet}
+	done
+
+	[ ${#canon} -ne 17 ] && return
+
+	printf "%02x:%02x:%02x:%02x:%02x:%02x" 0x${canon// / 0x} 2>/dev/null
+}
+
+dt_is_enabled() {
+	grep -q okay "/proc/device-tree/$1/status"
+}
diff --git a/package/base-files/files/lib/functions/uci-defaults.sh b/package/base-files/files/lib/functions/uci-defaults.sh
new file mode 100644
index 0000000..5293ce1
--- /dev/null
+++ b/package/base-files/files/lib/functions/uci-defaults.sh
@@ -0,0 +1,791 @@
+. /lib/functions.sh
+. /usr/share/libubox/jshn.sh
+
+json_select_array() {
+	local _json_no_warning=1
+
+	json_select "$1"
+	[ $? = 0 ] && return
+
+	json_add_array "$1"
+	json_close_array
+
+	json_select "$1"
+}
+
+json_select_object() {
+	local _json_no_warning=1
+
+	json_select "$1"
+	[ $? = 0 ] && return
+
+	json_add_object "$1"
+	json_close_object
+
+	json_select "$1"
+}
+
+ucidef_set_interface() {
+	local network=$1; shift
+
+	[ -z "$network" ] && return
+
+	json_select_object network
+	json_select_object "$network"
+
+	while [ -n "$1" ]; do
+		local opt=$1; shift
+		local val=$1; shift
+
+		[ -n "$opt" -a -n "$val" ] || break
+
+		[ "$opt" = "device" -a "$val" != "${val/ //}" ] && {
+			json_select_array "ports"
+			for e in $val; do json_add_string "" "$e"; done
+			json_close_array
+		} || {
+			json_add_string "$opt" "$val"
+		}
+	done
+
+	if ! json_is_a protocol string; then
+		case "$network" in
+			lan) json_add_string protocol static ;;
+			wan) json_add_string protocol dhcp ;;
+			*) json_add_string protocol none ;;
+		esac
+	fi
+
+	json_select ..
+	json_select ..
+}
+
+ucidef_set_board_id() {
+	json_select_object model
+	json_add_string id "$1"
+	json_select ..
+}
+
+ucidef_set_model_name() {
+	json_select_object model
+	json_add_string name "$1"
+	json_select ..
+}
+
+ucidef_set_compat_version() {
+	json_select_object system
+	json_add_string compat_version "${1:-1.0}"
+	json_select ..
+}
+
+ucidef_set_interface_lan() {
+	ucidef_set_interface "lan" device "$1" protocol "${2:-static}"
+}
+
+ucidef_set_interface_wan() {
+	ucidef_set_interface "wan" device "$1" protocol "${2:-dhcp}"
+}
+
+ucidef_set_interfaces_lan_wan() {
+	local lan_if="$1"
+	local wan_if="$2"
+
+	ucidef_set_interface_lan "$lan_if"
+	ucidef_set_interface_wan "$wan_if"
+}
+
+ucidef_set_bridge_device() {
+	json_select_object bridge
+	json_add_string name "${1:-switch0}"
+	json_select ..
+}
+
+ucidef_set_bridge_mac() {
+	json_select_object bridge
+	json_add_string macaddr "${1}"
+	json_select ..
+}
+
+_ucidef_set_network_device_common() {
+	json_select_object "network_device"
+	json_select_object "${1}"
+	json_add_string "${2}" "${3}"
+	json_select ..
+	json_select ..
+}
+
+ucidef_set_network_device_mac() {
+	_ucidef_set_network_device_common $1 macaddr $2
+}
+
+ucidef_set_network_device_path() {
+	_ucidef_set_network_device_common $1 path $2
+}
+
+ucidef_set_network_device_path_port() {
+	_ucidef_set_network_device_common $1 path $2
+	_ucidef_set_network_device_common $1 port $3
+}
+
+ucidef_set_network_device_gro() {
+	_ucidef_set_network_device_common $1 gro $2
+}
+
+ucidef_set_network_device_conduit() {
+	_ucidef_set_network_device_common $1 conduit $2
+}
+
+_ucidef_add_switch_port() {
+	# inherited: $num $device $need_tag $want_untag $role $index $prev_role
+	# inherited: $n_cpu $n_ports $n_vlan $cpu0 $cpu1 $cpu2 $cpu3 $cpu4 $cpu5
+
+	n_ports=$((n_ports + 1))
+
+	json_select_array ports
+		json_add_object
+			json_add_int num "$num"
+			[ -n "$device"     ] && json_add_string  device     "$device"
+			[ -n "$need_tag"   ] && json_add_boolean need_tag   "$need_tag"
+			[ -n "$want_untag" ] && json_add_boolean want_untag "$want_untag"
+			[ -n "$role"       ] && json_add_string  role       "$role"
+			[ -n "$index"      ] && json_add_int     index      "$index"
+		json_close_object
+	json_select ..
+
+	# record pointer to cpu entry for lookup in _ucidef_finish_switch_roles()
+	[ -n "$device" ] && {
+		export "cpu$n_cpu=$n_ports"
+		n_cpu=$((n_cpu + 1))
+	}
+
+	# create/append object to role list
+	[ -n "$role" ] && {
+		json_select_array roles
+
+		if [ "$role" != "$prev_role" ]; then
+			json_add_object
+				json_add_string role "$role"
+				json_add_string ports "$num"
+			json_close_object
+
+			prev_role="$role"
+			n_vlan=$((n_vlan + 1))
+		else
+			json_select_object "$n_vlan"
+				json_get_var port ports
+				json_add_string ports "$port $num"
+			json_select ..
+		fi
+
+		json_select ..
+	}
+}
+
+_ucidef_finish_switch_roles() {
+	# inherited: $name $n_cpu $n_vlan $cpu0 $cpu1 $cpu2 $cpu3 $cpu4 $cpu5
+	local index role roles num device need_tag want_untag port ports
+
+	json_select switch
+		json_select "$name"
+			json_get_keys roles roles
+		json_select ..
+	json_select ..
+
+	for index in $roles; do
+		eval "port=\$cpu$(((index - 1) % n_cpu))"
+
+		json_select switch
+			json_select "$name"
+				json_select ports
+					json_select "$port"
+						json_get_vars num device need_tag want_untag
+					json_select ..
+				json_select ..
+
+				if [ ${need_tag:-0} -eq 1 -o ${want_untag:-0} -ne 1 ]; then
+					num="${num}t"
+					device="${device}.${index}"
+				fi
+
+				json_select roles
+					json_select "$index"
+						json_get_vars role ports
+						json_add_string ports "$ports $num"
+						json_add_string device "$device"
+					json_select ..
+				json_select ..
+			json_select ..
+		json_select ..
+
+		json_select_object network
+			local devices
+
+			json_select_object "$role"
+				# attach previous interfaces (for multi-switch devices)
+				json_get_var devices device
+				if ! list_contains devices "$device"; then
+					devices="${devices:+$devices }$device"
+				fi
+			json_select ..
+		json_select ..
+
+		ucidef_set_interface "$role" device "$devices"
+	done
+}
+
+ucidef_set_ar8xxx_switch_mib() {
+	local name="$1"
+	local type="$2"
+	local interval="$3"
+
+	json_select_object switch
+		json_select_object "$name"
+			json_add_int ar8xxx_mib_type $type
+			json_add_int ar8xxx_mib_poll_interval $interval
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_switch() {
+	local name="$1"; shift
+	local port num role device index need_tag prev_role
+	local cpu0 cpu1 cpu2 cpu3 cpu4 cpu5
+	local n_cpu=0 n_vlan=0 n_ports=0
+
+	json_select_object switch
+		json_select_object "$name"
+			json_add_boolean enable 1
+			json_add_boolean reset 1
+
+			for port in "$@"; do
+				case "$port" in
+					[0-9]*@*)
+						num="${port%%@*}"
+						device="${port##*@}"
+						need_tag=0
+						want_untag=0
+						[ "${num%t}" != "$num" ] && {
+							num="${num%t}"
+							need_tag=1
+						}
+						[ "${num%u}" != "$num" ] && {
+							num="${num%u}"
+							want_untag=1
+						}
+					;;
+					[0-9]*:*:[0-9]*)
+						num="${port%%:*}"
+						index="${port##*:}"
+						role="${port#[0-9]*:}"; role="${role%:*}"
+					;;
+					[0-9]*:*)
+						num="${port%%:*}"
+						role="${port##*:}"
+					;;
+				esac
+
+				if [ -n "$num" ] && [ -n "$device$role" ]; then
+					_ucidef_add_switch_port
+				fi
+
+				unset num device role index need_tag want_untag
+			done
+		json_select ..
+	json_select ..
+
+	_ucidef_finish_switch_roles
+}
+
+ucidef_add_switch_attr() {
+	local name="$1"
+	local key="$2"
+	local val="$3"
+
+	json_select_object switch
+		json_select_object "$name"
+
+		case "$val" in
+			true|false) [ "$val" != "true" ]; json_add_boolean "$key" $? ;;
+			[0-9]) json_add_int "$key" "$val" ;;
+			*) json_add_string "$key" "$val" ;;
+		esac
+
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_switch_port_attr() {
+	local name="$1"
+	local port="$2"
+	local key="$3"
+	local val="$4"
+	local ports i num
+
+	json_select_object switch
+	json_select_object "$name"
+
+	json_get_keys ports ports
+	json_select_array ports
+
+	for i in $ports; do
+		json_select "$i"
+		json_get_var num num
+
+		if [ -n "$num" ] && [ $num -eq $port ]; then
+			json_select_object attr
+
+			case "$val" in
+				true|false) [ "$val" != "true" ]; json_add_boolean "$key" $? ;;
+				[0-9]) json_add_int "$key" "$val" ;;
+				*) json_add_string "$key" "$val" ;;
+			esac
+
+			json_select ..
+		fi
+
+		json_select ..
+	done
+
+	json_select ..
+	json_select ..
+	json_select ..
+}
+
+ucidef_set_interface_macaddr() {
+	local network="$1"
+	local macaddr="$2"
+
+	ucidef_set_interface "$network" macaddr "$macaddr"
+}
+
+ucidef_set_label_macaddr() {
+	local macaddr="$1"
+
+	json_select_object system
+		json_add_string label_macaddr "$macaddr"
+	json_select ..
+}
+
+ucidef_add_atm_bridge() {
+	local vpi="$1"
+	local vci="$2"
+	local encaps="$3"
+	local payload="$4"
+	local nameprefix="$5"
+
+	json_select_object dsl
+		json_select_object atmbridge
+			json_add_int vpi "$vpi"
+			json_add_int vci "$vci"
+			json_add_string encaps "$encaps"
+			json_add_string payload "$payload"
+			json_add_string nameprefix "$nameprefix"
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_adsl_modem() {
+	local annex="$1"
+	local firmware="$2"
+
+	json_select_object dsl
+		json_select_object modem
+			json_add_string type "adsl"
+			json_add_string annex "$annex"
+			json_add_string firmware "$firmware"
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_vdsl_modem() {
+	local annex="$1"
+	local tone="$2"
+	local xfer_mode="$3"
+
+	json_select_object dsl
+		json_select_object modem
+			json_add_string type "vdsl"
+			json_add_string annex "$annex"
+			json_add_string tone "$tone"
+			json_add_string xfer_mode "$xfer_mode"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_led_ataport() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" ata"$4"
+}
+
+_ucidef_set_led_common() {
+	local cfg="led_$1"
+	local name="$2"
+	local sysfs="$3"
+
+	json_select_object led
+
+	json_select_object "$1"
+	json_add_string name "$name"
+	json_add_string sysfs "$sysfs"
+}
+
+ucidef_set_led_default() {
+	local default="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string default "$default"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_heartbeat() {
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger heartbeat
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_gpio() {
+	local gpio="$4"
+	local inverted="$5"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger "$trigger"
+	json_add_string type gpio
+	json_add_int gpio "$gpio"
+	json_add_boolean inverted "$inverted"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_ide() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" disk-activity
+}
+
+ucidef_set_led_netdev() {
+	local dev="$4"
+	local mode="${5:-link tx rx}"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type netdev
+	json_add_string device "$dev"
+	json_add_string mode "$mode"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_oneshot() {
+	_ucidef_set_led_timer $1 $2 $3 "oneshot" $4 $5
+}
+
+ucidef_set_led_portstate() {
+	local port_state="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger port_state
+	json_add_string type portstate
+	json_add_string port_state "$port_state"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_rssi() {
+	local iface="$4"
+	local minq="$5"
+	local maxq="$6"
+	local offset="${7:-0}"
+	local factor="${8:-1}"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type rssi
+	json_add_string name "$name"
+	json_add_string iface "$iface"
+	json_add_string minq "$minq"
+	json_add_string maxq "$maxq"
+	json_add_string offset "$offset"
+	json_add_string factor "$factor"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_switch() {
+	local trigger_name="$4"
+	local port_mask="$5"
+	local speed_mask="$6"
+	local mode="$7"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger "$trigger_name"
+	json_add_string type switch
+	json_add_string mode "$mode"
+	json_add_string port_mask "$port_mask"
+	json_add_string speed_mask "$speed_mask"
+	json_select ..
+
+	json_select ..
+}
+
+_ucidef_set_led_timer() {
+	local trigger_name="$4"
+	local delayon="$5"
+	local delayoff="$6"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type "$trigger_name"
+	json_add_string trigger "$trigger_name"
+	json_add_int delayon "$delayon"
+	json_add_int delayoff "$delayoff"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_timer() {
+	_ucidef_set_led_timer $1 $2 $3 "timer" $4 $5
+}
+
+_ucidef_set_led_trigger() {
+	local trigger_name="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger "$trigger_name"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_usbdev() {
+	local dev="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type usb
+	json_add_string device "$dev"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_usbhost() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" usb-host
+}
+
+ucidef_set_led_usbport() {
+	local obj="$1"
+	local name="$2"
+	local sysfs="$3"
+	shift
+	shift
+	shift
+
+	_ucidef_set_led_common "$obj" "$name" "$sysfs"
+
+	json_add_string type usbport
+	json_select_array ports
+		for port in "$@"; do
+			json_add_string port "$port"
+		done
+	json_select ..
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_wlan() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" "$4"
+}
+
+ucidef_set_rssimon() {
+	local dev="$1"
+	local refresh="$2"
+	local threshold="$3"
+
+	json_select_object rssimon
+
+	json_select_object "$dev"
+	[ -n "$refresh" ] && json_add_int refresh "$refresh"
+	[ -n "$threshold" ] && json_add_int threshold "$threshold"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_add_gpio_switch() {
+	local cfg="$1"
+	local name="$2"
+	local pin="$3"
+	local default="${4:-0}"
+
+	json_select_object gpioswitch
+		json_select_object "$cfg"
+			json_add_string name "$name"
+			json_add_string pin "$pin"
+			json_add_int default "$default"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_hostname() {
+	local hostname="$1"
+
+	json_select_object system
+		json_add_string hostname "$hostname"
+	json_select ..
+}
+
+ucidef_set_timezone() {
+	local timezone="$1"
+	json_select_object system
+		json_add_string timezone "$timezone"
+	json_select ..
+}
+
+ucidef_set_wireless() {
+	local band="$1"
+	local ssid="$2"
+	local encryption="$3"
+	local key="$4"
+
+	case "$band" in
+	all|2g|5g|6g) ;;
+	*) return;;
+	esac
+	[ -z "$ssid" ] && return
+
+	json_select_object wlan
+		json_select_object defaults
+			json_select_object ssids
+				json_select_object "$band"
+					json_add_string ssid "$ssid"
+					[ -n "$encryption" ] && json_add_string encryption "$encryption"
+					[ -n "$key" ] && json_add_string key "$key"
+				json_select ..
+			json_select ..
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_country() {
+	local country="$1"
+
+	json_select_object wlan
+		json_select_object defaults
+			json_add_string country "$country"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_wireless_mac_count() {
+	local band="$1"
+	local mac_count="$2"
+
+	case "$band" in
+	2g|5g|6g) ;;
+	*) return;;
+	esac
+	[ -z "$mac_count" ] && return
+
+	json_select_object wlan
+		json_select_object defaults
+			json_select_object ssids
+				json_select_object "$band"
+					json_add_string mac_count "$mac_count"
+				json_select ..
+			json_select ..
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_root_password_plain() {
+	local passwd="$1"
+	json_select_object credentials
+		json_add_string root_password_plain "$passwd"
+	json_select ..
+}
+
+ucidef_set_root_password_hash() {
+	local passwd="$1"
+	json_select_object credentials
+		json_add_string root_password_hash "$passwd"
+	json_select ..
+}
+
+ucidef_set_ssh_authorized_key() {
+	local ssh_key="$1"
+	json_select_object credentials
+		json_select_array ssh_authorized_keys
+			json_add_string "" "$ssh_key"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_ntpserver() {
+	local server
+
+	json_select_object system
+		json_select_array ntpserver
+			for server in "$@"; do
+				json_add_string "" "$server"
+			done
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_poe() {
+	json_select_object poe
+		json_add_string "budget" "$1"
+		json_select_array ports
+			for port in $2; do
+				json_add_string "" "$port"
+			done
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_wlan() {
+	local path="$1"; shift
+
+	ucidef_wlan_idx=${ucidef_wlan_idx:-0}
+
+	json_select_object wlan
+	json_select_object "wl$ucidef_wlan_idx"
+	json_add_string path "$path"
+	json_add_fields "$@"
+	json_select ..
+	json_select ..
+
+	ucidef_wlan_idx="$((ucidef_wlan_idx + 1))"
+}
+
+board_config_update() {
+	json_init
+	[ -f ${CFG} ] && json_load "$(cat ${CFG})"
+
+	# auto-initialize model id and name if applicable
+	if ! json_is_a model object; then
+		json_select_object model
+			[ -f "/tmp/sysinfo/board_name" ] && \
+				json_add_string id "$(cat /tmp/sysinfo/board_name)"
+			[ -f "/tmp/sysinfo/model" ] && \
+				json_add_string name "$(cat /tmp/sysinfo/model)"
+		json_select ..
+	fi
+}
+
+board_config_flush() {
+	json_dump -i -o ${CFG}
+}
diff --git a/package/base-files/files/lib/preinit/02_default_set_state b/package/base-files/files/lib/preinit/02_default_set_state
new file mode 100644
index 0000000..28d5f1d
--- /dev/null
+++ b/package/base-files/files/lib/preinit/02_default_set_state
@@ -0,0 +1,5 @@
+define_default_set_state() {
+	. /etc/diag.sh
+}
+
+boot_hook_add preinit_main define_default_set_state
diff --git a/package/base-files/files/lib/preinit/02_sysinfo b/package/base-files/files/lib/preinit/02_sysinfo
new file mode 100644
index 0000000..65b5096
--- /dev/null
+++ b/package/base-files/files/lib/preinit/02_sysinfo
@@ -0,0 +1,10 @@
+do_sysinfo_generic() {
+	[ -d /proc/device-tree ] || return
+	mkdir -p /tmp/sysinfo
+	[ -e /tmp/sysinfo/board_name ] || \
+		echo "$(strings /proc/device-tree/compatible | head -1)" > /tmp/sysinfo/board_name
+	[ ! -e /tmp/sysinfo/model -a -e /proc/device-tree/model ] && \
+		echo "$(cat /proc/device-tree/model)" > /tmp/sysinfo/model
+}
+
+boot_hook_add preinit_main do_sysinfo_generic
diff --git a/package/base-files/files/lib/preinit/10_indicate_failsafe b/package/base-files/files/lib/preinit/10_indicate_failsafe
new file mode 100644
index 0000000..8c950bf
--- /dev/null
+++ b/package/base-files/files/lib/preinit/10_indicate_failsafe
@@ -0,0 +1,22 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+# commands for emitting messages to network in failsafe mode
+
+indicate_failsafe_led () {
+	set_state failsafe
+}
+
+indicate_failsafe() {
+	[ "$pi_preinit_no_failsafe" = "y" ] && return
+	local consoles="$(cat /sys/class/tty/console/active)"
+	[ -n "$consoles" ] || consoles=console
+	for console in $consoles; do
+		[ -c "/dev/$console" ] && echo "- failsafe -" >"/dev/$console"
+	done
+	preinit_net_echo "Entering Failsafe!\n"
+	indicate_failsafe_led
+	echo OpenWrt-failsafe > /proc/sys/kernel/hostname
+}
+
+boot_hook_add failsafe indicate_failsafe
diff --git a/package/base-files/files/lib/preinit/10_indicate_preinit b/package/base-files/files/lib/preinit/10_indicate_preinit
new file mode 100644
index 0000000..12f8fc2
--- /dev/null
+++ b/package/base-files/files/lib/preinit/10_indicate_preinit
@@ -0,0 +1,223 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+preinit_ip_config() {
+	local netdev vid
+
+	netdev=${1%\.*}
+	vid=${1#*\.}
+
+	if [ "$vid" = "$netdev" ]; then
+		vid=
+	fi
+
+	grep -q "$netdev" /proc/net/dev || return
+
+	if [ -n "$vid" ]; then
+		ip link add link $netdev name $1 type vlan id $vid
+	fi
+
+	ip link set dev $netdev up
+	if [ -n "$vid" ]; then
+		ip link set dev $1 up
+	fi
+	ip -4 address add $pi_ip/$pi_netmask broadcast $pi_broadcast dev $1
+}
+
+preinit_config_switch() {
+	local role roles ports device enable reset
+
+	local name=$1
+	local lan_if=$2
+
+	json_select switch
+	json_select $name
+
+	json_get_vars enable reset
+
+	if [ "$reset" -eq "1" ]; then
+		swconfig dev $name set reset
+	fi
+	swconfig dev $name set enable_vlan $enable
+
+	if json_is_a roles array; then
+		json_get_keys roles roles
+		json_select roles
+
+		for role in $roles; do
+			json_select "$role"
+			json_get_vars ports device
+			json_select ..
+
+			if [ "$device" = "$lan_if" ]; then
+				swconfig dev $name vlan $role set ports "$ports"
+			fi
+		done
+
+		json_select ..
+	fi
+
+	swconfig dev $name set apply
+
+	json_select ..
+	json_select ..
+}
+
+preinit_config_port() {
+	local original
+	local dev_port
+
+	local netdev="$1"
+	local path="$2"
+	local port="$3"
+
+	[ -d "/sys/devices/$path/net" ] || return
+
+	if [ -z "$port" ]; then
+		original="$(ls "/sys/devices/$path/net" | head -1)"
+	else
+		for device in /sys/devices/$path/net/*; do
+			dev_port="$(cat "$device/dev_port")"
+			if [ "$dev_port" = "$port" ]; then
+				original="${device##*/}"
+				break
+			fi
+		done
+
+		[ -z "$original" ] && return
+	fi
+
+	[ "$netdev" = "$original" ] && return
+
+	ip link set "$original" name "$netdev"
+}
+
+preinit_config_board() {
+	/bin/board_detect /tmp/board.json
+
+	[ -f "/tmp/board.json" ] || return
+
+	. /usr/share/libubox/jshn.sh
+
+	json_init
+	json_load "$(cat /tmp/board.json)"
+
+	# Find the current highest eth*
+	max_eth=$(grep -o '^ *eth[0-9]*:' /proc/net/dev | tr -dc '[0-9]\n' | sort -n | tail -1)
+	# Find and move netdevs using eth*s we are configuring
+	json_get_keys keys "network_device"
+	for netdev in $keys; do
+		json_select "network_device"
+			json_select "$netdev"
+				json_get_vars path path
+				if [ -n "$path" -a -h "/sys/class/net/$netdev" ]; then
+					ip link set "$netdev" down
+					ip link set "$netdev" name eth$((++max_eth))
+				fi
+			json_select ..
+		json_select ..
+	done
+
+	# Move interfaces by path to their netdev name
+	json_get_keys keys "network_device"
+	for netdev in $keys; do
+		json_select "network_device"
+			json_select "$netdev"
+				json_get_vars path path
+				json_get_vars port port
+				[ -n "$path" ] && preinit_config_port "$netdev" "$path" "$port"
+			json_select ..
+		json_select ..
+	done
+
+	json_select network
+		json_select "lan"
+			json_get_vars device
+			json_get_values ports ports
+		json_select ..
+	json_select ..
+
+	[ -n "$device" -o -n "$ports" ] || return
+
+	# swconfig uses $device and DSA uses ports
+	[ -z "$ports" ] && {
+		ports="$device"
+	}
+
+	# only use the first one
+	ifname=${ports%% *}
+
+	if [ -x /sbin/swconfig ]; then
+		# configure the switch, if present
+
+		json_get_keys keys switch
+		for key in $keys; do
+			preinit_config_switch $key $ifname
+		done
+	else
+		# trim any vlan ids
+		ifname=${ifname%\.*}
+		# trim any vlan modifiers like :t
+		ifname=${ifname%\:*}
+	fi
+
+	pi_ifname=$ifname
+
+	preinit_ip_config $pi_ifname
+}
+
+preinit_ip() {
+	[ "$pi_preinit_no_failsafe" = "y" ] && return
+
+	# if the preinit interface isn't specified and ifname is set in
+	# preinit.arch use that interface
+	if [ -z "$pi_ifname" ]; then
+		pi_ifname=$ifname
+	fi
+
+	if [ -n "$pi_ifname" ]; then
+		preinit_ip_config $pi_ifname
+	elif [ -d "/etc/board.d/" ]; then
+		preinit_config_board
+	fi
+
+	preinit_net_echo "Doing OpenWrt Preinit\n"
+}
+
+preinit_ip_deconfig() {
+	[ -n "$pi_ifname" ] && grep -q "$pi_ifname" /proc/net/dev && {
+		local netdev vid
+
+		netdev=${pi_ifname%\.*}
+		vid=${pi_ifname#*\.}
+
+		if [ "$vid" = "$netdev" ]; then
+			vid=
+		fi
+
+		ip -4 address flush dev $pi_ifname
+		ip link set dev $netdev down
+
+		if [ -n "$vid" ]; then
+			ip link delete $pi_ifname
+		fi
+	}
+}
+
+preinit_net_echo() {
+	[ -n "$pi_ifname" ] && grep -q "$pi_ifname" /proc/net/dev && {
+		{
+			[ "$pi_preinit_net_messages" = "y" ] || {
+				[ "$pi_failsafe_net_message" = "true" ] &&
+					[ "$pi_preinit_no_failsafe_netmsg" != "y" ]
+			}
+		} && netmsg $pi_broadcast "$1"
+	}
+}
+
+pi_indicate_preinit() {
+	set_state preinit
+}
+
+boot_hook_add preinit_main preinit_ip
+boot_hook_add preinit_main pi_indicate_preinit
diff --git a/package/base-files/files/lib/preinit/30_failsafe_wait b/package/base-files/files/lib/preinit/30_failsafe_wait
new file mode 100644
index 0000000..d4ab122
--- /dev/null
+++ b/package/base-files/files/lib/preinit/30_failsafe_wait
@@ -0,0 +1,106 @@
+# Copyright (C) 2006-2010 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+fs_wait_for_key () {
+	local timeout=$3
+	local timer
+	local do_keypress
+	local keypress_true="$(mktemp)"
+	local keypress_wait="$(mktemp)"
+	local keypress_sec="$(mktemp)"
+	if [ -z "$keypress_wait" ]; then
+		keypress_wait=/tmp/.keypress_wait
+		touch $keypress_wait
+	fi
+	if [ -z "$keypress_true" ]; then
+		keypress_true=/tmp/.keypress_true
+		touch $keypress_true
+	fi
+	if [ -z "$keypress_sec" ]; then
+		keypress_sec=/tmp/.keypress_sec
+		touch $keypress_sec
+	fi
+
+	trap "echo 'true' >$keypress_true; lock -u $keypress_wait ; rm -f $keypress_wait" INT
+	trap "echo 'true' >$keypress_true; lock -u $keypress_wait ; rm -f $keypress_wait" USR1
+
+	[ -n "$timeout" ] || timeout=1
+	[ $timeout -ge 1 ] || timeout=1
+	timer=$timeout
+	lock $keypress_wait
+	{
+		while [ $timer -gt 0 ]; do
+			pi_failsafe_net_message=true \
+				preinit_net_echo "Please press button now to enter failsafe"
+			echo "$timer" >$keypress_sec
+			timer=$(($timer - 1))
+			sleep 1
+		done
+		lock -u $keypress_wait
+		rm -f $keypress_wait
+	} &
+
+	local consoles="$(cat /sys/class/tty/console/active)"
+	[ -n "$consoles" ] || consoles=console
+	for console in $consoles; do
+		[ -c "/dev/$console" ] || continue
+		[ "$pi_preinit_no_failsafe" != "y" ] && echo "Press the [$1] key and hit [enter] $2" > "/dev/$console"
+		echo "Press the [1], [2], [3] or [4] key and hit [enter] to select the debug level" > "/dev/$console"
+		{
+			while [ -r $keypress_wait ]; do
+				timer="$(cat $keypress_sec)"
+
+				[ -n "$timer" ] || timer=1
+				timer="${timer%%\ *}"
+#				[ $timer -ge 1 ] || timer=1
+				timer=0
+				do_keypress=""
+				{
+					read -t "$timer" do_keypress < "/dev/$console"
+					case "$do_keypress" in
+					$1)
+						echo "true" >$keypress_true
+						;;
+					1 | 2 | 3 | 4)
+						echo "$do_keypress" >/tmp/debug_level
+						;;
+					*)
+						continue;
+						;;
+					esac
+					lock -u $keypress_wait
+					rm -f $keypress_wait
+				}
+			done
+		} &
+	done
+	lock -w $keypress_wait
+
+	keypressed=1
+	[ "$(cat $keypress_true)" = "true" ] && keypressed=0
+
+	trap - INT
+	trap - USR1
+
+	rm -f $keypress_true
+	rm -f $keypress_wait
+	rm -f $keypress_sec
+
+	return $keypressed
+}
+
+failsafe_wait() {
+	FAILSAFE=
+	[ "$pi_preinit_no_failsafe" = "y" ] && {
+		fs_wait_for_key "" "" $fs_failsafe_wait_timeout
+		return
+	}
+	grep -q 'failsafe=' /proc/cmdline && FAILSAFE=true && export FAILSAFE
+	if [ "$FAILSAFE" != "true" ]; then
+		fs_wait_for_key f 'to enter failsafe mode' $fs_failsafe_wait_timeout && FAILSAFE=true
+		[ -f "/tmp/failsafe_button" ] && FAILSAFE=true && echo "- failsafe button "$(cat /tmp/failsafe_button)" was pressed -"
+		[ "$FAILSAFE" = "true" ] && export FAILSAFE && touch /tmp/failsafe
+	fi
+}
+
+boot_hook_add preinit_main failsafe_wait
diff --git a/package/base-files/files/lib/preinit/40_run_failsafe_hook b/package/base-files/files/lib/preinit/40_run_failsafe_hook
new file mode 100644
index 0000000..e3f769a
--- /dev/null
+++ b/package/base-files/files/lib/preinit/40_run_failsafe_hook
@@ -0,0 +1,16 @@
+# Copyright (C) 2006-2010 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+run_failsafe_hook() {
+    [ "$pi_preinit_no_failsafe" = "y" ] && return
+    if [ "$FAILSAFE" = "true" ]; then
+	lock /tmp/.failsafe
+	boot_run_hook failsafe
+	while [ ! -e /tmp/sysupgrade ]; do
+	    lock -w /tmp/.failsafe
+	done
+	exit
+    fi
+}
+
+boot_hook_add preinit_main run_failsafe_hook
diff --git a/package/base-files/files/lib/preinit/50_indicate_regular_preinit b/package/base-files/files/lib/preinit/50_indicate_regular_preinit
new file mode 100644
index 0000000..f4afcdd
--- /dev/null
+++ b/package/base-files/files/lib/preinit/50_indicate_regular_preinit
@@ -0,0 +1,9 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+indicate_regular_preinit() {
+	preinit_net_echo "Continuing with Regular Preinit\n"
+	set_state preinit_regular
+}
+
+boot_hook_add preinit_main indicate_regular_preinit
diff --git a/package/base-files/files/lib/preinit/70_initramfs_test b/package/base-files/files/lib/preinit/70_initramfs_test
new file mode 100644
index 0000000..c5aae98
--- /dev/null
+++ b/package/base-files/files/lib/preinit/70_initramfs_test
@@ -0,0 +1,12 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+initramfs_test() {
+	if [ -n "$INITRAMFS" ]; then
+		boot_run_hook initramfs
+		preinit_ip_deconfig
+		break
+	fi
+}
+
+boot_hook_add preinit_main initramfs_test
diff --git a/package/base-files/files/lib/preinit/80_mount_root b/package/base-files/files/lib/preinit/80_mount_root
new file mode 100644
index 0000000..dd79b27
--- /dev/null
+++ b/package/base-files/files/lib/preinit/80_mount_root
@@ -0,0 +1,54 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+missing_lines() {
+	local file1 file2 line
+	file1="$1"
+	file2="$2"
+	oIFS="$IFS"
+	IFS=":"
+	while read line; do
+		set -- $line
+		grep -q "^$1:" "$file2" || echo "$line"
+	done < "$file1"
+	IFS="$oIFS"
+}
+
+# Rootfs mount options can be passed by declaring in the kernel
+# cmdline as much options as needed prefixed with "rootfs_mount_options."
+#
+# Example:
+# rootfs_mount_options.compress_algorithm=zstd rootfs_mount_options.noinline_data
+#
+compose_rootfs_mount_options() {
+	local mount_options
+	local cmdlinevar
+
+	for cmdlinevar in $(cat /proc/cmdline); do
+		if [ "$cmdlinevar" != "${cmdlinevar#rootfs_mount_options\.}" ]; then
+			append mount_options "${cmdlinevar#rootfs_mount_options\.}"
+		fi
+	done
+
+	echo $mount_options
+}
+
+do_mount_root() {
+	#mount_root start "$(compose_rootfs_mount_options)"
+	boot_run_hook preinit_mount_root
+	[ -f /sysupgrade.tgz -o -f /tmp/sysupgrade.tar ] && {
+		echo "- config restore -"
+		cp /etc/passwd /etc/group /etc/shadow /tmp
+		cd /
+		[ -f /sysupgrade.tgz ] && tar xzf /sysupgrade.tgz
+		[ -f /tmp/sysupgrade.tar ] && tar xf /tmp/sysupgrade.tar
+		missing_lines /tmp/passwd /etc/passwd >> /etc/passwd
+		missing_lines /tmp/group /etc/group >> /etc/group
+		missing_lines /tmp/shadow /etc/shadow >> /etc/shadow
+		rm /tmp/passwd /tmp/group /tmp/shadow
+		# Prevent configuration corruption on a power loss
+		sync
+	}
+}
+
+[ "$INITRAMFS" = "1" ] || boot_hook_add preinit_main do_mount_root
diff --git a/package/base-files/files/lib/preinit/99_10_failsafe_login b/package/base-files/files/lib/preinit/99_10_failsafe_login
new file mode 100644
index 0000000..f72a35e
--- /dev/null
+++ b/package/base-files/files/lib/preinit/99_10_failsafe_login
@@ -0,0 +1,23 @@
+# Copyright (C) 2006-2015 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+failsafe_shell() {
+	local consoles="$(cat /sys/class/tty/console/active)"
+	[ -n "$consoles" ] || consoles=console
+	for console in $consoles; do
+		case "$console" in
+			console|tty[0-9]*)
+				term=${TERM:-linux}
+				;;
+			*)
+				term=vt102
+				;;
+		esac
+		# Running asynchronously via the shell's & would ignore SIGINT,
+		# breaking ^C. Use start-stop-daemon instead.
+		[ -c "/dev/$console" ] && start-stop-daemon -Sb -p /dev/null -- env -i ash -c "while true; do setsid -c env -i USER=root LOGNAME=root SHELL=/bin/ash TERM="$term" ash --login <\"/dev/$console\" >\"/dev/$console\" 2>\"/dev/$console\"; sleep 1; done"
+	done
+
+}
+
+boot_hook_add failsafe failsafe_shell
diff --git a/package/base-files/files/lib/preinit/99_10_run_init b/package/base-files/files/lib/preinit/99_10_run_init
new file mode 100644
index 0000000..ebf77b0
--- /dev/null
+++ b/package/base-files/files/lib/preinit/99_10_run_init
@@ -0,0 +1,8 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+run_init() {
+	preinit_ip_deconfig
+}
+
+boot_hook_add preinit_main run_init
diff --git a/package/base-files/files/lib/upgrade/common.sh b/package/base-files/files/lib/upgrade/common.sh
new file mode 100644
index 0000000..af1182c
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/common.sh
@@ -0,0 +1,317 @@
+RAM_ROOT=/tmp/root
+
+export BACKUP_FILE=sysupgrade.tgz	# file extracted by preinit
+
+[ -x /usr/bin/ldd ] || ldd() { LD_TRACE_LOADED_OBJECTS=1 $*; }
+libs() { ldd $* 2>/dev/null | sed -E 's/(.* => )?(.*) .*/\2/'; }
+
+install_file() { # <file> [ <file> ... ]
+	local target dest dir
+	for file in "$@"; do
+		if [ -L "$file" ]; then
+			target="$(readlink -f "$file")"
+			dest="$RAM_ROOT/$file"
+			[ ! -f "$dest" ] && {
+				dir="$(dirname "$dest")"
+				mkdir -p "$dir"
+				ln -s "$target" "$dest"
+			}
+			file="$target"
+		fi
+		dest="$RAM_ROOT/$file"
+		[ -f "$file" -a ! -f "$dest" ] && {
+			dir="$(dirname "$dest")"
+			mkdir -p "$dir"
+			cp "$file" "$dest"
+		}
+	done
+}
+
+install_bin() {
+	local src files
+	src=$1
+	files=$1
+	[ -x "$src" ] && files="$src $(libs $src)"
+	install_file $files
+}
+
+run_hooks() {
+	local arg="$1"; shift
+	for func in "$@"; do
+		eval "$func $arg"
+	done
+}
+
+ask_bool() {
+	local default="$1"; shift;
+	local answer="$default"
+
+	[ "$INTERACTIVE" -eq 1 ] && {
+		case "$default" in
+			0) echo -n "$* (y/N): ";;
+			*) echo -n "$* (Y/n): ";;
+		esac
+		read answer
+		case "$answer" in
+			y*) answer=1;;
+			n*) answer=0;;
+			*) answer="$default";;
+		esac
+	}
+	[ "$answer" -gt 0 ]
+}
+
+_v() {
+	[ -n "$VERBOSE" ] && [ "$VERBOSE" -ge 1 ] && echo "$*" >&2
+}
+
+v() {
+	_v "$(date) upgrade: $@"
+	logger -p info -t upgrade "$@"
+}
+
+json_string() {
+	local v="$1"
+	v="${v//\\/\\\\}"
+	v="${v//\"/\\\"}"
+	echo "\"$v\""
+}
+
+rootfs_type() {
+	/bin/mount | awk '($3 ~ /^\/$/) && ($5 !~ /rootfs/) { print $5 }'
+}
+
+get_image() { # <source> [ <command> ]
+	local from="$1"
+	local cmd="$2"
+
+	if [ -z "$cmd" ]; then
+		local magic="$(dd if="$from" bs=2 count=1 2>/dev/null | hexdump -n 2 -e '1/1 "%02x"')"
+		case "$magic" in
+			1f8b) cmd="busybox zcat";;
+			*) cmd="cat";;
+		esac
+	fi
+
+	$cmd <"$from"
+}
+
+get_image_dd() {
+	local from="$1"; shift
+
+	(
+		exec 3>&2
+		( exec 3>&2; get_image "$from" 2>&1 1>&3 | grep -v -F ' Broken pipe'     ) 2>&1 1>&3 \
+			| ( exec 3>&2; dd "$@" 2>&1 1>&3 | grep -v -E ' records (in|out)') 2>&1 1>&3
+		exec 3>&-
+	)
+}
+
+get_magic_word() {
+	(get_image "$@" | dd bs=2 count=1 | hexdump -v -n 2 -e '1/1 "%02x"') 2>/dev/null
+}
+
+get_magic_long() {
+	(get_image "$@" | dd bs=4 count=1 | hexdump -v -n 4 -e '1/1 "%02x"') 2>/dev/null
+}
+
+get_magic_gpt() {
+	(get_image "$@" | dd bs=8 count=1 skip=64) 2>/dev/null
+}
+
+get_magic_vfat() {
+	(get_image "$@" | dd bs=3 count=1 skip=18) 2>/dev/null
+}
+
+get_magic_fat32() {
+	(get_image "$@" | dd bs=1 count=5 skip=82) 2>/dev/null
+}
+
+identify_magic_long() {
+	local magic=$1
+	case "$magic" in
+		"55424923")
+			echo "ubi"
+			;;
+		"31181006")
+			echo "ubifs"
+			;;
+		"68737173")
+			echo "squashfs"
+			;;
+		"d00dfeed")
+			echo "fit"
+			;;
+		"4349"*)
+			echo "combined"
+			;;
+		"1f8b"*)
+			echo "gzip"
+			;;
+		*)
+			echo "unknown $magic"
+			;;
+	esac
+}
+
+part_magic_efi() {
+	local magic=$(get_magic_gpt "$@")
+	[ "$magic" = "EFI PART" ]
+}
+
+part_magic_fat() {
+	local magic=$(get_magic_vfat "$@")
+	local magic_fat32=$(get_magic_fat32 "$@")
+	[ "$magic" = "FAT" ] || [ "$magic_fat32" = "FAT32" ]
+}
+
+export_bootdevice() {
+	local cmdline uuid blockdev uevent line class
+	local MAJOR MINOR DEVNAME DEVTYPE
+	local rootpart="$(cmdline_get_var root)"
+
+	case "$rootpart" in
+		PARTUUID=[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9]-[a-f0-9][a-f0-9])
+			uuid="${rootpart#PARTUUID=}"
+			uuid="${uuid%-[a-f0-9][a-f0-9]}"
+			for blockdev in $(find /dev -type b); do
+				set -- $(dd if=$blockdev bs=1 skip=440 count=4 2>/dev/null | hexdump -v -e '4/1 "%02x "')
+				if [ "$4$3$2$1" = "$uuid" ]; then
+					uevent="/sys/class/block/${blockdev##*/}/uevent"
+					break
+				fi
+			done
+		;;
+		PARTUUID=????????-????-????-????-??????????0?/PARTNROFF=1 | \
+		PARTUUID=????????-????-????-????-??????????02)
+			uuid="${rootpart#PARTUUID=}"
+			uuid="${uuid%/PARTNROFF=1}"
+			uuid="${uuid%0?}00"
+			for disk in $(find /dev -type b); do
+				set -- $(dd if=$disk bs=1 skip=568 count=16 2>/dev/null | hexdump -v -e '8/1 "%02x "" "2/1 "%02x""-"6/1 "%02x"')
+				if [ "$4$3$2$1-$6$5-$8$7-$9" = "$uuid" ]; then
+					uevent="/sys/class/block/${disk##*/}/uevent"
+					break
+				fi
+			done
+		;;
+		/dev/*)
+			uevent="/sys/class/block/${rootpart##*/}/../uevent"
+		;;
+		0x[a-f0-9][a-f0-9][a-f0-9] | 0x[a-f0-9][a-f0-9][a-f0-9][a-f0-9] | \
+		[a-f0-9][a-f0-9][a-f0-9] | [a-f0-9][a-f0-9][a-f0-9][a-f0-9])
+			rootpart=0x${rootpart#0x}
+			for class in /sys/class/block/*; do
+				while read line; do
+					export -n "$line"
+				done < "$class/uevent"
+				if [ $((rootpart/256)) = $MAJOR -a $((rootpart%256)) = $MINOR ]; then
+					uevent="$class/../uevent"
+				fi
+			done
+		;;
+	esac
+
+	if [ -e "$uevent" ]; then
+		while read line; do
+			export -n "$line"
+		done < "$uevent"
+		export BOOTDEV_MAJOR=$MAJOR
+		export BOOTDEV_MINOR=$MINOR
+		return 0
+	fi
+
+	return 1
+}
+
+export_partdevice() {
+	local var="$1" offset="$2"
+	local uevent line MAJOR MINOR DEVNAME DEVTYPE
+
+	for uevent in /sys/class/block/*/uevent; do
+		while read line; do
+			export -n "$line"
+		done < "$uevent"
+		if [ "$BOOTDEV_MAJOR" = "$MAJOR" -a $(($BOOTDEV_MINOR + $offset)) = "$MINOR" -a -b "/dev/$DEVNAME" ]; then
+			export "$var=$DEVNAME"
+			return 0
+		fi
+	done
+
+	return 1
+}
+
+hex_le32_to_cpu() {
+	[ "$(echo 01 | hexdump -v -n 2 -e '/2 "%x"')" = "3031" ] && {
+		echo "${1:0:2}${1:8:2}${1:6:2}${1:4:2}${1:2:2}"
+		return
+	}
+	echo "$@"
+}
+
+get_partitions() { # <device> <filename>
+	local disk="$1"
+	local filename="$2"
+
+	if [ -b "$disk" -o -f "$disk" ]; then
+		v "Reading partition table from $filename..."
+
+		local magic=$(dd if="$disk" bs=2 count=1 skip=255 2>/dev/null)
+		if [ "$magic" != $'\x55\xAA' ]; then
+			v "Invalid partition table on $disk"
+			exit
+		fi
+
+		rm -f "/tmp/partmap.$filename"
+
+		local part
+		part_magic_efi "$disk" && {
+			#export_partdevice will fail when partition number is greater than 15, as
+			#the partition major device number is not equal to the disk major device number
+			for part in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
+				set -- $(hexdump -v -n 48 -s "$((0x380 + $part * 0x80))" -e '4/4 "%08x"" "4/4 "%08x"" "4/4 "0x%08X "' "$disk")
+
+				local type="$1"
+				local lba="$(( $(hex_le32_to_cpu $4) * 0x100000000 + $(hex_le32_to_cpu $3) ))"
+				local end="$(( $(hex_le32_to_cpu $6) * 0x100000000 + $(hex_le32_to_cpu $5) ))"
+				local num="$(( $end - $lba + 1 ))"
+
+				[ "$type" = "00000000000000000000000000000000" ] && continue
+
+				printf "%2d %5d %7d\n" $part $lba $num >> "/tmp/partmap.$filename"
+			done
+		} || {
+			for part in 1 2 3 4; do
+				set -- $(hexdump -v -n 12 -s "$((0x1B2 + $part * 16))" -e '3/4 "0x%08X "' "$disk")
+
+				local type="$(( $(hex_le32_to_cpu $1) % 256))"
+				local lba="$(( $(hex_le32_to_cpu $2) ))"
+				local num="$(( $(hex_le32_to_cpu $3) ))"
+
+				[ $type -gt 0 ] || continue
+
+				printf "%2d %5d %7d\n" $part $lba $num >> "/tmp/partmap.$filename"
+			done
+		}
+	fi
+}
+
+indicate_upgrade() {
+	. /etc/diag.sh
+	set_state upgrade
+}
+
+# Flash firmware to MTD partition
+#
+# $(1): path to image
+# $(2): (optional) pipe command to extract firmware, e.g. dd bs=n skip=m
+default_do_upgrade() {
+	sync
+	echo 3 > /proc/sys/vm/drop_caches
+	if [ -n "$UPGRADE_BACKUP" ]; then
+		get_image "$1" "$2" | mtd $MTD_ARGS $MTD_CONFIG_ARGS -j "$UPGRADE_BACKUP" write - "${PART_NAME:-image}"
+	else
+		get_image "$1" "$2" | mtd $MTD_ARGS write - "${PART_NAME:-image}"
+	fi
+	[ $? -ne 0 ] && exit 1
+}
diff --git a/package/base-files/files/lib/upgrade/do_stage2 b/package/base-files/files/lib/upgrade/do_stage2
new file mode 100755
index 0000000..0e32445
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/do_stage2
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+. /lib/functions.sh
+
+include /lib/upgrade
+
+v "Performing system upgrade..."
+if type 'platform_do_upgrade' >/dev/null 2>/dev/null; then
+	platform_do_upgrade "$IMAGE"
+else
+	default_do_upgrade "$IMAGE"
+fi
+
+if [ -n "$UPGRADE_BACKUP" ] && type 'platform_copy_config' >/dev/null 2>/dev/null; then
+	platform_copy_config
+fi
+
+v "Upgrade completed"
+sleep 1
+
+v "Rebooting system..."
+umount -a
+reboot -f
+sleep 5
+echo b 2>/dev/null >/proc/sysrq-trigger
diff --git a/package/base-files/files/lib/upgrade/emmc.sh b/package/base-files/files/lib/upgrade/emmc.sh
new file mode 100644
index 0000000..78e398d
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/emmc.sh
@@ -0,0 +1,74 @@
+# Copyright (C) 2021 OpenWrt.org
+#
+
+. /lib/functions.sh
+
+emmc_upgrade_tar() {
+	local tar_file="$1"
+	[ "$CI_KERNPART" -a -z "$EMMC_KERN_DEV" ] && export EMMC_KERN_DEV="$(find_mmc_part $CI_KERNPART $CI_ROOTDEV)"
+	[ "$CI_ROOTPART" -a -z "$EMMC_ROOT_DEV" ] && export EMMC_ROOT_DEV="$(find_mmc_part $CI_ROOTPART $CI_ROOTDEV)"
+	[ "$CI_DATAPART" -a -z "$EMMC_DATA_DEV" ] && export EMMC_DATA_DEV="$(find_mmc_part $CI_DATAPART $CI_ROOTDEV)"
+	local has_kernel
+	local has_rootfs
+	local board_dir=$(tar tf "$tar_file" | grep -m 1 '^sysupgrade-.*/$')
+	board_dir=${board_dir%/}
+
+	tar tf "$tar_file" ${board_dir}/kernel 1>/dev/null 2>/dev/null && has_kernel=1
+	tar tf "$tar_file" ${board_dir}/root 1>/dev/null 2>/dev/null && has_rootfs=1
+
+	[ "$has_rootfs" = 1 -a "$EMMC_ROOT_DEV" ] && {
+		# Invalidate kernel image while rootfs is being written
+		[ "$has_kernel" = 1 -a "$EMMC_KERN_DEV" ] && {
+			dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 count=8
+			sync
+		}
+
+		export EMMC_ROOTFS_BLOCKS=$(($(tar xf "$tar_file" ${board_dir}/root -O | dd of="$EMMC_ROOT_DEV" bs=512 2>&1 | grep "records out" | cut -d' ' -f1)))
+		# Account for 64KiB ROOTDEV_OVERLAY_ALIGN in libfstools
+		EMMC_ROOTFS_BLOCKS=$(((EMMC_ROOTFS_BLOCKS + 127) & ~127))
+		sync
+	}
+
+	[ "$has_kernel" = 1 -a "$EMMC_KERN_DEV" ] &&
+		export EMMC_KERNEL_BLOCKS=$(($(tar xf "$tar_file" ${board_dir}/kernel -O | dd of="$EMMC_KERN_DEV" bs=512 2>&1 | grep "records out" | cut -d' ' -f1)))
+
+	if [ -z "$UPGRADE_BACKUP" ]; then
+		if [ "$EMMC_DATA_DEV" ]; then
+			dd if=/dev/zero of="$EMMC_DATA_DEV" bs=512 count=8
+		elif [ "$EMMC_ROOTFS_BLOCKS" ]; then
+			dd if=/dev/zero of="$EMMC_ROOT_DEV" bs=512 seek=$EMMC_ROOTFS_BLOCKS count=8
+		elif [ "$EMMC_KERNEL_BLOCKS" ]; then
+			dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS count=8
+		fi
+	fi
+}
+
+emmc_upgrade_fit() {
+	local fit_file="$1"
+	[ "$CI_KERNPART" -a -z "$EMMC_KERN_DEV" ] && export EMMC_KERN_DEV="$(find_mmc_part $CI_KERNPART $CI_ROOTDEV)"
+
+	if [ "$EMMC_KERN_DEV" ]; then
+		export EMMC_KERNEL_BLOCKS=$(($(get_image "$fit_file" | fwtool -i /dev/null -T - | dd of="$EMMC_KERN_DEV" bs=512 2>&1 | grep "records out" | cut -d' ' -f1)))
+
+		[ -z "$UPGRADE_BACKUP" ] && dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS count=8
+	fi
+}
+
+emmc_copy_config() {
+	if [ "$EMMC_DATA_DEV" ]; then
+		dd if="$UPGRADE_BACKUP" of="$EMMC_DATA_DEV" bs=512
+	elif [ "$EMMC_ROOTFS_BLOCKS" ]; then
+		dd if="$UPGRADE_BACKUP" of="$EMMC_ROOT_DEV" bs=512 seek=$EMMC_ROOTFS_BLOCKS
+	elif [ "$EMMC_KERNEL_BLOCKS" ]; then
+		dd if="$UPGRADE_BACKUP" of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS
+	fi
+}
+
+emmc_do_upgrade() {
+	local file_type=$(identify_magic_long "$(get_magic_long "$1")")
+
+	case "$file_type" in
+		"fit")  emmc_upgrade_fit $1;;
+		*)      emmc_upgrade_tar $1;;
+	esac
+}
diff --git a/package/base-files/files/lib/upgrade/fwtool.sh b/package/base-files/files/lib/upgrade/fwtool.sh
new file mode 100644
index 0000000..8bd00a3
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/fwtool.sh
@@ -0,0 +1,93 @@
+fwtool_check_signature() {
+	[ $# -gt 1 ] && return 1
+
+	[ ! -x /usr/bin/ucert ] && {
+		if [ "$REQUIRE_IMAGE_SIGNATURE" = 1 ]; then
+			return 1
+		else
+			return 0
+		fi
+	}
+
+	if ! fwtool -q -s /tmp/sysupgrade.ucert "$1"; then
+		v "Image signature not present"
+		[ "$REQUIRE_IMAGE_SIGNATURE" = 1 -a "$FORCE" != 1 ] && {
+			v "Use sysupgrade -F to override this check when downgrading or flashing to vendor firmware"
+		}
+		[ "$REQUIRE_IMAGE_SIGNATURE" = 1 ] && return 1
+		return 0
+	fi
+
+	fwtool -q -T -s /dev/null "$1" | \
+		ucert -V -m - -c "/tmp/sysupgrade.ucert" -P /etc/opkg/keys
+
+	return $?
+}
+
+fwtool_check_image() {
+	[ $# -gt 1 ] && return 1
+
+	. /usr/share/libubox/jshn.sh
+
+	if ! fwtool -q -i /tmp/sysupgrade.meta "$1"; then
+		v "Image metadata not present"
+		[ "$REQUIRE_IMAGE_METADATA" = 1 -a "$FORCE" != 1 ] && {
+			v "Use sysupgrade -F to override this check when downgrading or flashing to vendor firmware"
+		}
+		[ "$REQUIRE_IMAGE_METADATA" = 1 ] && return 1
+		return 0
+	fi
+
+	json_load "$(cat /tmp/sysupgrade.meta)" || {
+		v "Invalid image metadata"
+		return 1
+	}
+
+	device="$(cat /tmp/sysinfo/board_name)"
+	devicecompat="$(uci -q get system.@system[0].compat_version)"
+	[ -n "$devicecompat" ] || devicecompat="1.0"
+
+	json_get_var imagecompat compat_version
+	json_get_var compatmessage compat_message
+	[ -n "$imagecompat" ] || imagecompat="1.0"
+
+	# select correct supported list based on compat_version
+	# (using this ensures that compatibility check works for devices
+	#  not knowing about compat-version)
+	local supported=supported_devices
+	[ "$imagecompat" != "1.0" ] && supported=new_supported_devices
+	json_select $supported || return 1
+
+	json_get_keys dev_keys
+	for k in $dev_keys; do
+		json_get_var dev "$k"
+		if [ "$dev" = "$device" ]; then
+			# major compat version -> no sysupgrade
+			if [ "${devicecompat%.*}" != "${imagecompat%.*}" ]; then
+				v "The device is supported, but this image is incompatible for sysupgrade based on the image version ($devicecompat->$imagecompat)."
+				[ -n "$compatmessage" ] && v "$compatmessage"
+				return 1
+			fi
+
+			# minor compat version -> sysupgrade with -n required
+			if [ "${devicecompat#.*}" != "${imagecompat#.*}" ] && [ "$SAVE_CONFIG" = "1" ]; then
+				[ "$IGNORE_MINOR_COMPAT" = 1 ] && return 0
+				v "The device is supported, but the config is incompatible to the new image ($devicecompat->$imagecompat). Please upgrade without keeping config (sysupgrade -n)."
+				[ -n "$compatmessage" ] && v "$compatmessage"
+				return 1
+			fi
+
+			return 0
+		fi
+	done
+
+	v "Device $device not supported by this image"
+	local devices="Supported devices:"
+	for k in $dev_keys; do
+		json_get_var dev "$k"
+		devices="$devices $dev"
+	done
+	v "$devices"
+
+	return 1
+}
diff --git a/package/base-files/files/lib/upgrade/keep.d/base-files-essential b/package/base-files/files/lib/upgrade/keep.d/base-files-essential
new file mode 100644
index 0000000..7a7a253
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/keep.d/base-files-essential
@@ -0,0 +1,11 @@
+# Essential files that will be always kept
+/etc/hosts
+/etc/inittab
+/etc/group
+/etc/passwd
+/etc/profile
+/etc/shadow
+/etc/shells
+/etc/shinit
+/etc/sysctl.conf
+/etc/rc.local
diff --git a/package/base-files/files/lib/upgrade/legacy-sdcard.sh b/package/base-files/files/lib/upgrade/legacy-sdcard.sh
new file mode 100644
index 0000000..d2ae53b
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/legacy-sdcard.sh
@@ -0,0 +1,91 @@
+legacy_sdcard_check_image() {
+	local file="$1"
+	local diskdev partdev diff
+
+	export_bootdevice && export_partdevice diskdev 0 || {
+		v "Unable to determine upgrade device"
+	return 1
+	}
+
+	get_partitions "/dev/$diskdev" bootdisk
+
+	v "Extract boot sector from the image"
+	get_image_dd "$1" of=/tmp/image.bs count=1 bs=512b
+
+	get_partitions /tmp/image.bs image
+
+	#compare tables
+	diff="$(grep -F -x -v -f /tmp/partmap.bootdisk /tmp/partmap.image)"
+
+	rm -f /tmp/image.bs /tmp/partmap.bootdisk /tmp/partmap.image
+
+	if [ -n "$diff" ]; then
+		v "Partition layout has changed. Full image will be written."
+		ask_bool 0 "Abort" && exit 1
+		return 0
+	fi
+}
+
+legacy_sdcard_do_upgrade() {
+	local board=$(board_name)
+	local diskdev partdev diff
+
+	export_bootdevice && export_partdevice diskdev 0 || {
+		v "Unable to determine upgrade device"
+	return 1
+	}
+
+	sync
+
+	if [ "$UPGRADE_OPT_SAVE_PARTITIONS" = "1" ]; then
+		get_partitions "/dev/$diskdev" bootdisk
+
+		v "Extract boot sector from the image"
+		get_image_dd "$1" of=/tmp/image.bs count=1 bs=512b
+
+		get_partitions /tmp/image.bs image
+
+		#compare tables
+		diff="$(grep -F -x -v -f /tmp/partmap.bootdisk /tmp/partmap.image)"
+	else
+		diff=1
+	fi
+
+	if [ -n "$diff" ]; then
+		get_image_dd "$1" of="/dev/$diskdev" bs=4096 conv=fsync
+
+		# Separate removal and addtion is necessary; otherwise, partition 1
+		# will be missing if it overlaps with the old partition 2
+		partx -d - "/dev/$diskdev"
+		partx -a - "/dev/$diskdev"
+	else
+		v "Writing bootloader to /dev/$diskdev"
+		get_image_dd "$1" of="$diskdev" bs=512 skip=1 seek=1 count=2048 conv=fsync
+		#iterate over each partition from the image and write it to the boot disk
+		while read part start size; do
+			if export_partdevice partdev $part; then
+				v "Writing image to /dev/$partdev..."
+				get_image_dd "$1" of="/dev/$partdev" ibs="512" obs=1M skip="$start" count="$size" conv=fsync
+			else
+				v "Unable to find partition $part device, skipped."
+			fi
+		done < /tmp/partmap.image
+
+		v "Writing new UUID to /dev/$diskdev..."
+		get_image_dd "$1" of="/dev/$diskdev" bs=1 skip=440 count=4 seek=440 conv=fsync
+	fi
+
+	sleep 1
+}
+
+legacy_sdcard_copy_config() {
+	local partdev
+
+	if export_partdevice partdev 1; then
+		mkdir -p /boot
+		[ -f /boot/kernel.img ] || mount -o rw,noatime /dev/$partdev /boot
+		cp -af "$UPGRADE_BACKUP" "/boot/$BACKUP_FILE"
+		sync
+		umount /boot
+	fi
+}
diff --git a/package/base-files/files/lib/upgrade/nand.sh b/package/base-files/files/lib/upgrade/nand.sh
new file mode 100644
index 0000000..ca30255
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/nand.sh
@@ -0,0 +1,499 @@
+# Copyright (C) 2014 OpenWrt.org
+#
+
+. /lib/functions.sh
+
+# 'kernel' partition or UBI volume on NAND contains the kernel
+CI_KERNPART="${CI_KERNPART:-kernel}"
+
+# 'ubi' partition on NAND contains UBI
+# There are also CI_KERN_UBIPART and CI_ROOT_UBIPART if kernel
+# and rootfs are on separated UBIs.
+CI_UBIPART="${CI_UBIPART:-ubi}"
+
+# 'rootfs' UBI volume on NAND contains the rootfs
+CI_ROOTPART="${CI_ROOTPART:-rootfs}"
+
+ubi_mknod() {
+	local dir="$1"
+	local dev="/dev/$(basename $dir)"
+
+	[ -e "$dev" ] && return 0
+
+	local devid="$(cat $dir/dev)"
+	local major="${devid%%:*}"
+	local minor="${devid##*:}"
+	mknod "$dev" c $major $minor
+}
+
+nand_find_volume() {
+	local ubidevdir ubivoldir
+	ubidevdir="/sys/class/ubi/"
+	[ ! -d "$ubidevdir" ] && return 1
+	for ubivoldir in $ubidevdir/${1}_*; do
+		[ ! -d "$ubivoldir" ] && continue
+		if [ "$( cat $ubivoldir/name )" = "$2" ]; then
+			basename $ubivoldir
+			ubi_mknod "$ubivoldir"
+			return 0
+		fi
+	done
+}
+
+nand_find_ubi() {
+	local ubidevdir ubidev mtdnum cmtdnum
+	mtdnum="$( find_mtd_index $1 )"
+	[ ! "$mtdnum" ] && return 1
+	for ubidevdir in /sys/class/ubi/ubi*; do
+		[ ! -e "$ubidevdir/mtd_num" ] && continue
+		cmtdnum="$( cat $ubidevdir/mtd_num )"
+		if [ "$mtdnum" = "$cmtdnum" ]; then
+			ubidev=$( basename $ubidevdir )
+			ubi_mknod "$ubidevdir"
+			echo $ubidev
+			return 0
+		fi
+	done
+}
+
+nand_get_magic_long() {
+	($2 < "$1" | dd bs=4 "skip=${3:-0}" count=1 | hexdump -v -n 4 -e '1/1 "%02x"') 2> /dev/null
+}
+
+get_magic_long_tar() {
+	($2 < "$1" | tar xOf - "$3" | dd bs=4 count=1 | hexdump -v -n 4 -e '1/1 "%02x"') 2> /dev/null
+}
+
+identify() {
+	identify_magic_long $(nand_get_magic_long "$@")
+}
+
+identify_tar() {
+	identify_magic_long $(get_magic_long_tar "$@")
+}
+
+identify_if_gzip() {
+	if [ "$(identify "$1" "cat")" = gzip ]; then echo -n z; fi
+}
+
+nand_restore_config() {
+	local ubidev=$( nand_find_ubi "${CI_ROOT_UBIPART:-$CI_UBIPART}" )
+	local ubivol="$( nand_find_volume $ubidev rootfs_data )"
+	if [ ! "$ubivol" ]; then
+		ubivol="$( nand_find_volume $ubidev "$CI_ROOTPART" )"
+		if [ ! "$ubivol" ]; then
+			echo "cannot find ubifs data volume"
+			return 1
+		fi
+	fi
+	mkdir /tmp/new_root
+	if ! mount -t ubifs /dev/$ubivol /tmp/new_root; then
+		echo "cannot mount ubifs volume $ubivol"
+		rmdir /tmp/new_root
+		return 1
+	fi
+	if mv "$1" "/tmp/new_root/$BACKUP_FILE"; then
+		if umount /tmp/new_root; then
+			echo "configuration saved"
+			rmdir /tmp/new_root
+			return 0
+		fi
+	else
+		umount /tmp/new_root
+	fi
+	echo "could not save configuration to ubifs volume $ubivol"
+	rmdir /tmp/new_root
+	return 1
+}
+
+nand_remove_ubiblock() {
+	local ubivol="$1"
+
+	local ubiblk="ubiblock${ubivol:3}"
+	if [ -e "/dev/$ubiblk" ]; then
+		umount "/dev/$ubiblk" 2>/dev/null && echo "unmounted /dev/$ubiblk" || :
+		if ! ubiblock -r "/dev/$ubivol"; then
+			echo "cannot remove $ubiblk"
+			return 1
+		fi
+	fi
+}
+
+nand_attach_ubi() {
+	local ubipart="$1"
+	local has_env="${2:-0}"
+
+	local mtdnum="$( find_mtd_index "$ubipart" )"
+	if [ ! "$mtdnum" ]; then
+		>&2 echo "cannot find ubi mtd partition $ubipart"
+		return 1
+	fi
+
+	local ubidev="$( nand_find_ubi "$ubipart" )"
+	if [ ! "$ubidev" ]; then
+		>&2 ubiattach -m "$mtdnum"
+		ubidev="$( nand_find_ubi "$ubipart" )"
+
+		if [ ! "$ubidev" ]; then
+			>&2 ubiformat /dev/mtd$mtdnum -y
+			>&2 ubiattach -m "$mtdnum"
+			ubidev="$( nand_find_ubi "$ubipart" )"
+
+			if [ ! "$ubidev" ]; then
+				>&2 echo "cannot attach ubi mtd partition $ubipart"
+				return 1
+			fi
+
+			if [ "$has_env" -gt 0 ]; then
+				>&2 ubimkvol /dev/$ubidev -n 0 -N ubootenv -s 1MiB
+				>&2 ubimkvol /dev/$ubidev -n 1 -N ubootenv2 -s 1MiB
+			fi
+		fi
+	fi
+
+	echo "$ubidev"
+	return 0
+}
+
+nand_detach_ubi() {
+	local ubipart="$1"
+
+	local mtdnum="$( find_mtd_index "$ubipart" )"
+	if [ ! "$mtdnum" ]; then
+		echo "cannot find ubi mtd partition $ubipart"
+		return 1
+	fi
+
+	local ubidev="$( nand_find_ubi "$ubipart" )"
+	if [ "$ubidev" ]; then
+		for ubivol in $(find /dev -name "${ubidev}_*" -maxdepth 1 | sort); do
+			ubivol="${ubivol:5}"
+			nand_remove_ubiblock "$ubivol" || :
+			umount "/dev/$ubivol" && echo "unmounted /dev/$ubivol" || :
+		done
+		if ! ubidetach -m "$mtdnum"; then
+			echo "cannot detach ubi mtd partition $ubipart"
+			return 1
+		fi
+	fi
+}
+
+nand_upgrade_prepare_ubi() {
+	local rootfs_length="$1"
+	local rootfs_type="$2"
+	local rootfs_data_max="$(fw_printenv -n rootfs_data_max 2> /dev/null)"
+	[ -n "$rootfs_data_max" ] && rootfs_data_max=$((rootfs_data_max))
+
+	local kernel_length="$3"
+	local has_env="${4:-0}"
+	local kern_ubidev
+	local root_ubidev
+
+	[ -n "$rootfs_length" -o -n "$kernel_length" ] || return 1
+
+	if [ -n "$CI_KERN_UBIPART" -a -n "$CI_ROOT_UBIPART" ]; then
+		kern_ubidev="$( nand_attach_ubi "$CI_KERN_UBIPART" "$has_env" )"
+		[ -n "$kern_ubidev" ] || return 1
+		root_ubidev="$( nand_attach_ubi "$CI_ROOT_UBIPART" )"
+		[ -n "$root_ubidev" ] || return 1
+	else
+		kern_ubidev="$( nand_attach_ubi "$CI_UBIPART" "$has_env" )"
+		[ -n "$kern_ubidev" ] || return 1
+		root_ubidev="$kern_ubidev"
+	fi
+
+	local kern_ubivol="$( nand_find_volume $kern_ubidev "$CI_KERNPART" )"
+	local root_ubivol="$( nand_find_volume $root_ubidev "$CI_ROOTPART" )"
+	local data_ubivol="$( nand_find_volume $root_ubidev rootfs_data )"
+	[ "$root_ubivol" = "$kern_ubivol" ] && root_ubivol=
+
+	# remove ubiblocks
+	[ "$kern_ubivol" ] && { nand_remove_ubiblock $kern_ubivol || return 1; }
+	[ "$root_ubivol" ] && { nand_remove_ubiblock $root_ubivol || return 1; }
+	[ "$data_ubivol" ] && { nand_remove_ubiblock $data_ubivol || return 1; }
+
+	# kill volumes
+	[ "$kern_ubivol" ] && ubirmvol /dev/$kern_ubidev -N "$CI_KERNPART" || :
+	[ "$root_ubivol" ] && ubirmvol /dev/$root_ubidev -N "$CI_ROOTPART" || :
+	[ "$data_ubivol" ] && ubirmvol /dev/$root_ubidev -N rootfs_data || :
+
+	# create kernel vol
+	if [ -n "$kernel_length" ]; then
+		if ! ubimkvol /dev/$kern_ubidev -N "$CI_KERNPART" -s $kernel_length; then
+			echo "cannot create kernel volume"
+			return 1;
+		fi
+	fi
+
+	# create rootfs vol
+	if [ -n "$rootfs_length" ]; then
+		local rootfs_size_param
+		if [ "$rootfs_type" = "ubifs" ]; then
+			rootfs_size_param="-m"
+		else
+			rootfs_size_param="-s $rootfs_length"
+		fi
+		if ! ubimkvol /dev/$root_ubidev -N "$CI_ROOTPART" $rootfs_size_param; then
+			echo "cannot create rootfs volume"
+			return 1;
+		fi
+	fi
+
+	# create rootfs_data vol for non-ubifs rootfs
+	if [ "$rootfs_type" != "ubifs" ]; then
+		local rootfs_data_size_param="-m"
+		if [ -n "$rootfs_data_max" ]; then
+			rootfs_data_size_param="-s $rootfs_data_max"
+		fi
+		if ! ubimkvol /dev/$root_ubidev -N rootfs_data $rootfs_data_size_param; then
+			if ! ubimkvol /dev/$root_ubidev -N rootfs_data -m; then
+				echo "cannot initialize rootfs_data volume"
+				return 1
+			fi
+		fi
+	fi
+
+	return 0
+}
+
+# Write the UBI image to MTD ubi partition
+nand_upgrade_ubinized() {
+	local ubi_file="$1"
+	local cmd="$2"
+
+	local ubi_length=$( ($cmd < "$ubi_file" | wc -c) 2> /dev/null)
+
+	nand_detach_ubi "$CI_UBIPART" || return 1
+
+	local mtdnum="$( find_mtd_index "$CI_UBIPART" )"
+	$cmd < "$ubi_file" | ubiformat "/dev/mtd$mtdnum" -S "$ubi_length" -y -f - && ubiattach -m "$mtdnum"
+}
+
+# Write the UBIFS image to UBI rootfs volume
+nand_upgrade_ubifs() {
+	local ubifs_file="$1"
+	local cmd="$2"
+
+	local ubifs_length=$( ($cmd < "$ubifs_file" | wc -c) 2> /dev/null)
+
+	nand_upgrade_prepare_ubi "$ubifs_length" "ubifs" "" "" || return 1
+
+	local ubidev="$( nand_find_ubi "$CI_UBIPART" )"
+	local root_ubivol="$(nand_find_volume $ubidev "$CI_ROOTPART")"
+	$cmd < "$ubifs_file" | ubiupdatevol /dev/$root_ubivol -s "$ubifs_length" -
+}
+
+# Write the FIT image to UBI kernel volume
+nand_upgrade_fit() {
+	local fit_file="$1"
+	local cmd="$2"
+
+	local fit_length=$( ($cmd < "$fit_file" | wc -c) 2> /dev/null)
+
+	nand_upgrade_prepare_ubi "" "" "$fit_length" "1" || return 1
+
+	local fit_ubidev="$(nand_find_ubi "$CI_UBIPART")"
+	local fit_ubivol="$(nand_find_volume $fit_ubidev "$CI_KERNPART")"
+	$cmd < "$fit_file" | ubiupdatevol /dev/$fit_ubivol -s "$fit_length" -
+}
+
+# Write images in the TAR file to MTD partitions and/or UBI volumes as required
+nand_upgrade_tar() {
+	local tar_file="$1"
+	local cmd="${2:-cat}"
+	local jffs2_markers="${CI_JFFS2_CLEAN_MARKERS:-0}"
+
+	# WARNING: This fails if tar contains more than one 'sysupgrade-*' directory.
+	local board_dir="$($cmd < "$tar_file" | tar tf - | grep -m 1 '^sysupgrade-.*/$')"
+	board_dir="${board_dir%/}"
+
+	local kernel_mtd kernel_length
+	if [ "$CI_KERNPART" != "none" ]; then
+		kernel_mtd="$(find_mtd_index "$CI_KERNPART")"
+		kernel_length=$( ($cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | wc -c) 2> /dev/null)
+		[ "$kernel_length" = 0 ] && kernel_length=
+	fi
+	local rootfs_length=$( ($cmd < "$tar_file" | tar xOf - "$board_dir/root" | wc -c) 2> /dev/null)
+	[ "$rootfs_length" = 0 ] && rootfs_length=
+	local rootfs_type
+	[ "$rootfs_length" ] && rootfs_type="$(identify_tar "$tar_file" "$cmd" "$board_dir/root")"
+
+	local ubi_kernel_length
+	if [ "$kernel_length" ]; then
+		if [ "$kernel_mtd" ]; then
+			# On some devices, the raw kernel and ubi partitions overlap.
+			# These devices brick if the kernel partition is erased.
+			# Hence only invalidate kernel for now.
+			dd if=/dev/zero bs=4096 count=1 2> /dev/null | \
+				mtd write - "$CI_KERNPART"
+		else
+			ubi_kernel_length="$kernel_length"
+		fi
+	fi
+
+	local has_env=0
+	nand_upgrade_prepare_ubi "$rootfs_length" "$rootfs_type" "$ubi_kernel_length" "$has_env" || return 1
+
+	if [ "$rootfs_length" ]; then
+		local ubidev="$( nand_find_ubi "${CI_ROOT_UBIPART:-$CI_UBIPART}" )"
+		local root_ubivol="$( nand_find_volume $ubidev "$CI_ROOTPART" )"
+		$cmd < "$tar_file" | tar xOf - "$board_dir/root" | \
+			ubiupdatevol /dev/$root_ubivol -s "$rootfs_length" -
+	fi
+	if [ "$kernel_length" ]; then
+		if [ "$kernel_mtd" ]; then
+			if [ "$jffs2_markers" = 1 ]; then
+				flash_erase -j "/dev/mtd${kernel_mtd}" 0 0
+				$cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | \
+					nandwrite "/dev/mtd${kernel_mtd}" -
+			else
+				$cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | \
+					mtd write - "$CI_KERNPART"
+			fi
+		else
+			local ubidev="$( nand_find_ubi "${CI_KERN_UBIPART:-$CI_UBIPART}" )"
+			local kern_ubivol="$( nand_find_volume $ubidev "$CI_KERNPART" )"
+			$cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | \
+				ubiupdatevol /dev/$kern_ubivol -s "$kernel_length" -
+		fi
+	fi
+
+	return 0
+}
+
+nand_verify_if_gzip_file() {
+	local file="$1"
+	local cmd="$2"
+
+	if [ "$cmd" = zcat ]; then
+		echo "verifying compressed sysupgrade file integrity"
+		if ! gzip -t "$file"; then
+			echo "corrupted compressed sysupgrade file"
+			return 1
+		fi
+	fi
+}
+
+nand_verify_tar_file() {
+	local file="$1"
+	local cmd="$2"
+
+	echo "verifying sysupgrade tar file integrity"
+	if ! $cmd < "$file" | tar xOf - > /dev/null; then
+		echo "corrupted sysupgrade tar file"
+		return 1
+	fi
+}
+
+nand_do_flash_file() {
+	local file="$1"
+	local cmd="$2"
+	local file_type
+
+	[ -z "$cmd" ] && cmd="$(identify_if_gzip "$file")cat"
+	file_type="$(identify "$file" "$cmd" "")"
+
+	[ ! "$(find_mtd_index "$CI_UBIPART")" ] && CI_UBIPART=rootfs
+
+	case "$file_type" in
+		"fit")
+			nand_verify_if_gzip_file "$file" "$cmd" || return 1
+			nand_upgrade_fit "$file" "$cmd"
+			;;
+		"ubi")
+			nand_verify_if_gzip_file "$file" "$cmd" || return 1
+			nand_upgrade_ubinized "$file" "$cmd"
+			;;
+		"ubifs")
+			nand_verify_if_gzip_file "$file" "$cmd" || return 1
+			nand_upgrade_ubifs "$file" "$cmd"
+			;;
+		*)
+			nand_verify_tar_file "$file" "$cmd" || return 1
+			nand_upgrade_tar "$file" "$cmd"
+			;;
+	esac
+}
+
+nand_do_restore_config() {
+	local conf_tar="/tmp/sysupgrade.tgz"
+	[ ! -f "$conf_tar" ] || nand_restore_config "$conf_tar"
+}
+
+# Recognize type of passed file and start the upgrade process
+#
+# Supported firmware containers:
+# 1. Raw file
+# 2. Gzip
+# 3. Custom (requires passing extracting command)
+#
+# Supported data formats:
+# 1. Tar with kernel/rootfs
+# 2. UBI image (built using "ubinized")
+# 3. UBIFS image (to update UBI volume with)
+# 4. FIT image (to update UBI volume with)
+#
+# $(1): firmware file path
+# $(2): (optional) pipe command to extract firmware
+nand_do_upgrade() {
+	local file="$1"
+	local cmd="$2"
+
+	sync
+	nand_do_flash_file "$file" "$cmd" && nand_do_upgrade_success
+	nand_do_upgrade_failed
+}
+
+nand_do_upgrade_success() {
+	if nand_do_restore_config && sync; then
+		echo "sysupgrade successful"
+		umount -a
+		reboot -f
+	fi
+	nand_do_upgrade_failed
+}
+
+nand_do_upgrade_failed() {
+	sync
+	echo "sysupgrade failed"
+	# Should we reboot or bring up some failsafe mode instead?
+	umount -a
+	reboot -f
+}
+
+# Check if passed file is a valid one for NAND sysupgrade.
+# Currently it accepts 4 types of files:
+# 1) UBI: a ubinized image containing required UBI volumes.
+# 2) UBIFS: a UBIFS rootfs volume image.
+# 3) FIT: a FIT image containing kernel and rootfs.
+# 4) TAR: an archive that includes directory "sysupgrade-${BOARD_NAME}" containing
+#         a non-empty "CONTROL" file and required partition and/or volume images.
+#
+# You usually want to call this function in platform_check_image.
+#
+# $(1): board name, used in case of passing TAR file
+# $(2): file to be checked
+nand_do_platform_check() {
+	local board_name="$1"
+	local file="$2"
+
+	local cmd="$(identify_if_gzip "$file")cat"
+	local file_type="$(identify "$file" "$cmd" "")"
+	local control_length=$( ($cmd < "$file" | tar xOf - "sysupgrade-${board_name//,/_}/CONTROL" | wc -c) 2> /dev/null)
+
+	if [ "$control_length" = 0 ]; then
+		control_length=$( ($cmd < "$file" | tar xOf - "sysupgrade-${board_name//_/,}/CONTROL" | wc -c) 2> /dev/null)
+	fi
+
+	if [ "$control_length" != 0 ]; then
+		nand_verify_tar_file "$file" "$cmd" || return 1
+	else
+		nand_verify_if_gzip_file "$file" "$cmd" || return 1
+		if [ "$file_type" != "fit" -a "$file_type" != "ubi" -a "$file_type" != "ubifs" ]; then
+			echo "invalid sysupgrade file"
+			return 1
+		fi
+	fi
+
+	return 0
+}
diff --git a/package/base-files/files/lib/upgrade/stage2 b/package/base-files/files/lib/upgrade/stage2
new file mode 100755
index 0000000..5ce0b35
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/stage2
@@ -0,0 +1,175 @@
+#!/bin/sh
+
+. /lib/functions.sh
+. /lib/functions/system.sh
+
+export IMAGE="$1"
+COMMAND="$2"
+
+export INTERACTIVE=0
+export VERBOSE=1
+export CONFFILES=/tmp/sysupgrade.conffiles
+
+RAMFS_COPY_BIN=		# extra programs for temporary ramfs root
+RAMFS_COPY_DATA=	# extra data files
+
+include /lib/upgrade
+
+
+supivot() { # <new_root> <old_root>
+	/bin/mount | grep "on $1 type" 2>&- 1>&- || /bin/mount -o bind $1 $1
+	mkdir -p $1$2 $1/proc $1/sys $1/dev $1/tmp $1/overlay && \
+	/bin/mount -o noatime,move /proc $1/proc && \
+	pivot_root $1 $1$2 || {
+		/bin/umount -l $1 $1
+		return 1
+	}
+
+	/bin/mount -o noatime,move $2/sys /sys
+	/bin/mount -o noatime,move $2/dev /dev
+	/bin/mount -o noatime,move $2/tmp /tmp
+	/bin/mount -o noatime,move $2/overlay /overlay 2>&-
+	return 0
+}
+
+switch_to_ramfs() {
+	RAMFS_COPY_LOSETUP="$(command -v /usr/sbin/losetup)"
+	RAMFS_COPY_LVM="$(command -v lvm)"
+
+	for binary in \
+		/bin/busybox /bin/ash /bin/sh /bin/mount /bin/umount	\
+		pivot_root mount_root reboot sync kill sleep		\
+		md5sum hexdump cat zcat dd tar gzip			\
+		ls basename find cp mv rm mkdir rmdir mknod touch chmod \
+		'[' printf wc grep awk sed cut sort tail		\
+		mtd partx losetup mkfs.ext4 nandwrite flash_erase	\
+		ubiupdatevol ubiattach ubiblock ubiformat		\
+		ubidetach ubirsvol ubirmvol ubimkvol			\
+		snapshot snapshot_tool date logger			\
+		/usr/sbin/fw_printenv /usr/bin/fwtool			\
+		$RAMFS_COPY_LOSETUP $RAMFS_COPY_LVM			\
+		$RAMFS_COPY_BIN
+	do
+		local file="$(command -v "$binary" 2>/dev/null)"
+		[ -n "$file" ] && install_bin "$file"
+	done
+	install_file /etc/resolv.conf /lib/*.sh /lib/functions/*.sh	\
+		/lib/upgrade/*.sh /lib/upgrade/do_stage2 		\
+		/usr/share/libubox/jshn.sh /usr/sbin/fw_setenv		\
+		/etc/fw_env.config $RAMFS_COPY_DATA
+
+	mkdir -p $RAM_ROOT/var/lock
+
+	[ -L "/lib64" ] && ln -s /lib $RAM_ROOT/lib64
+
+	supivot $RAM_ROOT /mnt || {
+		v "Failed to switch over to ramfs. Please reboot."
+		exit 1
+	}
+
+	/bin/mount -o remount,ro /mnt
+	/bin/umount -l /mnt
+
+	grep -e "^/dev/dm-.*" -e "^/dev/loop.*" /proc/mounts | while read bdev mp _r; do
+		umount $mp
+	done
+
+	[ "$RAMFS_COPY_LOSETUP" ] && losetup -D
+	[ "$RAMFS_COPY_LVM" ] && {
+		mkdir -p /tmp/lvm/cache
+		$RAMFS_COPY_LVM vgchange -aln --ignorelockingfailure
+	}
+
+	grep /overlay /proc/mounts > /dev/null && {
+		/bin/mount -o noatime,remount,ro /overlay
+		/bin/umount -l /overlay
+	}
+}
+
+kill_remaining() { # [ <signal> [ <loop> ] ]
+	local loop_limit=10
+
+	local sig="${1:-TERM}"
+	local loop="${2:-0}"
+	local run=true
+	local stat
+	local proc_ppid=$(cut -d' ' -f4  /proc/$$/stat)
+
+	v "Sending $sig to remaining processes ..."
+
+	while $run; do
+		run=false
+		for stat in /proc/[0-9]*/stat; do
+			[ -f "$stat" ] || continue
+
+			local pid name state ppid rest
+			read pid rest < $stat
+			name="${rest#\(}" ; rest="${name##*\) }" ; name="${name%\)*}"
+			set -- $rest ; state="$1" ; ppid="$2"
+
+			# Skip PID1, our parent, ourself and our children
+			[ $pid -ne 1 -a $pid -ne $proc_ppid -a $pid -ne $$ -a $ppid -ne $$ ] || continue
+
+			[ -f "/proc/$pid/cmdline" ] || continue
+
+			local cmdline
+			read cmdline < /proc/$pid/cmdline
+
+			# Skip kernel threads
+			[ -n "$cmdline" ] || continue
+
+			v "Sending signal $sig to $name ($pid)"
+			kill -$sig $pid 2>/dev/null
+
+			[ $loop -eq 1 ] && sleep 2 && run=true
+		done
+
+		let loop_limit--
+		[ $loop_limit -eq 0 ] && {
+			v "Failed to kill all processes."
+			exit 1
+		}
+	done
+}
+
+indicate_upgrade
+
+while read -r a b c; do
+	case "$a" in
+		MemT*) mem="$b" ;; esac
+done < /proc/meminfo
+
+[ "$mem" -gt 32768 ] && \
+	skip_services="dnsmasq log network"
+for service in /etc/init.d/*; do
+	service=${service##*/}
+
+	case " $skip_services " in
+		*" $service "*) continue ;; esac
+
+	ubus call service delete '{ "name": "'"$service"'" }' 2>/dev/null
+done
+
+killall -9 telnetd 2>/dev/null
+killall -9 dropbear 2>/dev/null
+killall -9 ash 2>/dev/null
+
+kill_remaining TERM
+sleep 4
+kill_remaining KILL 1
+
+sleep 6
+
+echo 3 > /proc/sys/vm/drop_caches
+
+if [ -n "$IMAGE" ] && type 'platform_pre_upgrade' >/dev/null 2>/dev/null; then
+	platform_pre_upgrade "$IMAGE"
+fi
+
+if [ -n "$(rootfs_type)" ]; then
+	v "Switching to ramdisk..."
+	switch_to_ramfs
+fi
+
+# Exec new shell from ramfs
+exec /bin/busybox ash -c "$COMMAND"
diff --git a/package/base-files/files/lib/upgrade/tar.sh b/package/base-files/files/lib/upgrade/tar.sh
new file mode 100644
index 0000000..a9d1d55
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/tar.sh
@@ -0,0 +1,71 @@
+# SPDX-License-Identifier: GPL-2.0-or-later OR MIT
+
+# Example usage:
+#
+# {
+#         tar_print_member "date.txt" "It's $(date +"%Y")"
+#         tar_print_trailer
+# } > test.tar
+
+__tar_print_padding() {
+	dd if=/dev/zero bs=1 count=$1 2>/dev/null
+}
+
+tar_print_member() {
+	local name="$1"
+	local content="$2"
+	local mtime="${3:-$(date +%s)}"
+	local mode=644
+	local uid=0
+	local gid=0
+	local size=${#content}
+	local type=0
+	local link=""
+	local username="root"
+	local groupname="root"
+
+	# 100 byte of padding bytes, using 0x01 since the shell does not tolerate null bytes in strings
+	local pad=$'\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1'
+
+	# validate name (strip leading slash if present)
+	name=${name#/}
+
+	# truncate string header values to their maximum length
+	name=${name:0:100}
+	link=${link:0:100}
+	username=${username:0:32}
+	groupname=${groupname:0:32}
+
+	# construct header part before checksum field
+	local header1="${name}${pad:0:$((100 - ${#name}))}"
+	header1="${header1}$(printf '%07d\1' $mode)"
+	header1="${header1}$(printf '%07o\1' $uid)"
+	header1="${header1}$(printf '%07o\1' $gid)"
+	header1="${header1}$(printf '%011o\1' $size)"
+	header1="${header1}$(printf '%011o\1' $mtime)"
+
+	# construct header part after checksum field
+	local header2="$(printf '%d' $type)"
+	header2="${header2}${link}${pad:0:$((100 - ${#link}))}"
+	header2="${header2}ustar  ${pad:0:1}"
+	header2="${header2}${username}${pad:0:$((32 - ${#username}))}"
+	header2="${header2}${groupname}${pad:0:$((32 - ${#groupname}))}"
+
+	# calculate checksum over header fields
+	local checksum=0
+	for byte in $(printf '%s%8s%s' "$header1" "" "$header2" | tr '\1' '\0' | hexdump -ve '1/1 "%u "'); do
+		checksum=$((checksum + byte))
+	done
+
+	# print member header, padded to 512 byte
+	printf '%s%06o\0 %s' "$header1" $checksum "$header2" | tr '\1' '\0'
+	__tar_print_padding 183
+
+	# print content data, padded to multiple of 512 byte
+	printf "%s" "$content"
+	__tar_print_padding $((512 - (size % 512)))
+}
+
+tar_print_trailer() {
+	__tar_print_padding 1024
+}