Building the Image

A bbappend named for the right recipe version changes your Linux image. One named for the wrong version changes nothing. BitBake picks by name, version and layer priority.

Add the bbappend, then raise the vendor layer’s priority. Watch which BusyBox version wins and whether your append lands. Then we build, piece by piece, everything under it.

You need a shell and a rough idea that Linux boots from files on a disk. We build the rest from zero: what a recipe is, why images break, and how to rebuild the same one twice.

Built from primary sources: the Yocto Project documentation, the Buildroot manual, the NixOS manual, the Linux kernel docs and systemd man pages. The full list is in the Field Guide.

Resolve the recipe

PRIORITY OF LAYER meta-vendor (meta has 5)

YOUR APPEND FILE: busybox_….bbappend

PREFERRED_VERSION_busybox

A model of BitBake’s selection rules (bb/providers.py), not BitBake itself. The two BusyBox versions and the layer names are illustrative; the rules are the real ones.

Chapter 0

The bbappend That Did Nothing

Find out why a change that looks right leaves the image untouched, and learn the three rules BitBake uses to decide

You need BusyBox on your board to drop one small tool. You write a short file, rebuild the image, flash it, and the tool is still there. The build did not fail. It just ignored you.

This happens to everyone who builds Linux for a device. The cause is almost never a typo in the change. It is a mismatch in the file’s name. To see why, we first need four words.

Four words: image, recipe, layer, append

An image is the finished set of files you flash onto the board: the kernel, the programs, the settings. Think of it as a sealed lunch box. You do not cook inside the box; you cook elsewhere and pack it.

A recipe is a text file that tells the build tool how to make one package: where to download the source, which patches to apply, how to compile it. The build tool is BitBake. It reads recipes, works out the order, and runs them. A recipe file is named after the package and its version, for example busybox_1.36.1.bb.

A layer is a folder of recipes that belong together, such as the core ones, or the ones from your chip vendor. BitBake reads many layers at once. Two layers can hold a recipe for the same package, which is where the trouble starts.

A bbappend is a file that adds steps to a recipe you do not own. You never edit the vendor’s recipe. You write busybox_1.36.1.bbappend in your own layer, and BitBake glues its lines onto the end of the recipe with the same name. The Yocto manual puts the rule plainly: “When you create an append file, you must use the same root name as the corresponding recipe file.”

Rule 1: the name must match, version included

The append and the recipe are “version number-specific”, in the manual’s words. A busybox_1.35.0.bbappend belongs to busybox_1.35.0.bb and to nothing else. If the recipe moves to 1.36.1, the append stays attached to the old version.

You can loosen the match with %. The manual’s own example is someapp_6.%.bbappend, which targets every 6.x version of someapp. Then an error appears only if the recipe jumps to a new major version.

What if the append matches no recipe file anywhere? Then BitBake stops with an error at startup. That is the loud failure. The quiet failure is the one in our story: the append matches a real recipe, but that recipe is not the one BitBake chose to build.

Rule 2: which recipe gets built

Two layers can both offer BusyBox. BitBake must pick one, and it picks in a fixed order. This order is written in the BitBake source, in bb/providers.py.

  1. PREFERRED_VERSION. If you set PREFERRED_VERSION_busybox and a recipe has that version, it wins. Nothing below matters.
  2. Layer priority. Each layer sets BBFILE_PRIORITY. The manual says “a larger value … results in a higher precedence.” Only recipes in the highest-priority layer stay in the race.
  3. Version. Among the survivors, the highest version wins. A layer’s DEFAULT_PREFERENCE, a weak bias, is checked just before this step.

Read rule 2 again, because it surprises people. A newer BusyBox in a low-priority layer loses to an older BusyBox in a high-priority layer. Version only breaks ties.

Ask the three questions

Three layers offer BusyBox. Press Ask the next question to see candidates drop out. Then set PREFERRED_VERSION and ask again.

Illustrative layers and versions. The order of the questions follows bb/providers.py in BitBake: required or preferred version, then the highest-priority layer, then DEFAULT_PREFERENCE, then the highest version.

With nothing set, the first question drops no one. The second drops meta, because 5 is below 6. The third keeps BusyBox 1.37.0 from meta-local, so a 1.35.0 append targets a recipe that was never built. Set the preferred version to 1.36.1 and the answer flips at question one, even though that layer has the lowest priority.

The two instruments

Guessing is slow. BitBake ships two tools that show the truth.

# which appends exist, and which recipe files they attach to
bitbake-layers show-appends
# every variable, with the file and line that last set it
bitbake -e busybox | grep ^PV=
bitbake -e busybox | grep ^BBFILE_PRIORITY

