indicogniBuild a VMM

Contents

Chapter 15 · Part VII

Rings and a doorbell: the virtio-mmio transport

Needs a Mac Runs in browser ~4.5 h Lab: Virtio status handshake · Lab: Virtqueue visualizer
16 of 26

Course progress: chapter 15 is 16 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 14: Booting Linux to a shell

    A Linux boot log ends with timer_probe: no matching timers found, then Kernel panic - not syncing: Unable to initialise architected timer., and macvmm exits 5 after --timeout. What is wrong with the machine, and why did the VMM not stop on its own?

    Show answer

    The device tree has no /timer node (or one whose compatible Linux does not match), so stage 4 of the boot cannot find a clock and panics. A panicked kernel spins inside the guest without touching anything that traps, so the run loop sees no exit; only --timeout (exit 5) ends the run.

  2. From chapter 12: Why an interrupt controller, and why in the kernel

    A device tree node says interrupts = <0 5 4> under a GICv3. Which INTID will the device's interrupt arrive as, and how is it triggered?

    Show answer

    INTID 37. The first cell 0 means SPI (shared peripheral interrupt), and SPI n is INTID 32 + n, so SPI 5 is INTID 37. The third cell 4 means level-sensitive, active high.

  3. From chapter 08: System registers, injection, hypercalls and PSCI

    A VM exit reports the syndrome 0x62280520. Which instruction stopped the guest, and on which register?

    Show answer

    0x62280520 >> 26 = 0x18: a trapped msr or mrs. The ISS 0x280520 gives Op0 2, Op2 4, Op1 0, CRn 1, Rt 9, CRm 0, direction 0: an msr (a write) from x9 to the register at (2, 0, 1, 0, 4), which is OSLAR_EL1.

Concepts you'll need

Chapters before this one: chapter 14, Booting Linux to a shell.

  • Core, taught here: why virtio exists (one driver for every hypervisor, and far fewer exits), before any register; DMA (direct memory access), a device reading and writing RAM by itself (bus mastering); the doorbell (QueueNotify) and the used-buffer interrupt; the virtio-mmio version 2 transport, each register derived from a question; the device status state machine and feature negotiation; DEVICE_NEEDS_RESET; empty slots.
  • Core, from earlier: exit cost (chapters 03 and 14); paravirtual devices (chapter 00); GuestMemory and check_range (chapter 04); the virtio slots (chapter 05); MmioDevice and RAZ/WI (chapter 09); the device tree (chapter 10); level-triggered lines (chapter 11) and TestIrq (chapter 09).
  • Primers (review): reading-arm-specs (its section on MUST and SHOULD in the virtio specification); host-concurrency (locks and lost updates, for the interrupt's mutex).
  • Pointers: emulated NVMe (Non-Volatile Memory Express) and AHCI (Advanced Host Controller Interface) disk controllers, which have rings in real hardware (an Aside); the virtio 1.2 specification, section 4.2.2; virtio over PCI (a Production note).
  • Forward definitions: virtqueue, the ring the driver and device share (chapter 16 lays it out); descriptor, one entry of that ring (chapter 16); the device worker thread (chapter 17); TOCTOU, time of check to time of use (chapter 16). Each is defined in a sentence where it first appears.

Chapter 14 had you measure the cost of console text: between 2.4 and 2.7 virtual machine (VM) exits for every byte (2.4 for the shell's output, 2.7 for the boot log). Take the boot log: its 12,093 bytes left our PL011 serial port at a cost of about 32,800 memory-mapped I/O (MMIO) exits (VM exits caused by device register accesses). Now imagine that machinery behind a disk, where a 4 KiB block is a small request and a 64 MiB file an ordinary one. How could any design do better, while the guest still has to tell us what to write?

Predict A guest writes one 4 KiB block. Estimate the VM exits for (a) a disk built like our PL011, one register access per byte, (b) an emulated NVMe (Non-Volatile Memory Express) controller, the interface of most modern SSDs (solid-state drives), whose driver also writes requests into a queue in RAM and pokes one register, and (c) a virtio disk. Is (b) about the same as (c)?

Write your three numbers and one sentence of reasoning under ## Predict in your journal (its prompt repeats this question). Coarse answers are fine. Sitting A measures the PL011's cost per byte, which gives (a), and measures (c) on a real Mac; (b) we can only estimate. The answer comes in "Why a standard: virtio" below, after the measurements.

This chapter works on row 8 of the problem ledger, bulk I/O at a reasonable cost: by its end the transport that every fast device of this course uses is in place, and chapters 16 to 19 build the devices behind it.

Objectives: by the end you can

  • (Sitting A) From the measured cost of a PL011 byte and of one exit, explain why per-byte I/O is unaffordable, and derive the alternative: the data stays in guest RAM, the device reads and writes it there (DMA), one exit says "look now" (a doorbell) and one interrupt says "done".
  • (Sitting A) Compare virtio honestly with an emulated NVMe controller, which also uses rings and doorbells, and say what virtio's design for virtual machines adds.
  • (Sitting B) Derive each virtio-mmio register from a question the ring raises, and implement them as an MmioDevice, with every access width answered.
  • (Sitting B) Enforce the status state machine (bits in order, features checked, queues frozen, a bad ring answered with DEVICE_NEEDS_RESET), and drive the interrupt as a level line.
  • (Sitting B) Serve 32 slots, the empty ones answering DeviceID 0 on the bus while absent from the device tree, and verify it with virtio-probe.

Before you start. From the repository root, run scripts/learner start 15, which copies this chapter's journal to learner/journal/15.md. Sitting A runs the finished reference from the repository root; sitting B is code in learner/crates/vmm/src/virtio/: mod.rs, queue.rs, interrupt.rs, null.rs and mmio.rs, in an order given at its start.

What one byte costs

Here is chapter 14's measurement on a plain boot, every MMIO exit recorded by chapter 07's trace. scripts/run-linux.sh runs from the repository root, so give it absolute paths:

Shell
mkdir -p /tmp/ch15scripts/run-linux.sh --test boot --stats --trace exits:/tmp/ch15/boot.jsonl:mmio
TerminalReal output
scripts/run-linux.sh --test boot --stats --trace exits:/tmp/ch15/boot.jsonl:mmioexit: 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] OF: reserved mem: Reserved memory: No reserved-memory node in the DT[    0.000000] NUMA: Faking a node at [mem 0x0000000040000000-0x000000005fffffff][    0.000000] NODE_DATA(0) allocated [mem 0x5fd03780-0x5fd05c3f][    0.000000] Zone ranges:[    0.000000]   DMA      [mem 0x0000000040000000-0x000000005fffffff][    0.000000]   DMA32    empty[    0.000000]   Normal   empty[    0.000000] Movable zone start for each node[    0.000000] Early memory node ranges[    0.000000]   node   0: [mem 0x0000000040000000-0x000000005fffffff][    0.000000] Initmem setup node 0 [mem 0x0000000040000000-0x000000005fffffff][    0.000000] psci: probing for conduit method from DT.[    0.000000] psci: PSCIv1.1 detected in firmware.[    0.000000] psci: Using standard PSCI v0.2 function IDs[    0.000000] psci: Trusted OS migration not required[    0.000000] psci: SMC Calling Convention v1.1[    0.000000] percpu: Embedded 34 pages/cpu s99608 r8192 d31464 u139264[    0.000000] Detected PIPT I-cache on CPU0[    0.000000] CPU features: detected: Address authentication (IMP DEF algorithm)[    0.000000] CPU features: detected: GICv3 CPU interface[    0.000000] CPU features: detected: Spectre-v4[    0.000000] CPU features: detected: Spectre-BHB[    0.000000] alternatives: applying boot alternatives[    0.000000] Kernel command line: console=ttyAMA0 earlycon=pl011,0x09000000 macvmm.test=boot[    0.000000] printk: log buffer data + meta data: 131072 + 458752 = 589824 bytes[    0.000000] Dentry cache hash table entries: 65536 (order: 7, 524288 bytes, linear)[    0.000000] Inode-cache hash table entries: 32768 (order: 6, 262144 bytes, linear)[    0.000000] software IO TLB: SWIOTLB bounce buffer size adjusted to 0MB[    0.000000] software IO TLB: area num 1.[    0.000000] software IO TLB: mapped [mem 0x000000005f380000-0x000000005f400000] (0MB)[    0.000000] Fallback order for Node 0: 0 [    0.000000] Built 1 zonelists, mobility grouping on.  Total pages: 131072[    0.000000] Policy zone: DMA[    0.000000] mem auto-init: stack:all(zero), heap alloc:on, heap free:off[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1[    0.000000] Dynamic Preempt: none[    0.000000] rcu: Preemptible hierarchical RCU implementation.[    0.000000] rcu: 	RCU restricting CPUs from NR_CPUS=4096 to nr_cpu_ids=1.[    0.000000] 	Trampoline variant of Tasks RCU enabled.[    0.000000] 	Tracing variant of Tasks RCU enabled.[    0.000000] rcu: RCU calculated value of scheduler-enlistment delay is 100 jiffies.[    0.000000] rcu: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=1[    0.000000] RCU Tasks: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] RCU Tasks Trace: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] NR_IRQS: 64, nr_irqs: 64, preallocated irqs: 0[    0.000000] GICv3: 988 SPIs implemented[    0.000000] GICv3: 0 Extended SPIs implemented[    0.000000] Root IRQ handler: gic_handle_irq[    0.000000] GICv3: GICv3 features: 16 PPIs, RSS[    0.000000] GICv3: GICD_CTLR.DS=1, SCR_EL3.FIQ=0[    0.000000] GICv3: CPU0: found redistributor 0 region 0:0x00000000080a0000[    0.000000] rcu: srcu_init: Setting srcu_struct sizes based on contention.[    0.000000] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 1911260446275000 ns[    0.000000] arch_timer: cp15 timer running at 24.00MHz (virt).[    0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x588fe9dc0, max_idle_ns: 440795202592 ns[    0.000000] sched_clock: 56 bits at 24MHz, resolution 41ns, wraps every 4398046511097ns[    0.001424] kfence: initialized - using 2097152 bytes for 255 objects at 0x(____ptrval____)-0x(____ptrval____)[    0.002930] Console: colour dummy device 80x25[    0.003786] Calibrating delay loop (skipped), value calculated using timer frequency.. 48.00 BogoMIPS (lpj=24000)[    0.005194] pid_max: default: 32768 minimum: 301[    0.005932] LSM: initializing lsm=lockdown,capability,landlock,yama[    0.006912] landlock: Up and running.[    0.007492] Yama: becoming mindful.[    0.008020] Mount-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.009078] Mountpoint-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.010577] rcu: Hierarchical SRCU implementation.[    0.011317] rcu: 	Max phase no-delay instances is 400.[    0.012217] EFI services will not be available.[    0.013131] smp: Bringing up secondary CPUs ...[    0.014765] smp: Brought up 1 node, 1 CPU[    0.015353] SMP: Total of 1 processors activated.[    0.016928] CPU: All CPU(s) started at EL1[    0.017697] CPU features: detected: Branch Target Identification[    0.018603] CPU features: detected: ARMv8.4 Translation Table Level[    0.019478] CPU features: detected: Data cache clean to the PoU not required for I/D coherence[    0.020681] CPU features: detected: Common not Private translations[    0.021525] CPU features: detected: CRC32 instructions[    0.022378] CPU features: detected: Data independent timing control (DIT)[    0.023511] CPU features: detected: E0PD[    0.024086] CPU features: detected: Enhanced Privileged Access Never[    0.025073] CPU features: detected: Generic authentication (IMP DEF algorithm)[    0.026197] CPU features: detected: RCpc load-acquire (LDAPR)[    0.027066] CPU features: detected: LSE atomic instructions[    0.027931] CPU features: detected: Privileged Access Never[    0.028687] CPU features: detected: RAS Extension Support[    0.029449] CPU features: detected: Speculation barrier (SB)[    0.030257] CPU features: detected: TLB range maintenance instructions[    0.031158] CPU features: detected: Scalable Matrix Extension[    0.032041] CPU features: detected: SME2[    0.032633] alternatives: applying system-wide alternatives[    0.034314] SME: minimum available vector length 64 bytes per vector[    0.035235] SME: maximum available vector length 64 bytes per vector[    0.036162] SME: default vector length 64 bytes per vector[    0.036953] Memory: 464096K/524288K available (13312K kernel code, 1994K rwdata, 8460K rodata, 2048K init, 9282K bss, 57716K reserved, 0K cma-reserved)[    0.039374] devtmpfs: initialized[    0.040238] posixtimers hash table entries: 512 (order: 1, 8192 bytes, linear)[    0.041275] futex hash table entries: 256 (16384 bytes on 1 NUMA nodes, total 16 KiB, linear).[    0.042629] 23904 pages in range for non-PLT usage[    0.042630] 515424 pages in range for PLT usage[    0.043518] pinctrl core: initialized pinctrl subsystem[    0.044997] DMI not present or invalid.[    0.046292] NET: Registered PF_NETLINK/PF_ROUTE protocol family[    0.047469] DMA: preallocated 128 KiB GFP_KERNEL pool for atomic allocations[    0.048792] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA pool for atomic allocations[    0.050014] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA32 pool for atomic allocations[    0.051168] audit: initializing netlink subsys (disabled)[    0.052145] thermal_sys: Registered thermal governor 'step_wise'[    0.052152] audit: type=2000 audit(0.032:1): state=initialized audit_enabled=0 res=1[    0.054199] cpuidle: using governor ladder[    0.054830] cpuidle: using governor menu[    0.055412] hw-breakpoint: found 6 breakpoint and 4 watchpoint registers.[    0.056582] ASID allocator initialised with 65536 entries[    0.057394] Serial: AMBA PL011 UART driver[    0.058162] 9000000.pl011: ttyAMA0 at MMIO 0x9000000 (irq = 13, base_baud = 0) is a PL011 rev1[    0.059498] printk: console [ttyAMA0] enabled[    0.059498] printk: console [ttyAMA0] enabled[    0.060627] printk: legacy bootconsole [pl11] disabled[    0.060627] printk: legacy bootconsole [pl11] disabled[    0.062991] HugeTLB: registered 1.00 GiB page size, pre-allocated 0 pages[    0.062992] HugeTLB: 0 KiB vmemmap can be freed for a 1.00 GiB page[    0.062992] HugeTLB: registered 32.0 MiB page size, pre-allocated 0 pages[    0.062992] HugeTLB: 0 KiB vmemmap can be freed for a 32.0 MiB page[    0.062993] HugeTLB: registered 2.00 MiB page size, pre-allocated 0 pages[    0.062993] HugeTLB: 0 KiB vmemmap can be freed for a 2.00 MiB page[    0.062993] HugeTLB: registered 64.0 KiB page size, pre-allocated 0 pages[    0.062993] HugeTLB: 0 KiB vmemmap can be freed for a 64.0 KiB page[    0.063150] ACPI: Interpreter disabled.[    0.063156] iommu: Default domain type: Translated[    0.063156] iommu: DMA domain TLB invalidation policy: lazy mode[    0.063318] clocksource: Switched to clocksource arch_sys_counter[    0.076401] VFS: Disk quotas dquot_6.6.0[    0.076406] VFS: Dquot-cache hash table entries: 512 (order 0, 4096 bytes)[    0.076672] pnp: PnP ACPI: disabled[    0.077098] NET: Registered PF_INET protocol family[    0.077117] IP idents hash table entries: 8192 (order: 4, 65536 bytes, linear)[    0.084709] tcp_listen_portaddr_hash hash table entries: 256 (order: 0, 4096 bytes, linear)[    0.084714] Table-perturb hash table entries: 65536 (order: 6, 262144 bytes, linear)[    0.084717] TCP established hash table entries: 4096 (order: 3, 32768 bytes, linear)[    0.084721] TCP bind hash table entries: 4096 (order: 5, 131072 bytes, linear)[    0.084724] TCP: Hash tables configured (established 4096 bind 4096)[    0.084746] MPTCP token hash table entries: 512 (order: 2, 12288 bytes, linear)[    0.084751] UDP hash table entries: 256 (order: 2, 16384 bytes, linear)[    0.084752] UDP-Lite hash table entries: 256 (order: 2, 16384 bytes, linear)[    0.084767] NET: Registered PF_UNIX/PF_LOCAL protocol family[    0.084772] NET: Registered PF_XDP protocol family[    0.084775] PCI: CLS 0 bytes, default 64[    0.084849] Unpacking initramfs...[    0.094733] kvm [1]: HYP mode not available[    0.094893] Initialise system trusted keyrings[    0.094989] workingset: timestamp_bits=44 max_order=17 bucket_order=0[    0.102383] Key type asymmetric registered[    0.102386] Asymmetric key parser 'x509' registered[    0.102427] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 248)[    0.114393] io scheduler mq-deadline registered[    0.114396] io scheduler kyber registered[    0.114412] io scheduler bfq registered[    0.114790] Serial: 8250/16550 driver, 4 ports, IRQ sharing enabled[    0.115292] hv_vmbus: registering driver hyperv_keyboard[    0.118259] rtc-pl031 9010000.pl031: registered as rtc0[    0.118269] rtc-pl031 9010000.pl031: setting system clock to 2026-11-20T09:45:08 UTC (1795167908)[    0.118365] NET: Registered PF_INET6 protocol family[    0.120407] Segment Routing with IPv6[    0.120410] In-situ OAM (IOAM) with IPv6[    0.123964] registered taskstats version 1[    0.124018] Loading compiled-in X.509 certificates[    0.182678] Freeing initrd memory: 9204K[    0.187134] Loaded X.509 cert 'alpinelinux.org: Alpine Linux kernel key: 87fa969a47f3e2a6aa35859eb932a17c95abcd82'[    0.190027] Demotion targets for Node 0: null[    0.190081] Key type .fscrypt registered[    0.190082] Key type fscrypt-provisioning registered[    0.191925] clk: Disabling unused clocks[    0.191929] PM: genpd: Disabling unused power domains[    0.195396] Freeing unused kernel memory: 2048K[    0.195422] Run /init as init processmacvmm-initramfs: ready 6.18.60-0-virt[    0.200507] reboot: Power down--- stderr ---macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=12093 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 32829: hvc 16, sysreg 2, data abort 32811macvmm: stats: vcpu0 time: exec 0.111 s, wfi 0.000 smacvmm: stats: host cpu 0.252 s over 0.270 s wall (94%)macvmm: stats: rlimit core=0 nofile=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run from the repository root (scripts/run-linux.sh always runs there); the trace goes to /tmp/ch15.
course/captures/15-pl011-boot.txt

