Chapter 10 · Part IV
The Device Tree: the VMM's promise to the guest
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.
From chapter 09: A device is a state machine: the bus, PL011 and PL031
A guest reads the PL011's flag register
FRand gets0x90. May it write a byte toDRnow, and is there a byte for it to read?Show answer
0x90is 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 aDRread now would return 0.From chapter 09: A device is a state machine: the bus, PL011 and PL031
The host typed one letter,
a(0x61), and the guest reads the PL011'sDRtwice in a row. What does each read return, and why do they differ?Show answer
0x61, then 0. ADRread pops the receive FIFO: the first read removes the byte it returns, so the second finds the FIFO empty. A register whose read changes the device cannot be modelled as a stored value.From chapter 09: A device is a state machine: the bus, PL011 and PL031
IMSCis 0 when a byte arrives at the PL011. What doRISandMISread, and is the interrupt line high or low?Show answer
RIShas the receive bit (bit 4,0x10) set, and in our model the receive-timeout bit (bit 6) too: the device remembers that it wants attention.MISisRIS & IMSC= 0 and the line stays low: the mask says not to say so. SettingIMSCbit 4 later raises the line at once, because the condition still holds.From chapter 09: A device is a state machine: the bus, PL011 and PL031
The bus holds the PL011 at
0x0900_0000with size0x1000. What doesBus::insertanswer for a device at0x0900_0ff8with size0x10, and for one at0x0900_1000with size0x1000?Show answer
The first is refused with
BusError::Overlap: its first eight bytes fall inside the PL011's window. The second is accepted: it starts exactly where the PL011 ends, so the two windows are adjacent, not overlapping.From chapter 09: A device is a state machine: the bus, PL011 and PL031
A guest makes a 4-byte read at
0x0900_0ffe, two bytes below the end of the PL011's window. Which register does the PL011 see?Show answer
None. The access starts inside the window but runs past its end, so the bus answers
BusError::Straddleand the VMM treats it like an access to no device at all. No device ever sees a partial access, so no device has to reason about one.From chapter 09: A device is a state machine: the bus, PL011 and PL031
The guest stops reading its UART, and you keep typing. Why must the stdin thread's push into
SerialInputdrop bytes instead of waiting for room?Show answer
The same thread reads Ctrl-A x. If it blocked waiting for the guest, a guest that never reads would also stop the host from seeing the quit keys, and the user would lose every in-band way out. So
SerialInputholds 4 KiB, drops and counts the rest, and the thread goes straight back toread.From chapter 09: A device is a state machine: the bus, PL011 and PL031
You press Ctrl-A x in a running
macvmm, and in another run you send it SIGTERM. Which exit code do you get each time, and why that number?Show answer
130 both times. 130 is the shell's code for "ended by SIGINT" (128 + 2), and macvmm uses it for every user quit. A program killed by SIGTERM would report 143, but macvmm catches the signal, stops the VM cleanly and chooses its own code.
From chapter 09: A device is a state machine: the bus, PL011 and PL031
A guest prints the four bytes
ESC [ 6 nto the UART. What would your terminal do with them, and what does macvmm's output filter do?Show answer
They ask the terminal for the cursor position, and the terminal types its answer into the program's input, where the guest, or after macvmm exits your shell, would read it. The default (
safe) filter drops the sequence, so it never reaches the terminal.From chapter 09: A device is a state machine: the bus, PL011 and PL031
Why does the PL031 read the host's wall clock on every
RTCDRaccess instead of storing the boot time and adding the time elapsed since?Show answer
A monotonic clock such as Rust's
Instantstops while the Mac sleeps, so "boot time + elapsed" would fall behind the real date by every hour of sleep. Reading the wall clock each time stays right; the reference also never lets the value go backwards if the host clock is stepped back.From chapter 09: A device is a state machine: the bus, PL011 and PL031
A driver makes an 8-byte read of the PL011's
FR(offset0x18), then a 1-byte read of the same register. What does each return?Show answer
The 8-byte read returns 0, with a rate-limited warning: the PL011's registers are at most 32 bits wide, so that access names no register and is read-as-zero, write-ignored. The 1-byte read returns the low byte of
FR,0x90after reset: a narrow access at a register's offset reaches the register.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-bitwregister; WnR (bit 6) is 1, a write. A 4-byte store fromw2, such asstr w2, [x1].From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A trapped store has SRT = 31. What value does the VMM send to the device, and why must it never pass 31 to
hv_vcpu_get_reg?Show answer
Zero: in the data-register field of a load or store, 31 means
xzr, which reads as 0. In Hypervisor.framework's register numbering, 31 isHV_REG_PC, so passing it through would send the guest's PC to the device (and a load intoxzrwould overwrite the PC).From chapter 07: The exit loop: decoding syndromes and emulating MMIO
The test device holds
0x8001at some offset. What ends up in the destination register forldrh w3,ldrsh w3andldrsh x3from that offset?Show answer
ldrh w3gives0x8001(zero-extended).ldrsh w3gives0xffff8001: sign-extended to 32 bits, and writing awregister clears the upper half.ldrsh x3gives0xffffffffffff8001, sign-extended to 64 bits. SSE says whether to sign-extend; SF says to which width.From chapter 07: The exit loop: decoding syndromes and emulating MMIO
After your VMM handles each of these exits, where must the PC point before the next run: an
hvc, ansmc, and a data abort it emulated?Show answer
hvc: leave it, the hardware already moved it past the call.smc: add 4, it was intercepted before it executed. Data abort: add 4, the saved PC is the faulting instruction (a fault retries), and the VMM has now done its work.From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A guest runs
ldp x0, x1, [x2]withx2pointing into a device window. What is ISV in the syndrome, why, and what does this chapter's VMM do?Show answer
ISV is 0. The note has room for one register number (SRT) and one size, and a pair load moves two registers, so the hardware cannot describe it. The other syndrome fields are then UNKNOWN, so the VMM stops the VM with a fatal error that prints the instruction word, instead of guessing.
From chapter 07: The exit loop: decoding syndromes and emulating MMIO
The guest runs
strb w5, [x1]to a device, withx5 = 0x12345678. What value must reach the device, and which field tells you?Show answer
0x78. SAS is 0, so the access is 1 byte, and the VMM masks the register's value to that size before writing. Sending all ofx5would let the guest write bytes it never stored.From chapter 07: The exit loop: decoding syndromes and emulating MMIO
Why must
Exit::decodereturn a value for every possible 64-bit input instead of panicking on a value it does not expect?Show answer
The syndrome is the hardware's description of what a possibly hostile guest did. If some value made the decoder panic, the guest could crash the VMM on purpose by producing it. The checkpoint feeds the decoder a million random values to check this.
From chapter 07: The exit loop: decoding syndromes and emulating MMIO
Your VMM forgets to advance the PC after an emulated store. What does the exit trace look like, and how does the run end?
Show answer
The same record over and over: same
pc, sameipa, samevalue, onlyt_nsgrowing, hundreds of thousands per second. The guest retries the store forever, and the run ends only when--timeoutstops it (exit code 5).From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A guest stops with a fatal error after a long run. Where do you look first to see what led up to it, and what does it hold?
Show answer
The
last exits:part of the dump: the vCPU's ring of recent exits, oldest first, with the fatal one last. The ring keeps the last 256 exits of each vCPU whether or not--traceis on, and the dump prints the last 32.From chapter 03: A guest of your own, and what an exit costs
A guest prints
okand a newline through DEBUG_PUTC, then powers off. How many records with"ec":"0x16"does--trace exits:t.jsonl:hvcwrite, and why?Show answer
Four. Each printed byte is one
hvc(three bytes:o,k, newline), and the power-off call is one morehvc. Every one is an exception of class0x16.From chapter 03: A guest of your own, and what an exit costs
Decode the hypercall ID
0xC600_4D02field by field.Show answer
Bit 31 = 1, a fast call; bit 30 = 1, the 64-bit convention; bits 29 to 24 =
0x06, owner 6, vendor-specific hypervisor service; low 16 bits =0x4D02, the function. In macvmm that is DEBUG_EXIT, with the exit code inx1.From chapter 03: A guest of your own, and what an exit costs
A guest calls DEBUG_EXIT with
x1 = 3. What exit status doesmacvmmreturn to the shell, and what would it return forx1 = 0?Show answer
6 for any non-zero guest code (and it prints
guest exit code 3); 0 for code 0. The guest's own number and the monitor's exit status are different things.From chapter 03: A guest of your own, and what an exit costs
The flat binary of a guest is 11,866 bytes, and its linker map puts
__bss_startat0x40082e60with the image linked at0x40080000. After--raw guest.bin@0x40080000, what does a zero-initialised static at0x40082e60contain before_startruns?Show answer
Whatever that RAM held before: the file ends at offset 11,866 and
0x2e60is 11,872, so no byte of the file lands there. It reads 0 only if the monitor happened to hand over fresh, zeroed memory;_startmust zero the BSS itself.From chapter 03: A guest of your own, and what an exit costs
Your loader checks
addr + len <= ram_endwith a plain+. A user passes a 0x2000-byte file at address0xffff_ffff_ffff_f000. What goes wrong, and what is the fix?Show answer
With Rust's default release settings the sum wraps to
0x1000, which is below the end of RAM, so the check passes and the copy runs off the top of memory (withoverflow-checkson, as in our workspace, it panics instead: a crash, still not a clean refusal). Usechecked_addand refuse the file, exit code 2, when it returnsNone.From chapter 03: A guest of your own, and what an exit costs
exit-benchreports 3,600,000 ticks for 100,000 calls on a 24 MHz counter. What is one round trip in nanoseconds?Show answer
3,600,000 / 24,000,000 s = 0.15 s; divided by 100,000 that is 1.5 µs, 1,500 ns per round trip.
From chapter 03: A guest of your own, and what an exit costs
Why can a single store instruction not be timed with
CNTVCT_EL0, and what doesexit-bench's method do instead?Show answer
The counter ticks at 24 MHz, once every 41.7 ns, while a store takes a fraction of a nanosecond, so one store almost never spans a tick. Timing a loop of a million stores and dividing by a million gives the average.
From chapter 03: A guest of your own, and what an exit costs
A guest spins in
b .and you run it with--timeout 1. Why can the vCPU's own thread not notice the timeout, and what exit status do you get?Show answer
The thread is blocked inside
hv_vcpu_run, which does not return while the guest runs without exiting, so it cannot look at a clock. Another thread must notice the deadline and stop it (the reference kicks the vCPU; ending the process also works). The exit status is 5.From chapter 03: A guest of your own, and what an exit costs
After a DEBUG_PUTC exit, your run loop adds 4 to the PC before resuming. What happens to the guest?
Show answer
It skips the instruction after the
hvc. The hardware already saved the PC past thehvc(a call continues after itself), so the extra 4 jumps over code the guest meant to run; anhvcexit must resume with the PC unchanged.From chapter 03: A guest of your own, and what an exit costs
You delete
mov sp, x10from_start. The run prints nothing and the trace's only record iscanceledatpc=0x40080a00, with the guest's vectors at0x40080800. Where was the CPU, and why did no exit report the fault?Show answer
In the guest's own vector entry at
VBAR_EL1 + 0x200, for an exception taken at EL1 itself. Withsp= 0, the first stack store used an address no memory could have, so the fault was taken by the guest's own level, not forwarded to EL2; the handler then faulted on the same bad stack, again and again, until the timeout's kick stopped it.
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-cellsand#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 bycompatible; the DTB as a promise generated from the device table; fresh seeds; handing it over inx0. - 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 overhvc(chapter 08); the PL011, the PL031, their PrimeCell identification registers and theBus(chapter 09). - Primers (read first):
arm64-boot-protocol(what a kernel expects inx0and 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;
dtcas 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 nonemode (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
regproperty from the parent's#address-cellsand#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 whatdtcreports. - (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/chosenfromlayout.rs, fill the seeds from host randomness, and pass the blob's address inx0.
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:
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --timeout 10dtb-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: doneIt 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:
cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10macvmm: 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}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:
/// 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):
cargo run -q -p macvmm -- run --mem 64M --irqchip none --raw $G/hello.bin@0x40080000 --dtb-out v.dtb --timeout 10hello from guest, x0=0x40000000guest doneThe 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.
dtc -I dtb -O dts v.dtb/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"; };};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:
| Node | Properties that matter | What the kernel learns |
|---|---|---|
/ | compatible = "linux,dummy-virt", model, #address-cells = <2>, #size-cells = <2>, dma-coherent | a generic virtual board, and its name; how its children write addresses; devices see memory as the CPU does |
/chosen | stdout-path, rng-seed, kaslr-seed | where to print first, and random seeds; settings, not a device |
/memory@40000000 | device_type = "memory", reg | where RAM is and how much (64 MiB here) |
/cpus/cpu@0 | device_type = "cpu", reg = <0x00>, enable-method = "psci" | one CPU, identity 0, started through PSCI |
/psci | method = "hvc" | PSCI calls go through hvc, chapter 08's path |
/timer | compatible = "arm,armv8-timer", always-on | the CPU has Arm's generic timer (chapter 11), and it keeps counting in low-power states |
/apb-pclk | clock-frequency, #clock-cells = <0>, phandle = <0x02> | a fixed 24 MHz clock others can point to |
/pl011@9000000, /pl031@9010000 | compatible, reg, clocks | which 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:
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 explorerIf 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:
grep -obUa 'pl011@9000000' v.dtb189:pl011@9000000788:pl011@9000000Dump from 4 bytes before the second hit:
xxd -s 784 -l 80 v.dtb00000310: 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............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:
xxd -l 64 v.dtb00000000: 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 ................| Bytes | Field | Ours | Meaning |
|---|---|---|---|
| 0 to 3 | magic | d00dfeed | "this is a DTB" |
| 4 to 7 | totalsize | 0x4f7 | 1271 bytes in all |
| 8 to 11 | off_dt_struct | 0x38 | where the structure block starts |
| 12 to 15 | off_dt_strings | 0x424 | where the strings block starts |
| 16 to 19 | off_mem_rsvmap | 0x28 | where the reservation map starts |
| 20 to 23 | version | 0x11 = 17 | the format we write |
| 24 to 27 | last_comp_version | 0x10 = 16 | the oldest version a reader may be and still understand us |
| 28 to 31 | boot_cpuid_phys | 0 | the reg of the CPU that boots |
| 32 to 35 | size_dt_strings | 0xd3 | strings block length |
| 36 to 39 | size_dt_struct | 0x3ec | structure 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):
cp v.dtb bad.dtbprintf '\x25' | dd of=bad.dtb bs=1 seek=15 conv=notruncdtc -I dtb -O dts bad.dtbdtc -I dtb -O dts bad.dtbFATAL ERROR: String table extends past total sizeThe 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:
dtc -f -I dtb -O dts bad.dtb 2>/dev/null | head -20/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>; };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:
/// `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:
/// 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:
/// 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:
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:
/// 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:
/// 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:
/// 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:
/// 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:
/// 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:
// 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:
/// 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())}/// 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)}/// 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:
/// 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:
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/:
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:
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:
/// 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:
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:
/// 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:
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", ®64(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:
/// 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", ®64(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:
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:
/// `/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:
/// 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:
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:
/cpus, with#address-cells = <1>,#size-cells = <0>, and onecpu@Nper vCPU withdevice_type = "cpu",compatible = "arm,arm-v8",enable-method = "psci"and areg. Thatregis the vCPU's affinity: itsMPIDR_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, whoseMPIDR_EL1is0x8000_0000, hasreg = <0x0>and iscpu@0; the unit address is that number in hex./psci, with the threecompatiblestrings andmethod = "hvc", so the guest's power calls take chapter 08's path./timer, with its twocompatiblestrings and the empty propertyalways-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):
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):
/// 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:
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:
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/:
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --timeout 10cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --timeout 10dtb-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: doneWe 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.
cargo run -q -p macvmm -- run --mem 64M --raw $G/dtb-reader.bin@0x40080000 --dtb-out c.dtb --timeout 10We 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:
cargo run -q -p macvmm -- run --mem 64M --irqchip none --raw $G/dtb-reader.bin@0x40080000 --dtb-out c.dtb --timeout 10dtb-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: doneThe same reg=0x40000000+0x4000000. If you predicted that, you were right for the wrong reason. Here is how dtb-reader reads memory:
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:
dtc -I dtb -O dts -o /dev/null c.dtb/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'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:
cargo run -q -p macvmm -- run --mem 512M --kernel $C/Image-virt --initrd $C/initramfs-test.img --serial file:boot.txt --timeout 15macvmm: timeout: the guest was still running after --timeout 15sFrom 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:
head -9 boot.txt | tr -d '\r'[ 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 fffffffffe429000Machine 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:
scripts/checkpoint.sh 10[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 FAILWhat 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.
cargo run -q -p macvmm -- run --mem 512M --kernel $C/Image-virt --initrd $C/initramfs-test.img --serial file:boot.txt --timeout 20macvmm: 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}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 15macvmm: 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)grep -a -e pl031 -e 'ready' boot.txt | tr -d '\r'[ 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)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 MacRun this from the repository root:
scripts/checkpoint.sh 10You should see, as the last line:
CHECKPOINT 10 PASSIt 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:
scripts/checkpoint.sh 10[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 PASSWhat 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 fromlayout.rs, with fresh seeds, anddtcaccepts it without a warning; - the guest finds the tree through
x0 = 0x40000000, and a guest that reads it learns wherelayout.rsput 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_versionpromise a reader of version 16? - Devicetree Specification v0.4, section 2.3.5 (
#address-cellsand#size-cells): whose counts apply to a node'sreg, 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?