show-appends is described in the manual as “Lists .bbappend files and the recipe files to which they apply.” bitbake -e prints the environment of one recipe, with comments that say where each value was set. Together they answer both halves of the story: which recipe was chosen, and whether your append reached it.

Why a rebuild may also be a no-op

One more actor can hide your change: the sstate cache (shared state). BitBake saves the output of each task under a hash of its inputs. The manual says it “supports incremental builds” and lets build machines share task output. If your append did change the inputs, the hash changes and the task reruns. If the hash did not change, BitBake reuses the saved result. So a working append always shows up as a rerun task. Chapter 4 opens this up.

The failure, as symptom, measurement and fix. Symptom: the image is unchanged after a rebuild. Measurement: run bitbake-layers show-appends and look for your file; run bitbake -e busybox and read PV. Fix: rename the append with % or match the chosen version, or change the priority or PREFERRED_VERSION on purpose.

ON REAL HARDWARE Build core-image-minimal for a Raspberry Pi 4 Model B (the meta-raspberrypi layer), add your own layer, and write a bbappend for a package with two versions. Repeat the test above: run show-appends and check the file lands in tmp/work for the package you expect.
  1. Toolchains and sysroots: why a program that runs on the desk dies on the board.
  2. Root filesystems: BusyBox, systemd and a 120 second boot.
  3. Three build systems: Buildroot, Yocto and NixOS side by side.
  4. Yocto anatomy: layers, machine, distro, image, sstate, devtool.
  5. NixOS on vendor boards: closures, generations, forward porting.
  6. Flash storage: fsync and the power cut.
  7. Reproducibility and licences: SBOMs and the GPL.
  8. Field guide: numbers, a checklist and the resolver as code.
meta has BusyBox 1.36.1 at priority 5. meta-vendor has 1.35.0 at priority 6. You set no PREFERRED_VERSION and add busybox_1.36.1.bbappend. What happens?

Chapter 1

Toolchains and Sysroots

Build your program against the board’s own libraries, and see why a binary that runs on your desk can die on the device

Your small camera tool compiles on the laptop and runs fine there. You copy it to the board and type the name. The shell answers: version `GLIBC_2.38' not found. The program is correct. It was simply built against the wrong set of libraries.

What a toolchain is, and why it has a name like a code

A toolchain is the set of programs that turn C source into a binary: compiler, assembler, linker. Your laptop has one that makes laptop programs. A board with a different chip needs a cross toolchain: it runs on your laptop but writes programs for the board.

Every toolchain names its target with a triplet, three or four parts joined by dashes: chip, vendor or system, kernel, and C library. Examples: x86_64-linux-gnu for a laptop, aarch64-linux-gnu for a 64-bit Arm board such as the Raspberry Pi 4, arm-linux-gnueabihf for 32-bit Arm with hardware floating point. The last part, gnu, means the glibc library.

The sysroot: a copy of the board’s world

A program does not contain everything it uses. It calls the C library, a shared set of functions such as printf and open, which lives on the board in a file like libc.so.6. When you compile, the linker needs that library’s headers and files to check your calls. It must read the board’s copy, not your laptop’s.

A sysroot is a folder that looks like the board’s root directory: its /usr/include, its /usr/lib. You point the compiler at it with --sysroot=. The Yocto SDK manual says the sysroots “contain needed headers and libraries for generating binaries that run on the target architecture”, and that they are specific to the image the SDK was built against. An environment script you source sets the variables for you.

Why the error names a version

glibc gives each function a version tag so old programs keep working when the library changes. When your linker uses a function, it writes the newest tag it saw into your binary. At start-up the loader on the board checks every tag against its own library. If a tag is newer than the library, it stops.

Here is a concrete case. glibc 2.38 added strlcpy. A program that calls it on a build host with glibc 2.39 carries the tag GLIBC_2.38. A board image with glibc 2.35 does not have that tag, so the loader refuses. You read the tags with readelf -V, which the manual says “displays the contents of the version sections”.

Build it, copy it, run it on the board

The board image has glibc 2.35 on aarch64. Choose which compiler built camtool, and whether it is linked statically. Then read the verdict.

COMPILER


    

Illustrative versions. The glibc 2.38 tag for strlcpy and the loader message are real. The glibc 2.35 board and the 2.39 distro toolchain are example numbers, not a measured image.

Three outcomes appear. The laptop build fails at once, with “cannot execute binary file: Exec format error”, because the chip is wrong. The distro cross compiler gives a correct chip but the wrong library version. The image SDK builds against the library the board actually has, so it runs.

Glibc, musl, static, dynamic

glibc is the standard Linux C library: large, fast and complete. musl is a smaller one, popular in tiny images. You choose the library when you build the toolchain; you cannot swap it afterwards. A static binary copies the library code inside itself, so it needs no matching library on the board. The cost is size: every program carries its own copy, and a security fix to the library needs a rebuild of every program. A dynamic binary shares one library file. It is small, but it needs the right version, as you just saw.

Debug symbols add one more rule. Compile with -g to get names and line numbers in the file. They can make a binary several times bigger. Strip them for the image, keep the unstripped copy on the build host, and let gdbserver on the board talk to gdb on the host. Yocto does this split for you into -dbg packages.

The failure, as symptom, measurement and fix. Symptom: runs on the desk, dies on the board. Measurement: file camtool shows the chip; readelf -V camtool lists the needed tags; ldd --version on the board shows its library. Fix: build with the SDK that came from the same image, or link statically.

ON REAL HARDWARE Build an SDK with bitbake core-image-minimal -c populate_sdk for a Raspberry Pi 4 Model B. Source its environment script, compile a program that calls strlcpy, copy it over, and compare the output of readelf -V with ldd --version on the board.
A program built on an aarch64 Ubuntu laptop with glibc 2.39 fails on an aarch64 board with glibc 2.35: version `GLIBC_2.38' not found. Which fix is correct?

