From 073dc450b5ca91cfffd9097f0e3900dd390be399 Mon Sep 17 00:00:00 2001
From: Rodrigo Balerdi <lanchon@gmail.com>
Date: Fri, 15 Apr 2022 00:59:49 -0300
Subject: [PATCH] base-files: safer sysupgrade for kernel-in-UBI devices

Ensure that the kernel CRC is invalidated while rootfs is being updated.
This allows the bootloader to detect an interrupted sysupgrade and fall
back to an alternate booting method, instead of just going ahead with
normal boot and effectively bricking the device.

Possible fallbacks include a recovery initramfs partition or UBI volume
and TFTP. See here for an example U-Boot configuration with fallbacks:
https://shorturl.at/befsA (https://github.com/Lanchon/openwrt-tr4400-v2/
blob/e7d707d6bd7839fbd0b8d0bd180fce451df77e47/install-recovery.sh#L52-L63)

Signed-off-by: Rodrigo Balerdi <lanchon@gmail.com>
---
 package/base-files/files/lib/upgrade/nand.sh | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/package/base-files/files/lib/upgrade/nand.sh b/package/base-files/files/lib/upgrade/nand.sh
index b5c982b272..f927c066da 100644
--- a/package/base-files/files/lib/upgrade/nand.sh
+++ b/package/base-files/files/lib/upgrade/nand.sh
@@ -288,7 +288,7 @@ nand_upgrade_tar() {
 	local board_dir=$(tar tf "$tar_file" | grep -m 1 '^sysupgrade-.*/$')
 	board_dir=${board_dir%/}
 
-	kernel_length=$( (tar xf "$tar_file" ${board_dir}/kernel -O | wc -c) 2> /dev/null)
+	local kernel_length=$( (tar xf "$tar_file" ${board_dir}/kernel -O | wc -c) 2> /dev/null)
 	local has_rootfs=0
 	local rootfs_length
 	local rootfs_type
@@ -311,17 +311,17 @@ nand_upgrade_tar() {
 	nand_upgrade_prepare_ubi "$rootfs_length" "$rootfs_type" "${has_kernel:+$kernel_length}" "$has_env"
 
 	local ubidev="$( nand_find_ubi "$CI_UBIPART" )"
-	[ "$has_kernel" = "1" ] && {
-		local kern_ubivol="$( nand_find_volume $ubidev $CI_KERNPART )"
-		tar xf "$tar_file" ${board_dir}/kernel -O | \
-			ubiupdatevol /dev/$kern_ubivol -s $kernel_length -
-	}
-
 	[ "$has_rootfs" = "1" ] && {
 		local root_ubivol="$( nand_find_volume $ubidev $CI_ROOTPART )"
 		tar xf "$tar_file" ${board_dir}/root -O | \
 			ubiupdatevol /dev/$root_ubivol -s $rootfs_length -
 	}
+
+	[ "$has_kernel" = "1" ] && {
+		local kern_ubivol="$( nand_find_volume $ubidev $CI_KERNPART )"
+		tar xf "$tar_file" ${board_dir}/kernel -O | \
+			ubiupdatevol /dev/$kern_ubivol -s $kernel_length -
+	}
 	nand_do_upgrade_success
 }
 
-- 
2.30.2