Skip to the stats: serial_written=12093, and data abort 32811, the stage-2 faults that MMIO accesses become (chapter 07). Which registers took them? Count the trace by address and direction:

TerminalReal output
grep -o '"ipa":"0x90[0-9a-f]*","wnr":[a-z]*' /tmp/ch15/boot.jsonl | sort | uniq -c | sort -rnexit: 0--- stdout ---20490 "ipa":"0x9000018","wnr":false12093 "ipa":"0x9000000","wnr":true 123 "ipa":"0x9000030","wnr":true  65 "ipa":"0x9000030","wnr":false   5 "ipa":"0x9000038","wnr":true   3 "ipa":"0x9010000","wnr":false   3 "ipa":"0x9000044","wnr":true   2 "ipa":"0x900002c","wnr":true   2 "ipa":"0x9000028","wnr":true   2 "ipa":"0x9000024","wnr":true   1 "ipa":"0x9010ffc","wnr":false   1 "ipa":"0x9010ff8","wnr":false   1 "ipa":"0x9010ff4","wnr":false   1 "ipa":"0x9010ff0","wnr":false   1 "ipa":"0x9010fec","wnr":false   1 "ipa":"0x9010fe8","wnr":false   1 "ipa":"0x9010fe4","wnr":false   1 "ipa":"0x9010fe0","wnr":false   1 "ipa":"0x9010014","wnr":false   1 "ipa":"0x9010010","wnr":false   1 "ipa":"0x901000c","wnr":true   1 "ipa":"0x901000c","wnr":false   1 "ipa":"0x9010004","wnr":false   1 "ipa":"0x9000ffc","wnr":false   1 "ipa":"0x9000ff8","wnr":false   1 "ipa":"0x9000ff4","wnr":false   1 "ipa":"0x9000ff0","wnr":false   1 "ipa":"0x9000fec","wnr":false   1 "ipa":"0x9000fe8","wnr":false   1 "ipa":"0x9000fe4","wnr":false   1 "ipa":"0x9000fe0","wnr":false   1 "ipa":"0x9000038","wnr":false   1 "ipa":"0x9000034","wnr":true
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The trace from 15-pl011-boot.txt: every MMIO exit at the PL011 (0x0900_0000) and the PL031 (0x0901_0000).
course/captures/15-pl011-count.txt

Two lines carry nearly everything: 12,093 writes to 0x9000000, the PL011's data register, one per byte; and 20,490 reads of 0x9000018, its flag register, which Linux polls before (and, in earlycon, after) each byte. Counting every PL011 line, that is 32,795 exits for 12,093 bytes, about 2.7 per byte: higher than the 2.4 of chapter 14's shell output, because so much of the boot log goes through earlycon.

Chapter 03 measured one bare HVC (hypervisor call) round trip at about 1.4 µs, and an MMIO exit costs more (decode, bus lookup, device lock), so take 1.4 µs as a floor. A 4 KiB block at 2.7 exits per byte is about 11,000 exits, at least 15 ms of entering and leaving the guest. A 64 MiB file is about 180 million exits: at least four minutes, for a copy your Mac's own disk does in a fraction of a second. Faster exits cannot close that gap; only fewer exits can.

Leave the data where it is

When the guest writes a block, the data is already in its RAM: the guest put it there. And our VMM (virtual machine monitor) can already read guest RAM safely, through chapter 04's GuestMemory. So why push the bytes through a register one at a time?

Here is the design that follows. The guest writes a short description of the request into its own RAM: "4096 bytes at address 0x4410_0000, write them to sector 8" (a disk counts in 512-byte sectors). It then touches one register, once, meaning "look now": one exit. Our device reads the description, copies the 4096 bytes straight out of guest RAM, does the write, puts a "done" note back into RAM, and raises an interrupt; with chapter 12's in-kernel GIC (Generic Interrupt Controller), raising it costs no exit.

Real hardware works the same way: a disk controller reads and writes main memory by itself, which is called bus mastering, or DMA (direct memory access), the forward definition chapter 04 promised. The register that says "look now" is a doorbell, and the interrupt that says "done" is a used-buffer notification: virtio calls a buffer the device has finished with "used". Our device "does DMA" by copying through GuestMemory. In the picture, EL1 (exception level 1) is the level the guest kernel runs at.

 guest kernel (EL1)              guest RAM                    our VMM (host) -----------                     ---------                    -------------- 1. write the data       --->    [ data: 4096 bytes ] 2. write a description  --->    [ ring: addr, len  ] 3. store to the doorbell ------------ one VM exit ------->   4. read the ring                                 [ data ] <--- copy (DMA) --- 5. do the I/O                                 [ ring: done, len  ] <------ 6. write "done" 8. take the interrupt   <------------ level line -------    7. raise the line

Only step 3 is an exit; on virtio-mmio the guest's interrupt handler adds two register accesses (sitting B), however many bytes moved.

The description lives in a virtqueue: a ring of fixed-size slots in guest RAM, reused in a circle, so the guest can queue many requests behind one doorbell (chapter 16 lays it out). The visualizer, like the specification, calls one such description a descriptor. Try its ten-minute toy: one descriptor, one doorbell, one "done".

Lab

Virtqueue visualizer

Play the driver and the device on one split virtqueue: publish requests, ring the doorbell, walk and serve chains, reclaim them, then misbehave as the driver and watch which check refuses each hostile ring.