Chapter 2

Root Filesystems: BusyBox to systemd

Choose what goes in the folder that becomes the board’s root, and find out why one waiting service can hold up the whole boot

The robot is on the bench. You power it on and watch the console. The kernel finishes in two seconds. Then nothing happens for a very long time. The camera service you need has not started, and the log does not say why.

That wait belongs to the root filesystem, not to the kernel. To fix it you need to know what the root filesystem holds and who starts the programs in it.

What a root filesystem is

When the kernel finishes starting, it mounts one tree of files as /. This tree is the root filesystem, or rootfs. It holds the programs, the libraries, the settings in /etc and the device files. The kernel then runs one program from it, by default /sbin/init. That program has process number 1. Every other program on the board descends from it.

So init is the first program, and its job is to start the rest in the right order and to restart them if they die. Embedded images use two main kinds.

BusyBox init: small and plain

BusyBox is one program that behaves like hundreds of small tools. The binary checks the name you called it by and acts as ls, cp, sh or init. One file replaces a whole toolbox, which is why a rootfs with BusyBox can fit in a few megabytes. Its init reads a short text file, /etc/inittab, with lines such as “run this script at boot” and “respawn this program if it exits”. You can read the whole startup in one screen.

systemd: a service manager

systemd does more. It reads units, small files that name a service and say what it needs. A unit can say After= (start me later than X), Wants= (try to start X too) and Requires= (fail if X fails). systemd starts everything that does not depend on something else in parallel. It also gives you logging through journald, which keeps logs from all services in one indexed store, plus timers, sockets and control groups for limits on CPU and memory.

The price is size and complexity. A systemd rootfs is larger than a BusyBox one, and it has more ways to go wrong. The gain is a clear model of dependencies. Most Linux boards that run several services use it.

The wait that costs a minute or two

Many services say After=network-online.target. That target means “the network is up”. Something has to decide when it is up, and on many images that is systemd-networkd-wait-online. The systemd manual describes it as “a oneshot system service … that waits for the network to be configured”. Its --timeout= option fails the service if the network is not online in time, and the default is 120 seconds.

Now put the pieces together. The board boots in a lab with no cable plugged in. The camera service waits for the network that will not come. It gives up after the timeout, then starts. The operator sees a robot that takes two minutes to wake up.

Compose the rootfs, pull the cable

Pick an init system. Then unplug the cable and toggle whether the camera service waits for the network. Lower the wait-online timeout and watch the bar shrink.

120

Illustrative: 2.1 s for the kernel, 1.2 s (BusyBox) or 3.4 s (systemd) for init and base services, 2.5 s for a link that comes up. The 120 s default timeout of systemd-networkd-wait-online is from the systemd manual. With no cable, an ordered unit waits out the full timeout before starting.

With the cable out and the default timeout, the camera starts at about 125 seconds. Lower the timeout to 10 and it starts near 16. Remove the ordering and it starts at about 6, right after base services. Each of those three is a real fix, with a real cost: a short timeout may start the camera before the network exists, and no ordering means the service must cope with a missing network.

Find the wait with two commands

# every unit, slowest first
systemd-analyze blame
# the chain of units that actually held up the target
systemd-analyze critical-chain camera.service

Use both, because blame alone can mislead. The manual warns that “the initialization of one service might be slow simply because it waits for” another. critical-chain prints the tree of time-critical units, with @ for when a unit became active and + for how long it took. Read the chain from the bottom up and find the first long +.

The failure, as symptom, measurement and fix. Symptom: a boot that takes tens of seconds, only when the network is missing. Measurement: critical-chain shows systemd-networkd-wait-online.service with a long +. Fix: drop the After= from services that do not need the network, or lower the timeout, or change what “online” means for that link.

