Module 4 · Lesson 51 of 156

The U-Boot environment and its commands

Explain the U-Boot environment, persist variables with saveenv, and keep stored copies consistent using CRC checks and redundant copies.

  • Beginner to advanced
  • 7 min read
  • 25 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with the u-boot-tools package; a board at the U-Boot prompt is optional

Your place in the module
By the end you can 4 objectives
  • Inspect and modify environment variables with printenv, setenv and saveenv
  • Explain where the environment is stored on MMC, NAND and UBI, and where the default environment comes from
  • Describe how the CRC and redundant copies detect corruption and survive a power cut during saveenv
  • Export, edit and re-import an environment, and read it from Linux with fw_printenv
Video coming soonThe U-Boot environment and its commands
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Booting a kernel from U-Boot
  • fatload and ext4load copy a file from an mmc device:partition into RAM; bootm starts a uImage, bootz a zImage, booti an arm64 Image
  • bootm takes kernel address, optional initrd (a dash means none), then the device tree address
  • The boot command simply runs the bootcmd environment variable, which is what autoboot executes after bootdelay seconds
01

The environment: variables the bootloader remembers

3 min read

The last lesson ended at the U-Boot prompt, where boot behaviour is driven by saved variables. This lesson answers the default environment, saveenv, import and export, and how CRC and redundant copies keep it consistent.

The is where every setting you typed at the prompt actually lives. bootcmd, bootargs, bootdelay, ipaddr, serverip: each is one variable, stored as the text name=value, and the whole block is a list of such strings separated by NUL bytes. At startup U-Boot loads the block into RAM and builds a hash table over it, so every later lookup and every ${variable} expansion reads the RAM copy, not the flash.

Where does the very first environment come from? It is compiled into the U-Boot binary itself: the is assembled from include/env_default.h plus whatever the board adds through CONFIG_EXTRA_ENV_SETTINGS. On a freshly flashed board there is no saved block yet, so U-Boot runs on these defaults. That is why a board can autoboot out of the box, before anyone has ever typed saveenv.

The day-to-day commands are few:

bash
=> printenv bootcmd bootargs bootdelay
=> setenv bootdelay 3
=> setenv bootargs 'console=ttySTM0,115200 root=/dev/mmcblk0p2 rootwait'
=> saveenv

printenv with no arguments lists everything; with names it prints just those. setenv name value changes the RAM copy only. setenv name with no value deletes the variable. saveenv writes the whole RAM block to persistent storage, and only then does the change survive a reset. If you set a variable and power-cycle without saving, the old value comes back. To throw away your edits and return to the compiled-in defaults, use env default -a; adding -f also saves the reset result to storage.

One subtlety matters for bootargs. U-Boot expands ${...} references when a command line runs, so setenv bootargs console=${console} rootwait expands console immediately, at set time. Wrapping the value in single quotes stores the literal ${console} text, and the expansion happens later, each time bootargs is used. The final bootargs string is handed to the kernel as its command line, which is why it must match the parameters the kernel expects (see the bootparam(7) reference).

The life of an environment variableCompileddefaultsbuilt intoU-BootRead storedcopyMMC, NANDor UBICRC checkRAMvariableshash tableExit from step 3: bad CRCuse defaultssetenvedits RAMsaveenvwrites backCompileddefaultsbuilt intoU-BootRead storedcopyMMC, NANDor UBICRC checkRAMvariableshash tableExit from step 3: bad CRCuse defaultssetenvedits RAMsaveenvwrites back
From compiled-in defaults to RAM edits and back to storage
02

Where it lives, and how it stays consistent

4 min read

The storage backend is a build-time choice, and the flash layout lesson earlier in this session showed where the environment region sits. On SD cards and eMMC, CONFIG_ENV_IS_IN_MMC places the block at a raw byte offset (CONFIG_ENV_OFFSET, size CONFIG_ENV_SIZE) outside any partition; CONFIG_ENV_IS_IN_FAT instead keeps it as a file, conventionally uboot.env, on a FAT partition. On raw NAND, CONFIG_ENV_IS_IN_NAND uses an eraseblock-aligned offset. On NAND managed by UBI, CONFIG_ENV_IS_IN_UBI stores it in a named UBI volume (CONFIG_ENV_UBI_VOLUME), with an optional second volume for a redundant copy. SPI flash and EEPROM backends exist too. The commands you type are identical in every case; only the write path differs.

Whatever the medium, the stored block has the same shape: a 4-byte header, then the NUL-separated variable data. The CRC is computed over the data, and with redundancy enabled one extra flag byte sits between the CRC and the data. At boot U-Boot recomputes the CRC and compares it with the stored one. If the check fails and no other valid copy exists, it prints a warning of this form and loads the compiled-in defaults instead:

bash
*** Warning - bad CRC, using default environment

In the U-Boot source checked for this review the message comes from env/common.c, which prints *** Warning - %s, using default environment with the reason bad CRC. The exact wording can vary between U-Boot versions, but the behaviour does not: a corrupt stored block never stops the board, it falls back to defaults. The CRC detects accidental damage (a torn write, a flipped bit, a half-erased block); it is not a security measure, since anyone who can write the flash can also recompute the CRC.

One environment block, three storage backendseMMC / SD(MMC)Raw NANDUBI volumeKconfig optionENV_IS_IN_MMCENV_IS_IN_NANDENV_IS_IN_UBIAddressed bybyte offseteraseblockoffsetvolume nameWear handled byeMMCcontrollerredundantcopiesUBI wearlevelingSecond copyoptionaloffsetseconderaseblocksecond volume
The same environment block on three storage backends
Going deeperExplore the mechanism