Runs in browserOpen full page: Virtqueue visualizer
One request through a virtqueue, and a ring the device refuses Top, the toy: the guest writes 4096 bytes at 0x4410_0000 into its RAM, writes descriptor 0 (addr 0x4410_0000, len 4096) and puts head 0 in the available ring, then stores to the doorbell at 0x0a00_0050, the first VM exit. Our VMM reads avail.idx, the head and the descriptor, copies the 4096 bytes out of guest RAM to disk sector 8, writes used element id 0, len 0, publishes used.idx 1 and raises the interrupt line with no exit. The guest's handler reads InterruptStatus and writes InterruptACK, two more exits: 3 in all, where the PL011 path needed about 11,000. Bottom, the hostile ring: N is 8, descriptor 0 at addr 0x4000_8000, len 8, flags NEXT, next 0 points at itself; avail.idx is 1 and next_avail 0, so 1 request is pending with head 0. The walk takes hop 1 with budget 8 to 7, and so on to hop 8 with budget 1 to 0; hop 9 finds the budget exhausted, the device answers virtqueue: ChainTooLong { budget: 8 }, sets DEVICE_NEEDS_RESET and raises a configuration interrupt. The toy: one descriptor, one doorbell, one "done" 1 guest writes 4096 bytes at 0x4410_0000 (ordinary RAM: no exit) 2 guest desc 0 = {0x4410_0000, 4096} avail.idx 0 -> 1 (no exit) 3 guest stores to QueueNotify 0x0a00_0050 exit 1 4 VMM reads avail.idx, head 0, desc 0 5 VMM copies 4096 bytes to disk sector 8 6 VMM used.ring[0] = {id 0, len 0} used.idx = 1 7 VMM raises the line (no exit) 8 guest InterruptStatus, InterruptACK exits 2 and 3 3 exits for 4096 bytes. Through the PL011: about 11,000. Hostile: descriptor 0's next is itself N = 8 desc 0: addr 0x4000_8000, len 8, flags NEXT, next 0 avail.idx 1, next_avail 0: 1 pending hop 1: desc 0 (budget 8 -> 7) ... hop 8: desc 0 (budget 1 -> 0) hop 9: budget exhausted virtqueue: ChainTooLong { budget: 8 } -> DEVICE_NEEDS_RESET and a configuration interrupt; the VM keeps running

Why a standard: virtio

Early hypervisors each invented their own ring format, which cost guests one disk driver per hypervisor. virtio is the agreement that ended this: a standard, maintained by the OASIS consortium (Organization for the Advancement of Structured Information Standards), for paravirtual devices, designed for virtual machines rather than copied from hardware. The same Linux, FreeBSD and U-Boot drivers work on QEMU, Firecracker, crosvm and, by the end of this part, your VMM. (U-Boot is a bootloader; the U-Boot primer introduces it.)

Virtio has two layers. The device layer says what a disk or an entropy source (a source of random numbers) means (chapters 17 to 19). The transport says how a driver finds a device, configures it and rings its doorbell. This chapter builds the transport called virtio-mmio: one MMIO window per device, which on our board are chapter 05's 32 slots of 0x200 bytes from 0x0a00_0000.

Is this not what a real NVMe drive does? Partly. NVMe, and the older AHCI (Advanced Host Controller Interface) behind SATA (Serial AT Attachment) disks, are hardware disk controllers that already use rings in RAM, DMA and doorbell registers. A VMM can emulate one, and guests then use their stock drivers.

Aside

The NVMe base specification, at nvmexpress.org, describes NVMe's submission and completion queues and their doorbells; its Doorbell Buffer Config command, added in NVMe 1.3, is the shadow-doorbell mechanism mentioned below.

Back to your prediction. We have no NVMe controller in macvmm, so we have not been able to check (b). What we can measure is (c). The finished reference (its virtio disk is chapter 18; your VMM has no --disk yet) booted Linux, which read a whole 64 MiB image of zeros:

Shell
dd if=/dev/zero of=/tmp/ch15/disk64.img bs=1m count=64scripts/run-linux.sh --test vda --stats --disk /tmp/ch15/disk64.img --trace exits:/tmp/ch15/vda.jsonl:mmio
TerminalReal output
scripts/run-linux.sh --test vda --stats --disk /tmp/ch15/disk64.img --trace exits:/tmp/ch15/vda.jsonl:mmioexit: 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] OF: reserved mem: Reserved memory: No reserved-memory node in the DT[    0.000000] NUMA: Faking a node at [mem 0x0000000040000000-0x000000005fffffff][    0.000000] NODE_DATA(0) allocated [mem 0x5fd03440-0x5fd058ff][    0.000000] Zone ranges:[    0.000000]   DMA      [mem 0x0000000040000000-0x000000005fffffff][    0.000000]   DMA32    empty[    0.000000]   Normal   empty[    0.000000] Movable zone start for each node[    0.000000] Early memory node ranges[    0.000000]   node   0: [mem 0x0000000040000000-0x000000005fffffff][    0.000000] Initmem setup node 0 [mem 0x0000000040000000-0x000000005fffffff][    0.000000] psci: probing for conduit method from DT.[    0.000000] psci: PSCIv1.1 detected in firmware.[    0.000000] psci: Using standard PSCI v0.2 function IDs[    0.000000] psci: Trusted OS migration not required[    0.000000] psci: SMC Calling Convention v1.1[    0.000000] percpu: Embedded 34 pages/cpu s99608 r8192 d31464 u139264[    0.000000] Detected PIPT I-cache on CPU0[    0.000000] CPU features: detected: Address authentication (IMP DEF algorithm)[    0.000000] CPU features: detected: GICv3 CPU interface[    0.000000] CPU features: detected: Spectre-v4[    0.000000] CPU features: detected: Spectre-BHB[    0.000000] alternatives: applying boot alternatives[    0.000000] Kernel command line: console=ttyAMA0 earlycon=pl011,0x09000000 macvmm.test=vda[    0.000000] printk: log buffer data + meta data: 131072 + 458752 = 589824 bytes[    0.000000] Dentry cache hash table entries: 65536 (order: 7, 524288 bytes, linear)[    0.000000] Inode-cache hash table entries: 32768 (order: 6, 262144 bytes, linear)[    0.000000] software IO TLB: SWIOTLB bounce buffer size adjusted to 0MB[    0.000000] software IO TLB: area num 1.[    0.000000] software IO TLB: mapped [mem 0x000000005f380000-0x000000005f400000] (0MB)[    0.000000] Fallback order for Node 0: 0 [    0.000000] Built 1 zonelists, mobility grouping on.  Total pages: 131072[    0.000000] Policy zone: DMA[    0.000000] mem auto-init: stack:all(zero), heap alloc:on, heap free:off[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1[    0.000000] Dynamic Preempt: none[    0.000000] rcu: Preemptible hierarchical RCU implementation.[    0.000000] rcu: 	RCU restricting CPUs from NR_CPUS=4096 to nr_cpu_ids=1.[    0.000000] 	Trampoline variant of Tasks RCU enabled.[    0.000000] 	Tracing variant of Tasks RCU enabled.[    0.000000] rcu: RCU calculated value of scheduler-enlistment delay is 100 jiffies.[    0.000000] rcu: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=1[    0.000000] RCU Tasks: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] RCU Tasks Trace: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] NR_IRQS: 64, nr_irqs: 64, preallocated irqs: 0[    0.000000] GICv3: 988 SPIs implemented[    0.000000] GICv3: 0 Extended SPIs implemented[    0.000000] Root IRQ handler: gic_handle_irq[    0.000000] GICv3: GICv3 features: 16 PPIs, RSS[    0.000000] GICv3: GICD_CTLR.DS=1, SCR_EL3.FIQ=0[    0.000000] GICv3: CPU0: found redistributor 0 region 0:0x00000000080a0000[    0.000000] rcu: srcu_init: Setting srcu_struct sizes based on contention.[    0.000000] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 1911260446275000 ns[    0.000000] arch_timer: cp15 timer running at 24.00MHz (virt).[    0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x588fe9dc0, max_idle_ns: 440795202592 ns[    0.000000] sched_clock: 56 bits at 24MHz, resolution 41ns, wraps every 4398046511097ns[    0.001369] kfence: initialized - using 2097152 bytes for 255 objects at 0x(____ptrval____)-0x(____ptrval____)[    0.002852] Console: colour dummy device 80x25[    0.003558] Calibrating delay loop (skipped), value calculated using timer frequency.. 48.00 BogoMIPS (lpj=24000)[    0.005139] pid_max: default: 32768 minimum: 301[    0.005804] LSM: initializing lsm=lockdown,capability,landlock,yama[    0.006775] landlock: Up and running.[    0.007281] Yama: becoming mindful.[    0.007785] Mount-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.009569] Mountpoint-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.011140] rcu: Hierarchical SRCU implementation.[    0.011844] rcu: 	Max phase no-delay instances is 400.[    0.012937] EFI services will not be available.[    0.013608] smp: Bringing up secondary CPUs ...[    0.014437] smp: Brought up 1 node, 1 CPU[    0.014989] SMP: Total of 1 processors activated.[    0.016106] CPU: All CPU(s) started at EL1[    0.016939] CPU features: detected: Branch Target Identification[    0.018265] CPU features: detected: ARMv8.4 Translation Table Level[    0.019230] CPU features: detected: Data cache clean to the PoU not required for I/D coherence[    0.020803] CPU features: detected: Common not Private translations[    0.021904] CPU features: detected: CRC32 instructions[    0.022901] CPU features: detected: Data independent timing control (DIT)[    0.024082] CPU features: detected: E0PD[    0.024596] CPU features: detected: Enhanced Privileged Access Never[    0.025400] CPU features: detected: Generic authentication (IMP DEF algorithm)[    0.026339] CPU features: detected: RCpc load-acquire (LDAPR)[    0.027166] CPU features: detected: LSE atomic instructions[    0.028035] CPU features: detected: Privileged Access Never[    0.028839] CPU features: detected: RAS Extension Support[    0.029627] CPU features: detected: Speculation barrier (SB)[    0.030454] CPU features: detected: TLB range maintenance instructions[    0.031373] CPU features: detected: Scalable Matrix Extension[    0.032387] CPU features: detected: SME2[    0.032943] alternatives: applying system-wide alternatives[    0.034853] SME: minimum available vector length 64 bytes per vector[    0.035779] SME: maximum available vector length 64 bytes per vector[    0.036758] SME: default vector length 64 bytes per vector[    0.037549] Memory: 464092K/524288K available (13312K kernel code, 1994K rwdata, 8460K rodata, 2048K init, 9282K bss, 57720K reserved, 0K cma-reserved)[    0.040008] devtmpfs: initialized[    0.041315] posixtimers hash table entries: 512 (order: 1, 8192 bytes, linear)[    0.042219] futex hash table entries: 256 (16384 bytes on 1 NUMA nodes, total 16 KiB, linear).[    0.043735] 23904 pages in range for non-PLT usage[    0.043737] 515424 pages in range for PLT usage[    0.044536] pinctrl core: initialized pinctrl subsystem[    0.046431] DMI not present or invalid.[    0.047904] NET: Registered PF_NETLINK/PF_ROUTE protocol family[    0.048906] DMA: preallocated 128 KiB GFP_KERNEL pool for atomic allocations[    0.050325] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA pool for atomic allocations[    0.051715] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA32 pool for atomic allocations[    0.052934] audit: initializing netlink subsys (disabled)[    0.053809] thermal_sys: Registered thermal governor 'step_wise'[    0.053815] audit: type=2000 audit(0.033:1): state=initialized audit_enabled=0 res=1[    0.056431] cpuidle: using governor ladder[    0.057476] cpuidle: using governor menu[    0.058195] hw-breakpoint: found 6 breakpoint and 4 watchpoint registers.[    0.059527] ASID allocator initialised with 65536 entries[    0.060704] Serial: AMBA PL011 UART driver[    0.061587] 9000000.pl011: ttyAMA0 at MMIO 0x9000000 (irq = 13, base_baud = 0) is a PL011 rev1[    0.062984] printk: console [ttyAMA0] enabled[    0.062984] printk: console [ttyAMA0] enabled[    0.064093] printk: legacy bootconsole [pl11] disabled[    0.064093] printk: legacy bootconsole [pl11] disabled[    0.066567] HugeTLB: registered 1.00 GiB page size, pre-allocated 0 pages[    0.066569] HugeTLB: 0 KiB vmemmap can be freed for a 1.00 GiB page[    0.066569] HugeTLB: registered 32.0 MiB page size, pre-allocated 0 pages[    0.066570] HugeTLB: 0 KiB vmemmap can be freed for a 32.0 MiB page[    0.066570] HugeTLB: registered 2.00 MiB page size, pre-allocated 0 pages[    0.066570] HugeTLB: 0 KiB vmemmap can be freed for a 2.00 MiB page[    0.066570] HugeTLB: registered 64.0 KiB page size, pre-allocated 0 pages[    0.066570] HugeTLB: 0 KiB vmemmap can be freed for a 64.0 KiB page[    0.066721] ACPI: Interpreter disabled.[    0.066727] iommu: Default domain type: Translated[    0.066727] iommu: DMA domain TLB invalidation policy: lazy mode[    0.066941] clocksource: Switched to clocksource arch_sys_counter[    0.081574] VFS: Disk quotas dquot_6.6.0[    0.081579] VFS: Dquot-cache hash table entries: 512 (order 0, 4096 bytes)[    0.081878] pnp: PnP ACPI: disabled[    0.084396] NET: Registered PF_INET protocol family[    0.084423] IP idents hash table entries: 8192 (order: 4, 65536 bytes, linear)[    0.091058] tcp_listen_portaddr_hash hash table entries: 256 (order: 0, 4096 bytes, linear)[    0.091064] Table-perturb hash table entries: 65536 (order: 6, 262144 bytes, linear)[    0.091066] TCP established hash table entries: 4096 (order: 3, 32768 bytes, linear)[    0.091070] TCP bind hash table entries: 4096 (order: 5, 131072 bytes, linear)[    0.091074] TCP: Hash tables configured (established 4096 bind 4096)[    0.091097] MPTCP token hash table entries: 512 (order: 2, 12288 bytes, linear)[    0.091102] UDP hash table entries: 256 (order: 2, 16384 bytes, linear)[    0.091103] UDP-Lite hash table entries: 256 (order: 2, 16384 bytes, linear)[    0.091117] NET: Registered PF_UNIX/PF_LOCAL protocol family[    0.091122] NET: Registered PF_XDP protocol family[    0.091126] PCI: CLS 0 bytes, default 64[    0.091198] Unpacking initramfs...[    0.102153] kvm [1]: HYP mode not available[    0.102264] Initialise system trusted keyrings[    0.102300] workingset: timestamp_bits=44 max_order=17 bucket_order=0[    0.109961] Key type asymmetric registered[    0.109963] Asymmetric key parser 'x509' registered[    0.109985] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 248)[    0.128953] io scheduler mq-deadline registered[    0.128956] io scheduler kyber registered[    0.128967] io scheduler bfq registered[    0.129174] Serial: 8250/16550 driver, 4 ports, IRQ sharing enabled[    0.129555] hv_vmbus: registering driver hyperv_keyboard[    0.129697] rtc-pl031 9010000.pl031: registered as rtc0[    0.129705] rtc-pl031 9010000.pl031: setting system clock to 2026-11-20T09:45:21 UTC (1795167921)[    0.129780] NET: Registered PF_INET6 protocol family[    0.129936] Segment Routing with IPv6[    0.129943] In-situ OAM (IOAM) with IPv6[    0.140086] registered taskstats version 1[    0.140143] Loading compiled-in X.509 certificates[    0.191915] Freeing initrd memory: 9204K[    0.195510] Loaded X.509 cert 'alpinelinux.org: Alpine Linux kernel key: 87fa969a47f3e2a6aa35859eb932a17c95abcd82'[    0.198011] Demotion targets for Node 0: null[    0.198060] Key type .fscrypt registered[    0.198060] Key type fscrypt-provisioning registered[    0.199799] clk: Disabling unused clocks[    0.199802] PM: genpd: Disabling unused power domains[    0.203651] Freeing unused kernel memory: 2048K[    0.203670] Run /init as init processmacvmm-initramfs: ready 6.18.60-0-virt[    0.211136] virtio_blk virtio0: 1/0/0 default/read/poll queues[    0.211444] virtio_blk virtio0: [vda] 131072 512-byte logical blocks (67.1 MB/64.0 MiB)macvmm-vda: /dev/vda 131072 sectors ro=0macvmm-vda: sha256=3b6a07d0d404fab4e23b6d34bc6696a6a312dd92821332385e5af7c01c421351[    0.472510] reboot: Power down--- stderr ---macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=12378 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 33497: hvc 16, sysreg 2, data abort 33479macvmm: stats: vcpu0 time: exec 0.346 s, wfi 0.005 smacvmm: stats: host cpu 0.576 s over 0.539 s wall (107%)macvmm: stats: rlimit core=0 nofile=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The finished reference, which already has chapter 18's virtio disk; run from the repository root (scripts/run-linux.sh always runs there). /tmp/ch15/disk64.img is 64 MiB of zeros, made with dd as the lesson shows.
course/captures/15-vda-read.txt