ON REAL HARDWARE On a Raspberry Pi 4 Model B running a systemd image, boot with the Ethernet cable out and run systemd-analyze and systemd-analyze critical-chain. Then plug the cable in and repeat. The difference is your wait-online cost.
An image boots in 6 seconds with a cable and in about 2 minutes without one. The camera unit has After=network-online.target. Which tool finds the real cause?

Chapter 3

Buildroot, Yocto, NixOS: Choosing

Compare three ways to make an image, and see what each does when you change one library

You fix a bug in a small compression library, libz. Your image also holds an image viewer that uses it, through a PNG library. You rebuild. Which of those three programs now contains your fix? The answer depends on which build system you chose, and that choice is hard to undo.

All three tools do the same job: take source code and a description of your device, and produce an image. They differ in how they think about the work.

Buildroot: one tree, one configuration

Buildroot is a set of Makefiles. You run make menuconfig, tick the packages you want, and run make. It builds a toolchain, then each package, then the rootfs and the image, into one output/ folder. It is simple to learn and quick for a small device. There are no layers: you add your own packages by editing the tree or by using an external folder.

Buildroot makes a release every three months, in February, May, August and November, named like 2025.02. Starting with 2025.02, the project runs a long-term support branch with three years of support, and a new one comes every two years.

Yocto: layers and recipes

The Yocto Project is a toolkit for building your own Linux distribution. BitBake reads recipes from layers (Chapter 0), caches every task in the sstate cache, and can produce an SDK for the same image. It handles many products from one set of layers, because a vendor, a distribution and your product each sit in their own layer. The price is a long learning curve and a large first build.

NixOS: describe the system, derive the files

Nix treats a build as a pure function. A derivation describes how to build one thing from named inputs. The result goes into the Nix store at a path like /nix/store/<hash>-hello, where the hash covers every input. Change any input, even a compiler flag, and the path changes. NixOS builds a whole operating system this way from one declarative file. The manual says that you “create or edit a description of the desired configuration of your system” and the tool builds it. Chapter 5 goes deeper.

Change libz, then rebuild

Choose a build system, then press Change libz and rebuild. The chain is libz, libpng, viewer. BusyBox is unrelated.

A model of the rule each tool follows. Buildroot: the rebuild target restarts one package and, per the manual, does not rebuild packages that depend on it. Yocto: dependents get new task signatures. Nix: dependents get new store paths. Hash equivalence in Yocto can skip a rebuild when the output bytes do not change.

Buildroot with make libz-rebuild rebuilds only libz. The manual is blunt: “When a package listed in FOO_DEPENDENCIES is rebuilt or removed, the package foo is not automatically rebuilt.” The viewer still carries the old code until you rebuild it too, or clean the tree. Buildroot tracks each step with files named .stamp_<step> in output/build/<package>-<version>/. The rebuild target works by removing some of those stamps. It also does not rebuild the final rootfs image: you still run make.

Yocto and Nix behave differently because they track inputs. In Yocto the signature of libpng’s tasks includes the signature of libz, so the change flows down the chain. BusyBox keeps its signature and comes back from sstate. Nix does the same with store paths. Neither depends on you remembering which targets to rebuild.

How to choose

Use a plain list of questions. How many products share the code? Buildroot suits one device; Yocto suits many. Who maintains the base? Yocto has a vendor ecosystem, so chip vendors often ship layers for it. Do you need to roll back a whole system safely? NixOS keeps old versions bootable. How fast must a newcomer build? Buildroot is the shortest path. Each tool has a cost, and you pay it on the first day or the five-hundredth.

The failure, as symptom, measurement and fix. Symptom: the fix is in the source tree but the board still shows the old behaviour. Measurement: in Buildroot, look at the .stamp_* files and the timestamps of the dependents. Fix: rebuild the dependents too, or run a clean build when a low-level library changes.

ON REAL HARDWARE Build the same Raspberry Pi 4 Model B image with Buildroot. Change a low-level library, run its rebuild target, run make, and check the dependent program’s binary timestamp in output/target to see if it changed.
In Buildroot you run make libz-rebuild and then make. The viewer, which links libz dynamically, does not pick up the change in its own build. Why?

Chapter 4

Yocto Anatomy: Layers, Machine, Distro, Image, sstate

Learn the six objects Yocto is made of, and predict what a change rebuilds before you press go

A colleague changes one line in local.conf and the build takes four hours. You change a patch in a single library and it takes four minutes. Both are correct. To tell why, you need Yocto’s object model, which is smaller than it looks.

The six objects

