base-files: Align rootfs_data upgrades to 64KiB on eMMC
[openwrt/openwrt.git] / package / base-files / files / lib / upgrade / emmc.sh
1 # Copyright (C) 2021 OpenWrt.org
2 #
3
4 . /lib/functions.sh
5
6 emmc_upgrade_tar() {
7 local tar_file="$1"
8 [ "$CI_KERNPART" -a -z "$EMMC_KERN_DEV" ] && export EMMC_KERN_DEV="$(find_mmc_part $CI_KERNPART $CI_ROOTDEV)"
9 [ "$CI_ROOTPART" -a -z "$EMMC_ROOT_DEV" ] && export EMMC_ROOT_DEV="$(find_mmc_part $CI_ROOTPART $CI_ROOTDEV)"
10 [ "$CI_DATAPART" -a -z "$EMMC_DATA_DEV" ] && export EMMC_DATA_DEV="$(find_mmc_part $CI_DATAPART $CI_ROOTDEV)"
11 local has_kernel
12 local has_rootfs
13 local board_dir=$(tar tf "$tar_file" | grep -m 1 '^sysupgrade-.*/$')
14 board_dir=${board_dir%/}
15
16 tar tf "$tar_file" ${board_dir}/kernel 1>/dev/null 2>/dev/null && has_kernel=1
17 tar tf "$tar_file" ${board_dir}/root 1>/dev/null 2>/dev/null && has_rootfs=1
18
19 [ "$has_kernel" = 1 -a "$EMMC_KERN_DEV" ] &&
20 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)))
21
22 [ "$has_rootfs" = 1 -a "$EMMC_ROOT_DEV" ] && {
23 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)))
24 # Account for 64KiB ROOTDEV_OVERLAY_ALIGN in libfstools
25 EMMC_ROOTFS_BLOCKS=$(((EMMC_ROOTFS_BLOCKS + 127) & ~127))
26 }
27
28 if [ -z "$UPGRADE_BACKUP" ]; then
29 if [ "$EMMC_DATA_DEV" ]; then
30 dd if=/dev/zero of="$EMMC_DATA_DEV" bs=512 count=8
31 elif [ "$EMMC_ROOTFS_BLOCKS" ]; then
32 dd if=/dev/zero of="$EMMC_ROOT_DEV" bs=512 seek=$EMMC_ROOTFS_BLOCKS count=8
33 elif [ "$EMMC_KERNEL_BLOCKS" ]; then
34 dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS count=8
35 fi
36 fi
37 }
38
39 emmc_upgrade_fit() {
40 local fit_file="$1"
41 [ "$CI_KERNPART" -a -z "$EMMC_KERN_DEV" ] && export EMMC_KERN_DEV="$(find_mmc_part $CI_KERNPART $CI_ROOTDEV)"
42
43 if [ "$EMMC_KERN_DEV" ]; then
44 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)))
45
46 [ -z "$UPGRADE_BACKUP" ] && dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS count=8
47 fi
48 }
49
50 emmc_copy_config() {
51 if [ "$EMMC_DATA_DEV" ]; then
52 dd if="$UPGRADE_BACKUP" of="$EMMC_DATA_DEV" bs=512
53 elif [ "$EMMC_ROOTFS_BLOCKS" ]; then
54 dd if="$UPGRADE_BACKUP" of="$EMMC_ROOT_DEV" bs=512 seek=$EMMC_ROOTFS_BLOCKS
55 elif [ "$EMMC_KERNEL_BLOCKS" ]; then
56 dd if="$UPGRADE_BACKUP" of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS
57 fi
58 }
59
60 emmc_do_upgrade() {
61 local file_type=$(identify $1)
62
63 case "$file_type" in
64 "fit") emmc_upgrade_fit $1;;
65 *) emmc_upgrade_tar $1;;
66 esac
67 }