[PATCH v2 8/8] env: ubi: add support to create environment volume if it does not exist

Weijie Gao weijie.gao at mediatek.com
Tue Apr 21 10:36:39 CEST 2026


Add an option to allow environment volume being auto created if not
exist.

Signed-off-by: Weijie Gao <weijie.gao at mediatek.com>
---
v2: updated kconfig help text
    added error output when failed to create volume
---
 env/Kconfig | 11 +++++++++++
 env/ubi.c   | 30 ++++++++++++++++++++++++++++++
 2 files changed, 41 insertions(+)

diff --git a/env/Kconfig b/env/Kconfig
index 7abd82ab6f3..8404e0d44eb 100644
--- a/env/Kconfig
+++ b/env/Kconfig
@@ -716,6 +716,17 @@ config ENV_UBI_VOLUME_REDUND
 	help
 	  Name of the redundant volume that you want to store the environment in.
 
+config ENV_UBI_VOLUME_CREATE
+	bool "Create UBI volume if not exist"
+	depends on ENV_IS_IN_UBI
+	help
+	  This option is useful if u-boot will be booted from a fresh device
+	  where environment volume hasn't been created in the UBI partition.
+	  This is a common case where factory UBI image contains only volumes
+	  with valid data.
+	  By enabling this option, environment volume(s) will be created before
+	  loading if not exist.
+
 config ENV_UBI_VID_OFFSET
 	int "ubi environment VID offset"
 	depends on ENV_IS_IN_UBI
diff --git a/env/ubi.c b/env/ubi.c
index 46970ba754f..55c9c543444 100644
--- a/env/ubi.c
+++ b/env/ubi.c
@@ -103,6 +103,23 @@ static int env_ubi_save(void)
 }
 #endif /* CONFIG_ENV_REDUNDANT */
 
+static int env_ubi_volume_create(const char *volume)
+{
+	struct ubi_volume *vol;
+	int ret;
+
+	vol = ubi_find_volume(volume);
+	if (vol)
+		return 0;
+
+	ret = ubi_create_vol(volume, CONFIG_ENV_SIZE, true, UBI_VOL_NUM_AUTO,
+			     false);
+	if (ret)
+		printf("Failed to create environment volume '%s'\n", volume);
+
+	return ret;
+}
+
 #ifdef CONFIG_ENV_REDUNDANT
 static int env_ubi_load(void)
 {
@@ -132,6 +149,14 @@ static int env_ubi_load(void)
 		return -EIO;
 	}
 
+	if (IS_ENABLED(CONFIG_ENV_UBI_VOLUME_CREATE)) {
+		read1_fail = env_ubi_volume_create(CONFIG_ENV_UBI_VOLUME);
+		read2_fail = env_ubi_volume_create(CONFIG_ENV_UBI_VOLUME_REDUND);
+
+		if (read1_fail && read2_fail)
+			return -ENODEV;
+	}
+
 	read1_fail = ubi_volume_read(CONFIG_ENV_UBI_VOLUME, tmp_env1, 0,
 				     CONFIG_ENV_SIZE);
 	if (read1_fail)
@@ -169,6 +194,11 @@ static int env_ubi_load(void)
 		return -EIO;
 	}
 
+	if (IS_ENABLED(CONFIG_ENV_UBI_VOLUME_CREATE)) {
+		if (env_ubi_volume_create(CONFIG_ENV_UBI_VOLUME))
+			return -ENODEV;
+	}
+
 	if (ubi_volume_read(CONFIG_ENV_UBI_VOLUME, buf, 0, CONFIG_ENV_SIZE)) {
 		printf("\n** Unable to read env from %s:%s **\n",
 		       CONFIG_ENV_UBI_PART, CONFIG_ENV_UBI_VOLUME);
-- 
2.45.2



More information about the U-Boot mailing list