bcm4908: support "rootfs_data" on U-Boot devices
[openwrt/staging/jow.git] / target / linux / bcm4908 / base-files / lib / functions / bcm4908.sh
1 # SPDX-License-Identifier: GPL-2.0-or-later OR BSD-2-Clause
2
3 FS_STATE_READY=2
4
5 # $(1): file to read from
6 # $(2): offset in bytes
7 get_hex_u32_le() {
8 dd if="$1" skip=$2 bs=1 count=4 2>/dev/null | hexdump -v -e '1/4 "%02x"'
9 }
10
11 # Setup /tmp/env.config to provide "metadata" UBI volume access
12 #
13 # It can be used with "fw_printenv -c /tmp/env.config"
14 bcm4908_pkgtb_setup_env_config() {
15 local size=$((0x$(get_hex_u32_le /dev/ubi0_1 4)))
16
17 dd if=/dev/ubi0_1 of=/tmp/env.head count=8 iflag=count_bytes
18 dd if=/dev/ubi0_1 of=/tmp/env.body skip=8 iflag=skip_bytes
19 printf "%s\t0x%x\t0x%x\t0x%x" "/tmp/env.body" 0x0 $size $size > /tmp/env.config
20 }
21
22 bcm4908_committed_image_seq() {
23 bcm4908_pkgtb_setup_env_config
24
25 commited="$(fw_printenv -n -c /tmp/env.config COMMITTED)"
26 [ -n "$commited" ] && {
27 seq=$(fw_printenv -n -c /tmp/env.config SEQ | cut -d ',' -f $commited)
28 [ -n "$seq" ] && {
29 echo $seq
30 return
31 }
32 }
33
34 echo "Failed to read COMMITED and SEQ from metadata1" >&2
35 }
36
37 # Make sure "rootfs_data" UBI volume matches currently flashed image
38 #
39 # On mismatch "rootfs_data" will be wiped and assigned
40 #
41 # $1: UBI volume of "rootfs_data" (e.g. ubi0_123)
42 bcm4908_verify_rootfs_data() {
43 local ubivol="$1"
44 local dir=/tmp/rootfs_data
45 local seq="$(bcm4908_committed_image_seq)"
46
47 [ -z "$seq" ] && return
48
49 mkdir $dir
50 if ! mount -t ubifs /dev/$ubivol $dir; then
51 echo "Failed to mount $ubivol UBI volume" >&2
52 rmdir $dir
53 return
54 fi
55
56 # Wipe rootfs_data if it doesn't belong to us
57 [ "$(readlink $dir/.openwrt-image-seq)" != "$seq" ] && {
58 echo "Removing \"rootfs_data\" content"
59 rm -rf $dir/..?* $dir/.[!.]* $dir/*
60 }
61
62 # If rootfs_data is clean (or was just wiped) claim it
63 [ -z "$(ls -A $dir)" ] && {
64 echo "Assigning \"rootfs_data\" to the current firmware"
65 # Claim this "rootfs_data"
66 ln -s $seq $dir/.openwrt-image-seq
67 # Mark it ready to avoid "mount_root" wiping it again
68 ln -s $FS_STATE_READY $dir/.fs_state
69 }
70
71 umount $dir
72 rmdir $dir
73 }