A layer is a folder of metadata with a conf/layer.conf that sets its priority (Chapter 0). A recipe builds one package. A machine (MACHINE) describes the board: its chip family, kernel, boot loader. A distro (DISTRO) describes policy: which init system, which C library, which features such as systemd or Wi-Fi. An image recipe lists which packages go into the rootfs. sstate is the cache. Put another way: the machine says where, the distro says how, the image says what, the layers say who wrote it, and sstate says what we can skip.

Each recipe runs a fixed chain of tasks: fetch the source, unpack, patch, configure, compile, install, package. Tasks hold the real work. You call them by name: bitbake zlib -c compile runs the chain up to compile.

How sstate decides to skip

For each task BitBake computes a signature, a hash over everything the task reads: the recipe text, the variables it uses, the patches, and the signatures of the tasks it depends on. If a saved output exists for that hash, BitBake restores it. If not, it runs the task. The manual says this “supports incremental builds” and lets machines share task output.

Two consequences follow. A change that no task reads, such as a variable nobody uses, changes no signature and rebuilds nothing. A change that every task reads, such as the global compiler flags, changes every signature and rebuilds everything. The four-hour build was the second kind.

Predict the rebuild

Choose what you edit. Then see which recipes rerun. Switch the sstate cache off to see the cost of having none.

A model of signature propagation. The chain zlib, libpng, viewer and the unrelated busybox are illustrative; the rule (a task reruns when its signature, which includes the signatures of what it depends on, has no saved output) is from the Yocto documentation.

Patch zlib and three recipes rerun, because libpng and the viewer depend on it. Edit the viewer’s recipe and only the viewer reruns. Change the unused variable and nothing reruns at all. With the cache off, everything reruns every time.

Appends, the image and the SDK, once more

Your product normally adds three things in its own layer: a machine file for your board, a distro file for your policy, and an image recipe. The bbappend (Chapter 0) patches other layers’ recipes without editing them. When you need the same toolchain on a developer laptop, you build an SDK from the image. The SDK manual lists what it holds: a cross-development toolchain, sysroots and an environment setup script. The extensible SDK adds devtool.

devtool: the edit loop

# unpack the source of a package into a workspace you can edit
devtool modify busybox
# build and test just this recipe
devtool build busybox
# turn your commits into a patch and a bbappend in your layer
devtool finish busybox meta-mine

The loop gives you a normal Git tree for the source and writes the right bbappend for you at the end, so you do not hand-write the filename that caused Chapter 0.

Releases and support

The release page says a new Yocto LTS arrives every two years and is supported for four. Release 5.0 “Scarthgap” came in April 2024 and is supported until April 2028. Release 6.0 “Wrynose” came in May 2026 and is supported until April 2030. Buildroot works differently: a release every three months, and one long-term branch every two years with three years of support. Pick a long-term release for a product you must patch for years.

Three more ways a build fails

Stale sstate. A mirror holds outputs built with other settings. Symptom: a package behaves as it did last week. Measurement: bitbake-diffsigs or bitbake -e shows which variable differs. Fix: clean the task with -c cleansstate. Offline fetch failures. A build box without network cannot fetch sources. Set BB_NO_NETWORK = "1" to see every missing download at once, then fill a mirror. Licence allow-lists. A distro can refuse recipes whose licence you have not approved, so a package appears to be missing. Read the error: it names the licence flag.

ON REAL HARDWARE Build core-image-minimal for a Raspberry Pi 4 Model B twice. Time the second build after changing one recipe, then change a global flag and time it again. The ratio is the sstate cache at work.
You change a global compiler flag in the distro configuration. What does the sstate cache do?

Chapter 5

NixOS on a Vendor Board

See how generations make an update reversible, and what breaks when a vendor kernel patch meets a new baseline

A robot in the field gets an update. It boots, the camera driver is broken, and the robot is three hours away. On most embedded systems you now need a technician. On NixOS you pick the previous entry from the boot menu, and the old system is back, unchanged.

That is the promise of NixOS. This chapter shows the mechanism, then the hard part: chip vendors ship their own kernels, and fitting them into NixOS is real work.

Store paths, closures, generations

Chapter 3 showed that Nix builds everything into /nix/store/<hash>-name, where the hash covers every input. Two builds with different inputs never overwrite each other. They sit side by side.

A closure is a path plus everything it needs to run: its libraries, their libraries, and so on down. Copy a closure to another machine and the program runs there, because nothing is missing. A whole system is one closure: kernel, rootfs, services, settings.

Each time you change the configuration and switch, NixOS builds the new closure and records it as a new generation. The manual says that “every time you change the NixOS configuration … a new item is added to the menu”, which “allows you to easily roll back to a previous configuration if something goes wrong.” Going back does not rebuild or undo anything. It just points the boot at an older closure that is still on disk.

Why a vendor board is hard

A chip vendor such as NVIDIA ships a board support package (BSP): a kernel with their drivers, device trees for their boards, firmware and a flashing tool. It targets one baseline, often an Ubuntu release. NixOS wants its own package set. Someone must glue the two.

