Module 4 · Lesson 81 of 156

UBI and UBIFS on raw flash

Attach UBI volumes, build and mount a UBIFS filesystem on raw flash, and explain wear leveling, the journal and UBI fastmap.

  • Beginner to advanced
  • 8 min read
  • 40 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with mtd-utils and the nandsim kernel module; a board with raw NAND for the real-hardware version

Your place in the module
By the end you can 4 objectives
  • Attach an MTD device with ubiattach and create, resize and update UBI volumes
  • Build a UBIFS image with mkfs.ubifs, mount it, and choose sensible mount options
  • Explain how UBI wear-levels erase blocks and hides bad blocks
  • Describe the UBIFS journal, UBI fastmap and how UBI plus UBIFS compare with JFFS2
Video coming soonUBI and UBIFS on raw flash
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The MTD subsystem and flash types
  • MTD exposes raw flash as erase blocks, not sectors, through the /dev/mtdN character devices and /proc/mtd.
  • NOR is byte-addressable and executes code in place; NAND is page and block organized and needs ECC plus bad-block tracking.
  • Flash programs one way and erases a whole block, and both types wear out; NAND ships with bad blocks already marked.
01

UBI: volumes on top of raw flash

4 min read

Raw flash needs a layer that hides erase blocks, and that is UBI. This lesson answers ubiattach, ubinize and volumes, mkfs.ubifs with its journal and fastmap, and how UBIFS compares with JFFS2.

MTD exposes flash as it really is: a pile of erase blocks that must be erased before they are written, that wear out after a limited number of erase cycles, and that occasionally leave the factory with bad blocks. That is a hostile surface for a filesystem. Writing a filesystem directly on top of it, as JFFS2 does, forces the filesystem to solve erasing, wear and bad blocks for itself.

UBI, the Unsorted Block Images layer, hides all of it. It sits between MTD and the filesystem and turns the flat erase-block space of an MTD device into volumes, each of which looks like a reliable block device to the layer above. UBI's three jobs are , bad block handling (skipping and replacing blocks that are bad from the factory or that wear out in service), and volume management (splitting the device into independent, named regions). On top of a volume you run UBIFS.

The first command is ubiattach, which attaches an MTD device to UBI and creates a UBI device node. On a board where the root filesystem lives on an MTD partition:

bash
ubiattach /dev/ubi_ctrl -m 5

This attaches MTD device 5 and creates /dev/ubi0. ubinfo shows the device and its volumes. A fresh UBI device has no volumes until you make them; ubimkvol creates one:

bash
ubimkvol /dev/ubi0 -N rootfs -s 100MiB

This makes a 100 MiB volume named rootfs, which appears as /dev/ubi0_0. The name matters, because later you mount it as ubi0:rootfs. Volumes can be grown or shrunk with ubirsvol and deleted with ubirmvol.

When you build an image to flash at the factory you do not attach anything; you assemble the image with ubinize. It reads a small configuration file that lists the volumes and produces one UBI image that a flasher writes straight to the chip:

shell
[ubifs]
mode=ubi
image=rootfs.ubifs
vol_id=0
vol_type=dynamic
vol_name=rootfs
vol_size=100MiB
bash
ubinize -o rootfs.ubi -m 2048 -p 128KiB ubinize.cfg

Here -m is the minimum I/O unit size and -p the physical eraseblock size, both taken from the flash datasheet. An optional -s gives the sub-page size for NAND that supports sub-pages; by default it equals -m (ubinize --help), and the logical eraseblock size you pass to mkfs.ubifs later depends on it. The opposite direction is ubiupdatevol, which writes a new image into a volume that already exists, in place, on a running system. A firmware updater uses it to replace the root filesystem volume without touching the rest of the flash:

bash
ubiupdatevol /dev/ubi0_0 rootfs.ubifs
Step by stepFrom raw flash to a mounted UBIFS
  1. ubiformat or ubinize: put UBI headers on the flash, either live with ubiformat or into an image with ubinize.

  2. ubiattach: attach the MTD device, creating /dev/ubi0.

  3. ubimkvol: create a volume such as rootfs, giving /dev/ubi0_0.

  4. mkfs.ubifs: build the filesystem image from a directory tree.

  5. mount: mount ubi0:rootfs and use it like any filesystem.

Where UBI sits between MTD and UBIFSApplicationsyour program, initUBIFSjournal, on-flash indexUBIvolumes, wear leveling, fastmapMTD/dev/mtdN character deviceRaw flashNAND or NOR erase blocksreads and writes go down, data comes back upApplicationsyour program, initUBIFSjournal, on-flash indexUBIvolumes, wear leveling,fastmapMTD/dev/mtdN character deviceRaw flashNAND or NOR erase blocksreads and writes go down, datacomes back up
Where UBI sits between MTD and UBIFS
02

How UBI spreads the wear

2 min read

Wear leveling starts with a distinction between two kinds of erase block. A is the real thing. A is what a volume sees. UBI keeps a table that maps each LEB to a PEB, and it is free to change that mapping at any moment. The volume sees a tidy, continuous range of LEBs; the chip underneath is a scattered set of PEBs with uneven erase counts.

Every time a PEB is erased, UBI increments its counter. When it must hand out a free block for new data, it picks the PEB with the lowest erase count, so blocks that are rewritten often get moved around the chip and no single block is erased far more than the rest. This is dynamic wear leveling, and it handles data that changes. Data that never changes is the harder case: a read-only root filesystem would sit on the same PEBs for years while other blocks wore out around it. UBI therefore also does static wear leveling, copying stable data off low-wear blocks and onto high-wear ones so the whole chip ages together. The erase counters live in the header UBI writes to every PEB, so they survive power loss.

