indicogniBuild a VMM

Contents

Chapter 10 · Part IV

The Device Tree: the VMM's promise to the guest

Needs a Mac Runs in browser ~4.5 h Lab: DTB explorer
11 of 26

Course progress: chapter 10 is 11 of the 26 chapters written so far (numbering starts at 00)

Warm-up: three questions from earlier chapters

Answer each one in your head or on paper before you open its answer. They change on each visit.

  1. From chapter 09: A device is a state machine: the bus, PL011 and PL031

    A guest reads the PL011's flag register FR and gets 0x90. May it write a byte to DR now, and is there a byte for it to read?

    Show answer

    0x90 is bit 7 (TXFE, transmit FIFO empty) plus bit 4 (RXFE, receive FIFO empty). It may send: the transmit side is empty, so TXFF (full) is clear. There is nothing to read: RXFE says the receive FIFO is empty, and a DR read now would return 0.

  2. From chapter 07: The exit loop: decoding syndromes and emulating MMIO

    A data-abort exit carries the syndrome 0x93820046. Without looking at guest memory, say the direction, the size and the register of the access, and name one instruction that fits.

    Show answer

    EC is 0x93820046 >> 26 = 0x24, a data abort from the guest. Bit 24 (ISV) is 1, so the note is valid. SAS (bits 23:22) is 2, so 4 bytes; SSE is 0; SRT (bits 20:16) is 2; SF is 0, so a 32-bit w register; WnR (bit 6) is 1, a write. A 4-byte store from w2, such as str w2, [x1].

  3. From chapter 03: A guest of your own, and what an exit costs

    A guest prints ok and a newline through DEBUG_PUTC, then powers off. How many records with "ec":"0x16" does --trace exits:t.jsonl:hvc write, and why?

    Show answer

    Four. Each printed byte is one hvc (three bytes: o, k, newline), and the power-off call is one more hvc. Every one is an exception of class 0x16.

Concepts you'll need

