ASR_BASE

Change-Id: Icf3719cc0afe3eeb3edc7fa80a2eb5199ca9dda1
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
+}