Chapter 09 · Part IV
A device is a state machine: the bus, PL011 and PL031
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.
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 trappedmsrormrs. The ISS0x280520gives Op0 2, Op2 4, Op1 0, CRn 1, Rt 9, CRm 0, direction 0: anmsr(a write) fromx9to the register at (2, 0, 1, 0, 4), which isOSLAR_EL1.From chapter 08: System registers, injection, hypercalls and PSCI
The guest is at EL1h with
VBAR_EL1 = 0x40080800when your VMM injects an UNDEF. Where does the guest's PC go, and what is inESR_EL1?Show answer
To
0x40080800 + 0x200 = 0x40080a00, the synchronous entry for "current EL, usingSP_EL1".ESR_EL1holds0x02000000: exception class 0 ("unknown reason"), IL 1, ISS 0.From chapter 08: System registers, injection, hypercalls and PSCI
After injecting an UNDEF for an
mrsat0x4008126c, should your VMM also add 4 to the PC it saved inELR_EL1?Show answer
No. An UNDEF is a fault, so
ELR_EL1must hold the address of themrsitself, as real hardware would leave it. Whether to skip the instruction is the guest handler's decision, not the VMM's.From chapter 08: System registers, injection, hypercalls and PSCI
A guest that ran in EL0 makes an access your VMM must answer with an UNDEF. Which vector table offset does the injection use, and why not
0x200?Show answer
0x400: the exception comes from a lower level (EL0) running 64-bit code.0x200is for an exception taken at the same level, EL1, usingSP_EL1.From chapter 08: System registers, injection, hypercalls and PSCI
The guest calls
hvc #0withx0 = 0x84000008. What does it ask for, and what doesmacvmmreturn to the shell?Show answer
0x84000008is a fast, 32-bit-convention call of owner 4 (standard secure service), function 8: PSCISYSTEM_OFF. The VM stops andmacvmmexits with code 0.From chapter 08: System registers, injection, hypercalls and PSCI
A guest calls PSCI
SYSTEM_RESET, andmacvmmwas started with--on-reset exit. What happens, and what changes with the default setting?Show answer
The process ends with exit code 4. With the default
--on-reset reboot, the VMM rebuilds the machine from the same inputs and boots it again, unless the guest resets too often in a short window, which ends with exit code 3.From chapter 08: System registers, injection, hypercalls and PSCI
Your VMM handles a PSCI call that arrived through
smc #0at0x40081378. Where must the guest resume?Show answer
At
0x4008137c. Ansmcis intercepted before it executes, so the saved PC points at it, and the VMM advances it by 4. After anhvc, the PC already points past the call.From chapter 08: System registers, injection, hypercalls and PSCI
The guest reads a system register that no row of your policy table names. What does the reference VMM do, and why that default?
Show answer
It injects an UNDEF, with a rate-limited warning naming the register. A real CPU raises UNDEFINED for a register it does not have; answering 0 would let the guest believe something false without anyone noticing.
From chapter 08: System registers, injection, hypercalls and PSCI
The guest calls
hvc #0withx0 = 0x84000099. What comes back, and in which register?Show answer
NOT_SUPPORTED, -1 (all ones), inx0, with a warning on the VMM's standard error. An unknown function ID is never silent and never a crash.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 is1 << 2 = 0x4. The stack-pointer select bit 0 set meansSP_EL1:0x1. Together0x3c5, the mode EL1h.From chapter 06: vCPU state: registers, PSTATE and reset
A dump shows
cpsr=0x3c9. Which level and stack pointer is that, and what does HVF do if you start a vCPU there without offering EL2 to the guest?Show answer
M[3:0] = 0b1001: EL2 (bits 3 to 2 =0b10) with its own stack pointer, EL2h, all four masks set. Without EL2 offered, the guest cannot be in that mode, andhv_vcpu_runrefuses withHV_ILLEGAL_GUEST_STATEbefore the guest runs a single instruction: no VM exit at all.From chapter 06: vCPU state: registers, PSTATE and reset
A guest dies with
pc=0x200,VBAR_EL1=0x0,ELR_EL1=0x40081094andESR_EL1=0x96000021. What went wrong first, and where?Show answer
The PC is
VBAR_EL1 + 0x200, a vector entry, so the guest took an exception at EL1 first and its handler (which does not exist) faulted on the fetch. The first fault is inESR_EL1: class0x25, a data abort at the same level, with fault status0x21, an alignment fault, caused by the load at0x40081094.From chapter 06: vCPU state: registers, PSTATE and reset
The guest runs
svc #0x4dat EL1 with a vector table of its own installed. How many VM exits does thatsvccause, and why?Show answer
None. An
svcfrom EL1 is routed to EL1, so the guest's own vector table handles it (ESR_EL1 = 0x5600004d, class0x15). Only exceptions routed to EL2 and forwarded by HVF reach the VMM.From chapter 06: vCPU state: registers, PSTATE and reset
What value does the VMM give vCPU 0's
MPIDR_EL1, and why is the top bit set when the CPU number is 0?Show answer
0x8000_0000. The affinity fields that number the CPU (Aff0,Aff1, …) are all 0 for the first CPU, and bit 31 is defined as always 1 (RES1) by the architecture.From chapter 06: vCPU state: registers, PSTATE and reset
Reset clears three bits of
SCTLR_EL1. Which, and why does a kernel want them clear at entry?Show answer
M (bit 0, stage-1 address translation), C (bit 2, data caching) and I (bit 12, instruction caching). A kernel turns translation and caches on itself, in an order it controls; it cannot trust translation or cache state left behind by whatever ran before it.
From chapter 06: vCPU state: registers, PSTATE and reset
You start a test guest in EL1t (
0x3c4) instead of EL1h. Its start code setsspand prints fine, but the first exception it takes never returns. Which register explains it?Show answer
SP_EL1. In EL1t, the start code'sspisSP_EL0, soSP_EL1keeps its reset value 0. Taking an exception to EL1 always switches toSP_EL1, so the handler's first store goes below address 0, faults, and re-enters the same handler forever, inside the guest.From chapter 06: vCPU state: registers, PSTATE and reset
A guest asks the platform for a system reset. Is that the same thing as the reset state
Vcpu::resetcreates?Show answer
No. The reset state is the set of register values a CPU has at power-on, which
Vcpu::resetrecreates for one vCPU. A system reset is a request, made through PSCI (chapter 08), to restart the whole machine; it ends with every vCPU back in its reset state.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: anhvcfrom 64-bit code. For anhvc, the low 16 bits of the syndrome hold its immediate, so the guest ranhvc #0x2a.From chapter 02: An exception, one level up: your first VM exit
An exit shows exception class
0x17with the guest's PC at0x40001000. Before you run the vCPU again, where must the PC point, and why?Show answer
At
0x40001004. That class is ansmc, which the level above intercepts before it executes, so the saved PC still points at thesmcitself, as for a fault; run it again unchanged and the guest repeats the same call forever.From chapter 02: An exception, one level up: your first VM exit
An app at EL0 runs
svc #0at address0x1000. Which exception level handles it, and which register holds0x1004when the handler starts?Show answer
EL1, the kernel's level.
ELR_EL1holds0x1004, the preferred return address: a call continues after itself.From chapter 02: An exception, one level up: your first VM exit
You set the starting PSTATE to
0x3c4instead of0x3c5. What is different about how the guest starts?Show answer
The low four bits change from
0b0101to0b0100: still EL1, but using the stack pointer of EL0 (SP_EL0, "EL1t") instead of EL1's own (SP_EL1, "EL1h"). The four DAIF mask bits are still all set.From chapter 02: An exception, one level up: your first VM exit
A timer interrupt arrives while a guest is in the middle of a loop. Is that a synchronous or an asynchronous exception, and where does the saved return address point?
Show answer
Asynchronous: no instruction caused it. The saved address is the first instruction that had not run yet, so the loop carries on as if nothing happened when the handler returns.
From chapter 02: An exception, one level up: your first VM exit
A guest's first instruction is at
0x40000000, but your VMM mapped its 16 KiB of RAM at0x40004000. What comes back from the firsthv_vcpu_run?Show answer
A VM exit for an instruction abort (exception class
0x20) at PC0x40000000: the CPU could not fetch the first instruction, because no stage-2 mapping covers that guest address. Nothing in the guest ran.From chapter 02: An exception, one level up: your first VM exit
hv_vm_mapis asked to map 16 KiB of host memory at guest address0x40002000. What does it answer on a Mac with the default configuration, and why?Show answer
An error (
HV_BAD_ARGUMENT). Mappings come in host pages of 16 KiB, so the guest address, the host address and the size must all be multiples of 16 KiB, and0x40002000is not.From chapter 02: An exception, one level up: your first VM exit
The instruction word
0x14000000sits after thehvcin chapter 02's guest. What does it do, and why is it there?Show answer
It is
b ., a branch to itself with offset 0: an endless loop. If the VMM ever resumes the guest past thehvc, the vCPU parks there harmlessly instead of running into whatever bytes follow.From chapter 02: An exception, one level up: your first VM exit
Why does the saved PC point after an
hvcbut at a load that faulted?Show answer
A call wants to continue after itself once it is answered; a fault must be retried once its cause is fixed, so the faulting instruction runs again.
From chapter 02: An exception, one level up: your first VM exit
Your VMM creates a vCPU on one thread and reads one of its registers with
hv_vcpu_get_regfrom another. What happens, and why?Show answer
The call fails (the framework answers
HV_BAD_ARGUMENT), because a vCPU belongs to the thread that created it: the header says its calls "must be called by the owning thread". In our Rust wrapper it does not even compile, because theVcputype cannot be sent to another thread.
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,AccessSizeandBustypes; 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; theAtomicBoolstop flag incontrol.rs, and the kick that makes a running vCPU see it. - Core, from earlier: the
--timeoutdeadline (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 at0xFE0and how Linux matches on them);host-concurrency(threads,Arc,Mutex, atomics, lock order; itslock-orderlab);unix-signals(SIGINT, SIGTERM, exit code 130, the self-pipe trick);tty-termios(raw mode,stty -g, escape sequences; itsansi-filterlab). - 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-onlyRSR,ILPRandDMACR) and the identification registers at0xFE0to0xFFC, as a state machine in which aDRread 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,RISandMISin 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
Mutexaround 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:
/// 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):
| Offset | Register | What our model does |
|---|---|---|
0x000 | DR, data | write: send the low byte; read: pop the RX FIFO (0 when empty) |
0x004 | RSR, receive status | reads 0 (no line errors ever happen); writes do nothing |
0x018 | FR, flags | computed from the FIFO on every read; read-only |
0x020 | ILPR, infrared low-power | stored; unused by our guests |
0x024, 0x028 | IBRD, FBRD, integer and fractional baud divisors | stored and read back; a baud rate means nothing here |
0x02c | LCR_H, line control | stored; bit 4, FEN, selects a 32-byte FIFO, else a 1-byte one |
0x030, 0x034 | CR, control; IFLS, FIFO level select | stored (reset values 0x300 and 0x12) |
0x038 to 0x044 | IMSC, RIS, MIS, ICR | the interrupt mask and status, below |
0x048 | DMACR, DMA control | stored; there is no DMA (direct memory access) here |
0xfe0 to 0xffc | identification | eight 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 bit | Mask | Name | Meaning when 1 |
|---|---|---|---|
| 3 | 0x08 | BUSY | still shifting a byte out (ours: never) |
| 4 | 0x10 | RXFE | receive FIFO empty |
| 5 | 0x20 | TXFF | transmit FIFO full |
| 6 | 0x40 | RXFF | receive FIFO full |
| 7 | 0x80 | TXFE | transmit FIFO empty (ours: always) |
| Interrupt bit | Mask | Name | Raised when |
|---|---|---|---|
| 4 | 0x10 | RX | received data waits |
| 5 | 0x20 | TX | a byte was sent |
| 6 | 0x40 | RT | receive 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:
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:
/// 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>,}/// 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:
/// 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:
/// 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;}/// 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, })}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:
/// 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);}/// 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.
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 pokeLoading 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:
cargo test -q -p vmm --test poke_demo -- --nocapturerunning 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.00sRead 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:
/// 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);}/// 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:
/// 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):
cargo test -q -p vmm --test pl011_regsrunning 9 tests.........test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00smacvmm: 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)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:
/// 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.
/// 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:
// 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(); }})));/// 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 queueBoth 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/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10Wait 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:
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10uart-echo: readypongmacvmm: 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}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:
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10uart-echo: readymacvmm: timeout: the guest was still running after --timeout 10sNo 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.
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.jsonluart-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}macvmm: timeout: the guest was still running after --timeout 2sIn 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?
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10macvmm: timeout: the guest was still running after --timeout 10sNothing 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):
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 -c 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"macvmm: timeout: the guest was still running after --timeout 2sOne 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:
/// 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:
/// 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.
cargo run -q -p macvmm -- run --mem 64M --raw $G/tty-hygiene.bin@0x40080000 --timeout 10tty-hygiene: start\x1b[?1049h\x1b[?25l\x1b[?2004htty-hygiene: doneThe 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):
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.txtrc=0hello from guest, x0=0x40000000guest done0Raw 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:
/// 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:
/// 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:
/// 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:
/// 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:
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:
(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'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=9600The 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:
/// 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,}/// 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}/// 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:
/// 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) })}/// 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:
/// 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:
pkill -TERM -x macvmmOurs sent it from the same shell, 2 seconds after the start:
cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10 & sleep 2; kill -TERM $!; wait $!; echo rc=$?uart-echo: readyrc=130macvmm: user quituser 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:
| Constant | Offset | TRM name | What our model does |
|---|---|---|---|
DR | 0x000 | RTCDR | seconds since 1 January 1970, as a 32-bit number |
MR | 0x004 | RTCMR | the match register: an alarm time, below |
LR | 0x008 | RTCLR | a write sets the time DR reads from now on |
CR | 0x00c | RTCCR | the start bit, which our model always reads as 1 because our counter always runs |
IMSC, RIS, MIS, ICR | 0x010 to 0x01c | mask and status of the one alarm interrupt bit, as in the PL011 | |
0xfe0 to 0xffc | identification 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:
/// 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:
/// `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:
/// 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:
printf 'ping\n' | cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10uart-echo: readyponguart-echo: rtc seconds=1795164924uart-echo: rtc year=2026Now 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:
/// 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):
/// 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:
/// 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 }), }}/// 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:
/// 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:
/// [`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())}/// 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?
cargo run -q -p macvmm -- run --mem 64M --raw $G/uart-echo.bin@0x40080000 --timeout 10macvmm: MMIO bus: device pl031 at 0x9000800 (+0x1000) overlaps device pl011None: 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(B1toB8,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, thefrandintbit modules (withint::ALL), andPl011(new,rx_len,input_ready).vmm::devices::pl031:DR,MR,LR,CR,IMSC,RIS,MIS,ICR,PL031_SIZE,host_clock, andPl031(new,with_clock,dr).vmm::backend::serial:SerialInput(new,push,pop,len,is_empty,dropped,set_hook),SERIAL_INPUT_CAP, andSink(new,none,write_guest);vmm::backend::ansi::FilterPolicy(borrowed).vmm::irq::TestIrq(new,level,transitions,clear);vmm::devices::razwi::RazWi::new;vmm::config::VmConfigwith itstestdevfield;vmm::machine::virt::{register_devices, register_platform}; andvmm::Error::Bus.
Before the checkpoint, check:
cargo test -p vmminlearner/passes your PL011, PL031 and bus tests.uart-echoprintspongand a year from 2025 on when you typeping, and Ctrl-A x leaves your terminal working.- 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 MacRun this from the repository root:
scripts/checkpoint.sh 09You should see, as the last line:
CHECKPOINT 09 PASSIt 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:
scripts/checkpoint.sh 09checkpoint: 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 PASSWhat 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 setBUSYand clearTXFE, 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
RTCLRdo to the valueRTCDRreturns afterwards, and where does our model keep that difference?