Now count only the exits at slot 0, 0x0a00_0000 to 0x0a00_01ff:

TerminalReal output
grep -o '"ipa":"0xa000[0-9a-f]*","wnr":[a-z]*' /tmp/ch15/vda.jsonl | sort | uniq -cexit: 0--- stdout ---   1 "ipa":"0xa000000","wnr":false   1 "ipa":"0xa000004","wnr":false   1 "ipa":"0xa000008","wnr":false   1 "ipa":"0xa00000c","wnr":false   2 "ipa":"0xa000010","wnr":false   2 "ipa":"0xa000014","wnr":true   2 "ipa":"0xa000020","wnr":true   2 "ipa":"0xa000024","wnr":true   1 "ipa":"0xa000030","wnr":true   1 "ipa":"0xa000034","wnr":false   1 "ipa":"0xa000038","wnr":true   1 "ipa":"0xa000044","wnr":false   1 "ipa":"0xa000044","wnr":true  20 "ipa":"0xa000050","wnr":true  12 "ipa":"0xa000060","wnr":false  12 "ipa":"0xa000064","wnr":true   6 "ipa":"0xa000070","wnr":false   6 "ipa":"0xa000070","wnr":true   1 "ipa":"0xa000080","wnr":true   1 "ipa":"0xa000084","wnr":true   1 "ipa":"0xa000090","wnr":true   1 "ipa":"0xa000094","wnr":true   1 "ipa":"0xa0000a0","wnr":true   1 "ipa":"0xa0000a4","wnr":true   2 "ipa":"0xa0000fc","wnr":false   1 "ipa":"0xa000100","wnr":false   1 "ipa":"0xa000104","wnr":false   1 "ipa":"0xa00010c","wnr":false   1 "ipa":"0xa000114","wnr":false
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The trace from 15-vda-read.txt: only the exits at virtio slot 0 (0x0a00_0000 to 0x0a00_01ff).
course/captures/15-vda-count.txt

That is 85 exits for 64 MiB; the PL011 design would have needed about 180 million. Most lines are one-time setup. The steady state is 20 writes to 0x050, the doorbell, and 12 reads of 0x060 with 12 writes to 0x064, the interrupt's "what happened?" and "handled". The run's other 33,000-odd exits are the PL011 console again.

So a lone 4 KiB block costs about 3 exits (a doorbell, then two accesses in the interrupt handler), and in bulk well under one per block, because each request carries many blocks (up to 126 buffers in one chain, chapter 16) and Linux queues several requests behind one doorbell.

Now (b) against (c): both are thousands of times below (a). An emulated NVMe controller needs a submission doorbell per batch, a completion-queue head write to release the completions it consumed, and, depending on the driver, register writes to mask and unmask interrupts; we expect a few exits per batch, but have not measured it, and NVMe 1.3's shadow doorbells let a driver skip most of them. The difference is where each started. Virtio was designed for virtual machines: no data and no request description ever passes through a register, notification suppression ("do not notify me", through flags in RAM, chapter 16) is in its base ring format, one driver per device class works on every hypervisor, and there are no hardware quirks to copy. And the standard says what a device does with a misbehaving driver (it sets DEVICE_NEEDS_RESET, later in this chapter), where an emulated controller must copy whatever the real hardware happened to do.

That is the misconception to drop: virtio is not a protocol on a wire. It is a contract about shared memory, and the registers only find the rings and signal.

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

Every register answers a question

A virtqueue is really three areas in RAM: the descriptions, the driver's list of new ones, and the device's list of finished ones (chapter 16), so one queue needs three addresses. A device can have several queues (a console has one per direction), so the driver must say which queue it is configuring. Devices also differ in optional abilities, such as whether a disk is read-only or whether the ring may batch notifications; virtio calls each one a feature bit, and driver and device must agree on the set (more below). Features are a bit set larger than one register (64 bits in every device of this course, more in the specification), so they go 32 bits at a time, through a selector register; a selector beyond 1 reads 0 here.

Sitting B builds five files in learner/crates/vmm/src/virtio/, and this order compiles at every step:

  1. mod.rs: the device IDs, feature and status constants, and the VirtioDevice trait.
  2. queue.rs: one queue's registers (described in "Queue registers, and when they freeze").
  3. interrupt.rs: VirtioInterrupt, the line plus InterruptStatus (described in "The doorbell, and 'done'").
  4. null.rs: the empty device.
  5. mmio.rs: the transport itself.

If you would rather follow the text in reading order, stub Queue and VirtioInterrupt as empty structs when the trait first needs them, and fill them in when their sections arrive.

Each question then gets a 32-bit register at a fixed offset from the slot's base:

The driver needs to ask or sayRegister (offset)
Is this a virtio device at all, and which transport version?MagicValue (0x000) = 0x74726976, Version (0x004) = 2
Which device is it?DeviceID (0x008): 2 disk, 4 entropy, 0 nobody home; VendorID (0x00c), who made it (ours reads "MMVM")
Which optional features do you offer, and which do I take?DeviceFeatures (0x010) and DriverFeatures (0x020), with selectors DeviceFeaturesSel (0x014) and DriverFeaturesSel (0x024)
Which queue am I configuring, and how big may it be?QueueSel (0x030), QueueNumMax (0x034), QueueNum (0x038)
Where are its three areas?QueueDesc, QueueDriver, QueueDevice, each a low and high half (0x080 to 0x0a4)
This queue is readyQueueReady (0x044)
Look now!QueueNotify (0x050), the doorbell
What happened? I handled itInterruptStatus (0x060), InterruptACK (0x064)
Where am I in setting up, and have you given up on me?Status (0x070)
The device's own settings (a disk's size)the configuration space (config space for short) from 0x100, and ConfigGeneration (0x0fc)
Shared-memory regions and per-queue resetSHMSel, SHMLen, SHMBase (0x0ac to 0x0bc) and QueueReset (0x0c0): features we never offer. SHMLen and SHMBase read all-ones, meaning "no such region"; QueueReset reads 0

MagicValue is the four characters virt read as a little-endian 32-bit number: v is 0x76, the lowest byte. The constants, in learner/crates/vmm/src/virtio/mmio.rs:

crates/vmm/src/virtio/mmio.rslines 75-127
/// Register offsets (virtio 1.2 §4.2.2, table "MMIO Device Register Layout").pub mod reg {    pub const MAGIC: u64 = 0x000;    pub const VERSION: u64 = 0x004;    pub const DEVICE_ID: u64 = 0x008;    pub const VENDOR_ID: u64 = 0x00c;    pub const DEVICE_FEATURES: u64 = 0x010;    pub const DEVICE_FEATURES_SEL: u64 = 0x014;    pub const DRIVER_FEATURES: u64 = 0x020;    pub const DRIVER_FEATURES_SEL: u64 = 0x024;    pub const QUEUE_SEL: u64 = 0x030;    pub const QUEUE_NUM_MAX: u64 = 0x034;    pub const QUEUE_NUM: u64 = 0x038;    pub const QUEUE_READY: u64 = 0x044;    pub const QUEUE_NOTIFY: u64 = 0x050;    pub const INTERRUPT_STATUS: u64 = 0x060;    pub const INTERRUPT_ACK: u64 = 0x064;    pub const STATUS: u64 = 0x070;    pub const QUEUE_DESC_LOW: u64 = 0x080;    pub const QUEUE_DESC_HIGH: u64 = 0x084;    pub const QUEUE_DRIVER_LOW: u64 = 0x090;    pub const QUEUE_DRIVER_HIGH: u64 = 0x094;    pub const QUEUE_DEVICE_LOW: u64 = 0x0a0;    pub const QUEUE_DEVICE_HIGH: u64 = 0x0a4;    /// Shared-memory region selector (§4.2.2 SHMSel). Writes are ignored: no v1 device has a    /// shared-memory region (§2.10), so every ID names a region that does not exist.    pub const SHM_SEL: u64 = 0x0ac;    /// The selected region's length (§4.2.2 SHMLenLow/High): all-ones ("-1") for a region    /// that does not exist, which is how Linux `vm_get_shm_region` tells it is absent.    pub const SHM_LEN_LOW: u64 = 0x0b0;    pub const SHM_LEN_HIGH: u64 = 0x0b4;    /// The selected region's base (§4.2.2 SHMBaseLow/High): `0xffff_ffff_ffff_ffff` for a    /// region that does not exist.    pub const SHM_BASE_LOW: u64 = 0x0b8;    pub const SHM_BASE_HIGH: u64 = 0x0bc;    /// RAZ/WI: `VIRTIO_F_RING_RESET` is not offered.    pub const QUEUE_RESET: u64 = 0x0c0;    pub const CONFIG_GENERATION: u64 = 0x0fc;    /// Device-specific configuration space starts here.    pub const CONFIG: u64 = 0x100;}/// `"virt"` little-endian (§4.2.2 MagicValue).pub const MAGIC_VALUE: u32 = 0x7472_6976;/// The non-legacy virtio-mmio version (§4.2.2 Version).pub const MMIO_VERSION: u32 = 2;/// macvmm's VendorID: "MMVM" read as a little-endian u32 (any value is allowed, §4.2.2).pub const VENDOR_ID: u32 = 0x4d56_4d4d;/// The size of one transport window (slots are 0x200 apart, as on QEMU `virt`).pub const WINDOW_SIZE: u64 = 0x200;/// What each SHMLen/SHMBase half reads for a shared-memory region that does not exist/// (§4.2.2): together the halves make the 64-bit `-1` / `0xffff_ffff_ffff_ffff`.pub const NO_SHM_REGION: u32 = u32::MAX;