Raw NAND is where consistency gets interesting, because NAND cannot be overwritten in place: a whole eraseblock must be erased before it can be programmed, and a power cut mid-erase or mid-write leaves garbage. The answer is the , enabled with CONFIG_ENV_REDUNDANT (the Kconfig symbol in env/Kconfig of the U-Boot checked for this review; the old misspelled symbol CONFIG_SYS_REDUNDAND_ENVIRONMENT of older U-Boot no longer appears anywhere in that tree) and placed at CONFIG_ENV_OFFSET and CONFIG_ENV_OFFSET_REDUND (the STM32MP15 defconfigs set both, for example 0x280000 and 0x2C0000 in stm32mp15_trusted_defconfig).

Each copy carries a flag byte that acts as a generation counter. At boot U-Boot reads both copies and checks both CRCs. If both are valid, the copy with the newer flag is active. If one fails its CRC, the other is used. Crucially, saveenv writes the copy that is not currently active, with the flag incremented, and only that write makes it the newer one. So at every instant of a save, the active copy is untouched: a power cut during the erase or the write damages only the copy being written, and the next boot simply picks the intact one. As a side effect, alternating writes spread erase wear over two blocks, and CONFIG_ENV_RANGE lets the NAND backend skip bad blocks within a range. UBI goes further: its wear leveling and atomic volume updates handle the same problem for the whole volume, which is why frequent writers often prefer ENV_IS_IN_UBI.

Redundant saveenv writes the inactive copyU-BootCopy ACopy Bread at bootvalid, flag nread at bootvalid, older flagsaveenv: flag n+11. U-Boot → Copy Aread at boot2. Copy A → U-Bootvalid, flag n3. U-Boot → Copy Bread at boot4. Copy B → U-Bootvalid, older flag5. U-Boot → Copy Bsaveenv: flag n+1
saveenv writes the inactive copy, so the active one always survives
A raw offset is a promise

With ENV_IS_IN_MMC or ENV_IS_IN_NAND, the offset is just a number in the config. If it overlaps a partition table or a filesystem, saveenv silently destroys data, and repartitioning the card can silently destroy the environment. Keep the environment region in the flash layout table from the earlier lesson, and re-check it whenever the layout changes.

03

Import, export, and editing from Linux

2 min read

Because the environment is just text, it can leave the board. env export -t ${loadaddr} 0x1000 writes the variables as name=value lines into RAM at ${loadaddr}; -b exports the raw binary block and -c the checksummed block including the header. env import -t ${loadaddr} ${filesize} reads text lines back into the RAM environment, merging them with what is there; -d deletes the existing variables first, so the imported set fully replaces it. A typical round trip looks like this:

Step by stepExport, edit, re-import
  1. Export: env export -t ${loadaddr} 0x1000 puts the text form in RAM.

  2. Get it out: write the region to a file with fatwrite, or send it over the network with tftpput (the netboot lesson covers the network side).

  3. Edit on the host: change lines in any text editor; keep one name=value per line.

  4. Load it back: bring the file into RAM (for example tftpboot, which sets ${filesize}).

  5. Import and save: env import -t -d ${loadaddr} ${filesize}, then saveenv.

You can also touch the stored block from a running Linux system. On Ubuntu 24.04, sudo apt install u-boot-tools provides fw_printenv and fw_setenv, which read and write the same block with the same CRC rules, plus mkenvimage, which builds a valid block (header included) from a text file. They find the storage through /etc/fw_env.config, one line per copy:

bash
# device    offset   env-size   sector-size
/dev/mtd1   0x0      0x20000    0x20000

Those values are an example; yours must come from the board's flash layout. In the real test with a regular file the line was /w/ub/env.bin 0x0 0x1000 0x1000, mkenvimage -s 0x1000 -o env.bin env.txt produced a 4096-byte image whose first four bytes were the little-endian CRC32 (0x47be9734) of the data after them, fw_printenv -c fw_env.config printed the three variables, and after one byte of the data was overwritten it printed Cannot read environment, using default and Cannot read default environment from file. Two lines declare a redundant pair, and fw_setenv then performs the same write-the-inactive-copy dance as U-Boot. The device can even be a regular file, which is how the practice exercises let you rehearse all of this on Ubuntu without a board.

Two writers, one format

fw_setenv and U-Boot must agree exactly on offset, size, and whether redundancy is enabled. If fw_env.config describes a single copy while U-Boot expects two, or the offsets differ by one eraseblock, each writer corrupts what the other reads. Verify with fw_printenv before trusting fw_setenv on a new board.

You now know where boot behaviour is stored and how it survives. The next lesson, "U-Boot scripts and FIT images", builds on these variables: multi-line scripts stored in variables like bootcmd, and FIT images that bundle a kernel with its device tree, so the environment can select whole boot configurations instead of single files.

Key takeaways

  • setenv changes only the RAM copy; saveenv writes it to persistent storage
  • The stored block starts with a CRC32; a failed check makes U-Boot fall back to the compiled-in default environment
  • With redundancy enabled, saveenv writes the inactive copy and marks it newer, so a power cut cannot destroy the active one
  • fw_printenv and fw_setenv use the same format and CRC, driven by /etc/fw_env.config
Reflect
  1. Explain to a colleague, in two sentences: inspect and modify environment variables with printenv, setenv and saveenv
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close