The community project jetpack-nixos does this for NVIDIA Jetson. Its README says it packages JetPack components for NixOS: flashing scripts, a Linux kernel from JetPack that includes some open-source drivers, UEFI firmware, and GPU libraries such as CUDA and TensorRT. It supports JetPack 5, 6 and 7, and which one you can use depends on the module: Orin modules work with all three, Thor needs 7 and Xavier needs 5. On JetPack 6 and later you can switch to a mainline kernel. It is a community project, so treat it as such: read the code and test on your own module.

The work has a pattern. You overlay the vendor kernel and device tree onto the NixOS package set. You carry a few patches on top. And each time the NixOS baseline moves, you forward-port the patches: edit them until they apply to the new source again. Fewer and smaller patches mean less of this work. Sending patches upstream removes them from your list for good.

Think of a generation as a bookmark in a book that is never erased. Switching adds a bookmark. Rolling back moves you to an earlier one. The pages stay where they were, so a rollback costs seconds and needs no network. A rollback does not need the new build to be good; it only needs the old closure to still be on disk, so keep a few generations and clean old ones on a schedule, not by hand.

Why not simply keep the vendor image? Because the vendor image is a fixed snapshot. It is hard to rebuild from source, hard to pin, and its update path is often a full reflash. A NixOS system gives you the opposite trade: you own the whole description, you can rebuild it anywhere, and each update is a small switch. The price is the BSP glue you now maintain. Choose it when the fleet is large enough that safe rollback and exact rebuilds repay that work.

Switch, upgrade, roll back

Add the vendor kernel patch, then upgrade the baseline. See the patch fail to apply. Forward-port it, upgrade again, then roll back.

A model of the workflow. Baselines A and B, the patch and the conflict are illustrative. Generations and the boot-menu rollback are as the NixOS manual describes. The model never leaves the board on a broken system: a failed build adds no generation.

Watch the order in the model. The failed upgrade does not break the board, because the build fails before any switch. The patch must be forward-ported first. And a rollback only picks an existing generation.

The failure, as symptom, measurement and fix. Symptom: a baseline upgrade stops with a patch that does not apply. Measurement: the build log names the file and the hunk that fails. Fix: port the patch by hand against the new source, shrink it, and offer it upstream so you carry less next time.

ON REAL HARDWARE On a Jetson module supported by jetpack-nixos, run nixos-rebuild switch, reboot, and pick the previous entry from the boot menu. Compare uname -r in both generations to prove the old kernel is still there.
A NixOS baseline upgrade fails because your vendor kernel patch no longer applies. What is the state of the board?

Chapter 6

Storage and Filesystems for Flash

Follow one saved setting from write() to the flash chip, then cut the power at each step and see what survives

A robot saves its calibration to a file. The operator pulls the battery a second later. On the next boot the calibration file is empty, and the arm swings to a wrong position. The program called write() and got a success. So where did the data go?

Where the bytes wait

When a program calls write(), the kernel copies the bytes into memory, the page cache, and returns at once. The disk is slow, so the kernel writes the data out later. That gap is the danger: if power fails in the gap, the bytes are gone. A call to fsync on the file tells the kernel to push that file’s data to the storage and wait until it is there.

Saving a file safely has one more twist. The standard trick is to write a new file under a temporary name, then rename() it over the old name. Rename is atomic: a reader sees the old file or the new one, never half of each. But the new file’s name lives in the directory, and the directory is data too. The Linux man page says: “Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed.”

So the safe order has four steps: write the temp file, fsync it, rename it, fsync the directory. Try cutting the power after each one.

Save, then pull the plug

Turn the two fsync calls on or off. Drag the power cut along the four steps. Choose what the cache had flushed on its own.

3

A simplified model: it assumes the kernel may reorder what it has not been told to flush, which is the worst case POSIX allows. Real ext4 is kinder to one pattern: its default auto_da_alloc option detects replace-via-rename and forces the new data out first. Do not count on that on other filesystems.

With both calls on, no cut position ever gives a corrupt file. You get the old config or the new one. Turn off the first fsync, pick the second adversary and cut after step 3: the name points at data that never reached flash, so you get an empty or garbage file. That is the calibration bug from the opening. The rename was safe; the data was not.

Four filesystems for four jobs

ext4 keeps a journal, a small log of metadata changes, so it can recover fast after a crash. The kernel docs list three data modes. data=ordered, the default, writes the data to the main filesystem before committing its metadata. data=journal logs the data too, at the cost of writing it twice. data=writeback keeps no ordering. The journal commits every commit= seconds, five by default.

