[][OpenWrt Dev][Add support for u-boot env-tools for ubi devices]

[Description]
Add support for u-boot env-tools for ubi devices

[Release-log]
N/A

Change-Id: Idece98c690ae40f5814bff7f105026862923ddbb
Reviewed-on: https://gerrit.mediatek.inc/c/openwrt/feeds/mtk_openwrt_feeds/+/6105793
diff --git a/package-21.02/boot/uboot-envtools/files/mediatek b/package-21.02/boot/uboot-envtools/files/mediatek
index 7a0507a..6102d9b 100644
--- a/package-21.02/boot/uboot-envtools/files/mediatek
+++ b/package-21.02/boot/uboot-envtools/files/mediatek
@@ -10,6 +10,8 @@
 . /lib/uboot-envtools.sh
 . /lib/functions.sh
 
+CI_UBIPART=ubi
+
 block_dev_path() {
 	local dev_path
 
@@ -30,6 +32,37 @@
 	return 0
 }
 
+nand_find_volume() {
+	local ubidevdir ubivoldir
+	ubidevdir="/sys/devices/virtual/ubi/$1"
+	[ ! -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
+	mtdnum="$( find_mtd_index $1 )"
+	[ ! "$mtdnum" ] && return 1
+	for ubidevdir in /sys/devices/virtual/ubi/ubi*; do
+		[ ! -d "$ubidevdir" ] && continue
+		cmtdnum="$( cat $ubidevdir/mtd_num )"
+		[ ! "$mtdnum" ] && continue
+		if [ "$mtdnum" = "$cmtdnum" ]; then
+			ubidev=$( basename $ubidevdir )
+			ubi_mknod "$ubidevdir"
+			echo $ubidev
+			return 0
+		fi
+	done
+}
+
 board=$(board_name)
 
 case "$board" in
@@ -40,6 +73,29 @@
 	[ -n "$env_dev" ] && \
 		ubootenv_add_uci_config "$env_dev" "0" "0x80000"
 	;;
+
+mediatek,*-snand-rfb)
+	env_dev=$(cat /sys/module/boot_param/parameters/env_part 2>/dev/null)
+	if [ -n "$env_dev" ]; then
+		local mtdnum="$( find_mtd_index "$CI_UBIPART" )"
+		if [ ! "$mtdnum" ]; then
+			echo "cannot find ubi mtd partition $CI_UBIPART"
+			return 1
+		fi
+
+		local ubidev="$( nand_find_ubi "$CI_UBIPART" )"
+		if [ ! "$ubidev" ]; then
+			ubiattach -m "$mtdnum"
+			sync
+			ubidev="$( nand_find_ubi "$CI_UBIPART" )"
+		fi
+
+		local env_ubivol="$( nand_find_volume "${ubidev}" ${env_dev} )"
+		if [ -n "${env_ubivol}" ]; then
+			ubootenv_add_uci_config "/dev/$env_ubivol" "0" "0x80000" "0x80000" 1
+		fi
+	fi
+	;;
 esac
 
 config_load ubootenv