Bad blocks are handled by the same mapping. A PEB that fails, or one the factory marked bad, is removed from the free pool and never used again; UBI substitutes a spare from the pool of reserved PEBs it keeps for exactly this. The flash vendor ships every chip with spare blocks for this purpose, and UBI covers blocks that die during the product's life. The volume above never learns that anything went wrong, which is the point of the layer.

Logical erase blocks versus physical erase blocksLogical eraseblock (LEB)Physicalerase block(PEB)Seen bya UBI volumethe flashchipNumberingcontinuous,fixedscattered,remappedErase counternot visiblestored perblockBad blocksnever exposedskipped,replaced
Logical erase blocks remapped onto physical erase blocks
03

UBIFS: a filesystem with a journal, and UBI fastmap

4 min read

On top of a UBI volume you run UBIFS, the filesystem designed for it. You build the filesystem off-device with mkfs.ubifs, which packs a directory tree into a UBIFS image. The sizes must match the flash, so you pass them explicitly:

bash
mkfs.ubifs -r rootfs -m 2048 -e 126976 -c 2047 -x lzo -o rootfs.ubifs

-m is the minimum I/O unit, -e the logical eraseblock size (a physical eraseblock minus the two pages UBI uses for its headers), -c the maximum number of logical eraseblocks, which caps the filesystem size, -x the compression (lzo is the default, with zlib and zstd as options), and -o the output image. Getting -m and -e wrong is the classic first mistake; both come from the flash datasheet. On a chip with 2 KiB pages and 128 KiB erase blocks, -m is 2048 and -e is 126976.

To use it you mount the volume by name rather than a block device path:

bash
mount -t ubifs ubi0:rootfs /mnt

Mount options tune the behaviour. The generic sync option makes every write synchronous: safe against power loss but slow. UBIFS adds bulk_read (read-ahead for large sequential reads; no_bulk_read is the default), chk_data_crc and no_chk_data_crc (in the 6.8 documentation skipping the data CRC check, no_chk_data_crc, is the default, and chk_data_crc turns the check on), and compr=none, compr=lzo or compr=zlib to override the compressor (Documentation/filesystems/ubifs.rst). A read-only mount uses ro.

UBIFS is a journaled, copy-on-write filesystem. Every change, file data and metadata alike, is written into the journal first; when the journal is committed, the index is updated by writing new index nodes instead of modifying old ones, a design the UBIFS documentation calls the wandering tree. Because the old nodes stay in place until the new state is complete, a power cut leaves the last committed state intact, and the filesystem recovers to it on the next mount. Blocks holding superseded nodes are reclaimed by garbage collection, which runs in the background from a kernel thread (ubifs_bg_thread in fs/ubifs/commit.c).

Attaching a large UBI device normally means scanning the header of every physical eraseblock to rebuild the LEB to PEB table, and that scan takes longer as the device grows. shortens it. It belongs to UBI, not to UBIFS, it is an option you must build in (CONFIG_MTD_UBI_FASTMAP, marked experimental and off by default in the 6.8 Kconfig), and the kernel Kconfig help says it only makes sense on large devices where attaching by scanning takes long. If the fastmap is missing or invalid, UBI falls back to the full scan, so speed never trades away correctness. UBIFS itself keeps its index on flash and recovers from a power cut by replaying its journal when it is mounted.

Going deeperExplore the mechanism

UBIFS replaced an older filesystem, JFFS2, and the reason shows what UBI buys you. JFFS2 runs directly on an MTD device and keeps its index as nodes scattered across the flash; at mount it rebuilds that index by scanning the entire device. Two problems follow. Mount time grows linearly with device size, so a small NOR flash is fine but a large NAND takes seconds of pure scanning before it is usable. And JFFS2 does its own wear leveling and garbage collection in place, which on large flash produces long, unpredictable pauses and spreads wear badly. UBIFS fixes the first by keeping its index on flash (UBI can add fastmap to speed up its own attach scan), and the second by moving wear leveling and bad block handling down into UBI, where it works across the whole device instead of inside one filesystem. For a small NOR flash JFFS2 is still a reasonable and simpler choice; for the large NAND in a modern product, UBI plus UBIFS is the default. Choosing between them for one product is the subject of the next lesson.

The UBIFS write pathwrite()file dataandmetadatajournalcommitgroupedchangesindex nodescopy-on-write,wanderingtreegarbagecollectionbackground,reclaimsold blockswrite()file dataandmetadatajournalcommitgroupedchangesindex nodescopy-on-write,wanderingtreegarbagecollectionbackground,reclaimsold blocks
The write path through the journal to the index
Never flash a UBI image over a live volume

ubinize builds an image for the factory flash step, and ubiupdatevol replaces one volume. Do not mix the two: writing a ubinize image into a single volume with ubiupdatevol, or flashing a single-volume image where the factory layout expects several, silently corrupts the layout. Keep the ubinize configuration and the updater in the same source tree so they cannot drift apart.

Key takeaways

  • UBI hides erase blocks, wear and bad blocks behind volumes; UBIFS mounts on a volume
  • Wear leveling remaps logical to physical erase blocks using per-block erase counters
  • UBIFS is journaled and copy-on-write, so a power cut leaves the last committed state
  • JFFS2 scans the whole device at mount and wears large NAND badly; UBI plus UBIFS scales
Reflect
  1. Explain to a colleague, in two sentences: attach an MTD device with ubiattach and create, resize and update UBI volumes
  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

Official documentation first. Links checked when the lesson was published.

Find your next step

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