Chapters before this one: chapter 09, A device is a state machine: the bus, PL011 and PL031.

  • Core, taught here: why Arm platform devices cannot be probed; the Device Tree (nodes, properties, unit addresses, compatible, reg, #address-cells and #size-cells, cells, /chosen, phandles); the flattened format (FDT): header, reservation map, structure tokens, deduplicated strings, alignment, the 2 MiB cap, big-endian; driver binding by compatible; the DTB as a promise generated from the device table; fresh seeds; handing it over in x0.
  • Core, from earlier: layout.rs, the single memory map (chapter 05); the unhandled-MMIO (memory-mapped I/O) policy, --unhandled-mmio fatal|log (chapter 05); MPIDR_EL1, the register dump and last exits (chapters 06 and 07); PSCI (power state coordination interface) calls over hvc (chapter 08); the PL011, the PL031, their PrimeCell identification registers and the Bus (chapter 09).
  • Primers (read first): arm64-boot-protocol (what a kernel expects in x0 and where the DTB goes in RAM); reading-arm-specs (finding the header layout in chapter 5 of the Devicetree Specification).
  • Pointers: PCI enumeration and ACPI (an Aside: why a PC can probe); the kernel command line; fixed clocks and the clock binding; dtc as a checking tool; the Devicetree Specification v0.4, chapter 5. For the curious: the AArch64 reading primer (byte order) and the Linux boot sequence primer (how a node becomes a driver).
  • Forward definitions: interrupt properties and the interrupt controller node (chapter 12); the --irqchip none mode (chapter 11); the initramfs range and the kernel command line in /chosen (chapter 13); kernel address randomization (chapter 14). Each is defined in a sentence where it first appears.

Move one device. In layout.rs, move the PL011 serial port from 0x0900_0000 to 0x0904_0000, rebuild the virtual machine monitor (VMM), and run two test guests that have not been rebuilt. One dies on its first write to the serial port. The other reports the new address, correctly, without ever having been told. Which one, and where did it learn the address?

This chapter closes row 5 of chapter 00's problem ledger, a description of the machine: a kernel assumes somebody hands it one. Sitting A finds out why and reads a real description byte by byte (about 2 hours: one VMM run, then dtc, grep and xxd). Sitting B builds the writer and the machine's tree, hands it to the guest and breaks it (about 2.5 hours).

Objectives: by the end you can

  • (Sitting A) Explain, with the moved-PL011 runs as evidence, why a general kernel cannot hardcode device addresses and why Arm platform devices cannot be probed.
  • (Sitting A) Predict the byte length of a reg property from the parent's #address-cells and #size-cells, then check it in a hex dump of the reference's blob (and of yours, in sitting B).
  • (Sitting A) Decode a flattened device tree header by hand (magic, totalsize, the three block offsets, version 17, last compatible version 16) and diagnose a corrupted strings offset from what dtc reports.
  • (Sitting B) Implement a dependency-free writer that emits the header, an 8-byte-aligned reservation map, structure tokens and a deduplicated strings block, all big-endian, and refuses a property after a child, an unbalanced end, a name with a NUL and a blob over 2 MiB.
  • (Sitting B) Generate /memory, /cpus, /psci (method = "hvc"), /timer, the PL011 with its fixed clock, the PL031 and /chosen from layout.rs, fill the seeds from host randomness, and pass the blob's address in x0.

Before you start. From the repository root, run scripts/learner start 10; it copies this chapter's journal to learner/journal/10.md. Sitting A runs the reference from the repository root, where $G stands for target/guests/aarch64-unknown-none/release. Sitting B is your code, in learner/, where you set G=../target/guests/aarch64-unknown-none/release as in chapter 09.

Move one device, break one guest

We ran the opening experiment on the reference. It took two edits in layout.rs: PL011_BASE to 0x0904_0000, and GICR_WINDOW_END, which the reference defines as PL011_BASE (the interrupt controller's window ends where the serial port begins), pinned at 0x0900_0000 so that window does not grow over the PL031. First dtb-reader, a test guest that prints what it finds in the machine description it was handed:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --timeout 10exit: 0--- stdout ---dtb-reader: x0=0x40000000dtb-reader: magic okdtb-reader: model=macvmm-virtdtb-reader: memory@40000000 reg=0x40000000+0x4000000dtb-reader: pl011@9040000 compatible=arm,pl011dtb-reader: cpus=1dtb-reader: stdout-path=/pl011@9040000dtb-reader: rng-seed nonzerodtb-reader: kaslr-seed nonzerodtb-reader: done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Edit: PL011_BASE in crates/vmm/src/arch/layout.rs moved from 0x0900_0000 to 0x0904_0000, and GICR_WINDOW_END (defined there as PL011_BASE) pinned at 0x0900_0000 so the interrupt controller's window does not grow over the PL031.
  • Run in a copy of the reference with those two edits; $G is target/guests/aarch64-unknown-none/release.
course/captures/10-moved-dtb-reader.txt

It reports the serial port at its new address, pl011@9040000, which it can only have learned from that description. (It prints through chapter 03's debug hypercall, not through the UART, the universal asynchronous receiver-transmitter, so this run shows it finding the device, not driving it.) Now uart-echo, chapter 09's guest, which writes to the UART:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10exit: 3--- stderr ---macvmm: guest fatal: unhandled MMIO write at 0x900002c size 4 pc 0x40081184vcpu0: data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) SSE=0 SRT=9 SF=0 AR=0 FnV=0 S1PTW=0 WnR=1 DFSC=0x6 (translation fault)  esr=0x93890046 ipa=0x900002c  x0=0x0000000040000000 x1=0x0000000000000000 x2=0x0000000000000000 x3=0x0000000000000000  x4=0x0000000000000000 x5=0x0000000000000000 x6=0x0000000000000000 x7=0x0000000000000000  x8=0x000000000900002c x9=0x0000000000000070 x10=0x0000000040083000 x11=0x0000000000000001  x12=0x0000000000000000 x13=0x0000000000000000 x14=0x0000000000000000 x15=0x0000000000000000  x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000000000000 x19=0x0000000000000000  x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000  x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000  x28=0x0000000000000000 x29=0x0000000000000000 x30=0x0000000040081050  sp_el0=0x0 sp_el1=0x400930e0  pc=0x40081184 cpsr=0x600003c5 (EL1h, DAIF, nZCv)  ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0  VBAR_EL1=0x40080800 SCTLR_EL1=0x30000180 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0  insn at pc: 0xb9000109last exits: 1 (oldest first)  {"t_ns":245875,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081184","ipa":"0x900002c","wnr":true,"size":4,"reg":9,"action":"stop","isv":true}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Edit: PL011_BASE in crates/vmm/src/arch/layout.rs moved from 0x0900_0000 to 0x0904_0000, and GICR_WINDOW_END (defined there as PL011_BASE) pinned at 0x0900_0000 so the interrupt controller's window does not grow over the PL031.
  • Run in a copy of the reference with those two edits; $G is target/guests/aarch64-unknown-none/release.
course/captures/10-moved-uart-echo.txt

Exit code 3, an unhandled memory-mapped I/O (MMIO) write at 0x900002c: offset 0x2c of the old address, the PL011's line-control register, the first thing uart-echo configures. The register dump from chapter 06 shows the address in x8. Nothing answers there any more, so chapter 05's policy stopped the guest. Here is why it wrote there:

guests/common/uart.rslines 22-24
/// PL011 UART0 and PL031 RTC in the QEMU `virt` map, baked into the guest at build time.pub const PL011_BASE: usize = 0x0900_0000;pub const PL031_BASE: usize = 0x0901_0000;

uart-echo was compiled with the address baked in. That is fine for a test guest built for one board. A kernel that ships to thousands of different boards cannot do it: it would need one build per board, and every board maker who moved a device would need a new kernel.

Why a kernel cannot look for itself

A tempting way out: let the kernel read every address in the first 4 GiB until something looks like a UART. The first obstacle: an address with no device behind it does not politely answer "nothing here". On real hardware the access can fault or hang the bus, and in our VMM it is the unhandled access you saw above, fatal by default.

The second: even a device that can identify itself only does so once you know where to ask. The PrimeCell identification registers of chapter 09 sit at offsets 0xFE0 to 0xFFC of the device. To probe hardware means to find it by asking for it, and the devices on an Arm board's on-chip bus give you nobody to ask.

Aside

A PC can probe, because PCI (Peripheral Component Interconnect, the expansion bus) was designed for it: every PCI device answers at a fixed configuration address with its vendor and device number (PCI enumeration). What PCI cannot find, the firmware describes in ACPI tables (Advanced Configuration and Power Interface, specification at the UEFI Forum). Arm servers use ACPI too; embedded Arm boards and our VMM use a device tree.

So someone who knows the machine has to describe it. On a physical board that is the firmware; in a virtual machine it is us. The description is a Device Tree (DT), and the binary blob a kernel receives is a DTB (device tree blob). The arm64-boot-protocol primer gave its address: register x0, at the kernel's first instruction. For Linux on arm64 this is not optional configuration: the DTB is its only map of the machine, so a wrong tree is a wrong machine. That answers the opening: dtb-reader learned the new address from the DTB, and uart-echo, which never looks, died at the old one.

A tree of nodes and properties

Let us look at one. --dtb-out writes the blob a run handed its guest to a file. We add --irqchip none, a mode chapter 11 introduces that leaves out the interrupt controller, so the tree matches what you build in this chapter (chapter 12 adds the rest):

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --irqchip none --raw $G/hello.bin@0x40080000 --dtb-out v.dtb --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run in an unmodified copy of the reference, from its root; $G is target/guests/aarch64-unknown-none/release; v.dtb is written in the current directory (removed first).
course/captures/10-dtb-out-run.txt

The dtc (device tree compiler) turns a blob back into text, its source form (DTS, device tree source). Install it with brew install dtc (we assume Homebrew; without it, the checkpoint reports its dtc step as INFO, and you can follow the hex dumps here instead). It is an independent checker, written by other people, that knows nothing about our VMM; the dtc repository documents it.

TerminalReal output
dtc -I dtb -O dts v.dtbexit: 0--- stdout ---/dts-v1/;/ {	compatible = "linux,dummy-virt";	model = "macvmm-virt";	#address-cells = <0x02>;	#size-cells = <0x02>;	dma-coherent;	chosen {		stdout-path = "/pl011@9000000";		rng-seed = <0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00>;		kaslr-seed = <0x00 0x00>;	};	memory@40000000 {		device_type = "memory";		reg = <0x00 0x40000000 0x00 0x4000000>;	};	cpus {		#address-cells = <0x01>;		#size-cells = <0x00>;		cpu@0 {			device_type = "cpu";			compatible = "arm,arm-v8";			reg = <0x00>;			enable-method = "psci";		};	};	psci {		compatible = "arm,psci-1.0", "arm,psci-0.2", "arm,psci";		method = "hvc";	};	timer {		compatible = "arm,armv8-timer", "arm,armv7-timer";		always-on;	};	apb-pclk {		compatible = "fixed-clock";		#clock-cells = <0x00>;		clock-frequency = <0x16e3600>;		clock-output-names = "clk24mhz";		phandle = <0x02>;	};	pl011@9000000 {		compatible = "arm,pl011", "arm,primecell";		reg = <0x00 0x9000000 0x00 0x1000>;		clocks = <0x02 0x02>;		clock-names = "uartclk", "apb_pclk";	};	pl031@9010000 {		compatible = "arm,pl031", "arm,primecell";		reg = <0x00 0x9010000 0x00 0x1000>;		clocks = <0x02>;		clock-names = "apb_pclk";	};};
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • v.dtb is the file the run in 10-dtb-out-run wrote.
course/captures/10-dtc-dts.txt

Read it as a filesystem. Each node is a directory, / is the root, and the nodes are named name@unit-address, where the unit address repeats the device's first address. Each property is a named value, like a small file. The picture breaks quickly: a node cannot hold data except in properties, and the order of things inside the blob matters, as sitting B shows.

The values are counted in cells: 32-bit numbers, stored big-endian, most significant byte first (the opposite of the little-endian order of the AArch64 reading primer). <0x00 0x9000000 0x00 0x1000> is four cells.

What a kernel learns from each node:

NodeProperties that matterWhat the kernel learns
/compatible = "linux,dummy-virt", model, #address-cells = <2>, #size-cells = <2>, dma-coherenta generic virtual board, and its name; how its children write addresses; devices see memory as the CPU does
/chosenstdout-path, rng-seed, kaslr-seedwhere to print first, and random seeds; settings, not a device
/memory@40000000device_type = "memory", regwhere RAM is and how much (64 MiB here)
/cpus/cpu@0device_type = "cpu", reg = <0x00>, enable-method = "psci"one CPU, identity 0, started through PSCI
/pscimethod = "hvc"PSCI calls go through hvc, chapter 08's path
/timercompatible = "arm,armv8-timer", always-onthe CPU has Arm's generic timer (chapter 11), and it keeps counting in low-power states
/apb-pclkclock-frequency, #clock-cells = <0>, phandle = <0x02>a fixed 24 MHz clock others can point to
/pl011@9000000, /pl031@9010000compatible, reg, clockswhich device, where, and which clock feeds it

Every row is a promise: something answers at that address, behaving like that.

Two root properties promise things about the whole board. linux,dummy-virt is what Linux matches for a generic virtual machine with nothing board-specific to set up. dma-coherent says devices that read and write RAM themselves (direct memory access, chapter 15) see what the CPU's caches see, so no cache flushing is needed; true here, because guest RAM is ordinary host memory.

compatible names the device, most specific first: "arm,pl011" (exactly this UART), then "arm,primecell" (the family whose identification registers chapter 09 built). What each property of a device means is set by its binding document, one short schema per kind of device in the Linux source tree. And compatible is how a kernel picks a driver: each driver lists the strings it handles, and the kernel attaches a driver to every node that matches, driver binding (a different use of the word). For PrimeCells the bus code also reads the identification registers at 0xFE0 before it trusts the match; the Linux boot sequence primer walks the whole path.

reg lists (address, size) pairs. How many cells is each address? That is not in reg. It is in the parent's #address-cells and #size-cells: the root says 2 and 2, so the PL011's reg is one range of four cells, address 0x0_0900_0000, size 0x1000. /cpus says 1 and 0, so cpu@0's reg is one cell and no size.

/chosen describes no device: it carries settings for the operating system, here its console, and in chapter 13 the kernel command line, bootargs (the kernel's admin guide lists its parameters, such as console= and root=).

A phandle is a number a node is given so other nodes can point at it. The clock's #clock-cells = <0> says a reference to it is one cell, the phandle alone, so the PL011's clocks = <0x02 0x02> is two references to /apb-pclk, one for each of its two clock-names. The PL011 needs that clock because its driver asks for its rate, and Linux's PrimeCell bus will not attach a driver to a device whose apb_pclk (the clock of the APB, Arm's Advanced Peripheral Bus) is missing; the fixed-clock binding describes the node. Linux also says a driver "probes" a device when it attaches to a node it was told about; that is driver binding, not discovery.

rng-seed and kaslr-seed are random numbers: the first for the guest's random-number generator, the second for kernel address space layout randomization (KASLR, chapter 14). --dtb-out writes zeros in their place, so a saved file never records a real boot's secrets.

Open the explorer and load the same tree, or your own --dtb-out file (it is parsed in your browser, never uploaded). Click a node to see its bytes:

Lab

DTB explorer

Open a device tree blob, click a node to see its bytes, and watch #address-cells decide how every reg is read.

Runs in browserOpen full page: DTB explorer
DTB explorer: the PL011 node in the chapter's blob Bytes 0x310 to 0x35f of the --dtb-out file. At 0x310, 00000001 is FDT_BEGIN_NODE, followed by the name pl011@9000000, a NUL and padding. At 0x324, 00000003 is FDT_PROP with length 0x18 and name offset 0, the compatible property, whose value is arm,pl011 NUL arm,primecell NUL. At 0x348, a second FDT_PROP with length 0x10 and name offset 0x65 is reg: four cells 00000000 09000000 00000000 00001000. The root says #address-cells 2 and #size-cells 2, so reg is one range: address 0x0900_0000, size 0x1000. pl011@9000000 in the blob (from xxd -s 784 -l 80 v.dtb) 0310: 00000001 706c3031 31403930 30303030 FDT_BEGIN_NODE "pl011@9000000" 0320: 30000000 00000003 00000018 00000000 FDT_PROP len 0x18 nameoff 0 0330: 61726d2c 706c3031 31006172 6d2c7072 "arm,pl011\0arm,pr 0340: 696d6563 656c6c00 00000003 00000010 imecell\0" FDT_PROP len 0x10 0350: 00000065 00000000 09000000 00000000 nameoff 0x65 = "reg", cells... reg = <0x00 0x9000000 0x00 0x1000> (16 bytes) parent (root): #address-cells = 2, #size-cells = 2 so one range = 4 cells = 16 bytes address 0x0900_0000, size 0x1000 (4 KiB) With #address-cells = 1, a range is 12 bytes and 16 does not divide: dtc warns.

If the lab does not load, the next two sections do the same by hand.

Counting the bytes of one reg

How long is the PL011's reg property, in bytes? Work it out from the table before you look: one range, the root's 2 address cells plus 2 size cells, 4 bytes per cell. Then find the node in the blob. The name appears twice, once in /chosen's stdout-path and once as the node itself:

TerminalReal output
grep -obUa 'pl011@9000000' v.dtbexit: 0--- stdout ---189:pl011@9000000788:pl011@9000000
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • v.dtb is the file the run in 10-dtb-out-run wrote.
course/captures/10-grep-offset.txt

Dump from 4 bytes before the second hit:

TerminalReal output
xxd -s 784 -l 80 v.dtbexit: 0--- stdout ---00000310: 0000 0001 706c 3031 3140 3930 3030 3030  ....pl011@90000000000320: 3000 0000 0000 0003 0000 0018 0000 0000  0...............00000330: 6172 6d2c 706c 3031 3100 6172 6d2c 7072  arm,pl011.arm,pr00000340: 696d 6563 656c 6c00 0000 0003 0000 0010  imecell.........00000350: 0000 0065 0000 0000 0900 0000 0000 0000  ...e............
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • v.dtb is the file the run in 10-dtb-out-run wrote; 784 is the second offset grep printed (788) minus 4, the FDT_BEGIN_NODE token before the name.
course/captures/10-pl011-hex.txt

Read it in 32-bit big-endian words. 00000001 is a token meaning "a node begins", followed by its name, a NUL and zero padding to a multiple of 4. 00000003 means "a property": then its length (0x18, 24 bytes: "arm,pl011\0arm,primecell\0"), then the offset of its name in a separate table, then the value. The second property, its token at 0x348, is reg: length 0x10, 16 bytes, and the four cells 00000000 09000000 00000000 00001000. Journal question 1 asks what the length would be with one cell each.

The blob: header, structure, strings

That separate table and those tokens are the flattened device tree format (FDT), in chapter 5 of the Devicetree Specification (v0.4). The whole file has four parts:

 offset 0x000  header, 40 bytes           ten big-endian u32 fields offset 0x028  memory reservation map     (address, size) u64 pairs, ends with (0, 0); 8-aligned offset 0x038  structure block            tokens: BEGIN_NODE name, PROP len nameoff value,                                          END_NODE, ..., END; everything padded to 4 offset 0x424  strings block              property names, each once, NUL-terminated offset 0x4f7  end (totalsize)

Offsets from our blob; the header tells a reader where each part starts.

The header, in the first 40 bytes:

TerminalReal output
xxd -l 64 v.dtbexit: 0--- stdout ---00000000: d00d feed 0000 04f7 0000 0038 0000 0424  ...........8...$00000010: 0000 0028 0000 0011 0000 0010 0000 0000  ...(............00000020: 0000 00d3 0000 03ec 0000 0000 0000 0000  ................00000030: 0000 0000 0000 0000 0000 0001 0000 0000  ................
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • v.dtb is the file the run in 10-dtb-out-run wrote.
course/captures/10-header-hex.txt
BytesFieldOursMeaning
0 to 3magicd00dfeed"this is a DTB"
4 to 7totalsize0x4f71271 bytes in all
8 to 11off_dt_struct0x38where the structure block starts
12 to 15off_dt_strings0x424where the strings block starts
16 to 19off_mem_rsvmap0x28where the reservation map starts
20 to 23version0x11 = 17the format we write
24 to 27last_comp_version0x10 = 16the oldest version a reader may be and still understand us
28 to 31boot_cpuid_phys0the reg of the CPU that boots
32 to 35size_dt_strings0xd3strings block length
36 to 39size_dt_struct0x3ecstructure block length

The dump goes on past the header. The 16 zero bytes from 0x28 to 0x37 are the reservation map's (0, 0) terminator, and the 00000001 at 0x38 is the root node beginning, with an empty name.

The memory reservation map lists RAM a kernel must not use. Ours holds only that terminator, because Linux reserves the DTB itself. The structure block is the tree, written depth first as tokens.

The strings block holds property names, each stored once: our tree has seven compatible properties and one compatible string. That nameoff in every property points into it.

What if a header field is wrong? Change one byte of off_dt_strings, from 0x24 to 0x25, in a copy. Offset 15 is the least significant byte of off_dt_strings (bytes 12 to 15, big-endian):

Shell
cp v.dtb bad.dtbprintf '\x25' | dd of=bad.dtb bs=1 seek=15 conv=notruncdtc -I dtb -O dts bad.dtb
TerminalReal output
dtc -I dtb -O dts bad.dtbexit: 1--- stderr ---FATAL ERROR: String table extends past total size
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • bad.dtb is a copy of the --dtb-out file (run with --irqchip none) whose off_dt_strings byte at offset 15 was changed from 0x24 to 0x25 (printf + dd, as in the lesson).
course/captures/10-strings-plus-one.txt

The offset plus the strings size now runs past totalsize, and dtc checks that. One too low instead (0x23) stays inside the blob, so that check passes. dtc still refuses it, for "Duplicate property name"; forced with -f, it prints what a less careful reader would believe:

TerminalReal output
dtc -f -I dtb -O dts bad.dtb 2>/dev/null | head -20exit: 0--- stdout ---/dts-v1/;/ {		compatible = "linux,dummy-virt";	 = "macvmm-virt";	 = <0x02>;	 = <0x02>;	;	chosen {		 = "/pl011@9000000";		 = <0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00>;		 = <0x00 0x00>;	};	memory@40000000 {		 = "memory";		 = <0x00 0x40000000 0x00 0x4000000>;	};
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • bad.dtb is a copy of the --dtb-out file (run with --irqchip none) whose off_dt_strings byte at offset 15 was changed from 0x24 to 0x23 (printf + dd). Without -f, dtc refuses it (exit 2, "Duplicate property name" errors); -f forces the output. The exit shown is that of head.
course/captures/10-strings-minus-one.txt

Every name is read one byte early. Most become the empty string, and the first gains a tab: byte 0x423 is the last byte of the FDT_END token, 0x09. Values intact, names gone. These steps leave v.dtb and bad.dtb in the repository root; rm v.dtb bad.dtb when you are done.

Security

Our VMM never parses a DTB it did not build itself moments before, so it has no parser to attack; the reference keeps its reader for tests and the fuzzer only, and its audit fails the build if anything else uses it. A program that reads a DTB from a file or a guest is parsing hostile input: every offset and size checked against totalsize and the buffer with overflow-checked additions, every nameoff inside the strings block, names ending in a NUL, caps on depth and token count, and the boot protocol's size limit (a DTB "must not exceed 2 megabytes"). Journal question 3 asks you to list the checks.

Good place to stop. Sitting B needs your Mac, your learner workspace and about 2.5 hours.

A writer that refuses bad trees

The writer lives in learner/crates/vmm/src/fdt/writer.rs and uses no crate: the format is the lesson. It streams: you open a node, add its properties, open and close children, close it, and finish lays out the blob. The constants come from the specification and the boot protocol's cap:

crates/vmm/src/fdt/writer.rslines 41-58
/// `magic` (DT spec §5.2).pub const FDT_MAGIC: u32 = 0xd00d_feed;/// The format version we write, and the oldest version it is compatible with (§5.2: version/// 17, `last_comp_version` 16).pub const FDT_VERSION: u32 = 17;pub const FDT_LAST_COMP_VERSION: u32 = 16;/// Structure-block tokens (§5.4.1).pub const FDT_BEGIN_NODE: u32 = 0x1;pub const FDT_END_NODE: u32 = 0x2;pub const FDT_PROP: u32 = 0x3;pub const FDT_NOP: u32 = 0x4;pub const FDT_END: u32 = 0x9;/// `struct fdt_header` is ten `u32`s (§5.2).pub const FDT_HEADER_SIZE: usize = 40;/// One memory-reservation entry: `{u64 address, u64 size}` (§5.3).pub const FDT_RSV_ENTRY_SIZE: usize = 16;/// The largest blob we produce (booting.rst §2: at most 2 MiB).pub const FDT_MAX_SIZE: usize = 2 << 20;

Each refusal is one variant of an error type, a rule the caller broke:

crates/vmm/src/fdt/writer.rslines 71-104
/// Why the writer refused a call. All of these are bugs in the code that builds the tree/// (every name and value comes from our own code), so the machine build reports them as/// an internal error rather than a guest or user error.#[derive(Clone, Debug, PartialEq, Eq)]pub enum FdtError {    /// A node name with a NUL, a `/`, a character outside DT spec §2.2.1 Table 2.1, an empty    /// non-root name, or one that is too long.    InvalidNodeName { name: String },    /// A property name with a NUL or a character outside DT spec §2.2.4 Table 2.2, empty, or    /// longer than 31 characters.    InvalidPropName { name: String },    /// A string value with an interior NUL (it would end the string early).    StringHasNul { prop: String },    /// A property was added after the current node already has a child (§5.4.2).    PropAfterChild { prop: String },    /// A property was added with no node open.    PropOutsideNode { prop: String },    /// `end_node` was given a node that is not the innermost open one, or nothing is open.    UnbalancedEnd,    /// The first node is not the root (`""`), or a second root was started.    BadRoot,    /// Nesting deeper than [`MAX_DEPTH`].    TooDeep,    /// More than [`MAX_MEM_RESERVE`] reservation entries.    TooManyReservations,    /// `finish` with nodes still open, or with no root at all.    Unfinished,    /// The blob would exceed its size cap.    TooLarge { size: usize, max: usize },    /// The machine description cannot be turned into a tree (`fdt/machine.rs`).    InvalidMachine(String),    /// A blob handed to `machine::redact_seeds` is not one we can redact.    Malformed(&'static str),}

Give it a Display impl with one message per variant. The writer itself is two growing buffers, the name-to-offset map, the reservations and a stack of open nodes:

crates/vmm/src/fdt/writer.rslines 141-171
/// A handle to an open node, returned by [`FdtWriter::begin_node`] and consumed by/// [`FdtWriter::end_node`]. Deliberately not `Clone`: each node is closed exactly once.#[derive(Debug, PartialEq, Eq)]#[must_use = "a node must be closed with end_node"]pub struct NodeId(usize);/// One open node: its sequence number and whether it already has a child.#[derive(Debug)]struct Open {    id: usize,    has_child: bool,}/// The streaming writer (module docs).#[derive(Debug, Default)]pub struct FdtWriter {    /// The structure block so far (tokens, big-endian).    structure: Vec<u8>,    /// The strings block so far.    strings: Vec<u8>,    /// Name → offset into `strings` (dedup, §5.5).    string_offsets: BTreeMap<String, u32>,    /// Memory reservations (§5.3).    reservations: Vec<(u64, u64)>,    /// The stack of open nodes; `open[0]` is the root.    open: Vec<Open>,    /// Nodes begun so far (the next `NodeId`).    nodes: usize,    /// The root has been closed: nothing more may be added.    root_done: bool,}

The size the blob would have if finished now, counting the END_NODE tokens still owed, is checked after every append, so a runaway caller fails early:

crates/vmm/src/fdt/writer.rslines 230-265
impl FdtWriter {    /// An empty writer. The first call must be `begin_node("")` (the root).    pub fn new() -> FdtWriter {        FdtWriter::default()    }    fn token(&mut self, t: u32) {        self.structure.extend_from_slice(&t.to_be_bytes());    }    /// The size the blob would have now, if finished (header + reservations + blocks + the    /// `FDT_END` token, and `FDT_END_NODE` for every node still open).    fn projected_size(&self) -> Option<usize> {        let rsv = self            .reservations            .len()            .checked_add(1)?            .checked_mul(FDT_RSV_ENTRY_SIZE)?;        let closing = self.open.len().checked_add(1)?.checked_mul(4)?;        FDT_HEADER_SIZE            .checked_add(rsv)?            .checked_add(self.structure.len())?            .checked_add(closing)?            .checked_add(self.strings.len())    }    /// Refuse to grow past [`FDT_MAX_SIZE`].    fn check_size(&self) -> Result<(), FdtError> {        match self.projected_size() {            Some(size) if size <= FDT_MAX_SIZE => Ok(()),            size => Err(FdtError::TooLarge {                size: size.unwrap_or(usize::MAX),                max: FDT_MAX_SIZE,            }),        }    }

Opening a node writes the token and the padded name. The first node must be the root, named "". Every other name is checked: a NUL would end it early, a / would make it a path, and other characters must be in the specification's table:

crates/vmm/src/fdt/writer.rslines 186-209
/// Check a non-root node name: `node-name[@unit-address]` (§2.2.1). Rejects NUL and `/`/// explicitly as well as everything else outside the tables.pub fn check_node_name(name: &str) -> Result<(), FdtError> {    let bad = || FdtError::InvalidNodeName {        name: name.to_owned(),    };    if name.is_empty() || name.len() > MAX_NODE_NAME || name.bytes().any(|b| b == 0 || b == b'/') {        return Err(bad());    }    let (base, unit) = match name.split_once('@') {        Some((b, u)) => (b, Some(u)),        None => (name, None),    };    let base_ok = !base.is_empty()        && base.len() <= 31        && base.bytes().all(node_char_ok)        && base.bytes().next().is_some_and(|c| c.is_ascii_alphabetic());    let unit_ok = unit.is_none_or(|u| !u.is_empty() && u.bytes().all(node_char_ok));    if base_ok && unit_ok {        Ok(())    } else {        Err(bad())    }}

pad4 appends zero bytes until the length is a multiple of 4; check_prop_name is the same idea for property names, at most 31 characters. Then begin_node:

crates/vmm/src/fdt/writer.rslines 269-297
/// Open a node. The first node must be the root, named `""` (§5.4.1: "the root node's name/// is the empty string"); every later one needs a valid, non-empty name.pub fn begin_node(&mut self, name: &str) -> Result<NodeId, FdtError> {    // Nothing after the root closes, and the first node is the root.    if self.root_done || (self.open.is_empty() && !name.is_empty()) {        return Err(FdtError::BadRoot);    }    if !self.open.is_empty() {        check_node_name(name)?; // also refuses "" for a child    }    if self.open.len() >= MAX_DEPTH {        return Err(FdtError::TooDeep);    }    if let Some(parent) = self.open.last_mut() {        parent.has_child = true;    }    self.token(FDT_BEGIN_NODE);    self.structure.extend_from_slice(name.as_bytes());    self.structure.push(0); // NUL terminator, then zero padding to 4    pad4(&mut self.structure);    let id = self.nodes;    self.nodes = self.nodes.checked_add(1).ok_or(FdtError::TooDeep)?;    self.open.push(Open {        id,        has_child: false,    });    self.check_size()?;    Ok(NodeId(id))}

begin_node returns a NodeId that is not Clone, and end_node takes it back, so closing the wrong node is an error where it happens:

crates/vmm/src/fdt/writer.rslines 301-313
/// Close `node`, which must be the innermost open node.pub fn end_node(&mut self, node: NodeId) -> Result<(), FdtError> {    match self.open.last() {        Some(top) if top.id == node.0 => {}        _ => return Err(FdtError::UnbalancedEnd),    }    self.open.pop();    self.token(FDT_END_NODE);    if self.open.is_empty() {        self.root_done = true;    }    self.check_size()}

Property names go into the strings block once. The map from name to offset is the whole deduplication:

crates/vmm/src/fdt/writer.rslines 317-330
/// The strings-block offset of `name`, adding it on first use (§5.5).fn name_offset(&mut self, name: &str) -> Result<u32, FdtError> {    if let Some(&off) = self.string_offsets.get(name) {        return Ok(off);    }    let off = u32::try_from(self.strings.len()).map_err(|_| FdtError::TooLarge {        size: self.strings.len(),        max: FDT_MAX_SIZE,    })?;    self.strings.extend_from_slice(name.as_bytes());    self.strings.push(0);    self.string_offsets.insert(name.to_owned(), off);    Ok(off)}

A property must come before its node's first child. Readers such as libfdt and Linux stop collecting a node's properties at its first child, so a late property would silently vanish; the specification (section 5.4.2) forbids it. The writer makes it PropAfterChild:

crates/vmm/src/fdt/writer.rslines 334-351
/// Add a property with raw `value` bytes to the innermost open node (§5.4.1 `FDT_PROP`:/// `u32 len`, `u32 nameoff`, then `len` bytes padded to 4). Every typed helper below ends/// here.pub fn prop_bytes(&mut self, name: &str, value: &[u8]) -> Result<(), FdtError> {    check_prop_name(name)?;    match self.open.last() {        None => {            return Err(FdtError::PropOutsideNode {                prop: name.to_owned(),            });        }        Some(top) if top.has_child => {            return Err(FdtError::PropAfterChild {                prop: name.to_owned(),            });        }        Some(_) => {}    }

Then it checks the exact size the property would add, before touching the buffers, and appends it:

crates/vmm/src/fdt/writer.rslines 354-386
    // Check the size before touching the buffers: `value` may be large. Exact: the    // 12-byte `FDT_PROP` header, the value padded to 4, and the name if it is new.    let new_name = if self.string_offsets.contains_key(name) {        0    } else {        name.len().saturating_add(1)    };    let grown = self.projected_size().and_then(|s| {        s.checked_add(12)?            .checked_add(value.len().checked_next_multiple_of(4)?)?            .checked_add(new_name)    });    match grown {        Some(s) if s <= FDT_MAX_SIZE => {}        s => {            return Err(FdtError::TooLarge {                size: s.unwrap_or(usize::MAX),                max: FDT_MAX_SIZE,            });        }    }    let len = u32::try_from(value.len()).map_err(|_| FdtError::TooLarge {        size: value.len(),        max: FDT_MAX_SIZE,    })?;    let nameoff = self.name_offset(name)?;    self.token(FDT_PROP);    self.structure.extend_from_slice(&len.to_be_bytes());    self.structure.extend_from_slice(&nameoff.to_be_bytes());    self.structure.extend_from_slice(value);    pad4(&mut self.structure);    self.check_size()}

Typed helpers turn values into big-endian bytes: prop_u32 writes one cell, prop_cells an array of cells, prop_strs a list of strings, each NUL-terminated:

crates/vmm/src/fdt/writer.rslines 395-398
/// One big-endian cell (`<u32>`).pub fn prop_u32(&mut self, name: &str, v: u32) -> Result<(), FdtError> {    self.prop_bytes(name, &v.to_be_bytes())}
crates/vmm/src/fdt/writer.rslines 407-411
/// A `<prop-encoded-array>` of cells.pub fn prop_cells(&mut self, name: &str, cells: &[u32]) -> Result<(), FdtError> {    let bytes: Vec<u8> = cells.iter().flat_map(|c| c.to_be_bytes()).collect();    self.prop_bytes(name, &bytes)}
crates/vmm/src/fdt/writer.rslines 420-434
/// A `<stringlist>`: each string NUL-terminated, concatenated/// (`"arm,pl011\0arm,primecell\0"`).pub fn prop_strs(&mut self, name: &str, list: &[&str]) -> Result<(), FdtError> {    let mut bytes = Vec::new();    for s in list {        if s.as_bytes().contains(&0) {            return Err(FdtError::StringHasNul {                prop: name.to_owned(),            });        }        bytes.extend_from_slice(s.as_bytes());        bytes.push(0);    }    self.prop_bytes(name, &bytes)}

Four more are yours, each a few lines on top of these, taking &mut self and returning Result<(), FdtError>: prop_null(name), a property with an empty value; prop_u64(name, v), two cells, high first; prop_str(name, s), a one-item prop_strs; and add_mem_reserve(addr, size), which records one reservation, refuses more than MAX_MEM_RESERVE (64) with TooManyReservations, and runs the size check.

finish computes the offsets with checked_add and refuses anything over 2 MiB. The header is 40 bytes and each reservation entry 16, so the map and the structure block land 8-aligned with no padding:

crates/vmm/src/fdt/writer.rslines 448-482
/// Serialize: header, reservation map (8-aligned, `{0, 0}`-terminated), structure block/// (4-aligned, ending in `FDT_END`), strings block. `boot_cpuid` is the `reg` of the boot/// CPU (§5.2 `boot_cpuid_phys`).pub fn finish(mut self, boot_cpuid: u32) -> Result<Vec<u8>, FdtError> {    if !self.root_done || !self.open.is_empty() {        return Err(FdtError::Unfinished);    }    // No `check_size()` here: `projected_size` already counts this `FDT_END`, so it would    // count it twice. The exact `total` check below is the cap.    self.token(FDT_END);    let too_large = |size: usize| FdtError::TooLarge {        size,        max: FDT_MAX_SIZE,    };    // The header is 40 bytes, already a multiple of 8, so the reservation map follows it    // directly; each entry is 16 bytes, so the structure block is 8-aligned as well.    let off_rsvmap = FDT_HEADER_SIZE;    let rsv_len = self        .reservations        .len()        .checked_add(1)        .and_then(|n| n.checked_mul(FDT_RSV_ENTRY_SIZE))        .ok_or(too_large(usize::MAX))?;    let off_struct = off_rsvmap        .checked_add(rsv_len)        .ok_or(too_large(usize::MAX))?;    let off_strings = off_struct        .checked_add(self.structure.len())        .ok_or(too_large(usize::MAX))?;    let total = off_strings        .checked_add(self.strings.len())        .ok_or(too_large(usize::MAX))?;    if total > FDT_MAX_SIZE {        return Err(too_large(total));    }

Then it writes the ten header fields big-endian, the reservation map with its (0, 0) terminator, the structure block and the strings block:

crates/vmm/src/fdt/writer.rslines 485-509
    let u = |v: usize| u32::try_from(v).map_err(|_| too_large(v));    let header = [        FDT_MAGIC,        u(total)?,        u(off_struct)?,        u(off_strings)?,        u(off_rsvmap)?,        FDT_VERSION,        FDT_LAST_COMP_VERSION,        boot_cpuid,        u(self.strings.len())?,        u(self.structure.len())?,    ];    let mut blob = Vec::with_capacity(total);    for field in header {        blob.extend_from_slice(&field.to_be_bytes());    }    for (addr, size) in self.reservations.iter().chain(&[(0, 0)]) {        blob.extend_from_slice(&addr.to_be_bytes());        blob.extend_from_slice(&size.to_be_bytes());    }    blob.extend_from_slice(&self.structure);    blob.extend_from_slice(&self.strings);    Ok(blob)}

These names are frozen: the checkpoint's contract tests call them exactly as given. That means FdtWriter with new, begin_node, end_node, prop_bytes, the typed helpers, add_mem_reserve and finish; NodeId; the constants above in vmm::fdt::writer; and FdtError with at least the variants the tests match, PropAfterChild, UnbalancedEnd, Unfinished, InvalidNodeName, InvalidPropName, StringHasNul and TooLarge { size, max }.

The reader the tests use. The tests also read your blobs back through a reader, and feed that reader malformed blobs, each of which must be an error, never a panic. The reader is test equipment, not this chapter's subject, so copy the reference's, from learner/:

Shell
cp ../crates/vmm/src/fdt/reader.rs crates/vmm/src/fdt/

It imports your writer's constants by the names above. Declare it as the reference does, compiled only for tests and for the test-util feature the checkpoint builds your crate with:

crates/vmm/src/fdt/mod.rslines 19-25
pub mod machine;#[cfg(any(test, feature = "test-util"))]pub mod reader;pub mod writer;pub use machine::{MachineDesc, build_dtb, build_dtb_with, redact_seeds};pub use writer::{FdtError, FdtWriter, NodeId};

Re-export from machine only what your machine.rs defines. The reader shares our assumptions, since the same people wrote it; dtc is the independent check.

Production note

Production VMMs in Rust usually take the format from a shared crate (vm-fdt, in the rust-vmm family), and QEMU uses libfdt, the C library that ships with dtc. We write our own because the format is the lesson.

The machine, from one table

learner/crates/vmm/src/fdt/machine.rs turns the board into calls. Its rule: every address comes from layout.rs, the table chapter 05 built, so the tree and the devices on the bus cannot disagree about where. What changes from boot to boot arrives as one MachineDesc:

crates/vmm/src/fdt/machine.rslines 88-142
/// Everything about one boot that the tree describes. Pure data: tests fill the seeds with/// fixed values, the machine build with [`MachineDesc::from_entropy`].#[derive(Clone, PartialEq, Eq)]pub struct MachineDesc {    /// Number of vCPUs, `1..=MAX_CPUS`.    pub ncpus: u32,    /// RAM size in bytes (checked against the layout again here).    pub mem_bytes: u64,    /// `/chosen/bootargs`, if any (chapter 13: the kernel command line).    pub bootargs: Option<String>,    /// `/chosen/linux,initrd-{start,end}`: `[start, end)` (chapter 13).    pub initrd: Option<(u64, u64)>,    /// The populated virtio-mmio slot indices (chapter 15), each `< VIRTIO_MMIO_SLOTS`.    pub virtio_slots: Vec<usize>,    /// `/chosen/rng-seed`.    pub rng_seed: [u8; RNG_SEED_LEN],    /// `/chosen/kaslr-seed`.    pub kaslr_seed: u64,}impl fmt::Debug for MachineDesc {    /// Never prints the seeds: logs and `--dry-run` must not reveal them.    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        f.debug_struct("MachineDesc")            .field("ncpus", &self.ncpus)            .field("mem_bytes", &self.mem_bytes)            .field("bootargs", &self.bootargs)            .field("initrd", &self.initrd)            .field("virtio_slots", &self.virtio_slots)            .field("rng_seed", &"<redacted>")            .field("kaslr_seed", &"<redacted>")            .finish()    }}impl MachineDesc {    /// A description with fresh seeds from the host CSPRNG: what every real boot uses.    pub fn from_entropy(        ncpus: u32,        mem_bytes: u64,        entropy: &Entropy,    ) -> std::io::Result<MachineDesc> {        let mut rng_seed = [0u8; RNG_SEED_LEN];        entropy.fill(&mut rng_seed)?;        Ok(MachineDesc {            ncpus,            mem_bytes,            bootargs: None,            initrd: None,            virtio_slots: Vec::new(),            rng_seed,            kaslr_seed: entropy.u64()?,        })    }}

The seeds must be fresh host randomness on every boot, 64 bytes for rng-seed and 8 for kaslr-seed: Linux mixes the first into its random pool, and uses the second to choose where in memory the kernel runs. The reference calls the Mac's getentropy (chapter 17 shows the wrapper); in your workspace, reading 72 bytes from /dev/urandom with std::fs::File is enough. dtb-reader checks that both are nonzero, so zeros fail the checkpoint.

Two small helpers: bad wraps a message as InvalidMachine, and row finds the layout row that starts at an address, so a node's name and its reg come from the same row:

crates/vmm/src/fdt/machine.rslines 146-157
fn bad(why: impl Into<String>) -> FdtError {    FdtError::InvalidMachine(why.into())}/// The layout row starting at `base` (so a node name and its `reg` come from the same row).fn row(layout: &Layout, base: u64) -> Result<&Region, FdtError> {    layout        .regions        .iter()        .find(|r| r.base == base)        .ok_or_else(|| bad(format!("no layout region at {base:#x}")))}

A reg pair with two cells per number:

crates/vmm/src/fdt/machine.rslines 197-202
/// One `<u64 address u64 size>` entry with 2 address and 2 size cells.fn reg64(addr: u64, size: u64) -> [u32; 4] {    let hi = |v: u64| u32::try_from(v >> 32).unwrap_or(u32::MAX);    let lo = |v: u64| u32::try_from(v & 0xffff_ffff).unwrap_or(u32::MAX);    [hi(addr), lo(addr), hi(size), lo(size)]}

RAM is one bank, as big as --mem:

crates/vmm/src/fdt/machine.rslines 243-251
fn memory(w: &mut FdtWriter, layout: &Layout, d: &MachineDesc) -> Result<(), FdtError> {    layout        .ram_end(d.mem_bytes)        .map_err(|e| bad(format!("memory: {e}")))?;    let n = w.begin_node(&format!("memory@{RAM_BASE:x}"))?;    w.prop_str("device_type", "memory")?;    w.prop_cells("reg", &reg64(RAM_BASE, d.mem_bytes))?;    w.end_node(n)}

The PL011 and the PL031 are both PrimeCells, so one function writes either from its layout row: name and unit address, compatible, reg, then the clock. The with_gic lines add an interrupts property, which says which interrupt line the device raises; that needs the interrupt controller node of chapter 12, so leave them out for now:

crates/vmm/src/fdt/machine.rslines 171-193
/// An AMBA PrimeCell node (`arm,primecell.yaml`) named from its layout row: `reg`, one/// level-high SPI, and the APB clock(s) the AMBA bus enables before probing.fn primecell(    w: &mut FdtWriter,    region: &Region,    compatible: &[&str],    clock_names: &[&str],    with_gic: bool,) -> Result<(), FdtError> {    let intid = region        .intid        .ok_or_else(|| bad(format!("{} has no interrupt", region.name)))?;    let n = w.begin_node(&format!("{}@{}", region.name, region.unit_address()))?;    w.prop_strs("compatible", compatible)?;    w.prop_cells("reg", &reg64(region.base, region.size))?;    if with_gic {        w.prop_cells("interrupts", &spi_cells(intid)?)?;    }    let clocks: Vec<u32> = clock_names.iter().map(|_| APB_PCLK_PHANDLE).collect();    w.prop_cells("clocks", &clocks)?;    w.prop_strs("clock-names", clock_names)?;    w.end_node(n)}

The clock both point at, with its phandle:

crates/vmm/src/fdt/machine.rslines 338-346
fn apb_pclk(w: &mut FdtWriter) -> Result<(), FdtError> {    let n = w.begin_node("apb-pclk")?;    w.prop_str("compatible", "fixed-clock")?;    w.prop_u32("#clock-cells", 0)?;    w.prop_u32("clock-frequency", APB_PCLK_HZ)?;    w.prop_str("clock-output-names", "clk24mhz")?;    w.prop_u32("phandle", APB_PCLK_PHANDLE)?;    w.end_node(n)}

/chosen checks bootargs before writing it: Linux keeps at most 2,047 bytes plus the NUL and would cut a longer line silently, so the reference refuses it. The initrd lines are chapter 13's:

crates/vmm/src/fdt/machine.rslines 212-239
/// `/chosen` (devicetree specification section 3.6; booting.rst section 2; Linux/// `drivers/of/fdt.c`).fn chosen(w: &mut FdtWriter, layout: &Layout, d: &MachineDesc) -> Result<(), FdtError> {    let n = w.begin_node("chosen")?;    if let Some(args) = &d.bootargs {        // Linux would silently truncate a longer line; a NUL would end it early.        if args.len() > MAX_BOOTARGS || args.as_bytes().contains(&0) {            return Err(bad(format!(                "bootargs must be at most {MAX_BOOTARGS} bytes without NUL"            )));        }        w.prop_str("bootargs", args)?;    }    w.prop_str("stdout-path", &stdout_path(layout)?)?;    if let Some((start, end)) = d.initrd {        if start >= end {            return Err(bad("initrd end must be above its start"));        }        // Two cells each; the end is exclusive (Linux `early_init_dt_check_for_initrd`).        w.prop_u64("linux,initrd-start", start)?;        w.prop_u64("linux,initrd-end", end)?;    }    // Fresh per boot from the host's secure random generator; zeroed in --dtb-out copies, so    // a saved tree never leaks the seeds the guest used.    w.prop_bytes("rng-seed", &d.rng_seed)?;    w.prop_u64("kaslr-seed", d.kaslr_seed)?;    w.end_node(n)}

The entry point checks the description first:

crates/vmm/src/fdt/machine.rslines 367-388
/// Build the blob for `desc` on `layout` (module docs). Deterministic for a given `desc`.pub fn build_dtb(layout: &Layout, desc: &MachineDesc) -> Result<Vec<u8>, FdtError> {    build_dtb_with(layout, desc, true)}/// [`build_dtb`], or with `with_gic = false` the tree of the `--irqchip none` teaching mode/// (chapter 11): no `intc` node, no root `interrupt-parent`, and no `interrupts`/// on the timer and the PrimeCells, since nothing could deliver them. Test guests in that/// mode do not read the tree; this keeps it self-consistent anyway (no dangling phandle).pub fn build_dtb_with(    layout: &Layout,    desc: &MachineDesc,    with_gic: bool,) -> Result<Vec<u8>, FdtError> {    if desc.ncpus == 0 || desc.ncpus > MAX_CPUS {        return Err(bad(format!("{} vCPUs (1..={MAX_CPUS})", desc.ncpus)));    }    let mut slots = desc.virtio_slots.clone();    slots.sort_unstable();    if slots.windows(2).any(|p| p.first() == p.get(1)) {        return Err(bad("a virtio slot is listed twice"));    }

Then the root ties it together in the order dtc printed. Skip the with_gic branches until chapter 12, and leave out slots and the virtio_slot loop until chapter 15, where virtio devices arrive. cpus, psci and timer are the next section's; give each an empty body that returns Ok(()) for now, so this builds:

crates/vmm/src/fdt/machine.rslines 391-431
let mut w = FdtWriter::new();let root = w.begin_node("")?;w.prop_str("compatible", "linux,dummy-virt")?;w.prop_str("model", "macvmm-virt")?;w.prop_u32("#address-cells", 2)?;w.prop_u32("#size-cells", 2)?;if with_gic {    w.prop_u32("interrupt-parent", GIC_PHANDLE)?;}w.prop_null("dma-coherent")?;chosen(&mut w, layout, desc)?;memory(&mut w, layout, desc)?;cpus(&mut w, desc)?;psci(&mut w)?;timer(&mut w, with_gic)?;if with_gic {    gic(&mut w, layout, desc)?;}apb_pclk(&mut w)?;primecell(    &mut w,    row(layout, PL011_BASE)?,    &["arm,pl011", "arm,primecell"],    &["uartclk", "apb_pclk"],    with_gic,)?;primecell(    &mut w,    row(layout, PL031_BASE)?,    &["arm,pl031", "arm,primecell"],    &["apb_pclk"],    with_gic,)?;for slot in slots {    virtio_slot(&mut w, layout, slot)?;}w.end_node(root)?;// The boot CPU is vCPU 0, whose `reg` is 0.w.finish(0)

Your turn: three nodes

Three nodes are yours to write, with the dtc listing above as their specification:

  1. /cpus, with #address-cells = <1>, #size-cells = <0>, and one cpu@N per vCPU with device_type = "cpu", compatible = "arm,arm-v8", enable-method = "psci" and a reg. That reg is the vCPU's affinity: its MPIDR_EL1 (the Multiprocessor Affinity Register, chapter 06) with bit 31 and the other non-affinity bits cleared, keeping Aff3 in bits 39 to 32 and Aff2 to Aff0 in bits 23 to 0. So vCPU 0, whose MPIDR_EL1 is 0x8000_0000, has reg = <0x0> and is cpu@0; the unit address is that number in hex.
  2. /psci, with the three compatible strings and method = "hvc", so the guest's power calls take chapter 08's path.
  3. /timer, with its two compatible strings and the empty property always-on.

Stuck? scripts/learner hint 10 gives four hints, from a nudge to the exact reference file.

Handing it over in x0

The blob goes at 0x4000_0000, 8-byte aligned as the boot protocol requires. Chapter 03 reserved that slot: the first 512 KiB of RAM, up to 0x4008_0000 where test guests are linked (chapter 13 widens it to 2 MiB for Linux):

crates/vmm/src/loader/plan.rslines 206-210
let dtb = Placement {    what: "device tree (reserved)".into(),    addr: ram.base,    len: DTB_MAX_TEST_GUEST.min(ram.size),};

The plan sets x0 to the slot's address. Each boot then builds a fresh tree and sizes the slot to it (set_dtb_len refuses a tree bigger than the slot):

crates/vmm/src/machine/mod.rslines 166-190
/// Generate this boot's device tree and size `plan`'s DTB slot to it. Fresh/// `rng-seed`/`kaslr-seed` come from `host.entropy` on every boot; the first boot (generation/// 0; a guest reboot starts a new generation) also writes the seed-redacted copy to/// `--dtb-out`. The guest gets the real seeds.pub fn device_tree(    cfg: &VmConfig,    host: &HostIo,    plan: &mut BootPlan,    generation: u64,) -> Result<Vec<u8>> {    let mut desc = MachineDesc::from_entropy(cfg.cpus, cfg.mem_bytes, &host.entropy)        .map_err(Error::Entropy)?;    // Chapter 13: the kernel command line and the initrd range go to `/chosen`.    desc.bootargs.clone_from(&plan.bootargs);    desc.initrd = plan.initrd;    // Chapter 15: one `/virtio_mmio@…` node per populated slot.    desc.virtio_slots = virt::virtio_populated(cfg);    let with_gic = cfg.irqchip == IrqChip::InKernelGicV3;    let dtb = fdt::build_dtb_with(Layout::virt(), &desc, with_gic)?;    plan.set_dtb_len(u64::try_from(dtb.len()).unwrap_or(u64::MAX))?;    if generation == 0 {        host.write_dtb_out(&fdt::redact_seeds(&dtb)?)?;    }    Ok(dtb)}

Skip for now: bootargs and initrd (chapter 13), virtio_populated (chapter 15), and with_gic (chapter 11's --irqchip; yours is false). generation counts guest reboots (chapter 08's SYSTEM_RESET): every boot gets a new tree, and only the first writes the file. In your VMM, write the tree into guest memory at 0x4000_0000 before the vCPU starts.

The file gets a copy with both seeds zeroed. The reference walks the blob's tokens and zeroes those two values in place; the step for one property:

crates/vmm/src/fdt/machine.rslines 487-510
FDT_PROP => {    let (len, nameoff) = (be(pos)?, be(step(pos, 4))?);    let value = step(pos, 8);    let value_end = value        .checked_add(len)        .filter(|&e| e <= end)        .ok_or(FdtError::Malformed("property value"))?;    let name = strings        .get(nameoff..)        .and_then(|s| s.split(|&b| b == 0).next())        .ok_or(FdtError::Malformed("property name"))?;    let counter = match name {        b"rng-seed" => Some(&mut rng),        b"kaslr-seed" => Some(&mut kaslr),        _ => None,    };    if let Some(c) = counter {        *c = c.saturating_add(1);        out.get_mut(value..value_end)            .ok_or(FdtError::Malformed("property value"))?            .fill(0);    }    pos = align4(value_end);}

Simpler, and the same bytes: build the tree again from a clone of the MachineDesc with zero seeds. Add --dtb-out FILE in learner/crates/macvmm/src/cli.rs. Create the file with mode 0600 and refuse to follow a symlink, or a link planted at that path could make your VMM overwrite a file you own. The reference's open_output in crates/vmm/src/backend/hostio.rs also checks owner and link count; chapter 25 explains why.

And the boot vCPU starts with the slot's address in x0, and x1 to x3 zero, as the boot protocol requires:

crates/vmm/src/machine/mod.rslines 486-490
let boot = BootParams {    pc: self.plan.entry,    x: [self.plan.x0, 0, 0, 0],    cpsr: self.plan.cpsr,};

Since chapter 03 your VMM has put 0x4000_0000 in x0, an address with nothing behind it; chapter 03 promised a device tree would live there. Now one does. From learner/:

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --timeout 10
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --timeout 10exit: 0--- stdout ---dtb-reader: x0=0x40000000dtb-reader: magic okdtb-reader: model=macvmm-virtdtb-reader: memory@40000000 reg=0x40000000+0x4000000dtb-reader: pl011@9000000 compatible=arm,pl011dtb-reader: cpus=1dtb-reader: stdout-path=/pl011@9000000dtb-reader: rng-seed nonzerodtb-reader: kaslr-seed nonzerodtb-reader: done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run in an unmodified copy of the reference; $G is target/guests/aarch64-unknown-none/release. The checkpoint runs the same command on your VMM.
course/captures/10-dtb-reader-run.txt

We captured it on the reference; yours prints the same ten lines. magic ok is the evidence: the guest found 0xd00dfeed at x0.

One cell fewer

The tree is data. So is a number inside it that says how to read the other numbers.

Deliberate breakage 1: one address cell on the root. In build_dtb_with in your machine.rs, write 1 instead of 2 for the root's #address-cells, and nothing else.

Predict Will dtb-reader still print the same memory size?

Write your guess and one sentence of reasoning under ## Predict in your journal, then rebuild and run it.

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --dtb-out c.dtb --timeout 10

We captured it on the reference, which needs --irqchip none to leave out the interrupt controller your VMM does not have yet; yours needs no flag:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --irqchip none --raw $G/dtb-reader.bin@0x40080000 --dtb-out c.dtb --timeout 10exit: 0--- stdout ---dtb-reader: x0=0x40000000dtb-reader: magic okdtb-reader: model=macvmm-virtdtb-reader: memory@40000000 reg=0x40000000+0x4000000dtb-reader: pl011@9000000 compatible=arm,pl011dtb-reader: cpus=1dtb-reader: stdout-path=/pl011@9000000dtb-reader: rng-seed nonzerodtb-reader: kaslr-seed nonzerodtb-reader: done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: the root node's #address-cells in crates/vmm/src/fdt/machine.rs changed from 2 to 1; nothing else.
  • Run in a copy of the reference with that edit; $G is target/guests/aarch64-unknown-none/release. c.dtb is removed first. --irqchip none (the reference's flag, chapter 11) leaves out the interrupt controller, as your VMM does.
course/captures/10-cells-dtb-reader.txt

The same reg=0x40000000+0x4000000. If you predicted that, you were right for the wrong reason. Here is how dtb-reader reads memory:

guests/dtb-reader/main.rslines 49-60
let mut mem_name = "";fdt.children("/", "memory@", |n| mem_name = n);let mut path = [0u8; 64];let mem_path = join(&mut path, mem_name);let reg = fdt    .prop(mem_path, "reg")    .unwrap_or_else(|| fail("no memory reg"));let (base, size) = match (be64(reg), reg.get(8..).and_then(be64)) {    (Some(b), Some(s)) if reg.len() == 16 => (b, s),    _ => fail("memory reg is not one <u64 u64> pair"),};println!("dtb-reader: {mem_name} reg={base:#x}+{size:#x}");

It never reads #address-cells: it assumes two cells and two cells, exactly as uart-echo assumed 0x0900_0000. A reader that shares your assumption cannot catch your bug. dtc reads the counts:

TerminalReal output
dtc -I dtb -O dts -o /dev/null c.dtbexit: 0--- stderr ---/dev/null: Warning (reg_format): /memory@40000000:reg: property has invalid length (16 bytes) (#address-cells == 1, #size-cells == 2)/dev/null: Warning (reg_format): /pl011@9000000:reg: property has invalid length (16 bytes) (#address-cells == 1, #size-cells == 2)/dev/null: Warning (reg_format): /pl031@9010000:reg: property has invalid length (16 bytes) (#address-cells == 1, #size-cells == 2)/dev/null: Warning (pci_device_reg): Failed prerequisite 'reg_format'/dev/null: Warning (pci_device_bus_num): Failed prerequisite 'reg_format'/dev/null: Warning (simple_bus_reg): Failed prerequisite 'reg_format'/dev/null: Warning (i2c_bus_reg): Failed prerequisite 'reg_format'/dev/null: Warning (spi_bus_reg): Failed prerequisite 'reg_format'
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • c.dtb is the file the run in 10-cells-dtb-reader wrote (root #address-cells = 1).
course/captures/10-cells-dtc.txt

One range is now 1 + 2 = 3 cells, 12 bytes, and 16 is not a multiple of 12. And a real kernel? You cannot run this until chapter 13 fetches one; we booted the Linux kernel of chapter 14 on the reference with this one edit:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel $C/Image-virt --initrd $C/initramfs-test.img --serial file:boot.txt --timeout 15exit: 5--- stderr ---macvmm: timeout: the guest was still running after --timeout 15s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Edit: the root node's #address-cells in crates/vmm/src/fdt/machine.rs changed from 2 to 1; nothing else.
  • Run in a copy of the reference with that edit; $C is .cache/macvmm (the Linux kernel and initramfs chapter 13 fetches). boot.txt is removed first.
course/captures/10-cells-linux-run.txt

From outside, a kernel that has panicked looks like a guest still running: it stops in a loop, and --timeout ended it with exit 5. Its log:

TerminalReal output
head -9 boot.txt | tr -d '\r'exit: 0--- stdout ---[    0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][    0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[    0.000000] random: crng init done[    0.000000] Machine model: macvmm-virt[    0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[    0.000000] printk: legacy bootconsole [pl11] enabled[    0.000000] efi: UEFI not found.[    0.000000] Memory doesn't fit in the linear mapping, VA_BITS too small[    0.000000] Unable to handle kernel level 3 address size fault at virtual address fffffffffe429000
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • boot.txt is the serial log of the run in 10-cells-linux-run; tr removes the carriage returns the guest sends.
course/captures/10-cells-linux-log.txt

Machine model: macvmm-virt is Linux reading the root's model. Then it took one cell, 0x0, as the address and the next two, 0x40000000 and 0x0, as a size of 0x4000_0000_0000_0000 bytes, about 4.6 exabytes. "Doesn't fit in the linear mapping" means the kernel's own map of RAM is too small for that much; it faulted soon after. The early console worked because its address came from the command line our VMM passes Linux (earlycon=pl011,0x09000000), not from the tree. The checkpoint catches it through dtc:

TerminalReal output
scripts/checkpoint.sh 10exit: 1--- stdout ---[PASS] contract tests   fdt_writer (9 tests)[PASS] runs on your Mac dtb-reader: 10/10 serial markers, exit 0 in 0.13s[PASS] runs on your Mac hello-x0: 2/2 serial markers, exit 0 in 0.01s[FAIL] runs on your Mac dtc-clean: expected/dtc-clean.txt:2: forbidden marker "Warning" appears on stdout (1/1 serial markers matched before it)    stderr (last lines):[INFO] journal          not checked (not a learner tree)CHECKPOINT 10 FAIL
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: the root node's #address-cells in crates/vmm/src/fdt/machine.rs changed from 2 to 1; nothing else.
  • Run as scripts/checkpoint.sh 10 --impl . inside a copy of the reference with that edit; your own run targets learner/.
course/captures/10-checkpoint-cells.txt

What you saw: a guest that printed the right numbers, and a kernel that died on the same blob. The misconception it exposes: "the values did not change, so the guest sees the same machine"; the cell counts are structure, and the DTB is parsed, not read. The tool that found it: an independent reader, dtc, which shares none of our assumptions. Change the 1 back.

Move the PL011 on your VMM

Now compare dtc -I dtb -O dts of your own --dtb-out blob with the listing in sitting A. Then repeat the opening experiment: move PL011_BASE in your layout.rs to 0x0904_0000 (if your GICR_WINDOW_END is defined as PL011_BASE, pin it at 0x0900_0000 as we did), run dtb-reader and uart-echo, compare with the opening's captures, and move it back.

Try it

What does a guest do with a node for a device the bus does not have? We added a second node, pl031@9050000, to the reference's tree, left the bus alone, and booted Linux. With the default policy the virtual machine stopped on the first access, a read at 0x9050fe0: the PrimeCell bus code reads the identification registers before it picks a driver. With --unhandled-mmio log, those reads returned zero and Linux still reached its shell. Journal question 2 starts here.

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel $C/Image-virt --initrd $C/initramfs-test.img --serial file:boot.txt --timeout 20exit: 3--- stderr ---macvmm: guest fatal: unhandled MMIO read at 0x9050fe0 size 4 pc 0xffff800080859098  {"t_ns":54709916,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff8000808d0ea4","ipa":"0x9000018","wnr":false,"size":4,"reg":1,"value":"0x90","action":"mmio","isv":true}  {"t_ns":54746916,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff800080859098","ipa":"0x9010fe0","wnr":false,"size":4,"reg":2,"value":"0x31","action":"mmio","isv":true}  {"t_ns":54753625,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff800080859098","ipa":"0x9010fe4","wnr":false,"size":4,"reg":2,"value":"0x10","action":"mmio","isv":true}  {"t_ns":54755291,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff800080859098","ipa":"0x9010fe8","wnr":false,"size":4,"reg":2,"value":"0x14","action":"mmio","isv":true}  {"t_ns":54756875,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff800080859098","ipa":"0x9010fec","wnr":false,"size":4,"reg":2,"value":"0x0","action":"mmio","isv":true}  {"t_ns":54758458,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff8000808590d8","ipa":"0x9010ff0","wnr":false,"size":4,"reg":2,"value":"0xd","action":"mmio","isv":true}  {"t_ns":54760000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff8000808590d8","ipa":"0x9010ff4","wnr":false,"size":4,"reg":2,"value":"0xf0","action":"mmio","isv":true}  {"t_ns":54761541,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff8000808590d8","ipa":"0x9010ff8","wnr":false,"size":4,"reg":2,"value":"0x5","action":"mmio","isv":true}  {"t_ns":54763083,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff8000808590d8","ipa":"0x9010ffc","wnr":false,"size":4,"reg":2,"value":"0xb1","action":"mmio","isv":true}  {"t_ns":54776000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff800080859098","ipa":"0x9050fe0","wnr":false,"size":4,"reg":2,"action":"stop","isv":true}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Try it: a second node "pl031@9050000" (compatible arm,pl031 and arm,primecell, reg 0x0905_0000 size 0x1000) added to build_dtb_with in crates/vmm/src/fdt/machine.rs; the bus is unchanged, so no device answers there.
  • Run in a copy of the reference with that edit; $C is .cache/macvmm. stderr cut to its first line and its last 10 lines (sed); the exit code is macvmm's.
course/captures/10-phantom-fatal.txt
TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel $C/Image-virt --initrd $C/initramfs-test.img --serial file:boot.txt --unhandled-mmio log --timeout 15exit: 5--- stderr ---macvmm: warn: [vcpu0] guest: unhandled MMIO read at 0x9050fe0 size 4 pc 0xffff800080859098 (ignored: --unhandled-mmio log)macvmm: warn: [vcpu0] guest: unhandled MMIO read at 0x9050fe4 size 4 pc 0xffff800080859098 (ignored: --unhandled-mmio log)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Try it: a second node "pl031@9050000" (compatible arm,pl031 and arm,primecell, reg 0x0905_0000 size 0x1000) added to build_dtb_with in crates/vmm/src/fdt/machine.rs; the bus is unchanged, so no device answers there.
  • Run in a copy of the reference with that edit; $C is .cache/macvmm. stderr cut to its first 2 lines (sed); the exit code is macvmm's (5: stopped by --timeout at the shell prompt).
course/captures/10-phantom-log.txt
TerminalReal output
grep -a -e pl031 -e 'ready' boot.txt | tr -d '\r'exit: 0--- stdout ---[    0.059418] rtc-pl031 9010000.pl031: registered as rtc0[    0.059422] rtc-pl031 9010000.pl031: setting system clock to 2026-11-20T09:02:22 UTC (1795165342)macvmm-initramfs: ready 6.18.60-0-virt/ # [   10.216349] amba 9050000.pl031: deferred probe pending: (reason unknown)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • boot.txt is the serial log of the run in 10-phantom-log.
course/captures/10-phantom-log-grep.txt

amba is Linux's name for the PrimeCell bus. With the IDs reading zero it could not identify the device, so it parked it as "deferred" (the last line) and never bound a driver. In the fatal run, the trace lines before the stop are the real PL031 answering the same reads at 0x9010fe0 to 0x9010ffc with 0x31 0x10 0x14 0x00 and 0x0d 0xf0 0x05 0xb1: the identification registers you built in chapter 09. This is an early answer to chapter 09's open question about identification registers that read zero; chapter 14 answers it in full.

Checkpoint

Back at the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 10

You should see, as the last line:

CHECKPOINT 10 PASS

It runs the contract tests (header and alignment, one strings entry for two compatible properties, the ordering, balance, name and size errors, a round trip through the reader you copied, and that reader refusing malformed blobs). Then it runs dtb-reader on your VMM, expecting the ten lines above, and hello, expecting x0=0x40000000; if dtc is installed, it checks that your --dtb-out blob decompiles with no warning (otherwise INFO). It also checks that every journal heading has an answer. On the reference:

TerminalReal output
scripts/checkpoint.sh 10exit: 0--- stdout ---[PASS] contract tests   fdt_writer (9 tests)[PASS] runs on your Mac dtb-reader: 10/10 serial markers, exit 0 in 0.05s[PASS] runs on your Mac hello-x0: 2/2 serial markers, exit 0 in 0.01s[PASS] runs on your Mac dtc-clean: 1/1 serial markers, exit 0 in 0.02s[INFO] journal          not checked (not a learner tree)CHECKPOINT 10 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run as scripts/checkpoint.sh 10 --impl . inside an unmodified copy of the reference (journal not checked there); your own run targets learner/ and also checks your journal.
course/captures/10-checkpoint.txt

What now works:

  • your VMM writes a flattened device tree from scratch, and refuses the trees the format forbids;
  • the tree describes RAM, the CPUs, PSCI, the timer, the PL011, the PL031 and /chosen, all from layout.rs, with fresh seeds, and dtc accepts it without a warning;
  • the guest finds the tree through x0 = 0x40000000, and a guest that reads it learns where layout.rs put each device.

The next chapter starts from this state (the reference at the end of chapter 10).

What's next

/timer promises a timer, and nothing in our machine can interrupt the guest yet. Chapter 11 asks how a kernel gets the CPU back from a program that never yields, builds a bare interrupt with no controller, and counts what one exit to the VMM per tick costs.

Open question

The DTB and the device models come from one layout.rs, so the opening experiment moved the device and its description together. Which class of bug does that remove, and which class does it not: could the one-cell break of this chapter happen anyway, and what about a node whose compatible names a device our model does not behave like?

Spec hunt

  • Devicetree Specification v0.4, chapter 5, section 5.2 ("Header"): which header fields must a reader check before it trusts any offset, and what does last_comp_version promise a reader of version 16?
  • Devicetree Specification v0.4, section 2.3.5 (#address-cells and #size-cells): whose counts apply to a node's reg, and what default does a reader assume when a parent leaves them out?
  • Linux Documentation/arch/arm64/booting.rst, section "Setup the device tree": what alignment, size and placement rules does a DTB obey, and why does the 2 MiB block around it matter?
Progress is stored only in this browser.