indicogniBuild a VMM

Contents

Chapter 09 · Part IV

A device is a state machine: the bus, PL011 and PL031

Needs a Mac Runs in browser ~4 h Lab: PL011 poke · Lab: Lock order · Lab: ANSI filter
10 of 26

Course progress: chapter 09 is 10 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 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.

  2. From chapter 06: vCPU state: registers, PSTATE and reset

    Build the PSTATE value for "EL1, using EL1's own stack pointer, with debug, SError, IRQ and FIQ all masked". Show the three parts you add.

    Show answer

    The four mask bits D, A, I, F are bits 9 to 6: 0x200 + 0x100 + 0x80 + 0x40 = 0x3c0. EL1 in bits 3 to 2 is 1 << 2 = 0x4. The stack-pointer select bit 0 set means SP_EL1: 0x1. Together 0x3c5, the mode EL1h.

  3. From chapter 02: An exception, one level up: your first VM exit

    A VM exit reports the syndrome 0x5a00002a. Which instruction stopped the guest, and what number did it carry?

    Show answer

    The exception class is 0x5a00002a >> 26 = 0x16: an hvc from 64-bit code. For an hvc, the low 16 bits of the syndrome hold its immediate, so the guest ran hvc #0x2a.

Concepts you'll need

Chapters before this one: chapter 08, System registers, injection, hypercalls and PSCI.

  • Core, taught here: a device as a state machine with side-effecting reads; the frozen MmioDevice, AccessSize and Bus types; a device that answers every offset and width of its window (RAZ/WI plus a rate-limited warning); filtering guest output, and restoring the terminal on every exit path; the AtomicBool stop flag in control.rs, and the kick that makes a running vCPU see it.
  • Core, from earlier: the --timeout deadline (chapter 03); stage-2 holes, the machine's memory map and the unhandled-MMIO policy (chapter 05); decoding a memory-mapped I/O (MMIO) access, the one-entry bus and the exit trace (chapter 07); RAZ/WI and the exit codes (chapter 08).
  • Primers (read first): primecell-ids (the eight identification bytes at 0xFE0 and how Linux matches on them); host-concurrency (threads, Arc, Mutex, atomics, lock order; its lock-order lab); unix-signals (SIGINT, SIGTERM, exit code 130, the self-pipe trick); tty-termios (raw mode, stty -g, escape sequences; its ansi-filter lab).
  • Primers (review): reading-arm-specs (register pages, RAZ/WI); os-basics (what an interrupt is).
  • Pointers: UART (universal asynchronous receiver-transmitter) basics, with the PL011 technical reference manual (ARM DDI 0183), an Aside; the PL031 manual (ARM DDI 0224); panics and panic hooks (std::panic::set_hook), an Aside.
  • Forward definitions: interrupt status and mask (RIS, MIS, IMSC), a latched bit, a level-triggered line and the interrupt line a device drives (chapters 11 and 12); terminal injection (chapter 25); the interrupt controller's per-CPU frames (chapter 12). Each is defined at first use.

Type ping and press Enter. The five bytes travel from your keyboard into a queue inside the serial port your virtual machine monitor (VMM) emulates, where a guest program sits in a loop, waiting for them. Now change one thing: the port's status register always answers "nothing received". The bytes are still in the queue.

Predict The UART holds ping and a newline in its receive queue, but its flag register FR always reports RXFE = 1, "receive queue empty". Does the guest print pong anyway?

Write your answer and one sentence of reasoning under ## Predict in your journal. Sitting A builds the device; sitting B runs this experiment.

This chapter closes row 3 of chapter 00's problem ledger, devices at fixed physical addresses: since chapter 05, 0x0900_0000 has been a hole that stops the guest; by the end, a serial port answers there, with a clock beside it. Sitting A is the device itself, checked by host tests, no guest needed (about 2 hours); sitting B is the host side, threads, terminal and signals, then the clock and the bus (about 2 hours).

Objectives: by the end you can

  • (Sitting A) Implement the PL011 registers that Linux and U-Boot use (DR, FR, IBRD, FBRD, LCR_H, CR, IFLS, IMSC, RIS, MIS, ICR, plus the stored-only RSR, ILPR and DMACR) and the identification registers at 0xFE0 to 0xFFC, as a state machine in which a DR read pops the receive FIFO (first in, first out queue).
  • (Sitting A) Make the device total over its 4 KiB window: answer every offset and every access width, with RAZ/WI and a rate-limited warning for what names no register; predict the value of FR, RIS and MIS in hex after a sequence of accesses.
  • (Sitting B) Feed received bytes from a stdin thread through a bounded SerialInput, filter guest output before it reaches the terminal, choose where it goes with --serial stdio|file:F|none, and restore the terminal on every exit path (normal stop, Ctrl-A x, SIGINT and SIGTERM, a panic).
  • (Sitting B) Implement the stop flag and the kick, and explain with an example why the Mutex around each device is needed (the stdin thread is a real second thread) and in which order two locks are taken.
  • (Sitting B) Implement PL031 reads from the host's wall clock, then turn chapter 07's bus into the checked Bus, which refuses overlapping, empty and overflowing windows when they are inserted.

Before you start. From the repository root, run scripts/learner start 09. It copies this chapter's journal to learner/journal/09.md. The code goes into your learner/ workspace, in the files named above each block; the checkpoint tests your crates through the same public names. Before sitting B, do the lock-order lab in the host-concurrency primer.

What a guest asks of a serial port

A UART (universal asynchronous receiver-transmitter) is the oldest console there is: the guest stores a byte to one address to send it, and loads from the same address to receive one. Ours is Arm's PL011, at 0x0900_0000, where QEMU's virt machine puts it, so stock kernels and firmware find their console with no help from us.

Aside

A real UART sends a byte one bit at a time, at a rate set by a divisor of its clock (the baud rate), and buffers bytes in two small queues, one for transmit (TX) and one for receive (RX). The PL011's manual, the technical reference manual (TRM) ARM DDI 0183, is free from Arm's developer site; chapter 3, "Programmers Model", is the part we implement.

Here is how our test guests drive it, from guests/common/uart.rs. Every read and write is a load or store at the UART's address:

guests/common/uart.rslines 54-77
/// Transmit one byte (waits while the TX FIFO is full; macvmm's never is).pub fn putc(byte: u8) {    while read(PL011_BASE, FR) & FR_TXFF != 0 {}    write(PL011_BASE, DR, u32::from(byte));}/// One received byte, if the RX FIFO has one.pub fn getc() -> Option<u8> {    if read(PL011_BASE, FR) & FR_RXFE != 0 {        None    } else {        Some((read(PL011_BASE, DR) & 0xff) as u8)    }}/// Poll until a byte arrives.pub fn getc_blocking() -> u8 {    loop {        if let Some(b) = getc() {            return b;        }        core::hint::spin_loop();    }}

Read it as the device would. The guest asks FR, the flag register, before every move: TXFF (transmit FIFO full) before it sends, RXFE (receive FIFO empty) before it reads. Only then does it touch DR, the data register. A FIFO (first in, first out) is the device's small queue.

Every one of these accesses lands in a stage-2 hole, so each is a data abort. Chapter 07's decoder turns it into "a 4-byte load from 0x9000018 into w11"; the trace prints addresses without the underscores, so 0x9000018 is 0x0900_0018, the UART's base plus 0x18, which is FR. What the guest knows about the device is exactly what those loads return.

Registers with consequences

The registers our model implements, with their names from the TRM (the PL011 calls them UARTDR and so on; we drop the prefix):

OffsetRegisterWhat our model does
0x000DR, datawrite: send the low byte; read: pop the RX FIFO (0 when empty)
0x004RSR, receive statusreads 0 (no line errors ever happen); writes do nothing
0x018FR, flagscomputed from the FIFO on every read; read-only
0x020ILPR, infrared low-powerstored; unused by our guests
0x024, 0x028IBRD, FBRD, integer and fractional baud divisorsstored and read back; a baud rate means nothing here
0x02cLCR_H, line controlstored; bit 4, FEN, selects a 32-byte FIFO, else a 1-byte one
0x030, 0x034CR, control; IFLS, FIFO level selectstored (reset values 0x300 and 0x12)
0x038 to 0x044IMSC, RIS, MIS, ICRthe interrupt mask and status, below
0x048DMACR, DMA controlstored; there is no DMA (direct memory access) here
0xfe0 to 0xffcidentificationeight constant bytes, from the primecell-ids primer

FR is the register to know by heart, because every guest reads it before every byte. Its bits, and the interrupt bits that IMSC, RIS, MIS and ICR share:

FR bitMaskNameMeaning when 1
30x08BUSYstill shifting a byte out (ours: never)
40x10RXFEreceive FIFO empty
50x20TXFFtransmit FIFO full
60x40RXFFreceive FIFO full
70x80TXFEtransmit FIFO empty (ours: always)
Interrupt bitMaskNameRaised when
40x10RXreceived data waits
50x20TXa byte was sent
60x40RTreceive timeout (below)

So FR = 0x90 after reset is 0x80 | 0x10, TXFE | RXFE: both queues empty. And 0xc0 is 0x80 | 0x40, TXFE | RXFF: nothing to send, and the receive FIFO full. In learner/crates/vmm/src/devices/pl011.rs, the offsets and bits:

crates/vmm/src/devices/pl011.rslines 72-116
pub const DR: u64 = 0x000;pub const RSR: u64 = 0x004;pub const FR: u64 = 0x018;pub const ILPR: u64 = 0x020;pub const IBRD: u64 = 0x024;pub const FBRD: u64 = 0x028;pub const LCR_H: u64 = 0x02c;pub const CR: u64 = 0x030;pub const IFLS: u64 = 0x034;pub const IMSC: u64 = 0x038;pub const RIS: u64 = 0x03c;pub const MIS: u64 = 0x040;pub const ICR: u64 = 0x044;pub const DMACR: u64 = 0x048;/// First identification register (`UARTPeriphID0`).pub const ID_BASE: u64 = 0xfe0;/// `UARTFR` bits (TRM §3.3.3).pub mod fr {    pub const BUSY: u32 = 1 << 3;    pub const RXFE: u32 = 1 << 4;    pub const TXFF: u32 = 1 << 5;    pub const RXFF: u32 = 1 << 6;    pub const TXFE: u32 = 1 << 7;}/// Interrupt bits, shared by `IMSC`, `RIS`, `MIS` and `ICR` (TRM §3.3.10-13).pub mod int {    pub const RX: u32 = 1 << 4;    pub const TX: u32 = 1 << 5;    pub const RT: u32 = 1 << 6;    /// Every defined bit (`RIMIM` .. `OEIM`).    pub const ALL: u32 = 0x7ff;}/// `UARTLCR_H.FEN`: enable the FIFOs.pub const LCR_H_FEN: u32 = 1 << 4;/// `UARTFR` after reset: both FIFOs empty.pub const FR_RESET: u32 = fr::TXFE | fr::RXFE;/// `UARTCR` after reset: transmit and receive enabled, UART disabled (TRM §3.3.8).pub const CR_RESET: u32 = 0x300;/// `UARTIFLS` after reset: both FIFO trigger levels at 1/2 (TRM §3.3.9).pub const IFLS_RESET: u32 = 0x12;/// `UARTPeriphID0-3`, `UARTPCellID0-3` (TRM §3.3.15-22; QEMU `pl011_id_arm`).pub const ID_BYTES: [u8; 8] = [0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1];

Now the question that decides the design: what is the device's state? Not one value per register. Most registers are plain storage, but DR is a window onto a queue, and FR stores nothing at all: it is computed from the queue each time it is read, as is most of RIS:

crates/vmm/src/devices/pl011.rslines 120-136
/// The UART's state.pub struct Pl011 {    ilpr: u32,    ibrd: u32,    fbrd: u32,    lcr_h: u32,    cr: u32,    ifls: u32,    imsc: u32,    dmacr: u32,    /// The latched raw status bits that are not derived from the FIFO (only `TX` today).    latched: u32,    rx: VecDeque<u8>,    sink: SinkHandle,    input: Option<Arc<SerialInput>>,    irq: Arc<dyn IrqLine>,}
crates/vmm/src/devices/pl011.rslines 151-172
/// A UART in its reset state that transmits to `sink`, receives from `input` (if any) and/// drives `irq`.pub fn new(sink: SinkHandle, input: Option<Arc<SerialInput>>, irq: Arc<dyn IrqLine>) -> Pl011 {    let mut u = Pl011 {        ilpr: 0,        ibrd: 0,        fbrd: 0,        lcr_h: 0,        cr: CR_RESET,        ifls: IFLS_RESET,        imsc: 0,        dmacr: 0,        latched: 0,        rx: VecDeque::with_capacity(PL011_FIFO_DEPTH),        sink,        input,        irq,    };    u.refill();    u.update_irq();    u}

Three things come in from outside. A sink is where guest output goes: a filter, then a bounded queue drained by a writer thread; the Output section builds it. SerialInput is the host's input queue, built in sitting B. The interrupt line comes in the next section.

For sitting A, stand-ins are enough, in learner/crates/vmm/src/backend/serial.rs. Make Sink a struct holding a Mutex<Box<dyn Write + Send>>, with a write_guest(&self, bytes) that writes the bytes as they are, and SinkHandle an Arc<Sink>. Make SerialInput a struct holding a Mutex<VecDeque<u8>> with the pop method that refill calls.

A device is a state machine: hidden state (the FIFO, and a few bits the device sets and keeps until they are cleared), moved by inputs (register accesses, bytes arriving from the host), producing outputs (values the guest reads, bytes to the terminal, an interrupt line). The registers are its interface, not its memory. The clearest sign is a side-effecting read: reading DR removes the byte it returns, so two reads give two answers.

The status half, computed on demand:

crates/vmm/src/devices/pl011.rslines 185-216
/// Move bytes from `SerialInput` into the FIFO until it is full (lock order: this device's/// mutex is held, `SerialInput`'s is taken inside `pop`).fn refill(&mut self) {    let Some(input) = &self.input else { return };    while self.rx.len() < self.depth() {        match input.pop() {            Some(b) => self.rx.push_back(b),            None => break,        }    }}/// The raw interrupt status (`UARTRIS`).pub fn ris(&self) -> u32 {    let rx = if self.rx.is_empty() {        0    } else {        int::RX | int::RT    };    (self.latched | rx) & int::ALL}fn fr(&self) -> u32 {    let mut v = fr::TXFE;    if self.rx.is_empty() {        v |= fr::RXFE;    }    if self.rx.len() >= self.depth() {        v |= fr::RXFF;    }    v}

FR tells a lie: TXFE (transmit FIFO empty) is always 1 and BUSY always 0, because our "transmission" is over the moment the guest writes DR. A real UART would show BUSY for the time it takes to shift the byte out. The lie is fine because it is consistent: an always-ready port is a very fast one, and every driver must accept a fast one. Journal question 1 asks you to push on this.

Writing DR sends the byte on and sets the transmit bit, which stays set until the guest clears it. Reading DR pops, then refills from the host's queue:

crates/vmm/src/devices/pl011.rslines 241-248
/// A guest store to `UARTDR`: transmit the low byte. It goes through the sink's terminal/// filter onto the sink's bounded queue; `write(2)` happens on the sink's writer thread,/// never here. The transmit "completes" at once, so `RIS.TX` is set.fn write_dr(&mut self, value: u32) {    let byte = u8::try_from(value & 0xff).unwrap_or(0); // 8 data bits; the rest ignored    Sink::write_guest(&self.sink, &[byte]);    self.latched |= int::TX;}
crates/vmm/src/devices/pl011.rslines 252-281
/// A guest load from `UARTDR`: pop the FIFO (0 when empty), then refill it.fn read_dr(&mut self) -> u32 {    let v = self.rx.pop_front().map_or(0, u32::from);    self.refill();    v}fn read_reg(&mut self, offset: u64) -> Option<u32> {    Some(match offset {        DR => self.read_dr(),        RSR => 0,        FR => self.fr(),        ILPR => self.ilpr,        IBRD => self.ibrd,        FBRD => self.fbrd,        LCR_H => self.lcr_h,        CR => self.cr,        IFLS => self.ifls,        IMSC => self.imsc,        RIS => self.ris(),        MIS => self.ris() & self.imsc,        ICR => 0, // write-only        DMACR => self.dmacr,        0xfe0..=0xffc => {            let i = usize::try_from(offset.checked_sub(ID_BASE)? / 4).ok()?;            u32::from(*ID_BYTES.get(i)?)        }        _ => return None,    })}
crates/vmm/src/devices/pl011.rslines 285-307
fn write_reg(&mut self, offset: u64, v: u32) -> bool {    match offset {        DR => self.write_dr(v),        RSR => {} // clears the (always clear) error flags        ILPR => self.ilpr = v & 0xff,        IBRD => self.ibrd = v & 0xffff,        FBRD => self.fbrd = v & 0x3f,        LCR_H => {            // Turning the FIFO off with bytes in it keeps them until they are read (FR            // shows RXFF); no input is lost by a mode change.            self.lcr_h = v & 0xff;            self.refill();        }        CR => self.cr = v & 0xffff,        IFLS => self.ifls = v & 0x3f,        IMSC => self.imsc = v & int::ALL,        ICR => self.latched &= !v,        DMACR => self.dmacr = v & 0x7,        FR | RIS | MIS | 0xfe0..=0xffc => {} // read-only        _ => return false,    }    true}

Remembering versus telling

Four registers handle "I need attention". Here is the idea in one sentence, ahead of its full story: the device remembers that it wants attention, and a mask says whether to say so; who listens is chapters 11 and 12. RIS (raw interrupt status) is the remembering: RX while received data waits, TX after a transmit. In our model RT comes with RX; on real hardware, receive timeout means data has sat in the FIFO for a while unread, and we raise it whenever data waits.

IMSC (interrupt mask set/clear) is the mask the guest writes. MIS (masked interrupt status) is RIS & IMSC. ICR (interrupt clear) clears latched bits when the guest writes 1s to it.

The device turns MIS into a level on an interrupt line: the line stays high for as long as MIS is non-zero, rather than pulsing once (a level-triggered line). The line is an object with one method, set_level, which chapter 12 connects to the interrupt controller and freezes. Until then the machine passes a line connected to nothing (NullIrq), and the tests pass one that records every change (TestIrq, with new, level, transitions and clear); all three live in learner/crates/vmm/src/irq.rs:

crates/vmm/src/irq.rslines 51-56
/// One level-sensitive interrupt line. Frozen: devices depend on exactly this.pub trait IrqLine: Send + Sync {    /// Drive the line. All macvmm device lines are level-sensitive: assert while the device    /// condition holds, deassert when it clears. Idempotent.    fn set_level(&self, high: bool);}
crates/vmm/src/devices/pl011.rslines 220-224
/// Drive the interrupt line to the OR of the masked status (`UARTMIS != 0`): a level, not/// an event, recomputed after every access and every input push (PL011 TRM, UARTINTR).pub fn update_irq(&self) {    self.irq.set_level(self.ris() & self.imsc != 0);}

Step through it in the lab: write registers, push bytes from the "host" side, and watch FR, the FIFO, RIS and MIS move.

Lab

PL011 poke

Write and read the UART's registers as the guest, type bytes as the host, and watch FR, the receive FIFO, RIS, MIS and the interrupt line change.

Runs in browserOpen full page: PL011 poke

Loading the lab. If nothing appears, your browser may have JavaScript turned off or the lab failed to load.

If the lab does not load, here is the same walk run against the reference device on a real Mac, by a short test written for this page:

TerminalReal output
cargo test -q -p vmm --test poke_demo -- --nocaptureexit: 0--- stdout ---running 1 teststep                         read    status after the stepreset                                FR=0x90 RIS=0x00 MIS=0x00 line=lowwrite DR = 'h' (0x68)                FR=0x90 RIS=0x20 MIS=0x00 line=lowwrite IMSC = 0x10 (RX)               FR=0x90 RIS=0x20 MIS=0x00 line=lowhost types "ok"                      FR=0xc0 RIS=0x70 MIS=0x10 line=highwrite ICR = 0x70                     FR=0xc0 RIS=0x50 MIS=0x10 line=highread DR                      0x6f    FR=0xc0 RIS=0x50 MIS=0x10 line=highread DR                      0x6b    FR=0x90 RIS=0x00 MIS=0x00 line=lowread DR (FIFO empty)         0x00    FR=0x90 RIS=0x00 MIS=0x00 line=lowsent to the terminal: "h".test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • A throwaway test written for this page (not part of the reference): it drives the reference PL011 through MmioDevice::read and write, as the bus does, pushes "ok" into its SerialInput as the stdin thread would, and prints FR, RIS, MIS and the interrupt line after each step. LCR_H is left at reset, so the receive FIFO holds one byte.
course/captures/09-poke.txt

Read it line by line, with the tables above. After the DR write, RIS = 0x20 is TX, but MIS stays 0: the mask 0x10 lets only RX through. When the host types ok, RIS = 0x70 is RX | TX | RT, and FR = 0xc0 is TXFE | RXFF: not empty, and full, because with FEN clear the FIFO holds one byte (the k waits in the host's queue).

Writing ICR = 0x70 clears the latched TX bit (RIS drops to 0x50) but, in our model, not the receive bits: their condition still holds, so the device still wants attention. Only the reads of DR change that.

An answer for every access

A guest can make any access it likes: a 1-byte store to offset 0x7, an 8-byte load of FR, a read at 0x800, where nothing lives. Each still arrives as a data abort, and each needs an answer. The rule: the device is total over its window. Every offset and every width gets a defined result, never a panic.

The contract a device fulfils is two frozen types: the checkpoint, later chapters and the lifelines all use them exactly as given. Chapter 07 had you write a first version; declare these in learner/crates/vmm/src/bus.rs:

crates/vmm/src/bus.rslines 90-97
/// An emulated device on the bus. Frozen from chapter 9 on: later chapters rely on it unchanged.pub trait MmioDevice: Send {    /// `offset` is relative to the device base. Return value is zero-extended to 64 bits;    /// the caller sign-extends if the instruction asked for it.    fn read(&mut self, offset: u64, size: AccessSize) -> u64;    /// `value` holds the low `size` bytes of the source register.    fn write(&mut self, offset: u64, size: AccessSize, value: u64);}
crates/vmm/src/bus.rslines 39-86
/// The width of one MMIO access (a load or store of 1, 2, 4 or 8 bytes). Frozen from/// chapter 9 on: later chapters rely on it unchanged.#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]pub enum AccessSize {    B1 = 1,    B2 = 2,    B4 = 4,    B8 = 8,}impl AccessSize {    /// The size in bytes.    pub const fn bytes(self) -> u64 {        self as u64    }    /// The low `bytes() * 8` bits set: `0xff`, `0xffff`, `0xffff_ffff` or `u64::MAX`.    pub const fn mask(self) -> u64 {        match self {            AccessSize::B1 => 0xff,            AccessSize::B2 => 0xffff,            AccessSize::B4 => 0xffff_ffff,            AccessSize::B8 => u64::MAX,        }    }    /// From a data abort's `SAS` field (`size = 1 << SAS`). Only the low two bits are used,    /// so every input gives a size.    pub const fn from_sas(sas: u8) -> AccessSize {        match sas & 3 {            0 => AccessSize::B1,            1 => AccessSize::B2,            2 => AccessSize::B4,            _ => AccessSize::B8,        }    }    /// From a byte count, if it is 1, 2, 4 or 8.    pub const fn from_bytes(n: u64) -> Option<AccessSize> {        match n {            1 => Some(AccessSize::B1),            2 => Some(AccessSize::B2),            4 => Some(AccessSize::B4),            8 => Some(AccessSize::B8),            _ => None,        }    }}

The Send bound comes into play in sitting B, when a second thread arrives. Now the PL011's side of that contract: 8-, 16- and 32-bit accesses at a register's aligned offset reach the register, and everything else is RAZ/WI (read as zero, writes ignored) with a warning:

crates/vmm/src/devices/pl011.rslines 312-346
/// The register an access names, if it is one this device answers: 4-byte aligned, at most/// 32 bits wide.fn reg_offset(offset: u64, size: AccessSize) -> Option<u64> {    (offset.is_multiple_of(4) && size != AccessSize::B8 && offset < PL011_SIZE).then_some(offset)}impl MmioDevice for Pl011 {    fn read(&mut self, offset: u64, size: AccessSize) -> u64 {        let v = reg_offset(offset, size).and_then(|o| self.read_reg(o));        self.update_irq();        match v {            Some(v) => u64::from(v) & size.mask(),            None => {                crate::guest_warn!(                    "pl011: {}-byte read at offset {offset:#x} names no register (read as zero)",                    size.bytes()                );                0            }        }    }    fn write(&mut self, offset: u64, size: AccessSize, value: u64) {        // `value` holds the low `size` bytes; registers are 32 bits.        let v = u32::try_from(value & size.mask() & 0xffff_ffff).unwrap_or(0);        let ok = reg_offset(offset, size).is_some_and(|o| self.write_reg(o, v));        self.update_irq();        if !ok {            crate::guest_warn!(                "pl011: {}-byte write at offset {offset:#x} names no register (ignored)",                size.bytes()            );        }    }}

The warning is rate-limited, because a guest decides how often it fires. Here is the reference's own register test, which sweeps every offset at every width (we ran it on a real Mac):

TerminalReal output
cargo test -q -p vmm --test pl011_regsexit: 0--- stdout ---running 9 tests.........test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s--- stderr ---macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x1 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x1 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x2 names no register (read as zero)macvmm: warn: [serial_input_is_bounded_at_4k_and_never_blocks] console input: the guest is not reading its UART; typed bytes are being dropped (see serial_input_dropped in --stats). Ctrl-A x still quits.macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x2 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x3 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x3 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x5 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x5 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x6 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x6 names no register (ignored)macvmm: warn: [narrow_accesses] guest: pl011: 8-byte write at offset 0x30 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x7 names no register (read as zero)macvmm: warn: [narrow_accesses] guest: pl011: 8-byte read at offset 0x18 names no register (read as zero)macvmm: warn: [narrow_accesses] guest: pl011: 1-byte read at offset 0x19 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x7 names no register (ignored)macvmm: warn: [narrow_accesses] guest: pl011: 1-byte write at offset 0x2 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x8 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x8 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x9 names no register (read as zero)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x9 names no register (ignored)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x3f3 names no register (read as zero) (989 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x3f3 names no register (ignored) (989 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0x7db names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0x7db names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0xbc3 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0xbc3 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte read at offset 0xfab names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 1-byte write at offset 0xfab names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte read at offset 0x3a9 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte write at offset 0x3a9 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte read at offset 0x791 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte write at offset 0x791 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte read at offset 0xb79 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte write at offset 0xb79 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte read at offset 0xf61 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 2-byte write at offset 0xf61 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte read at offset 0x360 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte write at offset 0x360 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte read at offset 0x748 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte write at offset 0x748 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte read at offset 0xb30 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte write at offset 0xb30 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte read at offset 0xf18 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 4-byte write at offset 0xf18 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte read at offset 0x30b names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte write at offset 0x30c names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte read at offset 0x6f3 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte write at offset 0x6f4 names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte read at offset 0xadb names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte write at offset 0xadc names no register (ignored) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte read at offset 0xec3 names no register (read as zero) (999 similar messages suppressed)macvmm: warn: [every_offset_and_width_is_total] guest: pl011: 8-byte write at offset 0xec4 names no register (ignored) (999 similar messages suppressed)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference's own PL011 register tests (the checkpoint's contract tests are a frozen copy of them), run in an unmodified copy of the reference.
course/captures/09-pl011-tests.txt

Nine tests pass, and the warnings show the limiter at work. Each call site prints its first 10 messages, then one in every thousand, hence "989 similar messages suppressed" the first time and "999" after that. A guest probing every byte of the window costs a handful of lines, not a flooded terminal.

Where the UART plugs in

Chapter 07 gave your machine a bus with one entry, the test device. Your MMIO handler, handle in learner/crates/vmm/src/vcpu/mmio.rs, already sends every device access through env.bus, and applies chapter 05's unhandled-MMIO policy when the bus answers Unmapped (no device there) or Straddle (an access that runs past a window's end).

So the UART needs no new routing: it becomes a second entry, inserted at the first run. Chapter 07's bus checks nothing about its entries; with two, you can check by eye that they do not overlap, and the last section makes the bus check it.

Good place to stop. Sitting A ends when, in learner/, cargo build -p vmm succeeds and cargo test -p vmm pl011 passes your own unit tests of the device (reset FR is 0x90; a DR write sets TX; two DR reads after one pushed byte give the byte, then 0). The checkpoint's PL011 contract also needs the real SerialInput and the filtered sink, so it passes only after sitting B.

Input needs a second thread

The guest polls FR, but who puts bytes into the FIFO? Not the thread of the virtual CPU (vCPU): it spends its life inside hv_vcpu_run, and if it stopped to wait for the keyboard, the guest would freeze with it. So a second thread does one thing forever: read standard input, and hand the bytes over. In learner/crates/macvmm/src/term.rs:

crates/macvmm/src/term.rslines 278-317
/// Run the stdin thread (detached; it ends at EOF, on a read error, or after Ctrl-A x).pub fn spawn_stdin(host: Arc<HostIo>) -> io::Result<()> {    std::thread::Builder::new()        .name("stdin".into())        .spawn(move || stdin_loop(&host))        .map(|_| ())}fn stdin_loop(host: &HostIo) {    let mut stdin = io::stdin().lock();    let mut buf = [0u8; 4096];    let mut parser = EscapeParser::default();    let mut to_guest = Vec::with_capacity(buf.len());    let mut cmds = Vec::new();    loop {        let n = match stdin.read(&mut buf) {            Ok(0) => return, // EOF: the guest just sees no more input            Ok(n) => n,            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,            Err(_) => return,        };        to_guest.clear();        parser.feed(buf.get(..n).unwrap_or(&[]), &mut to_guest, &mut cmds);        if !to_guest.is_empty() {            // The PL011's queue (or, from chapter 17, the console's: whichever sink is stdio).            host.stdin_queue().push(&to_guest); // never waits for room        }        for cmd in cmds.drain(..) {            match cmd {                Command::Quit => {                    host.request_quit();                    return;                }                Command::DumpRing => err(host.hostctl.dump_rings().trim_end()),                Command::Stats => err(&format!("macvmm: stats: {}", host.io_stats())),                Command::Help => err(HELP),            }        }    }}

The parser takes the Ctrl-A escapes out before anything reaches the guest, so a guest can never produce a host command. The rest goes to SerialInput, now the real queue in learner/crates/vmm/src/backend/serial.rs. It holds 4 KiB (SERIAL_INPUT_CAP) and never waits for room: it may wait a few milliseconds for the UART's lock, never indefinitely.

crates/vmm/src/backend/serial.rslines 737-765
/// Queue `bytes` for the guest. What does not fit in [`SERIAL_INPUT_CAP`] is dropped and/// counted, with one warning; this never blocks. Then the hook runs (the queue unlocked)./// Returns how many bytes were accepted.pub fn push(&self, bytes: &[u8]) -> usize {    let accepted = {        let mut q = lock(&self.q);        let room = SERIAL_INPUT_CAP.saturating_sub(q.len());        let take = bytes.len().min(room);        q.extend(bytes.iter().take(take).copied());        take    };    let lost = bytes.len().saturating_sub(accepted);    if lost > 0 {        self.dropped.fetch_add(len64(lost), Ordering::Relaxed);        if !self.warned.swap(true, Ordering::Relaxed) {            crate::warn!(                "console input: the guest is not reading {}; typed bytes are being \                 dropped (see {} in --stats). Ctrl-A x still quits.",                self.device,                self.stat            );        }    }    let hook = lock(&self.hook).clone();    if let Some(h) = hook {        h();    }    accepted}

Why drop bytes rather than wait for room? The same thread reads Ctrl-A x. If a guest stopped reading its UART and the push waited, the thread could never see your quit keys again. Besides push and pop, give it new, len, is_empty, dropped (the count of bytes it refused) and set_hook.

After a push, the hook moves bytes into the UART's FIFO and updates its line. The machine installs it when it builds the UART:

crates/vmm/src/machine/mod.rslines 425-432
// Input pushed by the stdin thread wakes this boot's UART. A weak reference: the// hook never keeps a torn-down machine's device alive.let weak = Arc::downgrade(&uart);host.serial_input.set_hook(Some(Arc::new(move || {    if let Some(u) = weak.upgrade() {        crate::sync::lock(&u).input_ready();    }})));
crates/vmm/src/devices/pl011.rslines 228-232
/// Host input arrived in `SerialInput` (the push hook): refill the FIFO and update the line.pub fn input_ready(&mut self) {    self.refill();    self.update_irq();}

The hook holds a Weak: an Arc that does not keep its value alive, whose upgrade() gives None once the last Arc is dropped. A strong Arc here would form a cycle, the UART holding the input and the input's hook holding the UART, and neither would ever be freed.

Now the UART is touched by two threads: the vCPU's (register accesses) and the stdin thread's (the hook). That is why each device sits behind an Arc<Mutex<…>>. Without the lock, the compiler will not let two threads call its &mut self methods through a shared Arc (the host-concurrency primer); with it, each access or push is applied whole.

And two locks are now in play, the device's and the queue's. refill takes the queue's lock while holding the device's; push calls the hook only after releasing the queue's. So both threads take them in the same order:

stdin thread:  lock queue, push, unlock queue -> hook -> lock device -> refill -> lock queuevCPU thread:                                             lock device -> read DR -> refill -> lock queue

Both threads take the device before the queue, so the deadlock from the primer's lock-order lab cannot happen.

The first run

Write register_platform(bus, sink, input, ncpus) in learner/crates/vmm/src/machine/virt.rs, for now with one bus.insert("pl011", PL011_BASE, PL011_SIZE, uart) that returns the UART, and call it where chapter 07 calls register_devices. Build the test guests if you have not since chapter 03 (scripts/build-guests.sh from the repository root), then, from inside learner/:

Shell
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10

Wait for uart-echo: ready, type ping, press Enter. The guest answers pong, then reads a clock at 0x0901_0000, which this chapter builds last. In your tree that address is still a hole, so the run stops right after pong with unhandled MMIO read at 0x9010000 size 4 and exit code 3. That is expected: the UART works, and the dump shows the clock is missing. Ours, from a reference with the clock removed, fed the line through a pipe so it could be recorded:

TerminalReal output
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10exit: 3--- stdout ---uart-echo: readypong--- stderr ---macvmm: guest fatal: unhandled MMIO read at 0x9010000 size 4 pc 0x40081168vcpu0: data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) SSE=0 SRT=0 SF=0 AR=0 FnV=0 S1PTW=0 WnR=0 DFSC=0x6 (translation fault)  esr=0x93800006 ipa=0x9010000  x0=0x000000000000000a x1=0x0000000000000067 x2=0x0000000000000004 x3=0x000000004008133c  x4=0x0000000000000000 x5=0x0000000000000000 x6=0x0000000000000000 x7=0x0000000000000000  x8=0x0000000009010000 x9=0x0000000009000000 x10=0x0000000009000000 x11=0x000000000000000a  x12=0x000000000000000a x13=0x0000000000000000 x14=0x0000000000000000 x15=0x0000000000000000  x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040082e0e x19=0x0000000000000000  x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000  x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000  x28=0x0000000000000000 x29=0x0000000000000000 x30=0x00000000400810d8  sp_el0=0x0 sp_el1=0x400930e0  pc=0x40081168 cpsr=0x600003c5 (EL1h, DAIF, nZCv)  ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0  VBAR_EL1=0x40080800 SCTLR_EL1=0x30000180 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0  insn at pc: 0xb9400100last exits: 32 (oldest first)  {"t_ns":1731333,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x72","action":"mmio","isv":true}  {"t_ns":1733166,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1734750,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x65","action":"mmio","isv":true}  {"t_ns":1736541,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1738166,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x61","action":"mmio","isv":true}  {"t_ns":1739958,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1741583,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x64","action":"mmio","isv":true}  {"t_ns":1743375,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1745000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x79","action":"mmio","isv":true}  {"t_ns":1747416,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400812e4","ipa":"0x9000018","wnr":false,"size":4,"reg":9,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1749000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400812f4","ipa":"0x9000000","wnr":true,"size":4,"reg":8,"value":"0xa","action":"mmio","isv":true}  {"t_ns":1751000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0x9000018","wnr":false,"size":4,"reg":11,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1752583,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008129c","ipa":"0x9000000","wnr":false,"size":4,"reg":11,"value":"0x70","action":"mmio","isv":true}  {"t_ns":1754416,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0x9000018","wnr":false,"size":4,"reg":11,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1756000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008129c","ipa":"0x9000000","wnr":false,"size":4,"reg":11,"value":"0x69","action":"mmio","isv":true}  {"t_ns":1757666,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0x9000018","wnr":false,"size":4,"reg":11,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1759250,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008129c","ipa":"0x9000000","wnr":false,"size":4,"reg":11,"value":"0x6e","action":"mmio","isv":true}  {"t_ns":1760875,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0x9000018","wnr":false,"size":4,"reg":11,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1762458,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008129c","ipa":"0x9000000","wnr":false,"size":4,"reg":11,"value":"0x67","action":"mmio","isv":true}  {"t_ns":1764041,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0x9000018","wnr":false,"size":4,"reg":11,"value":"0x80","action":"mmio","isv":true}  {"t_ns":1765625,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008129c","ipa":"0x9000000","wnr":false,"size":4,"reg":11,"value":"0xa","action":"mmio","isv":true}  {"t_ns":1767416,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x90","action":"mmio","isv":true}  {"t_ns":1769000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x70","action":"mmio","isv":true}  {"t_ns":1770833,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x90","action":"mmio","isv":true}  {"t_ns":1772458,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x6f","action":"mmio","isv":true}  {"t_ns":1774291,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x90","action":"mmio","isv":true}  {"t_ns":1775958,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x6e","action":"mmio","isv":true}  {"t_ns":1777916,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081370","ipa":"0x9000018","wnr":false,"size":4,"reg":8,"value":"0x90","action":"mmio","isv":true}  {"t_ns":1779625,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081378","ipa":"0x9000000","wnr":true,"size":4,"reg":1,"value":"0x67","action":"mmio","isv":true}  {"t_ns":1781541,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400812e4","ipa":"0x9000018","wnr":false,"size":4,"reg":9,"value":"0x90","action":"mmio","isv":true}  {"t_ns":1783208,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400812f4","ipa":"0x9000000","wnr":true,"size":4,"reg":8,"value":"0xa","action":"mmio","isv":true}  {"t_ns":1784958,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081168","ipa":"0x9010000","wnr":false,"size":4,"reg":0,"action":"stop","isv":true}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Your tree at the first run: the UART is on the bus, the clock is not yet. Made from the reference by deleting the PL031's bus.insert (and its now-unused imports) in crates/vmm/src/machine/virt.rs; nothing else changed. $G is the repository's target/guests/aarch64-unknown-none/release; ping arrives through a pipe instead of the keyboard.
course/captures/09-first-run-no-rtc.txt

Now the Predict fork: in your fr(), start from TXFE | RXFE instead of TXFE, so FR always claims the receive FIFO is empty, and run again. Ours, on the finished chapter:

TerminalReal output
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10exit: 5--- stdout ---uart-echo: ready--- stderr ---macvmm: timeout: the guest was still running after --timeout 10s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Predict fork: in crates/vmm/src/devices/pl011.rs, fr() starts from TXFE | RXFE instead of TXFE, so FR always says the receive FIFO is empty. Nothing else changed.
course/captures/09-predict-rxfe.txt

No pong: the guest polled until the timeout ended it (exit code 5). The exit trace shows what it was doing for those seconds. The command runs the guest for 2 seconds with --trace exits:t.jsonl:mmio, then prints four things from the trace: the number of records, the number of FR reads, the number of DR reads, and the last record. Its exit: 0 is the last command's, tail; macvmm itself exited 5, as above.

TerminalReal output
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 2 --trace exits:t.jsonl:mmio; wc -l < t.jsonl; grep -c '"ipa":"0x9000018","wnr":false' t.jsonl; grep -c '"ipa":"0x9000000","wnr":false' t.jsonl; tail -n 1 t.jsonlexit: 0--- stdout ---uart-echo: ready  6014536014350{"t_ns":2003670666,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0x9000018","wnr":false,"size":4,"reg":11,"value":"0x90","action":"mmio","isv":true}--- stderr ---macvmm: timeout: the guest was still running after --timeout 2s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Predict fork, the same broken FR (always RXFE = 1), run for 2 s with the exit trace on. Then, from the trace: the number of records, the number of FR reads (loads from 0x9000018), the number of DR reads (loads from 0x9000000), and the last record.
course/captures/09-predict-rxfe-trace.txt

In 2 seconds, 601,453 MMIO exits. All but 18 of them are 4-byte reads of 0x9000018 (FR) returning 0x90, like the last one shown; the 18 are the LCR_H setup and the 17 bytes of uart-echo: ready and its newline. And there are zero reads of DR.

The bytes were in the FIFO the whole time; the guest never asked for them, because the flags said there was nothing to ask for. If you predicted "yes", you were thinking of the device as storage. A driver acts on what the status registers say: the status register is half of the data path.

Deliberate breakage 1: a transmit FIFO that is always full. Undo the fork, then make fr() start from TXFE | TXFF. Predict: what does the guest print, and how does the run end?

TerminalReal output
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10exit: 5--- stderr ---macvmm: timeout: the guest was still running after --timeout 10s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: in crates/vmm/src/devices/pl011.rs, fr() starts from TXFE | TXFF instead of TXFE, so FR always says the transmit FIFO is full. Nothing else changed.
course/captures/09-break-txff.txt

Nothing at all, not even ready. putc waits while TXFF is set, so the very first byte never leaves. The same trace, counted the same way, with every record that is not an FR read, and the number of records per PC (program counter):

TerminalReal output
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 2 --trace exits:t.jsonl:mmio; wc -l < t.jsonl; grep -c '"ipa":"0x9000018","wnr":false' t.jsonl; grep -v '"ipa":"0x9000018","wnr":false' t.jsonl; grep -o '"pc":"0x[0-9a-f]*"' t.jsonl | sort | uniq -cexit: 0--- stdout ---  509269509268{"t_ns":218000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081184","ipa":"0x900002c","wnr":true,"size":4,"reg":9,"value":"0x70","action":"mmio","isv":true}   1 "pc":"0x40081184"509268 "pc":"0x40081370"--- stderr ---macvmm: timeout: the guest was still running after --timeout 2s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1, the same broken FR (always TXFF = 1), run for 2 s with the exit trace on. $G is the repository's target/guests/aarch64-unknown-none/release. Then, from the trace: the number of records, the number of FR reads (loads from 0x9000018), every record that is not an FR read, and how many records each PC produced. The exit: line is the last command's (uniq); macvmm itself exited 5, as in the run above.
course/captures/09-break-txff-trace.txt

One LCR_H write (0x900002c, value 0x70, which sets FEN), then 509,268 FR reads, all at one PC, the putc loop's. What you saw: silence, then exit 5. The misconception: "a device is whatever the datasheet's register list says"; both registers were "implemented", but the state machine behind them was wrong. The tool that finds it: the exit trace.

Output: never trust the bytes

The other direction starts in write_dr, which hands each byte to the sink. The sink passes it through the output filter before anything else.

Security

The guest chooses every byte it writes to DR, and your terminal does not only display bytes: it obeys escape sequences, which can retitle the window, write your clipboard, or make the terminal type a reply into whatever reads its input next. That is terminal injection, guest bytes driving the host terminal; the threat model in chapter 25 treats it in full. So guest output is filtered on every sink, a file included, with an allow-list of harmless sequences (colours, cursor movement, erasing, and a few terminal modes such as the alternate screen and bracketed paste, which macvmm resets on exit); everything else is dropped whole.

The filter is a byte-at-a-time state machine of its own, about 500 lines, and its rules are the tty-termios primer's subject, not this chapter's. Borrow it: scripts/learner lifeline backend::ansi copies the reference's backend/ansi.rs into your tree (declare it with pub mod ansi; in backend/mod.rs), and the checkpoint then passes marked as borrowed. Its entry point is one call:

crates/vmm/src/backend/ansi.rslines 176-196
/// Filter `input`, appending what may reach the terminal to `out`.pub fn push(&mut self, input: &[u8], out: &mut Vec<u8>) {    self.push_at(input, out, Instant::now());}/// [`AnsiFilter::push`] with an explicit time for the BEL rate limit.pub fn push_at(&mut self, input: &[u8], out: &mut Vec<u8>, now: Instant) {    match self.policy {        FilterPolicy::Safe => {            for &b in input {                self.byte(b, out, now);            }        }        FilterPolicy::Strict => {            for &b in input {                self.strict_byte(b, out);            }        }        FilterPolicy::Raw => out.extend_from_slice(input),    }}

Now replace your stand-in sink. Sink::new(name, out, policy) takes a Box<dyn Write + Send> and a FilterPolicy; Sink::none() discards everything. write_guest filters, then writes what survives:

crates/vmm/src/backend/serial.rslines 333-369
/// Filter `bytes` from the guest and queue what survives (module docs). Never fails, never/// panics, and never waits longer than [`SINK_FULL_WAIT`].pub fn write_guest(&self, bytes: &[u8]) {    self.write_guest_within(bytes, &mut FullWait::new());}/// [`Sink::write_guest`] for one of several writes made under one device-mutex hold: all/// of them share `wait`, so together they wait at most [`SINK_FULL_WAIT`] (module docs).pub fn write_guest_within(&self, bytes: &[u8], wait: &mut FullWait) {    let mut guard = lock(&self.front);    let f = &mut *guard;    f.buf.clear();    f.filter.push(bytes, &mut f.buf);    if f.buf.is_empty() {        return;    }    // A file sink stops at its cap (`,max=`); the guest is not told, nor stopped.    let n = f.buf.len();    let room = usize::try_from(f.max.saturating_sub(f.accepted)).unwrap_or(usize::MAX);    let take = n.min(room);    if take < n {        self.over_cap(n.saturating_sub(take), f.max);    }    let data = f.buf.get(..take).unwrap_or(&[]);    if data.is_empty() {        return;    }    // The cap counts what was actually queued (or written), not what a full queue dropped.    let queued = match f.inline.as_mut() {        Some(w) => self.write_inline(w, data),        None => self.enqueue(data, wait),    };    f.accepted = f.accepted.saturating_add(len64(queued));    if f.inline.is_some() && self.is_none() {        f.inline = None;    }}

A sink made by Sink::new writes on the caller's thread (the inline branch); that is the sink the contract tests build, and it is enough for a file.

Under the hood

The stdout sink never writes from the vCPU's thread: it has a bounded queue drained by its own writer thread, and a vCPU waits at most 10 ms for room, then drops the rest. A stalled stdout (a pager waiting for a key) would otherwise block the vCPU outside hv_vcpu_run, where no stop request can reach it.

Try it

Run the tty-hygiene guest. It switches to the alternate screen (ESC [ ? 1049 h), hides the cursor (ESC [ ? 25 l), turns on bracketed paste (ESC [ ? 2004 h), asks for the cursor position (ESC [ 6 n) and writes the clipboard (an ESC ] 52 sequence). Check whether the last two survive.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/tty-hygiene.bin@0x40080000 --timeout 10exit: 0--- stdout ---tty-hygiene: start\x1b[?1049h\x1b[?25l\x1b[?2004htty-hygiene: done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, stdout a pipe (not a terminal). The capture tool prints the escape byte 0x1b as \x1b.
course/captures/09-filter.txt

The screen, cursor and paste modes passed (macvmm undoes them when it exits on a terminal); the cursor query and the clipboard write are gone. To see what the safe policy keeps and drops for bytes of your own, use the ansi-filter lab in the tty-termios primer.

Where the sink writes is the --serial option: stdio (the default), file:F or none. Parse it in parse_serial, in learner/crates/macvmm/src/cli.rs, into a kind and a path; the reference also accepts a policy and a size cap after a comma, which you can skip. A file console must leave stdout empty. Here the console goes to s.txt; the command then prints the exit code, the file, and how many stdout lines mention the greeting (the capture's exit: 1 is that last grep, which found none):

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --serial file:s.txt --timeout 10 > stdout.txt; echo rc=$?; cat s.txt; grep -c 'hello from guest' stdout.txtexit: 1--- stdout ---rc=0hello from guest, x0=0x40000000guest done0
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, with the console sent to the file s.txt. Then: the exit code, the file, and how many lines of stdout mention the guest's greeting. $G is the repository's target/guests/aarch64-unknown-none/release.
course/captures/09-serial-file-run.txt

Raw mode, and every way out

A console wants each keystroke as it is typed, so when stdin is a terminal macvmm switches it to raw mode, the setting from the tty-termios primer:

crates/macvmm/src/term.rslines 125-148
/// Enter raw mode if `interactive` (the serial or the console sink is `stdio`, so stdin is/// bound to the guest: `HostIo::stdin` is not `Unbound`) and stdin is a TTY. Installs the/// panic hook first, so the terminal is never raw without a way back.pub fn setup(interactive: bool) -> Terminal {    install_panic_hook();    let stdin_tty = hvf::host::isatty(hvf::host::STDIN_FILENO);    let stdout_tty = hvf::host::isatty(hvf::host::STDOUT_FILENO);    let mut raw = false;    if interactive        && stdin_tty        && let Ok(t) = hvf::host::Termios::get(hvf::host::STDIN_FILENO)    {        let mut slot = saved();        if t.raw_variant().apply(hvf::host::STDIN_FILENO).is_ok() {            *slot = Some(t);            raw = true;        }    }    Terminal {        stdin_tty,        stdout_tty,        raw,    }}

Raw mode includes Ctrl-C: it becomes a byte for the guest, not a signal. So on a terminal, Ctrl-C no longer quits macvmm; use Ctrl-A x. SIGINT still arrives when stdin is not a terminal, or from kill -INT <pid> in another window.

Raw mode is a promise to put things back, on every path out. The saved settings live in one place that every exit path can reach:

crates/macvmm/src/term.rslines 96-112
/// The termios to put back, shared with the panic hook and the signal path. `None` when the/// terminal was not changed or is already restored.static SAVED: Mutex<Option<hvf::host::Termios>> = Mutex::new(None);fn saved() -> std::sync::MutexGuard<'static, Option<hvf::host::Termios>> {    SAVED.lock().unwrap_or_else(|p| p.into_inner())}/// Put the saved termios back and flush unread input. Idempotent; true if it restored.fn restore_saved() -> bool {    let Some(t) = saved().take() else {        return false;    };    let _ = t.apply(hvf::host::STDIN_FILENO);    let _ = hvf::host::tcflush_input(hvf::host::STDIN_FILENO);    true}

There are four paths: a normal stop (the terminal's Drop), Ctrl-A x, a signal, and a panic. The last needs a hook, installed before raw mode is entered:

crates/macvmm/src/term.rslines 214-225
/// Install (once) a panic hook that restores the terminal before the default hook prints the/// panic.pub fn install_panic_hook() {    static ONCE: Once = Once::new();    ONCE.call_once(|| {        let previous = std::panic::take_hook();        std::panic::set_hook(Box::new(move |info| {            emergency_restore();            previous(info);        }));    });}

Aside

A Rust panic runs the panic hook first, then unwinds the thread. std::panic::set_hook replaces the hook for the whole process, which is why ours calls the previous one after restoring the terminal. The standard library's documentation for std::panic::set_hook has the details.

The hook only repairs the terminal. Stopping the virtual machine (VM) is a second job: a guard on each vCPU thread notices the unwind (std::thread::panicking() in its Drop) and requests a stop, so a VMM bug ends the run with exit code 1 instead of leaving it half alive. In learner/crates/vmm/src/vcpu/manager.rs:

crates/vmm/src/vcpu/manager.rslines 75-89
/// Posts a stop if the vCPU thread ends without one (a panic, or a missing verdict).struct StopOnExit<'a>(&'a VmControl);impl Drop for StopOnExit<'_> {    fn drop(&mut self) {        if std::thread::panicking() {            self.0                .request_stop(StopReason::Vmm(Error::Internal("a vCPU thread panicked")));        } else if !self.0.is_stopping() {            self.0.request_stop(StopReason::Vmm(Error::Internal(                "a vCPU loop ended without a stop reason",            )));        }    }}

We have not found a way to make the reference panic from the command line, so the panic path is the one exit this chapter does not show running.

To check Ctrl-A x yourself, run under script, which gives the run a real terminal, and print the terminal settings before and after; press Ctrl-A, then x, once ready appears:

Shell
script -q /dev/null sh -c 'stty -g; cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10; echo rc=$?; stty -g'

We typed the two keys through a pipe so the run could be recorded:

TerminalReal output
(sleep 2; printf '\001x'; sleep 1) | script -q /dev/null sh -c 'stty -g; cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10; echo rc=$?; stty -g'exit: 0--- stdout ---gfmt1:cflag=4b00:iflag=2b02:lflag=5cb:oflag=3:discard=f:dsusp=19:eof=4:eol=ff:eol2=ff:erase=7f:intr=3:kill=15:lnext=16:min=1:quit=1c:reprint=12:start=11:status=14:stop=13:susp=1a:time=0:werase=17:ispeed=9600:ospeed=9600macvmm: console attached; Ctrl-A x quits, Ctrl-A h lists the escapesuart-echo: ready\x1b[0m\x1b[?25h\x1b[?1049l\x1b[?1047l\x1b[?47l\x1b[?2004l\x1b[?1l\x1b[?7h\x1b[?12l\x1b[0 q\x1b[4l\x1b>\x1b(B\x1b)B\x1b7\x1b[r\x1b8macvmm: user quitrc=130gfmt1:cflag=4b00:iflag=2b02:lflag=5cb:oflag=3:discard=f:dsusp=19:eof=4:eol=ff:eol2=ff:erase=7f:intr=3:kill=15:lnext=16:min=1:quit=1c:reprint=12:start=11:status=14:stop=13:susp=1a:time=0:werase=17:ispeed=9600:ospeed=9600
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. script(1) runs the command on a pseudo-terminal, so macvmm sees a real terminal and enters raw mode; the bytes Ctrl-A (0x01) and x arrive on it 2 s after the start, as if typed. $G is the repository's target/guests/aarch64-unknown-none/release. The capture tool prints the escape byte as \x1b and a carriage return as \x0d.
course/captures/09-tty-escape-run.txt

The two gfmt1: lines are identical: the terminal is exactly as macvmm found it. The long run of escape sequences before macvmm: user quit is the reset written after the guest's last byte, which undoes any mode a guest set, and the exit code is 130.

Stopping from another thread: the flag

Ctrl-A x is read by the stdin thread; SIGINT and SIGTERM by a signal thread, fed by the self-pipe from the unix-signals primer. Neither can stop the vCPU loop directly. They need to tell it, and that takes two parts. The message is the stop flag, an AtomicBool in learner/crates/vmm/src/control.rs:

crates/vmm/src/control.rslines 174-183
/// The VM's stop flag, first stop reason, vCPU kick list and PSCI state, shared by every/// thread of one boot.#[derive(Debug, Default)]pub struct VmControl {    stopping: AtomicBool,    reason: Mutex<Option<StopReason>>,    changed: Condvar,    handles: Mutex<Vec<VcpuHandle>>,    psci: Psci,}
crates/vmm/src/control.rslines 236-251
/// Ask the VM to stop for `reason`. Returns true if this was the first request (whose/// reason is the verdict). Callable from any thread, any number of times.pub fn request_stop(&self, reason: StopReason) -> bool {    let first = {        let mut slot = lock(&self.reason);        let first = slot.is_none();        if first {            *slot = Some(reason);        }        first    };    self.stopping.store(true, Ordering::SeqCst); // the flag before the kick (module docs)    self.kick_all_vcpus();    self.changed.notify_all();    first}
crates/vmm/src/control.rslines 212-215
/// True once a stop was requested. vCPU loops check it before every run.pub fn is_stopping(&self) -> bool {    self.stopping.load(Ordering::SeqCst)}

The first request_stop wins: its reason decides the exit code (UserQuit gives 130, Timeout 5). changed is a condition variable that wakes the main thread waiting for the verdict. The flag uses Ordering::SeqCst, the host-concurrency primer's rule until chapter 16 refines it.

The second part is the kick. A vCPU inside hv_vcpu_run never looks at the flag, so it must be forced out. If you kept chapter 03's simple timeout, which ended the process instead, implement the kick now: declare hv_vcpus_exit in your ffi.rs as in chapter 01, and wrap it. Each vCPU thread registers its handle with VmControl::register when it creates its vCPU, and kick_all_vcpus kicks them all:

crates/hvf/src/vcpu.rslines 180-198
/// Force every listed vCPU out of `hv_vcpu_run` (any thread). A handle whose vCPU is not/// running gets a sticky kick: its next run returns CANCELED immediately. A stale handle (its/// vCPU destroyed) is harmless: the framework rejects the id, or a new vCPU that reused it/// sees one spurious CANCELED.pub fn vcpus_exit(handles: &[VcpuHandle]) -> Result<(), CallError> {    if handles.is_empty() {        return Ok(());    }    let mut ids: Vec<ffi::hv_vcpu_t> = handles.iter().map(|h| h.0).collect();    let count = u32::try_from(ids.len()).map_err(|_| CallError {        call: "hv_vcpus_exit",        error: HvError::BadArgument,    })?;    // SAFETY: `ids` is a live, writable array of exactly `count` vCPU ids (the C prototype    // takes a non-const pointer, so we pass our own copy).    check("hv_vcpus_exit", unsafe {        ffi::hv_vcpus_exit(ids.as_mut_ptr(), count)    })}
crates/vmm/src/control.rslines 256-265
/// Make every vCPU look at the stop flag: wake the parked ones (PSCI OFF, waiting in/// `vcpu::wait` on their target's condition variable), then force the running ones out of/// `hv_vcpu_run` with one `hv_vcpus_exit` over every registered handle. The kick is sticky/// (measured on this Mac): a vCPU about to enter the guest returns `CANCELED` at once./// With N vCPUs this is one framework call, not N.fn kick_all_vcpus(&self) {    self.psci.wake_all();    let handles = lock(&self.handles).clone();    kick(&handles);}

The order matters: the flag is set before the kick. A vCPU checks the flag right before each hv_vcpu_run. If it checked a moment too early, it still stops: a kick sent to a vCPU that is not in the guest makes its next hv_vcpu_run return at once, and then it sees the flag. The signal side, in learner/crates/macvmm/src/signals.rs:

crates/macvmm/src/signals.rslines 31-52
/// Route the signals to the self-pipe and start the (detached) thread that serves it.pub fn spawn(host: Arc<HostIo>) -> std::io::Result<()> {    let pipe = SignalPipe::install(&[SIGINT, SIGTERM, SIGHUP, SIGUSR1])?;    std::thread::Builder::new()        .name("signal".into())        .spawn(move || {            loop {                match pipe.wait() {                    Ok(SIGUSR1) => err(host.hostctl.dump_rings().trim_end()),                    Ok(_) => {                        if !host.request_quit() {                            term::emergency_restore();                            term::emergency_line("macvmm: user quit (second signal: exiting now)");                            hvf::host::exit_now(USER_QUIT);                        }                    }                    Err(_) => return,                }            }        })        .map(|_| ())}

SIGHUP (the terminal went away) is treated like SIGTERM. SIGUSR1 prints the exit trace's ring, a debugging aid you can skip. A second quit signal, if the first did not stop the VM, restores the terminal and exits at once with 130.

To try SIGTERM, start the guest in one window and, once ready appears, send the signal from a second:

Shell
pkill -TERM -x macvmm

Ours sent it from the same shell, 2 seconds after the start:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10 & sleep 2; kill -TERM $!; wait $!; echo rc=$?exit: 0--- stdout ---uart-echo: readyrc=130--- stderr ---macvmm: user quit
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. macvmm runs in the background; 2 s later this shell sends it SIGTERM, as pkill -TERM -x macvmm from a second window would. $G is the repository's target/guests/aarch64-unknown-none/release.
course/captures/09-sigterm-run.txt

user quit, exit code 130, the same as Ctrl-A x. A process killed by SIGTERM would report 143 (128 + 15), but macvmm catches the signal, stops the VM, and chooses its own code.

A second device: the clock, and a real bus

The guest wanted the year. Where does it get it? A CPU's counter (chapter 11) says how much time has passed, not what time it is. A real-time clock, an RTC, knows the date; QEMU's virt machine has Arm's PL031 at 0x0901_0000. The manual is ARM DDI 0224. The constant names in the first column are the ones the contract tests import from vmm::devices::pl031:

ConstantOffsetTRM nameWhat our model does
DR0x000RTCDRseconds since 1 January 1970, as a 32-bit number
MR0x004RTCMRthe match register: an alarm time, below
LR0x008RTCLRa write sets the time DR reads from now on
CR0x00cRTCCRthe start bit, which our model always reads as 1 because our counter always runs
IMSC, RIS, MIS, ICR0x010 to 0x01cmask and status of the one alarm interrupt bit, as in the PL011
0xfe0 to 0xffcidentification bytes

This one is yours: write learner/crates/vmm/src/devices/pl031.rs, in the PL011's shape, with PL031_SIZE (4 KiB). Two pieces from the reference to start from. The clock is passed in as a WallClock, so tests can control time; host_clock() reads the wall clock on every call and never goes backwards:

crates/vmm/src/devices/pl031.rslines 88-101
/// Where the host's seconds come from: the real clock, or a test's.pub type WallClock = Box<dyn Fn() -> u64 + Send>;/// Host wall-clock seconds, read on every call and never below the last value returned/// (module docs: correct across host sleep, never backwards).pub fn host_clock() -> WallClock {    let last = AtomicU64::new(0);    Box::new(move || {        let now = SystemTime::now()            .duration_since(SystemTime::UNIX_EPOCH)            .map_or(0, |d| d.as_secs());        last.fetch_max(now, Ordering::Relaxed).max(now)    })}

Relaxed is enough here, an exception to the primer's rule: fetch_max is one indivisible step on one value, and nothing else is ordered by it (chapter 16's memory-ordering primer explains why that suffices).

A guest that sets the clock through LR gets an offset, applied in wrapping 32-bit arithmetic:

crates/vmm/src/devices/pl031.rslines 265-268
/// `RTCDR`: the guest's view of the time, `host + offset` in wrapping u32 seconds.fn dr(&self) -> u32 {    self.host_secs().wrapping_add(self.offset)}

Why the wall clock on every read, not the boot time plus the time elapsed? Rust's Instant stops while the Mac sleeps, so that sum would fall behind.

The interrupt half is an alarm the guest sets: a write to MR arms a match that fires when the counter equals it, MR - DR seconds ahead in wrapping arithmetic. So a value in the past is 2^32 seconds away, about 136 years. On each access, if that second has come, RIS becomes 1, and the line follows RIS & IMSC as in the PL011:

crates/vmm/src/devices/pl031.rslines 272-288
/// Arm the match for when the counter next *equals* `MR`: `MR - DR` seconds from now,/// unsigned and wrapping, so an `MR` in the past is ~2^32 s away (module docs; QEMU/// `pl031_set_alarm`).fn arm(&mut self) {    let now = (self.clock)();    let ticks = self.mr.wrapping_sub(low32(now).wrapping_add(self.offset));    self.alarm = Some(now.saturating_add(u64::from(ticks)));}/// Set the match flag once the armed second has come (on an access or from the alarm/// thread, whichever is first).fn check_match(&mut self) {    if self.alarm.is_some_and(|at| (self.clock)() >= at) {        self.alarm = None;        self.ris = 1;    }}

A guest that arms the alarm and then waits for the interrupt never touches the device again, so the reference also runs a helper thread that checks the match when the second comes. It matters only once interrupts reach the guest; it is optional until chapter 12. The contract tests build your RTC with Pl031::with_clock(clock, irq) and Pl031::new(irq) (which uses host_clock()), read dr(), and check the match against a clock they move by hand.

With the clock on the bus, the first run finishes:

TerminalReal output
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10exit: 0--- stdout ---uart-echo: readyponguart-echo: rtc seconds=1795164924uart-echo: rtc year=2026
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. $G is target/guests/aarch64-unknown-none/release; ping arrives through a pipe instead of the keyboard.
course/captures/09-echo-pipe.txt

Now two devices need routing, and chapter 07's in-order list would work, today. But its entries would have to be checked by hand, forever, for one property: no two windows may overlap, or one address would have two owners. So the check moves into the bus, once. The Bus, our MMIO bus, is a list of windows sorted by base address:

crates/vmm/src/bus.rslines 151-165
/// One device window.struct Entry {    name: &'static str,    base: u64,    /// One past the last byte; `base < end` (checked by `insert`).    end: u64,    dev: Arc<Mutex<dyn MmioDevice>>,}/// The machine's device windows, sorted by base, immutable once the VM runs. Frozen/// from chapter 9 on: later chapters rely on it unchanged.#[derive(Default)]pub struct Bus {    entries: Vec<Entry>,}

insert refuses a window of size 0 or one whose end overflows a u64 (BusError::InvalidRange), and one that overlaps a window already there (BusError::Overlap):

crates/vmm/src/bus.rslines 184-219
/// Add `dev` at `[base, base + size)`. Refuses size 0, an overflowing end and any/// overlap. Called only while the machine is built.pub fn insert(    &mut self,    name: &'static str,    base: u64,    size: u64,    dev: Arc<Mutex<dyn MmioDevice>>,) -> Result<(), BusError> {    let end = match base.checked_add(size) {        Some(end) if size > 0 => end,        _ => return Err(BusError::InvalidRange { name, base, size }),    };    // The first window that ends after `base` is the only one that can overlap.    let at = self.entries.partition_point(|e| e.end <= base);    if let Some(next) = self.entries.get(at)        && next.base < end    {        return Err(BusError::Overlap {            name,            base,            size,            with: next.name,        });    }    self.entries.insert(        at,        Entry {            name,            base,            end,            dev,        },    );    Ok(())}

Lookup is a binary search, and an access that starts inside a window but runs past its end is refused as a Straddle, so no device ever sees a partial access:

crates/vmm/src/bus.rslines 223-243
/// The window containing `ipa`, and the offset of `ipa` inside it. Binary search: the last/// window whose base is `≤ ipa` is the only candidate.fn find(&self, ipa: u64) -> Option<(&Entry, u64)> {    let after = self.entries.partition_point(|e| e.base <= ipa);    let e = self.entries.get(after.checked_sub(1)?)?;    if ipa < e.end {        Some((e, ipa.wrapping_sub(e.base))) // ipa ≥ base: no wrap    } else {        None    }}/// The device and offset for a `size`-byte access at `ipa` (module docs): total, never/// panics for any input.fn route(&self, ipa: u64, size: AccessSize) -> Result<(&Entry, u64), BusError> {    let (e, offset) = self.find(ipa).ok_or(BusError::Unmapped { ipa })?;    match ipa.checked_add(size.bytes()) {        Some(last) if last <= e.end => Ok((e, offset)),        _ => Err(BusError::Straddle { ipa, size }),    }}
crates/vmm/src/bus.rslines 247-259
/// A `size`-byte read at `ipa`, zero-extended.pub fn read(&self, ipa: u64, size: AccessSize) -> Result<u64, BusError> {    let (e, offset) = self.route(ipa, size)?;    let value = lock(&e.dev).read(offset, size);    Ok(value & size.mask())}/// A `size`-byte write at `ipa`; only the low `size` bytes of `value` are passed on.pub fn write(&self, ipa: u64, size: AccessSize, value: u64) -> Result<(), BusError> {    let (e, offset) = self.route(ipa, size)?;    lock(&e.dev).write(offset, size, value & size.mask());    Ok(())}

The table is built once, before the first vCPU runs, and never changes, so looking up needs no lock; only the device found is locked, for one call. Add new, len, is_empty and device_at, and keep register_devices from chapter 07 inserting the test device.

One more window belongs to the machine. Chapter 05's map reserves room for the interrupt controller's per-CPU frames, one 128 KiB frame per vCPU (chapter 12 explains them), but a machine with one vCPU uses only the first. A guest may probe the rest, and it must get an answer, not a fatal unhandled-MMIO stop. So the rest of that window, from GICR_BASE + gicr_size(ncpus) to GICR_WINDOW_END (both from your layout.rs), goes on the bus as a RazWi device named gicr-unused, in learner/crates/vmm/src/devices/razwi.rs:

crates/vmm/src/devices/razwi.rslines 25-54
/// A read-as-zero, write-ignored window named `name` (for the debug log).#[derive(Clone, Copy, Debug)]pub struct RazWi {    name: &'static str,}impl RazWi {    pub fn new(name: &'static str) -> RazWi {        RazWi { name }    }}impl MmioDevice for RazWi {    fn read(&mut self, offset: u64, size: AccessSize) -> u64 {        crate::guest_debug!(            "{}: {}-byte read at offset {offset:#x} (RAZ)",            self.name,            size.bytes()        );        0    }    fn write(&mut self, offset: u64, size: AccessSize, _value: u64) {        crate::guest_debug!(            "{}: {}-byte write at offset {offset:#x} (WI)",            self.name,            size.bytes()        );    }}

The checkpoint calls the four-argument register_platform, and expects it to insert exactly three windows: pl011, pl031 and gicr-unused. The reference writes it as a wrapper:

crates/vmm/src/machine/virt.rslines 398-407
/// [`register_platform_with`] with both interrupt lines connected to nothing: the chapter 09/// machine, and the host tests.pub fn register_platform(    bus: &mut Bus,    serial: &SinkHandle,    input: &Arc<SerialInput>,    ncpus: u32,) -> Result<Arc<Mutex<Pl011>>> {    register_platform_with(bus, serial, input, ncpus, PlatformIrqs::none())}
crates/vmm/src/machine/virt.rslines 411-461
/// Put the devices every `virt` machine has on `bus` (the memory map in `arch/layout.rs`):/// - the PL011 UART0, transmitting to `serial` and receiving from `input`;/// - the PL031 RTC;/// - a RAZ/WI window over the part of the interrupt controller's per-CPU window that `ncpus`///   vCPUs leave unused (one 128 KiB frame per vCPU; chapter 12 explains the frames).////// Their interrupt lines are `irqs` (connected to nothing until the interrupt controller/// arrives in chapter 12). Returns the UART so the caller can connect `input`'s push hook.pub fn register_platform_with(    bus: &mut Bus,    serial: &SinkHandle,    input: &Arc<SerialInput>,    ncpus: u32,    irqs: PlatformIrqs,) -> Result<Arc<Mutex<Pl011>>> {    let uart = Arc::new(Mutex::new(Pl011::new(        Arc::clone(serial),        Some(Arc::clone(input)),        irqs.pl011,    )));    bus.insert("pl011", PL011_BASE, PL011_SIZE, uart.clone())        .map_err(Error::Bus)?;    bus.insert(        "pl031",        PL031_BASE,        PL031_SIZE,        Arc::new(Mutex::new(Pl031::with_clock(            crate::timer::pl031_time_base(),            irqs.pl031,        ))),    )    .map_err(Error::Bus)?;    let frames = Layout::virt()        .gicr_size(ncpus)        .ok_or(Error::Internal("vCPU count outside 1..=MAX_CPUS"))?;    let rest = GICR_BASE        .checked_add(frames)        .filter(|start| *start < GICR_WINDOW_END);    if let Some(start) = rest {        bus.insert(            "gicr-unused",            start,            GICR_WINDOW_END.saturating_sub(start),            Arc::new(Mutex::new(RazWi::new("gicr-unused"))),        )        .map_err(Error::Bus)?;    }    Ok(uart)}

Two names in it come from later chapters. PlatformIrqs holds the two interrupt lines, and PlatformIrqs::none() is two NullIrqs; crate::timer::pl031_time_base() is host_clock() until chapter 11 adds the timer module. Your version can be the one function, with Arc::new(NullIrq) for each line and host_clock() for the clock.

Deliberate breakage 2: two owners for one address. Insert the PL031 at PL011_BASE + 0x800 instead of PL031_BASE. Predict: which access fails, and when?

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10exit: 1--- stderr ---macvmm: MMIO bus: device pl031 at 0x9000800 (+0x1000) overlaps device pl011
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 2: in crates/vmm/src/machine/virt.rs, register_platform_with inserts the PL031 at PL011_BASE + 0x800 instead of PL031_BASE, half-way into the PL011's window.
course/captures/09-break-overlap.txt

None: the VM never starts. The overlap is refused while the machine is built, with both names, and macvmm exits with code 1 before a single guest instruction runs. What you saw: an error at build time, not a strange value at run time. The misconception: "the guest will tell us if the map is wrong". It would not; with a list searched in order, the first entry silently wins. The tool that finds it: the check in insert, which the contract tests exercise with adjacent, overlapping, empty and overflowing windows.

Your turn

The contract tests use these public names; each must exist with the signature shown on this page:

  • vmm::bus: AccessSize (B1 to B8, bytes, mask), MmioDevice, Bus (new, insert, read, write, device_at, len, is_empty), BusError::{Overlap, InvalidRange, Straddle, Unmapped}.
  • vmm::devices::pl011: the register constants, LCR_H_FEN, PL011_SIZE, PL011_FIFO_DEPTH, the fr and int bit modules (with int::ALL), and Pl011 (new, rx_len, input_ready).
  • vmm::devices::pl031: DR, MR, LR, CR, IMSC, RIS, MIS, ICR, PL031_SIZE, host_clock, and Pl031 (new, with_clock, dr).
  • vmm::backend::serial: SerialInput (new, push, pop, len, is_empty, dropped, set_hook), SERIAL_INPUT_CAP, and Sink (new, none, write_guest); vmm::backend::ansi::FilterPolicy (borrowed).
  • vmm::irq::TestIrq (new, level, transitions, clear); vmm::devices::razwi::RazWi::new; vmm::config::VmConfig with its testdev field; vmm::machine::virt::{register_devices, register_platform}; and vmm::Error::Bus.

Before the checkpoint, check:

  1. cargo test -p vmm in learner/ passes your PL011, PL031 and bus tests.
  2. uart-echo prints pong and a year from 2025 on when you type ping, and Ctrl-A x leaves your terminal working.
  3. Your journal has the Predict entry, written before you ran the fork.

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

Checkpoint

Back at the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 09

You should see, as the last line:

CHECKPOINT 09 PASS

It runs the contract tests (the PL011's reset state, the DR, RIS, MIS, IMSC and ICR behaviour, the identification bytes, narrow accesses, a 33rd input byte that stays queued, the PL031 against an injected clock, and the bus's overlap, adjacency, size-0, overflow and straddle rules), then four runs on your Mac: uart-echo with ping, a file console, Ctrl-A x under a real terminal, and SIGTERM. Then it checks your journal:

TerminalReal output
scripts/checkpoint.sh 09exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   pl011_regs (9 tests), pl031_regs (7 tests), bus_overlap (5 tests)[PASS] runs on your Mac uart-echo: 4/4 serial markers, exit 0 in 0.08s[PASS] runs on your Mac serial-file: 3/3 serial markers, exit 0 in 0.02s[PASS] runs on your Mac tty-escape: 3/3 serial markers, 2 equal gfmt1: lines, exit 0 in 0.13s[PASS] runs on your Mac sigterm: 2/2 serial markers, exit 130 in 0.02s[INFO] journal          not checked (not a learner tree)CHECKPOINT 09 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The chapter's checkpoint, run against an unmodified copy of the reference (scripts/checkpoint.sh 09 --impl <tree>): what a finished chapter 09 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/09-checkpoint.txt

What now works:

  • a device that answers every access to its window, with the side effects of the real one;
  • a console in both directions, through a stdin thread, a bounded queue and an output filter;
  • every way out of macvmm, normal or not, leaves your terminal as it found it, and the user's quit always reaches the vCPU through the stop flag and the kick;
  • a clock that tells the guest the date, and a bus that cannot hand one address to two devices.

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

What's next

Our guests find the UART because 0x0900_0000 is written into their source. A general kernel cannot be compiled for every machine, so the VMM must describe the machine to it: its memory, its CPUs, and which devices sit at which addresses. Chapter 10 generates that description, a device tree blob (DTB), from the same layout.rs table the bus is filled from.

Open question

Our test guests never read the identification registers at 0xFE0. Linux does, before it binds a driver to the device. What happens to a guest that probes our UART and reads zeros there? Record your guess in the journal; chapter 14 boots Linux and checks it.

Spec hunt

  • PL011 TRM (ARM DDI 0183), the register description of UARTFR: after a write to UARTDR, when does a real PL011 set BUSY and clear TXFE, and which of those bits does our model hold constant?
  • PL011 TRM, the section on interrupts and the description of UARTICR: in which two ways can the real receive interrupt be cleared, and how does our model, which keeps the receive bits set while the FIFO holds data, differ?
  • PL031 TRM (ARM DDI 0224), RTCDR and RTCLR: what does a write to RTCLR do to the value RTCDR returns afterwards, and where does our model keep that difference?
Progress is stored only in this browser.