The authority is the virtio 1.2 specification (free from OASIS), section 4.2.2, "MMIO Device Register Layout". Read it with the reading-arm-specs primer's habit: a sentence with MUST binds the driver or the device. In the reference's comments, a section sign followed by a number is a section of that specification; the other tags in its comments refer to the reference's own design documents, and you need none of them here.

Is anybody there? The empty slot

QEMU's board lists all 32 virtio-mmio transports in its device tree, populated or not. We list only populated slots, but a guest that scans the fixed addresses (as our probe does) must still get a defined answer rather than an unhandled-MMIO fault. The specification defines an empty transport: valid MagicValue and Version, DeviceID 0, and "the driver MUST ignore a device with DeviceID 0x0".

Every slot holds a device model behind a trait, with two implementations within two chapters (the empty one now, the entropy device in chapter 17). In learner/crates/vmm/src/virtio/mod.rs, declare every method with exactly these signatures, because the contract tests' mock device implements all of them (stub Queue and VirtioInterrupt now if you have not written them yet):

crates/vmm/src/virtio/mod.rslines 242-279
/// A virtio device model behind the transport. The transport owns the/// registers and the status machine; the device owns its queues once activated.pub trait VirtioDevice: Send {    /// The virtio device ID (§5): 2 blk, 3 console, 4 rng, 1 net; 0 for an empty slot.    fn device_id(&self) -> u32;    /// One entry per queue: its maximum size (a power of two, ≤ [`QUEUE_SIZE_MAX`]).    fn queue_max_sizes(&self) -> &[u16];    /// The features offered. MUST include [`features::VERSION_1`] and none of    /// [`features::NEVER_OFFERED`].    fn device_features(&self) -> u64;    /// Called once, at a FEATURES_OK write the transport accepted (`accepted ⊆ offered`).    fn ack_features(&mut self, accepted: u64);    /// The size of the device configuration space in bytes: the per-device bound the    /// transport enforces (it refuses any config access beyond it).    fn config_len(&self) -> u32 {        0    }    /// Read `data.len()` config bytes at `offset`; the transport already checked    /// `offset + data.len() ≤ config_len()`.    fn read_config(&self, offset: u32, data: &mut [u8]);    /// Write config bytes (same bound). Read-only fields MUST ignore writes.    fn write_config(&mut self, offset: u32, data: &[u8]);    /// At DRIVER_OK, after every ready queue passed `Queue::validate`. `queues` has one entry    /// per `queue_max_sizes` entry (check `Queue::ready`).    fn activate(        &mut self,        mem: Arc<dyn GuestMemoryOrdered>,        queues: Vec<Queue>,        irq: Arc<VirtioInterrupt>,    ) -> Result<(), VirtioError>;    /// Process at most `budget` chains of queue `index`, then return, so one busy    /// queue cannot starve the others. On `Err` the    /// caller puts the device into DEVICE_NEEDS_RESET.    fn process_queue(&mut self, index: usize, budget: u16) -> Result<QueueProgress, VirtioError>;    /// Status ← 0: drop the queues and the memory handle. Nothing may use the old    /// ring addresses afterwards.    fn reset(&mut self);}

Some names arrive later. Queue is this chapter's register file for one queue (below). VirtioInterrupt is the interrupt line plus InterruptStatus (the last section). VirtioError is "why a device refused"; any enum will do today. GuestMemoryOrdered has been in your files since chapter 04 (chapter 16 explains it). QueueProgress is an enum with Drained and MoreWork, for chapter 17. Today your devices give read_config, write_config and process_queue trivial bodies.

The device IDs, and the empty device in learner/crates/vmm/src/virtio/null.rs, which can never activate:

crates/vmm/src/virtio/mod.rslines 68-73
/// Device IDs (virtio 1.2 §5, "Device Types"). 0 means "no device" (§4.2.3.1.1).pub const DEVICE_ID_NONE: u32 = 0;pub const DEVICE_ID_NET: u32 = 1;pub const DEVICE_ID_BLOCK: u32 = 2;pub const DEVICE_ID_CONSOLE: u32 = 3;pub const DEVICE_ID_RNG: u32 = 4;
crates/vmm/src/virtio/null.rslines 22-53
/// The empty-slot device: ID 0, no queues, no features, no config.#[derive(Clone, Copy, Debug, Default)]pub struct NullDevice;impl VirtioDevice for NullDevice {    fn device_id(&self) -> u32 {        DEVICE_ID_NONE    }    fn queue_max_sizes(&self) -> &[u16] {        &[]    }    fn device_features(&self) -> u64 {        0    }    fn ack_features(&mut self, _accepted: u64) {}    fn read_config(&self, _offset: u32, data: &mut [u8]) {        data.fill(0);    }    fn write_config(&mut self, _offset: u32, _data: &[u8]) {}    fn activate(        &mut self,        _mem: Arc<dyn GuestMemoryOrdered>,        _queues: Vec<Queue>,        _irq: Arc<VirtioInterrupt>,    ) -> Result<(), VirtioError> {        Err(VirtioError::Device("an empty slot cannot be activated"))    }    fn process_queue(&mut self, index: usize, _budget: u16) -> Result<QueueProgress, VirtioError> {        Err(VirtioError::NoSuchQueue(index))    }    fn reset(&mut self) {}}

The machine puts a transport in all 32 slots, in learner/crates/vmm/src/machine/virt.rs; chapter 17 replaces this with a version that also builds devices:

crates/vmm/src/machine/virt.rslines 163-178
/// Put all 32 virtio-mmio transports on `bus` with no device in any of them (host tests)./// Refuses a `cfg` that asks for a device: use [`register_virtio_with`].pub fn register_virtio(cfg: &VmConfig, bus: &mut Bus) -> Result<()> {    if !virtio_populated(cfg).is_empty() {        return Err(Error::Internal(            "register_virtio cannot build devices: use register_virtio_with",        ));    }    for slot in 0..crate::arch::layout::VIRTIO_MMIO_SLOTS {        let (base, _intid) = Layout::virt()            .virtio_slot(slot)            .ok_or(Error::Internal("virtio slot outside the layout"))?;        insert_transport(bus, base, VirtioMmio::empty())?;    }    Ok(())}

insert_transport wraps the transport in Arc<Mutex<…>> and calls chapter 09's Bus::insert with the slot's base and its 0x200-byte window. virtio_populated returns the slots the command line filled; your VMM has no device options yet, so it returns none and the check always passes today. register_virtio_with is the version chapter 17 adds.

Only populated slots appear in the device tree. Each node gives the window, the level-high (level-triggered, chapter 11) SPI (shared peripheral interrupt) 16 + i, which is INTID 48 + i (chapter 05), and dma-coherent: the device's memory accesses see the same data as the CPU caches, so the guest needs no cache maintenance around DMA. In learner/crates/vmm/src/fdt/machine.rs:

crates/vmm/src/fdt/machine.rslines 350-363
/// One `/virtio_mmio@…` node (`virtio/mmio.yaml`; virtio 1.2 §4.2.2): slot `i` of the layout,/// its 0x200-byte window and its level-high SPI (16 + i). Only populated slots are described:/// a node for an empty slot would make the guest probe a device that answers "no device".fn virtio_slot(w: &mut FdtWriter, layout: &Layout, slot: usize) -> Result<(), FdtError> {    let (base, intid) = layout        .virtio_slot(slot)        .ok_or_else(|| bad(format!("virtio slot {slot} does not exist")))?;    let n = w.begin_node(&format!("virtio_mmio@{base:x}"))?;    w.prop_str("compatible", "virtio,mmio")?;    w.prop_cells("reg", &reg64(base, VIRTIO_MMIO_STRIDE))?;    w.prop_cells("interrupts", &spi_cells(intid)?)?;    w.prop_null("dma-coherent")?;    w.end_node(n)}

One transport per slot

The transport is the MmioDevice the bus sees for a slot. It owns the registers and the status machine; the device behind it owns its queues once activated, and never touches a register:

crates/vmm/src/virtio/mmio.rslines 149-169
/// One virtio-mmio transport (module docs). It is the `MmioDevice` the bus sees for a slot.pub struct VirtioMmio {    device: Arc<Mutex<dyn VirtioDevice>>,    device_id: u32,    device_features: u64,    config_len: u32,    max_sizes: Vec<u16>,    interrupt: Arc<VirtioInterrupt>,    mem: Option<Arc<dyn GuestMemoryOrdered>>,    notifier: Option<Arc<dyn QueueNotifier>>,    status: u32,    device_features_sel: u32,    driver_features_sel: u32,    driver_features: u64,    /// The driver wrote a non-zero word to DriverFeatures with a selector beyond bit 63: bits    /// nobody offered, so FEATURES_OK must fail (`accepted ⊆ offered`).    driver_features_beyond: bool,    queue_sel: u32,    queues: Vec<Queue>,    config_generation: u32,}

The notifier field belongs to chapter 17's worker thread; here it is always None.

What the tests call, and where it must be public:

  • vmm::virtio::VirtioMmio and vmm::virtio::VirtioInterrupt (re-exported from mmio.rs and interrupt.rs), and the modules vmm::virtio::features and vmm::virtio::status.
  • vmm::virtio::mmio::{MAGIC_VALUE, VENDOR_ID, reg}, the constants shown above; and chapter 09's vmm::irq::TestIrq.
  • VirtioMmio::new(device: Arc<Mutex<dyn VirtioDevice>>, interrupt: Arc<VirtioInterrupt>, mem: Option<Arc<dyn GuestMemoryOrdered>>) -> Result<VirtioMmio, &'static str>. Memory is an Option because a device that never activates needs none. A refusal is a bug in our VMM, never the guest's doing, so a fixed message is enough. It refuses a device that does not offer VIRTIO_F_VERSION_1, offers any feature in NEVER_OFFERED (below), has a queue size that is not a power of two from 1 to 32768, or has a config space that does not fit in the window (more than 0x100 bytes). That last check bounds every later config access.
  • VirtioMmio::empty() for an empty slot; queue(i), an Option<&Queue>; and config_changed(), which bumps ConfigGeneration and raises a configuration interrupt.
  • VirtioInterrupt::new(line: Arc<dyn IrqLine>), with the methods the transport and devices call: signal_used (bit 0), signal_config (bit 1), ack(bits), set_needs_reset and needs_reset.

One more case needs a rule. If a device's code panics while it holds its mutex, Rust marks the mutex poisoned (the host-concurrency primer's note on poisoning), because the data inside may be half-updated. The transport then treats the slot as dead: is_dead() asks the mutex whether it is poisoned, live_device() locks the device or returns None for a dead one, and every access to a dead slot is RAZ/WI with a rate-limited warning from dead_device_warning(). A dead slot is a bug in our VMM, and the guest cannot revive it.

Section 4.2.2 says the driver MUST use only aligned 32-bit accesses to the control registers. A driver that does not is broken or hostile, and chapter 09's rule applies: answer every access, RAZ/WI (read as zero, write ignored) plus a rate-limited warning. Config space holds device-defined fields of different widths, so there our device takes 1, 2, 4 or 8 bytes, each checked against the device's config length:

crates/vmm/src/virtio/mmio.rslines 756-795
impl MmioDevice for VirtioMmio {    fn read(&mut self, offset: u64, size: AccessSize) -> u64 {        if self.is_dead() {            dead_device_warning();            return 0;        }        if offset >= reg::CONFIG {            return self.read_config(offset, size);        }        if size != AccessSize::B4 || !offset.is_multiple_of(4) {            // §4.2.2.1: control registers take aligned 32-bit accesses only.            crate::guest_warn!(                "virtio-mmio: {:?}-byte read at {offset:#x} is not an aligned 32-bit access (RAZ)",                size.bytes()            );            return 0;        }        u64::from(self.read_reg(offset))    }    fn write(&mut self, offset: u64, size: AccessSize, value: u64) {        if self.is_dead() {            dead_device_warning();            return;        }        if offset >= reg::CONFIG {            self.write_config(offset, size, value);            return;        }        if size != AccessSize::B4 || !offset.is_multiple_of(4) {            crate::guest_warn!(                "virtio-mmio: {:?}-byte write at {offset:#x} is not an aligned 32-bit access (WI)",                size.bytes()            );            return;        }        let [lo, _] = split(value);        self.write_reg(offset, lo);    }}

Reads, with the empty slot handled first:

crates/vmm/src/virtio/mmio.rslines 348-388
fn read_reg(&self, offset: u64) -> u32 {    if self.device_id == DEVICE_ID_NONE {        // §4.2.3.1.1: an empty slot is Magic + Version + DeviceID 0; the rest is RAZ.        return match offset {            reg::MAGIC => MAGIC_VALUE,            reg::VERSION => MMIO_VERSION,            _ => 0,        };    }    match offset {        reg::MAGIC => MAGIC_VALUE,        reg::VERSION => MMIO_VERSION,        reg::DEVICE_ID => self.device_id,        reg::VENDOR_ID => VENDOR_ID,        reg::DEVICE_FEATURES => {            let [lo, hi] = split(self.device_features);            match self.device_features_sel {                0 => lo,                1 => hi,                _ => 0,            }        }        reg::QUEUE_NUM_MAX => self.selected().map_or(0, |q| u32::from(q.max_size())),        reg::QUEUE_READY => self.selected().map_or(0, |q| u32::from(q.ready())),        reg::INTERRUPT_STATUS => self.interrupt.status(),        reg::STATUS => self.status(),        // §4.2.2: "Reading from a non-existent region ... results in a length of -1" and        // a base of all-ones. Reading 0 here would tell Linux region 0 exists, at 0, empty.        reg::SHM_LEN_LOW | reg::SHM_LEN_HIGH | reg::SHM_BASE_LOW | reg::SHM_BASE_HIGH => {            NO_SHM_REGION        }        reg::QUEUE_RESET => 0,        reg::CONFIG_GENERATION => self.config_generation,        _ => {            crate::guest_debug!(                "virtio-mmio: read of write-only or reserved register {offset:#x} (RAZ)"            );            0        }    }}

And writes, which an empty slot ignores. Each case hands off to a method the following sections build; two rules live here directly: QueueReady takes only 0 or 1, and InterruptACK keeps only the two defined bits (INT_MASK, bits 0 and 1):

crates/vmm/src/virtio/mmio.rslines 392-441
fn write_reg(&mut self, offset: u64, v: u32) {    if self.device_id == DEVICE_ID_NONE {        crate::guest_debug!("virtio-mmio: write to an empty slot at {offset:#x} (WI)");        return;    }    match offset {        reg::DEVICE_FEATURES_SEL => self.device_features_sel = v,        reg::DRIVER_FEATURES_SEL => self.driver_features_sel = v,        reg::DRIVER_FEATURES => self.write_driver_features(v),        reg::QUEUE_SEL => self.queue_sel = v,        reg::QUEUE_NUM => {            if let Some(q) = self.selected_writable("QueueNum") {                match u16::try_from(v) {                    Ok(n) if q.size_ok(n) => q.set_size(n),                    _ => crate::guest_warn!(                        "virtio-mmio: QueueNum {v:?} ignored: not a power of two in 1..={:?}",                        q.max_size()                    ),                }            }        }        reg::QUEUE_READY => {            if let Some(q) = self.selected_writable_ready() {                match v {                    0 => q.set_ready(false),                    1 => q.set_ready(true),                    _ => crate::guest_warn!("virtio-mmio: QueueReady {v:?} ignored"),                }            }        }        reg::QUEUE_NOTIFY => self.notify(v),        reg::INTERRUPT_ACK => self.interrupt.ack(v & INT_MASK),        reg::STATUS => self.write_status(v),        reg::SHM_SEL => {            crate::guest_debug!("virtio-mmio: SHMSel {v:?} ignored: no shared-memory regions")        }        reg::QUEUE_DESC_LOW | reg::QUEUE_DESC_HIGH => {            self.write_ring_addr(offset, v, Queue::desc_table, Queue::set_desc_table)        }        reg::QUEUE_DRIVER_LOW | reg::QUEUE_DRIVER_HIGH => {            self.write_ring_addr(offset, v, Queue::avail_ring, Queue::set_avail_ring)        }        reg::QUEUE_DEVICE_LOW | reg::QUEUE_DEVICE_HIGH => {            self.write_ring_addr(offset, v, Queue::used_ring, Queue::set_used_ring)        }        _ => crate::guest_debug!(            "virtio-mmio: write to read-only or reserved register {offset:#x} (WI)"        ),    }}

The probe guest scans all 32 slots, tries wrong-sized reads (1, 2 and 8 bytes) of MagicValue, and counts the device tree's virtio_mmio nodes. Chapter 13's loader runs its ELF (Executable and Linkable Format) file directly. From inside learner/, with G set as in chapter 09:

Shell
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --kernel $G/virtio-probe --timeout 10

The reference's run, recorded by the checkpoint:

TerminalReal output
macvmm run --mem 64M --kernel {guests}/virtio-probe --timeout 10exit: 0--- stdout ---virtio-probe: 32 slots magic ok version 2virtio-probe: 32 empty (device id 0)virtio-probe: narrow read RAZ okvirtio-probe: dt lists 0 virtio_mmio nodes ok--- stderr ---macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)
captured: run "probe-empty" of checkpoint 15, captured from the reference on real hardwarecourse/captures/15-probe-empty.txt

All 32 slots say virt, version 2, device 0; the device tree lists none; every wrong-sized read came back zero (the rate limit keeps the log to ten warnings).

The handshake is a state machine

What does it take to bring a device up? We gave the reference chapter 17's entropy device (--rng) in slot 0 and traced the probe's handshake. This run uses the reference, because your VMM has no --rng yet, so it starts from the repository root, with its own G (the directory from sitting A may be gone after a reboot, hence the mkdir):

Shell
cd ..mkdir -p /tmp/ch15G=target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --rng --kernel $G/virtio-probe --timeout 10 --trace exits:/tmp/ch15/rng.jsonl:mmiogrep -o '"ipa":"0xa0000[^}]*' /tmp/ch15/rng.jsonl | cut -d, -f1,2,5
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --rng --kernel $G/virtio-probe --timeout 10 --trace exits:/tmp/ch15/rng.jsonl:mmioexit: 0--- stdout ---virtio-probe: slot 0 device 4 features okvirtio-probe: slot 0 device id 4 status 0xfvirtio-probe: rng 32 bytes nonzerovirtio-probe: 32 slots magic ok version 2virtio-probe: 31 empty (device id 0)virtio-probe: narrow read RAZ okvirtio-probe: dt lists 1 virtio_mmio nodes ok--- stderr ---macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • A forward look: the finished reference, run from the repository root with G=target/guests/aarch64-unknown-none/release; its --rng puts chapter 17's entropy device in slot 0.
course/captures/15-probe-rng.txt
TerminalReal output
grep -o '"ipa":"0xa0000[^}]*' /tmp/ch15/rng.jsonl | cut -d, -f1,2,5exit: 0--- stdout ---"ipa":"0xa000000","wnr":false,"value":"0x74726976""ipa":"0xa000004","wnr":false,"value":"0x2""ipa":"0xa000000","wnr":false,"value":"0x0""ipa":"0xa000000","wnr":false,"value":"0x0""ipa":"0xa000000","wnr":false,"value":"0x0""ipa":"0xa000008","wnr":false,"value":"0x4""ipa":"0xa000070","wnr":true,"value":"0x0""ipa":"0xa000070","wnr":true,"value":"0x1""ipa":"0xa000070","wnr":true,"value":"0x3""ipa":"0xa000014","wnr":true,"value":"0x1""ipa":"0xa000010","wnr":false,"value":"0x1""ipa":"0xa000024","wnr":true,"value":"0x0""ipa":"0xa000020","wnr":true,"value":"0x0""ipa":"0xa000024","wnr":true,"value":"0x1""ipa":"0xa000020","wnr":true,"value":"0x1""ipa":"0xa000070","wnr":true,"value":"0xb""ipa":"0xa000070","wnr":false,"value":"0xb""ipa":"0xa000008","wnr":false,"value":"0x4""ipa":"0xa000030","wnr":true,"value":"0x0""ipa":"0xa000034","wnr":false,"value":"0x40""ipa":"0xa000038","wnr":true,"value":"0x10""ipa":"0xa000080","wnr":true,"value":"0x40085000""ipa":"0xa000084","wnr":true,"value":"0x0""ipa":"0xa000090","wnr":true,"value":"0x40085400""ipa":"0xa000094","wnr":true,"value":"0x0""ipa":"0xa0000a0","wnr":true,"value":"0x40085800""ipa":"0xa0000a4","wnr":true,"value":"0x0""ipa":"0xa000044","wnr":true,"value":"0x1""ipa":"0xa000070","wnr":true,"value":"0xf""ipa":"0xa000070","wnr":false,"value":"0xf""ipa":"0xa000050","wnr":true,"value":"0x0""ipa":"0xa000060","wnr":false,"value":"0x1""ipa":"0xa000064","wnr":true,"value":"0x1"
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The trace from 15-probe-rng.txt: every exit at slot 0, in order; fields ipa, wnr (true = a write) and value (the size field is cut).
course/captures/15-handshake-trace.txt

The trace drops leading zeros, so slot 0's Status register, 0x0a00_0070, appears as 0xa000070. The three reads at 0xa000000 returning 0x0, after the magic and version, are the wrong-sized reads, answered RAZ.

Read the Status writes (0xa000070, "wnr":true): 0, 1, 3, 0xb, 0xf. Each step adds one bit to the device status, and each bit is a promise:

crates/vmm/src/virtio/mod.rslines 102-110
/// Device status bits (virtio 1.2 §2.1).pub mod status {    pub const ACKNOWLEDGE: u32 = 1;    pub const DRIVER: u32 = 2;    pub const DRIVER_OK: u32 = 4;    pub const FEATURES_OK: u32 = 8;    pub const DEVICE_NEEDS_RESET: u32 = 64;    pub const FAILED: u32 = 128;}

The bit values are not in step order: FEATURES_OK (8) was added to the specification after DRIVER_OK (4), so the driver sets 8 before 4.

StatusBit addedMeaning
0x0(none)reset the device
0x1ACKNOWLEDGE"I have seen a virtio device"
0x3DRIVER"and I have a driver for it"
0xbFEATURES_OK"these are the features I will use"; the device may refuse
0xfDRIVER_OK"the queues are set up, start working"
+0x80FAILED"I gave up on this device"; accepted at any step and latched until Status is written 0

Between 0x3 and 0xb, the probe set DeviceFeaturesSel to 1, read 0x1 (bit 32 of the whole set), and accepted exactly that. Between 0xb and 0xf it configured queue 0: QueueNumMax said 64, the probe chose 16, wrote three ring addresses as halves, and set QueueReady. Then one doorbell (0xa000050), one InterruptStatus read of 0x1 (a used buffer) and one InterruptACK.

Step through the handshake in the lab, then try its "driver misbehaves" presets:

Lab

Virtio status handshake

Step through a driver bringing up a virtio-mmio device (status bits, feature negotiation, queue setup, the doorbell), then play drivers that misbehave and see what the device refuses.

Runs in browserOpen full page: Virtio status handshake
The virtio status handshake The driver writes Status 0 (reset), then 0x1 ACKNOWLEDGE, 0x3 adding DRIVER, accepts features (VERSION_1, bit 32), writes 0xb adding FEATURES_OK and reads it back, sets up queue 0 (size 16, three ring addresses, QueueReady 1), then writes 0xf adding DRIVER_OK. Bits only accumulate; writing 0 is the one way back. The device refuses FEATURES_OK if the driver accepted a bit it never offered or did not accept VERSION_1, ignores queue writes while a queue is ready (except a QueueReady 0 before DRIVER_OK, which unfreezes it) or once DRIVER_OK is set, and answers a ring outside RAM at DRIVER_OK with DEVICE_NEEDS_RESET (64) and a configuration interrupt. The probe's handshake, as traced on a real Mac 0x0 0x1 0x3 0xb 0xf reset ACKNOWLEDGE +DRIVER +FEATURES_OK +DRIVER_OK accept VERSION_1 set up queue 0 The device has the last word FEATURES_OK with an unoffered bit, or without VERSION_1: not latched a skipped step or a cleared bit: ignored (bits only accumulate) queue writes while the queue is ready, or after DRIVER_OK: ignored (before DRIVER_OK, writing QueueReady 0 still unfreezes the queue) a ring outside RAM at DRIVER_OK: DEVICE_NEEDS_RESET (64) + config interrupt narrow or misaligned control access: read as zero, write ignored Writing 0 to Status resets the device: the one way back.

The device enforces that order, because each step commits it to something. Bits only accumulate; FAILED is allowed at any time, and writing 0 is the one way back. STATUS_STEPS is the list of the four legal values, [0x1, 0x3, 0xb, 0xf], in order: the steps of the table above.

crates/vmm/src/virtio/mmio.rslines 503-544
/// A Status write (module docs; §2.1, §3.1.1).fn write_status(&mut self, v: u32) {    if v == 0 {        self.reset();        return;    }    if v & st::FAILED != 0 {        // The driver gave up (§2.1): latched until reset; the device does nothing more.        self.status |= st::FAILED;        return;    }    if self.status & st::FAILED != 0 || self.interrupt.needs_reset() {        crate::guest_warn!(            "virtio-mmio: Status {v:?} ignored: the device needs a reset (write 0)"        );        return;    }    // DRIVER implies ACKNOWLEDGE, which gates nothing (U-Boot quirk).    let v = if v & st::DRIVER != 0 {        v | st::ACKNOWLEDGE    } else {        v    };    // Bits are only ever added, and only in the order of STATUS_STEPS.    if self.status & !v != 0 || !STATUS_STEPS.contains(&v) {        crate::guest_warn!(            "virtio-mmio: Status {v:?} after {:?} ignored: bits out of order",            self.status        );        return;    }    let added = v & !self.status;    if added & st::FEATURES_OK != 0 && !self.features_ok() {        // Not latched: the driver reads FEATURES_OK back clear and must give up (§3.1.1).        self.status = v & (st::ACKNOWLEDGE | st::DRIVER);        return;    }    self.status = v;    if added & st::DRIVER_OK != 0 {        self.driver_ok();    }}

DRIVER implying ACKNOWLEDGE is a compatibility rule: U-Boot resets a device and then writes DRIVER alone, QEMU accepts that, and ACKNOWLEDGE gates nothing in the device.

Features: the device has the last word

This exchange is feature negotiation. Why must the device be able to refuse? Features change what the queues and the config space look like, so both sides must agree before any queue is set up. And the driver may accept a bit the device never offered, by mistake or on purpose. FEATURES_OK is the device's one chance to say no before it is committed.

The one bit every device must offer is VIRTIO_F_VERSION_1, bit 32: "I follow virtio 1.0 or later". The older legacy virtio had a different register layout, served by transport version 1, which we do not implement. NEVER_OFFERED lists features whose ring formats or mechanisms our devices do not implement; VirtioMmio::new refuses a device that offers one, so no driver can ever negotiate them:

crates/vmm/src/virtio/mod.rslines 77-98
/// Reserved feature bits (virtio 1.2 §6). Device-specific bits are 0..=23 and live with each/// device.pub mod features {    /// `VIRTIO_F_INDIRECT_DESC` (§2.7.5.3): indirect descriptor tables. Offered only by blk.    pub const INDIRECT_DESC: u64 = 1 << 28;    /// `VIRTIO_F_EVENT_IDX` (§2.7.7.2, §2.7.10): **not offered** in v1.    pub const EVENT_IDX: u64 = 1 << 29;    /// `VIRTIO_F_VERSION_1` (§6.1): a modern (non-legacy) device. Required (§4.2.2: legacy    /// interfaces are not supported by a Version 2 transport).    pub const VERSION_1: u64 = 1 << 32;    /// `VIRTIO_F_ACCESS_PLATFORM` (§6.1): an IOMMU translates addresses. Not offered.    pub const ACCESS_PLATFORM: u64 = 1 << 33;    /// `VIRTIO_F_RING_PACKED` (§2.8): the packed ring. Not offered.    pub const RING_PACKED: u64 = 1 << 34;    /// `VIRTIO_F_NOTIFICATION_DATA` (§6.1). Not offered.    pub const NOTIFICATION_DATA: u64 = 1 << 38;    /// `VIRTIO_F_RING_RESET` (§2.6.1): per-queue reset; QueueReset is RAZ. Not offered.    pub const RING_RESET: u64 = 1 << 40;    /// Features v1 must never offer without new hostile tests.    pub const NEVER_OFFERED: u64 =        EVENT_IDX | ACCESS_PLATFORM | RING_PACKED | NOTIFICATION_DATA | RING_RESET;}

The driver's choice is collected half by half, and only while DRIVER is set and FEATURES_OK is not:

crates/vmm/src/virtio/mmio.rslines 481-499
fn write_driver_features(&mut self, v: u32) {    if self.status & st::DRIVER == 0 || self.status & st::FEATURES_OK != 0 {        crate::guest_warn!(            "virtio-mmio: DriverFeatures ignored in status {:?} (§3.1.1 order)",            self.status        );        return;    }    let [lo, hi] = split(self.driver_features);    match self.driver_features_sel {        0 => self.driver_features = join(v, hi),        1 => self.driver_features = join(lo, v),        _ => {            if v != 0 {                self.driver_features_beyond = true;            }        }    }}

At the FEATURES_OK write, everything accepted must have been offered, VERSION_1 included, or the bit does not latch; section 3.1.1 tells the driver to read Status back (the probe's 0xb read) and give up if it is clear:

crates/vmm/src/virtio/mmio.rslines 548-574
/// FEATURES_OK: `accepted ⊆ offered` and `VERSION_1 ∈ accepted` (§2.2.1, §6.1)./// On success the device learns the set and the queues learn whether indirect descriptors/// were negotiated.fn features_ok(&mut self) -> bool {    let accepted = self.driver_features;    let unoffered = accepted & !self.device_features;    if unoffered != 0 || self.driver_features_beyond {        crate::guest_warn!(            "virtio-mmio: FEATURES_OK refused: features {unoffered:#x?} were not offered"        );        return false;    }    if accepted & features::VERSION_1 == 0 {        crate::guest_warn!("virtio-mmio: FEATURES_OK refused: VIRTIO_F_VERSION_1 not accepted");        return false;    }    let Some(mut device) = self.live_device() else {        return false;    };    device.ack_features(accepted);    drop(device);    let indirect = accepted & features::INDIRECT_DESC != 0;    for q in &mut self.queues {        q.set_indirect(indirect);    }    true}

Queue registers, and when they freeze

Queue registers act on the queue QueueSel names; a selector beyond the last queue reads 0 and ignores writes. QueueNum must be a power of two from 1 to QueueNumMax, because chapter 16's ring arithmetic depends on it. Once a queue is ready, or DRIVER_OK is set, its registers are frozen:

crates/vmm/src/virtio/mmio.rslines 326-344
/// The selected queue if its registers may still change (not ready, no DRIVER_OK).fn selected_writable(&mut self, what: &str) -> Option<&mut Queue> {    let frozen = self.status & st::DRIVER_OK != 0;    let sel = self.queue_sel;    let Some(q) = usize::try_from(sel)        .ok()        .and_then(|i| self.queues.get_mut(i))    else {        crate::guest_warn!("virtio-mmio: {what} for queue {sel:?}, which does not exist");        return None;    };    if frozen || q.ready() {        crate::guest_warn!(            "virtio-mmio: {what} for queue {sel:?} ignored: the queue is ready or DRIVER_OK is set"        );        return None;    }    Some(q)}

One exception: the QueueReady register stays writable while the others are frozen, so a driver can write 0 to it before DRIVER_OK and unfreeze the queue. Only DRIVER_OK freezes QueueReady itself:

crates/vmm/src/virtio/mmio.rslines 445-459
/// QueueReady may go 1 → 0 before DRIVER_OK, so only DRIVER_OK freezes it.fn selected_writable_ready(&mut self) -> Option<&mut Queue> {    if self.status & st::DRIVER_OK != 0 {        crate::guest_warn!("virtio-mmio: QueueReady ignored after DRIVER_OK");        return None;    }    let sel = self.queue_sel;    let q = usize::try_from(sel)        .ok()        .and_then(|i| self.queues.get_mut(i));    if q.is_none() {        crate::guest_warn!("virtio-mmio: QueueReady for queue {sel:?}, which does not exist");    }    q}

A ring address arrives as two 32-bit halves, in either order, possibly twice. Each write replaces one half and keeps the other; never build the address by adding, which would mix a stale half into the new value:

crates/vmm/src/virtio/mmio.rslines 463-477
/// One half of a 64-bit ring address: `hi << 32 | lo`, never an addition.fn write_ring_addr(    &mut self,    offset: u64,    v: u32,    get: fn(&Queue) -> GuestAddress,    set: fn(&mut Queue, GuestAddress),) {    let high = !offset.is_multiple_of(8); // the High halves sit at 0x084, 0x094, 0x0a4    if let Some(q) = self.selected_writable("a ring address") {        let [lo, hi] = split(get(q).0);        let (lo, hi) = if high { (lo, v) } else { (v, hi) };        set(q, GuestAddress(join(lo, hi)));    }}

Your Queue this chapter is a register file, in learner/crates/vmm/src/virtio/queue.rs: new(max_size), getters (size, ready, desc_table, avail_ring, used_ring), setters, and size_ok. It also needs validate, called at DRIVER_OK, which for now checks one rule: each ring lies entirely inside one RAM region (chapter 04's check_range), with lengths 16·N, 6 + 2·N and 6 + 8·N bytes for a queue of size N (chapter 16 derives them and adds the remaining checks).

DRIVER_OK: the device commits

DRIVER_OK is where the device starts trusting the ring addresses, so this is where they are checked, once, before anything uses them. A bad ring neither panics nor is ignored. The device sets DEVICE_NEEDS_RESET (64 in Status), raises a configuration interrupt (bit 1 of InterruptStatus), and refuses all work until the driver writes 0. (This is not the "dead" slot of a poisoned mutex: a device that needs reset recovers when the driver resets it.)

crates/vmm/src/virtio/mmio.rslines 578-603
/// DRIVER_OK: validate every ready queue, then activate; any failure → NEEDS_RESET.fn driver_ok(&mut self) {    let Some(mem) = self.mem.clone() else {        crate::guest_warn!("virtio-mmio: DRIVER_OK on a device without guest memory");        self.interrupt.set_needs_reset();        return;    };    for (i, q) in self.queues.iter().enumerate() {        if q.ready()            && let Err(e) = q.validate(&*mem)        {            crate::guest_warn!("virtio-mmio: queue {i:?} refused at DRIVER_OK: {e}");            self.interrupt.set_needs_reset();            return;        }    }    let Some(mut device) = self.live_device() else {        return;    };    let r = device.activate(mem, self.queues.clone(), Arc::clone(&self.interrupt));    drop(device);    if let Err(e) = r {        crate::guest_warn!("virtio-mmio: activation failed: {e}");        self.interrupt.set_needs_reset();    }}

The interrupt side latches the flag and raises the line in one step, under the lock that guards InterruptStatus:

crates/vmm/src/virtio/interrupt.rslines 107-113
/// Latch DEVICE_NEEDS_RESET and raise a configuration interrupt (§2.1.2).pub fn set_needs_reset(&self) {    let mut s = lock(&self.state);    s.needs_reset = true;    s.status |= INT_CONFIG;    self.line.set_level(true);}

Security

The guest chooses every value written to this window: unoffered feature bits, a QueueSel of four billion, a ring at the top of the address space. None of it may crash the VMM or make a device use unchecked memory. The state machine is that boundary: it decides when values are accepted, checked, and frozen.

Writing 0 to Status resets the device. The transport locks the device first, which matters from chapter 17 on, when a device worker thread (a host thread that does one device's queue work) may be mid-request: the lock makes it finish before the queues are dropped.

crates/vmm/src/virtio/mmio.rslines 607-624
/// Status ← 0: the device mutex is taken first, so an in-flight worker batch/// finishes before the queues and the memory handle are dropped. A dead device (a worker panicked) is/// left alone: the VM is stopping.fn reset(&mut self) {    let Some(mut device) = self.live_device() else {        return;    };    device.reset();    drop(device);    self.queues = self.max_sizes.iter().map(|&n| Queue::new(n)).collect();    self.status = 0;    self.device_features_sel = 0;    self.driver_features_sel = 0;    self.driver_features = 0;    self.driver_features_beyond = false;    self.queue_sel = 0;    self.interrupt.reset();}

The doorbell, and "done"

A QueueNotify write carries a queue index. It counts only for a healthy, activated device and an existing ready queue; anything else is a warning:

crates/vmm/src/virtio/mmio.rslines 628-654
/// QueueNotify: only for an activated, healthy device and an existing ready queue.fn notify(&mut self, v: u32) {    if self.status & st::DRIVER_OK == 0        || self.status & st::FAILED != 0        || self.interrupt.needs_reset()    {        crate::guest_warn!(            "virtio-mmio: QueueNotify {v:?} ignored in status {:?}",            self.status()        );        return;    }    let Some(index) = usize::try_from(v)        .ok()        .filter(|i| self.queues.get(*i).is_some_and(Queue::ready))    else {        crate::guest_warn!(            "virtio-mmio: QueueNotify {v:?} ignored: no such ready queue ({:?} queues)",            self.queues.len()        );        return;    };    match &self.notifier {        Some(n) => n.notify(index),        None => self.process_inline(index),    }}

With no worker thread, the transport calls the device's process_queue on the vCPU (virtual CPU) thread that took the exit, at most INLINE_BATCHES (4) times, so a guest cannot keep its own vCPU busy forever. Any error becomes DEVICE_NEEDS_RESET:

crates/vmm/src/virtio/mmio.rslines 659-674
fn process_inline(&self, index: usize) {    let budget = self.queues.get(index).map_or(0, |q| q.size());    let Some(mut d) = self.live_device() else {        return;    };    for _ in 0..INLINE_BATCHES {        match d.process_queue(index, budget) {            Ok(QueueProgress::Drained) => return,            Ok(QueueProgress::MoreWork) => {}            Err(e) => {                report_error(&self.interrupt, index, &e);                return;            }        }    }}
crates/vmm/src/virtio/mmio.rslines 726-729
pub fn report_error(interrupt: &VirtioInterrupt, queue: usize, err: &VirtioError) {    crate::guest_warn!("virtio: queue {queue:?} failed, device needs reset: {err}");    interrupt.set_needs_reset();}

The other direction is InterruptStatus: bit 0 for "used buffers added", bit 1 for "configuration changed" (including DEVICE_NEEDS_RESET). The driver reads it, handles the causes, and writes the bits it handled to InterruptACK. The line is level-triggered (chapter 11): high exactly while InterruptStatus is not zero, so an interrupt cannot be lost while the guest has interrupts masked. In learner/crates/vmm/src/virtio/interrupt.rs:

crates/vmm/src/virtio/interrupt.rslines 73-98
fn raise(&self, bit: u32) {    let mut s = lock(&self.state);    s.status |= bit;    // Under the lock: the line equals `status != 0` after every operation (module docs).    self.line.set_level(true);}/// The device added used buffers: set bit 0 and raise the line.pub fn signal_used(&self) {    self.raise(INT_USED_RING);}/// The configuration changed: set bit 1 and raise the line.pub fn signal_config(&self) {    self.raise(INT_CONFIG);}/// InterruptACK: clear `bits` (masked to bits 0–1) and lower the line once no bit/// is left.pub fn ack(&self, bits: u32) {    let mut s = lock(&self.state);    s.status &= !(bits & INT_MASK);    if s.status == 0 {        self.line.set_level(false);    }}

Under the hood

Why one mutex for the bits and the line? From chapter 17 on, a worker thread sets bit 0 while a vCPU writes InterruptACK. As separate steps, the vCPU could compute "now zero" and lower the line right after the worker raised it; the guest would sleep forever on a ring with work in it.

One more register guards config space. A disk's capacity is 64 bits, read as two 32-bit halves, and the device may change it between the reads. ConfigGeneration is a counter the device bumps on every change; the driver reads it before and after the fields and retries if it moved. Linux did exactly that in our 64 MiB run:

TerminalReal output
grep -o '"ipa":"0xa000[^}]*' /tmp/ch15/vda.jsonl | cut -d, -f1,2,5 | head -40exit: 0--- stdout ---"ipa":"0xa000000","wnr":false,"value":"0x74726976""ipa":"0xa000004","wnr":false,"value":"0x2""ipa":"0xa000008","wnr":false,"value":"0x2""ipa":"0xa00000c","wnr":false,"value":"0x4d564d4d""ipa":"0xa000070","wnr":true,"value":"0x0""ipa":"0xa000070","wnr":false,"value":"0x0""ipa":"0xa000070","wnr":true,"value":"0x1""ipa":"0xa000070","wnr":false,"value":"0x1""ipa":"0xa000070","wnr":true,"value":"0x3""ipa":"0xa000014","wnr":true,"value":"0x1""ipa":"0xa000010","wnr":false,"value":"0x1""ipa":"0xa000014","wnr":true,"value":"0x0""ipa":"0xa000010","wnr":false,"value":"0x10000244""ipa":"0xa000024","wnr":true,"value":"0x1""ipa":"0xa000020","wnr":true,"value":"0x1""ipa":"0xa000024","wnr":true,"value":"0x0""ipa":"0xa000020","wnr":true,"value":"0x10000244""ipa":"0xa000070","wnr":false,"value":"0x3""ipa":"0xa000070","wnr":true,"value":"0xb""ipa":"0xa000070","wnr":false,"value":"0xb""ipa":"0xa000030","wnr":true,"value":"0x0""ipa":"0xa000044","wnr":false,"value":"0x0""ipa":"0xa000034","wnr":false,"value":"0x100""ipa":"0xa000038","wnr":true,"value":"0x100""ipa":"0xa000080","wnr":true,"value":"0x4405c000""ipa":"0xa000084","wnr":true,"value":"0x0""ipa":"0xa000090","wnr":true,"value":"0x4405d000""ipa":"0xa000094","wnr":true,"value":"0x0""ipa":"0xa0000a0","wnr":true,"value":"0x4405e000""ipa":"0xa0000a4","wnr":true,"value":"0x0""ipa":"0xa000044","wnr":true,"value":"0x1""ipa":"0xa00010c","wnr":false,"value":"0x7e""ipa":"0xa000114","wnr":false,"value":"0x200""ipa":"0xa0000fc","wnr":false,"value":"0x0""ipa":"0xa000100","wnr":false,"value":"0x20000""ipa":"0xa000104","wnr":false,"value":"0x0""ipa":"0xa0000fc","wnr":false,"value":"0x0""ipa":"0xa000070","wnr":false,"value":"0xb""ipa":"0xa000070","wnr":true,"value":"0xf""ipa":"0xa000050","wnr":true,"value":"0x0"
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The trace from 15-vda-read.txt: Linux's own virtio-blk driver bringing up slot 0, the first 40 exits in order; fields ipa, wnr (true = a write) and value.
course/captures/15-linux-handshake.txt

Find 0xa0000fc (generation 0x0), then the capacity at 0xa000100 and 0xa000104 (0x20000 sectors, 64 MiB), then 0xa0000fc again. Journal question 3 asks what race that pattern closes.

Production note

Most VMMs offer virtio over PCI (Peripheral Component Interconnect), where the guest enumerates a bus and interrupts are memory writes (message-signalled interrupts). Firecracker was built on virtio-mmio alone, and still uses it by default, choosing it to keep a whole PCI emulation, and its attack surface, out of the VMM.

Breaking it on purpose

Deliberate breakage 1: accept queue writes after DRIVER_OK. In selected_writable, delete frozen || (and the frozen line), so only a ready queue is frozen; in selected_writable_ready, delete the early return after DRIVER_OK. Predict: does anything fail, and what could a guest now do? Your learner/ is its own git repository, so do it there: from the repository root, commit your working transport first (git -C learner add crates && git -C learner commit -m 'ch15 works'), make the edit, run scripts/checkpoint.sh 15, then undo the edit with git -C learner checkout -- crates. The capture below was made on a separate copy of the reference, hence the --impl <tree>:

TerminalReal output
scripts/checkpoint.sh 15 --impl <tree>exit: 1--- stdout ---checkpoint: implementation <tree>[FAIL] L1 contract  virtio_mmio_state: 1 failed: queue_registers_are_frozen_after_driver_ok    ---- queue_registers_are_frozen_after_driver_ok stdout ----        thread 'queue_registers_are_frozen_after_driver_ok' (123480609) panicked at tests/virtio_mmio_state.rs:292:5:    assertion failed: !f.t.queue(1).unwrap().ready()    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace            failures:        queue_registers_are_frozen_after_driver_ok        test result: FAILED. 23 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s    [PASS] L2 run       probe-empty: 4/4 serial markers, exit 0 in 0.20s[INFO] L3 journal   not checked (not a learner tree)CHECKPOINT 15 FAIL
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: in VirtioMmio::selected_writable the 'frozen ||' test is deleted, and in selected_writable_ready the early return after DRIVER_OK is deleted, so queue registers accept writes after DRIVER_OK. The broken copy is built and checked in its own tree.
course/captures/15-break-frozen.txt

One contract test fails: after DRIVER_OK, the guest made queue 1 ready and resized it. The probe passes, since it never writes a queue after DRIVER_OK. Our device copied the queues at DRIVER_OK, so nothing crashed; but a VMM that read ring addresses from its registers at notify time would now walk rings no validate ever saw: the guest's half of a TOCTOU problem (time of check to time of use), chapter 16's subject.

What you saw: one failing state test, a passing probe, no crash. The misconception it exposes: "a register is only data; the device can sort it out later". A state machine is a security boundary. The tool that finds it: a contract test that drives the transport through MmioDevice::read and write exactly as a trapped vCPU access would.

Your turn

Before the checkpoint, check:

  1. Your virtio/{mod.rs, mmio.rs, null.rs, interrupt.rs, queue.rs} build, and the machine puts a transport in all 32 slots.
  2. virtio-probe, run from inside learner/, prints the four lines of the empty-slot run above.
  3. Your journal has the Predict entry, written before you read sitting A's measurements.

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

Try it

Take the test's mock device, which offers VERSION_1 and device bit 0, accept bit 29 (VIRTIO_F_EVENT_IDX) as well, write 0xb to Status and read it back. Predict the value first. Then accept only bit 29, without VERSION_1: does the answer change? Start from the test features_ok_requires_version_1 in course/checkpoints/15/contract/virtio_mmio_state.rs, whose helper negotiate(lo, hi) drives the whole sequence and returns Status read back.

Checkpoint

From the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 15

You should see, as the last line:

CHECKPOINT 15 PASS

It runs 24 contract tests, which drive your transport through MmioDevice with a mock device, guest memory in a vector and a TestIrq (every rule of sitting B, from status order to InterruptACK lowering the line), then virtio-probe, expecting the four lines of the empty-slot run and exit code 0. On the reference:

TerminalReal output
scripts/checkpoint.sh 15exit: 0--- stdout ---[PASS] contract tests   virtio_mmio_state (24 tests)[PASS] runs on your Mac probe-empty: 4/4 serial markers, exit 0 in 0.06s[INFO] journal          not checked (not a learner tree)CHECKPOINT 15 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The chapter's checkpoint, run against the reference (scripts/checkpoint.sh 15 --ref): what a finished chapter 15 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/15-checkpoint.txt

What now works: 32 virtio-mmio windows; a transport that negotiates features, validates rings once at DRIVER_OK and fails safe; a doorbell that reaches a device; and an interrupt that is a level. The next chapter starts from this state (the reference at the end of chapter 15).

What's next

Our transport knows where the rings are, and no device of ours reads them yet. Chapter 16 lays out the split virtqueue (a descriptor table, an available ring and a used ring) and walks it as a hostile guest would rather we did not: a guest can rewrite a descriptor while we read it, point a chain at itself, or claim four gigabytes.

Open question

The driver writes QueueDescLow and QueueDescHigh, a guest-physical address, into two registers. What must you check before you activate the queue, and what can the guest still change after you have checked it?

Spec hunt

  • Virtio 1.2, section 4.2.2, "MMIO Device Register Layout", and its driver requirements in 4.2.2.2: which registers are read-only and which write-only, and whose obligation is it not to read a write-only one?
  • Virtio 1.2, section 2.1.2, "Device Requirements: Device Status Field": is setting DEVICE_NEEDS_RESET a MUST or a SHOULD, and what MUST the device send the driver if DRIVER_OK is set?
  • Virtio 1.2, section 3.1.1, "Driver Requirements: Device Initialization": in which step does the driver read FEATURES_OK back, and what must it do if the bit is clear?
Progress is stored only in this browser.