F2FS is built for flash. It never overwrites in place; it appends to the log and leaves old blocks as garbage. The kernel docs say it divides the volume into segments “fixed to 2MB in size”, cleans in the background when idle, and cleans on demand “when there are not enough free segments”. That on-demand cleaning is the catch: a nearly full F2FS volume stalls writes while it cleans, and you see latency spikes. Measure them with fio and iostat.

Write amplification is the flash bytes written divided by the bytes your program asked to write. It matters because flash wears out. Journalling data and moving live data during cleaning both raise it. A log that rewrites a 4 KB file as 4 KB plus 4 KB of journal has an amplification of 2.

squashfs is, in the kernel docs’ words, “a compressed read-only filesystem”. It is ideal for a root that must never change. To keep some things writable, you stack an overlayfs on top: a read-only lower layer and a writable upper layer. The docs show the mount as lowerdir=/lower,upperdir=/upper,workdir=/work. A write to a lower file first copies it to the upper layer. UBIFS is the choice for raw NAND chips, with wear levelling handled by the UBI layer under it. Managed storage such as eMMC hides all this behind its own controller.

The failure, as symptom, measurement and fix. Symptom: settings that do not persist on a read-only squashfs root with a tmpfs overlay. Measurement: mount shows the upper layer on tmpfs, so it lives in RAM and vanishes at reboot. Fix: a dedicated writable partition for state, with the save procedure above. For wear, mmc extcsd read /dev/mmcblk0 from the mmc-utils package reads the eMMC’s extended registers, which include health fields.

ON REAL HARDWARE On a Raspberry Pi 4 Model B, run the save procedure in a loop on an ext4 partition and cut power at random with a switched supply. Count empty files after 50 cuts with and without the fsync calls.
You write config.tmp, fsync it, rename it to config, and never fsync the directory. Power fails right after the rename. What can the next boot show?

Chapter 7

Reproducibility, SBOMs and Licensing

Prove what is inside an image, rebuild it bit for bit, and meet the duties that come with the code you ship

A customer reports a bug in an image you shipped a year ago. You rebuild it from the same sources. The new image works differently, and you cannot say why. Or a customer asks which open-source parts are in the box, and you spend a week finding out.

Both problems come from the same gap: the image was built, but not recorded. This chapter closes it with three tools: reproducible builds, an SBOM, and licence compliance.

Reproducible builds

The Yocto test manual defines it this way: a build is reproducible when a given input configuration gives the same binary output, whenever and wherever you build it. Same inputs, same bytes. You can check it by comparing hashes.

What breaks it? Anything that leaks the build environment into the output. The usual culprits are the build time stored in a file header, the path of the build folder, and the order of files in an archive. The standard cure for time is the SOURCE_DATE_EPOCH environment variable: a fixed timestamp that tools use instead of the clock. Yocto sets a value per recipe for you in reproducible_binaries.bbclass. The project tests this with an oe-selftest case, and when two builds differ, diffoscope can show which bytes moved.

Here is a worked check. Build the root filesystem twice in two folders. Run sha256sum on both files. Say the first digest starts 9f3a and the second starts c17e (toy values). They differ, so something leaked. Run diffoscope on the two files. It unpacks the archives and shows the first differing byte, perhaps a build time in a header. Fix that one leak, build again, and the digests match. One leak at a time is the whole method.

Why care? Because a reproducible image lets anyone check that a binary really came from the published source. And because you can fix one bug in a year-old image without moving anything else.

The SBOM

An SBOM (software bill of materials) is a list of every component in the image, with versions, licences and sources. Think of the ingredient list on a food package. The Yocto manual says the build system generates it by default through the create-spdx class, in SPDX format, a standard data format for such lists. Build an image and you find IMAGE-MACHINE.spdx.json in tmp/deploy/images/MACHINE/. You can also make a recipe-only SBOM with bitbake <recipe> -c create_recipe_sbom.

Licences and the GPL

Every package has a licence, and each licence has duties. The licence of the Linux kernel and of BusyBox is the GPL version 2 (the kernel adds an exception for user programs that call it). Other parts use permissive licences, such as Apache 2.0 for OpenSSL 3. The duty that catches companies is in section 3 of the GPL version 2: when you give someone the binary, you must either “accompany it with the complete corresponding machine-readable source code”, or accompany it with “a written offer, valid for at least three years” to supply that source.

“Give someone” includes selling a device that contains the image. So the duty starts the day you ship. Version 3 of the GPL has its own, stricter terms. This lesson is engineering notes, not legal advice; ask a lawyer about your product.

Ship the image, then audit it

The image holds four parts. Choose what your release process does. The tree shows which duties are met.

The packages are an illustrative image. The GPL v2 section 3 duty and the SPDX file name are from the licence text and the Yocto manual. The two hashes are a toy: one byte of the stored time changes between builds. This is not legal advice.

Start with everything off. The kernel and BusyBox are GPL parts with an unmet duty, the SBOM is missing, and two builds differ because each stored its own build time. Turn on the source offer and the SBOM, and turn off the stored time. Now the duties are met and the two hashes match.

The failure, as symptom, measurement and fix. Symptom: a customer asks for the source of the kernel in your device, and you have none for that exact build. Measurement: the SBOM lists the GPL parts, and your release folder either holds the matching source archives or it does not. Fix: archive sources with every release, tie them to the image version, and keep them for the full offer period.

ON REAL HARDWARE Build core-image-minimal for a Raspberry Pi 4 Model B twice, in two different build folders, and compare the root filesystem images with sha256sum. If they differ, run diffoscope on them.
Two builds of the same commit produce different image hashes. What is the first thing to check?

Chapter 8

Field Guide

Keep the numbers, the checklist and the resolver in one place, and send yourself to the right next lesson

An image is a set of files, and every file comes from a choice made by a build system. This lesson followed those choices from a bbappend (Chapter 0) through libraries, init, three build tools, the cache, the Nix store, flash storage and licences. The common thread: the build must be explainable. For any byte on the board you should be able to say which recipe, which version and which layer put it there.

Term or numberValueSource
Version choice orderPREFERRED_VERSION, then layer priority, then DEFAULT_PREFERENCE, then highest versionBitBake bb/providers.py
bbappend wildcardsomeapp_6.%.bbappend matches every 6.xYocto dev manual, layers
Higher priority wins“A larger value … results in a higher precedence”BitBake variables glossary
Yocto LTSEvery 2 years, 4 years of support. 5.0 Scarthgap: Apr 2024 to Apr 2028. 6.0 Wrynose: May 2026 to Apr 2030Yocto release process
Buildroot releasesEvery 3 months (Feb, May, Aug, Nov). LTS from 2025.02, 3 years, one every 2 yearsBuildroot manual, LTS page
Buildroot rebuildRebuilds one package; dependents are not rebuiltBuildroot manual
wait-online timeout120 s by defaultsystemd-networkd-wait-online man page
ext4 commit interval5 s by default; data=ordered is the default modeLinux ext4 docs
F2FS segment2 MB; background and on-demand cleaningLinux F2FS docs
squashfs block sizeDefault 128 KB, up to 1 MBLinux squashfs docs
GPL v2 offerWritten offer valid for at least 3 yearsGPL v2, section 3(b)
cgroups v1Removed in systemd 258; only v2 remains (secondary reports, check the release notes)LWN, Linuxiac

The image-build debugging checklist

The resolver as code

This is the whole of the hero in a few lines of Python. The real BitBake does the same, with more bookkeeping.

def resolve(recipes, preferred=None, append="1.%"):
    # recipes: [{"layer": "meta", "prio": 5, "ver": "1.36.1"}, ...]
    win = next((r for r in recipes if r["ver"] == preferred), None)
    if win is None:
        top = max(r["prio"] for r in recipes)          # rule 2: layer priority
        pool = [r for r in recipes if r["prio"] == top]
        win = max(pool, key=lambda r: tuple(map(int, r["ver"].split("."))))  # rule 3
    pat = re.compile("^" + re.escape(append).replace("%", ".*") + "$")
    matched = [r for r in recipes if pat.match(r["ver"])]
    if not matched:
        raise SystemExit("append matches no recipe file")   # loud failure at startup
    return win, win in matched                          # (what is built, does the append apply)

Keep going

Before this lesson: the Linux boot chain, which starts the kernel your rootfs then serves. After it: secure boot and OTA updates, which sign and replace the image you now know how to build. Related: Embedded Linux, Real-time Linux, Embedded systems intro, Advanced C, and from the vector table to main for the microcontroller side of boot.

Sources

Yocto Project documentation: layers, release process, SBOM, SDK manual. The BitBake variables glossary and its source file providers.py. Buildroot manual and LTS page. NixOS manual, the Nix derivations reference, and the community jetpack-nixos project. Linux kernel docs for ext4, F2FS, squashfs and overlayfs; man pages for fsync and readelf; the systemd-analyze and wait-online pages; the GPL v2. Not opened for this page: the NixOS Jetson notes in nixos-hardware, and the job-posting counts from the planning notes, which are left out.

The takeaway. BitBake resolves by name, version and layer priority, and every other step of an image build has a rule just as plain. Learn the rules and a build that did nothing stops being a mystery.

Teach it back with Teach or practise the story with Present, then go back to the resolver at the top and predict each result before you press.

A newer BusyBox sits in a low-priority layer and an older one in a high-priority layer. No PREFERRED_VERSION is set. Which is built?
Building the Image
Yocto docs · Buildroot manual · Back to Gleams