indicogniBuild a VMM

Contents

Chapter 08 · Part III

System registers, injection, hypercalls and PSCI

Needs a Mac Runs in browser ~4.5 h Lab: System registers and SMCCC IDs
9 of 26

Course progress: chapter 08 is 9 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 07: The exit loop: decoding syndromes and emulating MMIO

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

    Show answer

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

  2. From chapter 05: Two stages, one map: holes in stage 2 on purpose

    A guest stores a byte to 0x0900_0000, where its UART should be, but your VMM has mapped an ordinary page of RAM there. What does the guest see, and what does your VMM see?

    Show answer

    The guest sees a store that worked: the byte sits in RAM, and a load from the same address returns it. Nothing is printed. Your VMM sees nothing at all: a mapped address never causes a VM exit, so the VMM never learns the store happened. A device register needs a stage-2 hole, so each access stops the guest.

  3. From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI

    Your doctor prints hv_vm_create: HV_BUSY (0xfae94002). What is the most likely cause in your own code?

    Show answer

    A VM already exists in this process: Hypervisor.framework allows one per process. Usually an earlier Vm is still alive, or was dropped without Drop calling hv_vm_destroy.

Concepts you'll need

Chapters before this one: chapter 07, The exit loop: decoding syndromes and emulating MMIO.

  • Core, taught here: the system-register trap and its syndrome (exception class 0x18: Op0, Op1, CRn, CRm, Op2, Rt, direction); the policy table (emulate, RAZ/WI, inject UNDEF), with a reason per row; exception injection, done by hand, and choosing its entry in the vector table; dispatch of the SMC calling convention (SMCCC) over two conduits; the power state coordination interface (PSCI): VERSION, FEATURES, SYSTEM_OFF and SYSTEM_RESET; the exit-code table and --on-reset.
  • Core, from earlier: the exception entry sequence, the vector table base and the call-versus-retry rule (chapter 02); the two supervisors, Hypervisor.framework (HVF) and our virtual machine monitor (VMM) (chapter 01); PSTATE modes, the 16-entry vector table, ELR_EL1, ESR_EL1, SCTLR_EL1 and the reset state (chapter 06); the Exit enum, its SysReg variant, the PC-advance table and the exit trace (chapter 07).
  • Primers (read first): reading-arm-specs (RAZ/WI, UNDEFINED and the register pages of the Arm Architecture Reference Manual).
  • Primers (review): smccc (function-ID fields, fast and yielding calls, the two conduits); os-basics (what firmware is); aarch64-reading (mrs, msr and system-register names).
  • Pointers: ID registers and feature discovery; the trap-control registers HCR_EL2 and MDCR_EL2, which belong to HVF; the debug OS lock. Each is an Aside or a linked sentence below.
  • Forward definitions: the interrupt controller and --irqchip none (chapters 11 and 12); the device tree's method = "hvc" (chapter 10); CPU_ON and the per-CPU power table (chapter 20).

Your guest asks its CPU a question the CPU cannot answer: it reads a register for a hardware counter the CPU does not have. The read traps to your virtual machine monitor (VMM), and you must reply. You could hand back zero. Nothing crashes, the guest carries on, every test still runs. Or you could do what a real CPU does with a register it lacks, and raise an exception inside the guest.

Predict Make the VMM answer 0 to every register read it would otherwise refuse with an exception, then run the sysreg-probe test guest. Will the guest notice?

Write your answer and one sentence of reasoning under ## Predict in your journal. Sitting A runs it, as the first deliberate breakage.

This chapter answers row 4 of chapter 00's problem ledger, a way to ask the platform to power off or reset (starting other CPUs waits for chapter 20), and finishes row 1, the CPU, by deciding what to do with every privileged register access that reaches us. Sitting A (about 2.5 hours) is system registers and injection; sitting B (about 2 hours) is hypercalls, PSCI (the power state coordination interface) and exit codes.

Objectives: by the end you can

  • (Sitting A) Decode an exception-class 0x18 syndrome into Op0, Op1, CRn, CRm, Op2, Rt and direction, and name the register (OSLAR_EL1, PMCR_EL0, or S3_0_C15_C0_0 for one with no name).
  • (Sitting A) Explain our half of trapping: Hypervisor.framework forwards only some accesses, so which registers trap is measured; then give each a policy (emulate the OS lock, RAZ/WI (read-as-zero, writes ignored) for debug registers, inject UNDEF for everything else) with a written reason.
  • (Sitting A) Inject an UNDEFINED exception by doing by hand what the hardware does on exception entry, and compute the new PC from the 16-entry vector table.
  • (Sitting B) Implement an SMCCC dispatcher with PSCI 1.1 PSCI_VERSION, PSCI_FEATURES, SYSTEM_OFF and SYSTEM_RESET, returning NOT_SUPPORTED (-1) for unknown IDs with a rate-limited warning, over both conduits with their different PC rules.
  • (Sitting B) Map every way a virtual machine (VM) stops to macvmm's exit code, including --on-reset reboot and --on-reset exit.

Before you start. Run scripts/learner start 08 from the repository root. It copies this chapter's journal to learner/journal/08.md. As in chapter 07, you write your own version in learner/ against the contract tests: arch/sysreg.rs, arch/inject.rs, smccc.rs (the dispatcher, which answers VERSION, FEATURES, SYSTEM_OFF and SYSTEM_RESET) and control.rs under crates/vmm/src/, plus a system-register decoder in arch/esr.rs and new arms in vcpu/exit.rs. One file is borrowed, not written: psci.rs, the per-CPU power table that chapter 20 teaches. Sitting B starts by fetching it.

What reaches us is an experiment

Which guest actions reach our VMM is decided by trap settings that we do not own: Hypervisor.framework (HVF) sets them, from its seat at exception level 2 (EL2), one level above the guest's kernel at EL1. So "which system registers trap?" is an experiment you run, not a fact you look up in the Arm Architecture Reference Manual (the ARM ARM).

Aside

The settings live in two trap-control registers at EL2: HCR_EL2 (Hypervisor Configuration Register), which chooses the kinds of instruction that trap, and MDCR_EL2 (Monitor Debug Configuration Register), the same for debug and performance-monitor registers. Each has a page in the ARM ARM (document DDI 0487); only HVF writes them.

The sysreg-probe test guest, new in this chapter, touches four kinds of system register (the mrs/msr registers of the aarch64-reading primer). In order, it:

  1. reads PMCR_EL0, the control register of a performance counter this CPU does not have, and expects exactly one exception (its first two lines of output);
  2. reads LORID_EL1, a register that does exist, and expects no exception (the lo= and lorid lines);
  3. reads MDCCSR_EL0, a debug status register, and expects one exception (the mdccsr lines);
  4. sets and then clears the operating system's debug lock (the OS lock, explained below), and reads its status after each (the oslsr lines).

Its handler counts exceptions: undef count=N ec=... gives how many it took and the class of the last (0, "unknown reason", is an UNDEF; 0xffffffffffffffff means none). elr ok means the guest's exception link register, ELR_EL1 (chapter 06's dump), pointed at the mrs, as a real exception leaves it; "Rt untouched" means the mrs did not overwrite its destination register. With the exit trace's sysreg category on, the VMM writes one record per access that reaches it. From learner/, as in chapter 07:

Shell
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/sysreg-probe.bin@0x40080000 --trace exits:/tmp/s.jsonl:sysreg --timeout 10cat /tmp/s.jsonl

Our captures, made from the root of a copy of the reference, say target/guests/... where you say $G. Here is the reference in the default configuration, the checkpoint's own run, with the trace printed after it:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --trace exits:/tmp/s.jsonl:sysreg --timeout 10; cat /tmp/s.jsonlexit: 0--- stdout ---sysreg-probe: undef count=1 ec=0x0sysreg-probe: elr ok (the mrs at 0x400811ec; Rt untouched)sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=1 ec=0x0sysreg-probe: mdccsr elr ok (the mrs at 0x40081048; Rt untouched)sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok{"t_ns":585625,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081244","value":"0x0","sysreg":"LORID_EL1","sysreg_enc":"0xc527","action":"sysreg"}{"t_ns":764041,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081048","sysreg":"MDCCSR_EL0","sysreg_enc":"0x9808","action":"inject_undef"}{"t_ns":990666,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812ec","value":"0x1","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}{"t_ns":996750,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812f4","value":"0xa","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}{"t_ns":1001250,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081304","value":"0x0","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}{"t_ns":1005416,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x4008131c","value":"0x8","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}--- stderr ---macvmm: warn: [vcpu0] guest: vcpu0: MRS MDCCSR_EL0 at pc 0x40081048: injecting UNDEF
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference sysreg-probe and VMM in the default configuration, the checkpoint's own run; the trace file is printed after the run, and the exit status is macvmm's.
course/captures/08-sysreg-default.txt

Six records, four registers: LORID_EL1, MDCCSR_EL0, and the OS lock pair OSLAR_EL1 and OSLSR_EL1. None is PMCR_EL0, although the probe's first line, undef count=1 ec=0x0, shows that its read of PMCR_EL0 (step 1) took one exception. Now the same guest with the interrupt controller built into HVF switched off. An interrupt controller is the hardware that collects device interrupts and hands them to CPUs (chapter 12); HVF's runs in the macOS kernel, not in our process, and the flag --irqchip none runs without one (chapter 11). It is hidden: --help leaves it out, as it exists for teaching.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --irqchip none --trace exits:/tmp/n.jsonl:sysreg --timeout 10; cat /tmp/n.jsonlexit: 0--- stdout ---sysreg-probe: undef count=1 ec=0x0sysreg-probe: elr ok (the mrs at 0x400811ec; Rt untouched)sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=0 ec=0xffffffffffffffffsysreg-probe: mdccsr FAILED: elr=0x400811ec want 0x40081048, Rt=0x0sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok{"t_ns":692541,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400811ec","sysreg":"PMCR_EL0","sysreg_enc":"0xdce0","action":"inject_undef"}{"t_ns":998958,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081244","value":"0x0","sysreg":"LORID_EL1","sysreg_enc":"0xc527","action":"sysreg"}{"t_ns":1476958,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812ec","value":"0x1","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}{"t_ns":1481291,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812f4","value":"0xa","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}{"t_ns":1484916,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081304","value":"0x0","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}{"t_ns":1488375,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x4008131c","value":"0x8","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}--- stderr ---macvmm: warn: [vcpu0] guest: vcpu0: MRS PMCR_EL0 at pc 0x400811ec: injecting UNDEF
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference sysreg-probe and VMM, without the in-kernel interrupt controller (--irqchip none); the trace file is printed after the run, and the exit status is macvmm's.
course/captures/08-sysreg-nogic.txt

We checked both on a real Mac, and they disagree:

Guest accessDefault configurationWith --irqchip none
mrs PMCR_EL0 (performance monitor control)HVF raises the UNDEF itself; no exitreaches us
mrs LORID_EL1reaches usreaches us
mrs MDCCSR_EL0 (debug channel status)reaches usHVF returns 0 itself; no exit
msr OSLAR_EL1, mrs OSLSR_EL1 (the OS lock, explained below)reach usreach us

Same guest, same CPU: what reaches the VMM depends on how HVF is configured.

Nothing in the ARM ARM predicts the swap in the first and third rows; it is HVF's choice, and a future macOS may make another. So the reference keeps a policy for registers that do not reach us today, and the trace records every register that does.

In the --irqchip none run the probe prints mdccsr FAILED. It expected an exception for MDCCSR_EL0, but there HVF answers the read itself with 0, and our VMM never sees it. The FAILED line is the probe noticing HVF's choice, not a bug in our VMM.

Why a guest reads registers it might not have

Kernels discover features by reading ID registers: before using a performance counter, a kernel asks the CPU "do you have a performance counter?" by reading a register whose fields answer it. HVF answers ID-register reads itself, so we never see them; we only have to agree with what it said. If we answer every unknown read with zeros, the kernel believes whatever zero means. Real hardware raises an Undefined Instruction exception for a register it does not have, so UNDEF is the honest answer.

Aside

The ID registers are read-only registers such as ID_AA64PFR0_EL1 (which floating-point and interrupt-controller features exist), ID_AA64MMFR1_EL1 (memory-system features) and ID_AA64DFR0_EL1 (debug features). Each field is a small number, and 0 usually means "not implemented"; their pages in the ARM ARM list every value.

ID_AA64DFR0_EL1.PMUVer (bits 11 to 8) gives the version of the performance monitoring unit (PMU), the CPU's performance counters. We added one line to a copy of the probe that prints the register before step 1:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --timeout 10exit: 0--- stdout ---sysreg-probe: ID_AA64DFR0_EL1=0x10305006 PMUVer=0sysreg-probe: undef count=1 ec=0x0sysreg-probe: elr ok (the mrs at 0x400811ec; Rt untouched)sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=1 ec=0x0sysreg-probe: mdccsr elr ok (the mrs at 0x40081048; Rt untouched)sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok--- stderr ---macvmm: warn: [vcpu0] guest: vcpu0: MRS MDCCSR_EL0 at pc 0x40081048: injecting UNDEF
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • sysreg-probe with one added line at the start of main that reads ID_AA64DFR0_EL1 and prints it with its PMUVer field (bits 11:8); the VMM is the reference, in the default configuration. Run in a copy of the reference with that edit.
course/captures/08-pmuver.txt

PMUVer=0: not implemented. So PMCR_EL0, the PMU's control register, must be UNDEFINED: the guest was told there is no PMU.

LORID_EL1 is the opposite case. The guest sees ID_AA64MMFR1_EL1.LO = 1 (the probe's lo=1), which says the CPU has limited ordering regions (LOR), a memory-ordering feature no guest here uses. So that register exists and must not UNDEF. The reference reads it as zero, meaning "zero regions": a real answer, not a lie. The rule behind both: a policy must agree with what the ID registers told the guest.

Decoding the trap: exception class 0x18

A trapped mrs or msr arrives as exception class (EC) 0x18. As for the data aborts of chapter 07, the hardware has already decoded the instruction and written a note in the instruction-specific syndrome (ISS), the low 25 bits of the exception syndrome register (ESR): which register, which general-purpose register, which direction. To see a raw syndrome, we added one print line to a copy of the reference's handler and ran the probe without the interrupt controller:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --irqchip none --timeout 10exit: 0--- stdout ---sysreg-probe: undef count=1 ec=0x0sysreg-probe: elr ok (the mrs at 0x400811ec; Rt untouched)sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=0 ec=0xffffffffffffffffsysreg-probe: mdccsr FAILED: elr=0x400811ec want 0x40081048, Rt=0x0sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok--- stderr ---sysreg trap: esr=0x6230e419 pc=0x400811ecsysreg trap: esr=0x623e2aa9 pc=0x40081244macvmm: warn: [vcpu0] guest: vcpu0: MRS PMCR_EL0 at pc 0x400811ec: injecting UNDEFsysreg trap: esr=0x62280520 pc=0x400812ecsysreg trap: esr=0x622806a3 pc=0x400812f4sysreg trap: esr=0x62280500 pc=0x40081304sysreg trap: esr=0x62280683 pc=0x4008131c
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference sysreg-probe; the VMM has one added line in sysreg_trap (crates/vmm/src/vcpu/exit.rs) that prints the raw syndrome and PC of every system-register exit to stderr.
course/captures/08-sysreg-esr.txt

Take the first one, 0x6230e419, at the mrs of PMCR_EL0. The syndrome stores the fields out of name order (Op2 sits above Op1, CRm sits below Rt), so read them by bit position, then rearrange. IL is the instruction-length bit:

 0x6230e419 >> 26 = 0x18 (EC: MSR, MRS or system instruction), bit 25 = 1 (IL: 32-bit instruction) ISS = 0x30e419:   bits 21:20  Op0        = 3   bits 19:17  Op2        = 0   bits 16:14  Op1        = 3   bits 13:10  CRn        = 9   bits  9:5   Rt         = 0    (x0)   bits  4:1   CRm        = 12   bit   0     Direction  = 1    (1 = read, an mrs) (Op0, Op1, CRn, CRm, Op2) = (3, 3, 9, 12, 0)  ->  PMCR_EL0, read into x0

The five coordinates are the register's name; Rt and Direction say what the instruction wanted.

Each register's ARM ARM page lists these five numbers under "Accessing"; that is how you name one. A register no table names is printed in the spelling assemblers accept, S<op0>_<op1>_C<n>_C<m>_<op2>, for example S3_0_C15_C0_0. The trace's sysreg_enc (0xdce0 here) packs the same five numbers as HVF's hv_sys_reg_t (chapter 06's SysReg::new): Op0<<14 | Op1<<11 | CRn<<7 | CRm<<3 | Op2. The decoded access, in crates/vmm/src/arch/esr.rs:

crates/vmm/src/arch/esr.rslines 165-186
/// A trapped `MSR`/`MRS`/system instruction (EC 0x18; D17.2.40, "ISS encoding for an exception/// from MSR, MRS, or System instruction execution in AArch64 state"). Frozen.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct SysRegAccess {    pub op0: u8,    pub op1: u8,    pub crn: u8,    pub crm: u8,    pub op2: u8,    /// The general-purpose register; 31 means XZR.    pub rt: u8,    /// `Direction = 1`: MRS (a read into Rt).    pub read: bool,}impl SysRegAccess {    /// The register as `hv_sys_reg_t` (`op0<<14 | op1<<11 | CRn<<7 | CRm<<3 | op2`), the id    /// `hv_vcpu_{get,set}_sys_reg` takes (verified against the header by `hvf`'s tests).    pub const fn encoding(&self) -> SysReg {        SysReg::new(self.op0, self.op1, self.crn, self.crm, self.op2)    }}
crates/vmm/src/arch/esr.rslines 243-254
/// Decode a sysreg-trap ISS (EC 0x18).pub const fn decode_sysreg(esr: u64) -> SysRegAccess {    SysRegAccess {        op0: field8(esr, 20, 2),        op2: field8(esr, 17, 3),        op1: field8(esr, 14, 3),        crn: field8(esr, 10, 4),        rt: field8(esr, 5, 5),        crm: field8(esr, 1, 4),        read: bit(esr, 0),    }}

Now decode the third syndrome of the capture, 0x62280520, by hand: the five coordinates, the register, Rt and the direction. Check yourself against the answer, which follows the policy code in the next section.

The policy table: our half

HVF decided what reaches us; what we do with it is ours: a policy table, with a written reason per row. Three answers cover it, in the reading-arm-specs primer's vocabulary:

  • Emulate the debug OS lock, which an operating system sets while it saves or restores debug registers, so that an external debugger cannot interfere. It is set at power-on (cold reset) and Linux clears it early in boot, so a boot touches it whatever we do. We keep its bit per virtual CPU (vCPU): OSLAR_EL1 writes it, OSLSR_EL1 reads it, and OSDLR_EL1, the "double lock" used around power-down, is a second bit kept the same way.
  • RAZ/WI (read-as-zero, writes ignored) for the breakpoint and watchpoint registers and two debug control registers, MDCCINT_EL1 and MDSCR_EL1. Every Armv8 CPU has the two control registers and at least two breakpoints and two watchpoints; ID_AA64DFR0_EL1 says how many (its BRPs and WRPs fields, 5 and 3 in the PMUVer capture above: six breakpoints, four watchpoints). UNDEF for those would contradict the ID registers; zero says "nothing set, nothing enabled". The reference's row is a simplification: it covers all 16 slots, including the ones this CPU does not advertise, and HVF answers these registers itself, so none has reached us. The LOR registers are RAZ/WI too (they exist, with zero regions), except LORID_EL1, which is read-only, so a write to it is UNDEF (RazRo in the code).
  • Inject UNDEF for the PMU and for every register in no row. The default is never "let it through".
crates/vmm/src/arch/sysreg.rslines 167-225
/// The policy table (module docs). Coordinates are `(op0, op1, CRn, CRm, op2)` as each/// register's ARM ARM description prints them ("Accessing <register>"); [`span`] rows give/// inclusive `(lo, hi)` ranges for `CRm` and `op2`. First match wins; a register in no row/// gets [`Policy::Undef`]: unknown/// registers fail loudly in the guest instead of reading as a made-up value.pub const POLICY: &[Rule] = &[    // The OS lock (ARM ARM D19.3: OSLAR_EL1 2,0,1,0,4; OSLSR_EL1 2,0,1,1,4; OSDLR_EL1 2,0,1,3,4).    one("OSLAR_EL1", (2, 0, 1, 0, 4), Policy::OsLockAccess),    one("OSLSR_EL1", (2, 0, 1, 1, 4), Policy::OsLockStatus),    one("OSDLR_EL1", (2, 0, 1, 3, 4), Policy::OsDoubleLock),    // Breakpoint and watchpoint value/control registers: DBGBVR<n> op2 4, DBGBCR<n> 5,    // DBGWVR<n> 6, DBGWCR<n> 7, with n = CRm (2,0,0,n,op2).    span(        "DBG{B,W}{V,C}R<n>_EL1",        (2, 0, 0),        (0, 15),        (4, 7),        Policy::RazWi,    ),    one("MDCCINT_EL1", (2, 0, 0, 2, 0), Policy::RazWi),    one("MDSCR_EL1", (2, 0, 0, 2, 2), Policy::RazWi),    // FEAT_LOR, advertised by `ID_AA64MMFR1_EL1.LO = 1` (module docs): LORSA_EL1 3,0,10,4,0,    // LOREA_EL1 3,0,10,4,1, LORN_EL1 3,0,10,4,2, LORC_EL1 3,0,10,4,3 and LORID_EL1 3,0,10,4,7.    // 3,0,10,4,4..6 (MPAMIDR_EL1 and reserved) are not LOR registers and keep the default.    span(        "LOR (LORSA, LOREA, LORN, LORC)",        (3, 0, 10),        (4, 4),        (0, 3),        Policy::RazWi,    ),    one("LORID_EL1", (3, 0, 10, 4, 7), Policy::RazRo),    // PMU (ARM ARM D24.5): PMCR/PMCNTENSET/PMCNTENCLR/PMOVSCLR/PMSWINC/PMSELR/PMCEID0/1    // (3,3,9,12,*), PMCCNTR/PMXEVTYPER/PMXEVCNTR (3,3,9,13,*), PMUSERENR/PMOVSSET (3,3,9,14,*),    // PMINTENSET/PMINTENCLR/PMMIR (3,0,9,14,*), PMEVCNTR<n>/PMEVTYPER<n>/PMCCFILTR (3,3,14,8..15,*).    // Listed explicitly, although UNDEF is also the default, so the table documents the decision    // and a later RAZ/WI exception has a row to replace.    span(        "PMU (PMCR_EL0 .. PMOVSSET_EL0)",        (3, 3, 9),        (12, 14),        (0, 7),        Policy::Undef,    ),    span(        "PMU (PMINTEN{SET,CLR}_EL1, PMMIR)",        (3, 0, 9),        (14, 14),        (0, 7),        Policy::Undef,    ),    span(        "PMU (PMEV*<n>_EL0, PMCCFILTR)",        (3, 3, 14),        (8, 15),        (0, 7),        Policy::Undef,    ),];

MDCCSR_EL0 is in no row, so it gets the default UNDEF. That is a judgement call, not a rule: the debug channel belongs to the base debug architecture, so a real CPU would not raise an exception here, and KVM (Kernel-based Virtual Machine, Linux's hypervisor) reads it as zero. We keep the UNDEF because no guest we run touches the register and the probe uses it to test our injection in the default configuration; the reference's sysreg.rs records it as an open question.

Direction matters: OSLAR_EL1 is write-only, so an mrs of it is UNDEFINED too. The whole decision is a pure function of the access and the vCPU's emulated lock, which is what lets the contract tests sweep all 65,536 encodings on your laptop with no VM at all:

crates/vmm/src/arch/sysreg.rslines 317-340
/// Resolve one trapped access. `value` is `X[Rt]` for an `MSR` (ignored for an `MRS`). Pure:/// only `state` changes, and only for the OS-lock registers.pub fn handle(state: &mut SysRegState, access: &SysRegAccess, value: u64) -> SysRegOutcome {    match (policy_for(access.encoding()), access.read) {        (Policy::OsLockAccess, false) => {            state.os_lock = value & 1 != 0; // OSLAR_EL1.OSLK, bit 0            SysRegOutcome::Written        }        (Policy::OsLockStatus, true) => SysRegOutcome::Read(state.oslsr()),        (Policy::OsDoubleLock, true) => SysRegOutcome::Read(u64::from(state.os_double_lock)),        (Policy::OsDoubleLock, false) => {            state.os_double_lock = value & 1 != 0; // OSDLR_EL1.DLK, bit 0            SysRegOutcome::Written        }        (Policy::RazWi | Policy::RazRo, true) => SysRegOutcome::Read(0),        (Policy::RazWi, false) => SysRegOutcome::Written,        // MRS OSLAR_EL1, MSR OSLSR_EL1 and MSR LORID_EL1 are UNDEFINED, like every unlisted        // register.        (Policy::OsLockAccess, true)        | (Policy::OsLockStatus, false)        | (Policy::RazRo, false)        | (Policy::Undef, _) => SysRegOutcome::Undef,    }}

The exercise: 0x62280520 is (2, 0, 1, 0, 4), Rt 9, direction 0, an msr writing x9 to OSLAR_EL1.

Injection: doing the hardware's job

HVF handed this exception to us, but the guest expects exactly what the hardware would have done. So our code does the hardware's job, the exception entry chapter 02's stepper showed, in five steps, in software: exception injection.

Where does the PC go? Chapter 06 drew all sixteen entries of the vector table at VBAR_EL1 (the vector base address register) to read a dump; injection has to pick one, so here is the same table with each row's mode named. Each entry is 0x80 bytes (32 instructions), so the table is 2 KiB. The row is chosen by where the exception came from, the column by its kind, and the distance from VBAR_EL1 is the entry's vector offset:

                                    synchronous  IRQ      FIQ      SError                                    +0x000       +0x080   +0x100   +0x180 current level, using SP_EL0 (EL1t) 0x000        0x080    0x100    0x180 current level, using SP_EL1 (EL1h) 0x200        0x280    0x300    0x380 lower level, AArch64 (from EL0)    0x400        0x480    0x500    0x580 lower level, AArch32 (from EL0)    0x600        0x680    0x700    0x780 (offsets from VBAR_EL1)

Columns: synchronous, IRQ (interrupt request), FIQ (fast interrupt request), SError (system error). An injected UNDEF is synchronous, so it lands in the first column of one of the first three rows. We never run 32-bit code, so the last row is never ours.

One real trap, with real numbers. In a copy of the reference, the probe's UNDEF handler prints what it found, and the VMM prints the registers it read and wrote. Run without the interrupt controller, so PMCR_EL0 reaches our VMM:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --irqchip none --timeout 10exit: 0--- stdout ---sysreg-probe: undef count=1 ec=0x0sysreg-probe: handler saw ELR_EL1=0x400812e8 SPSR_EL1=0x600003c5 ESR_EL1=0x2000000 VBAR_EL1=0x40080800sysreg-probe: in the handler PAN=0x400000 SCTLR_EL1=0x30000180sysreg-probe: elr ok (the mrs at 0x400812e8; Rt untouched)sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=0 ec=0xffffffffffffffffsysreg-probe: mdccsr FAILED: elr=0x400812e8 want 0x40081048, Rt=0x0sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok--- stderr ---inject: SCTLR_EL1=0x30000180; CPSR 0x600003c5 -> 0x604003c5; PC 0x400812e8 -> 0x40080a00macvmm: warn: [vcpu0] guest: vcpu0: MRS PMCR_EL0 at pc 0x400812e8: injecting UNDEF
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Worked example: sysreg-probe with one change, its UNDEF hook also records SPSR_EL1, ESR_EL1, VBAR_EL1, PAN and SCTLR_EL1 and prints them (the 'handler saw' and 'in the handler' lines, printed only after an UNDEF); the VMM has one added line in inject_undef (crates/vmm/src/vcpu/exit.rs) that prints SCTLR_EL1 and the CPSR and PC before and after the injection (the 'inject:' line).
  • Run without the in-kernel interrupt controller (--irqchip none), the configuration in which Hypervisor.framework forwards PMCR_EL0 to the VMM. Run in a copy of the reference with those edits.
course/captures/08-inject-nogic.txt

Addresses moved (the mrs is at 0x400812e8 here, 0x400811ec in the reference) because the copy has extra code. Before the trap the guest was at EL1h with a current program status register (CPSR) of 0x600003c5, as the inject: line shows. The 0x6 on top is the Z and C condition flags; the low bits are chapter 06's EL1h, 0x3c5.

The syndrome we decoded earlier (class 0x18) is EL2's view of the trap, handed to us by HVF; the guest never sees it. A real CPU without the register would raise an Undefined Instruction exception at EL1, whose class is 0 ("unknown reason"), so that is what we write into the guest's own syndrome register, ESR_EL1. Our injection writes:

StepRegisterValueWhy
1ELR_EL1 (exception link register: where to return) ← PC0x400812e8an UNDEF is a fault, so the saved PC points at the instruction
2SPSR_EL1 (saved program status register) ← CPSR0x600003c5the state to return to, flags and all
3ESR_EL1 ← EC << 26 | IL << 25 | ISS0x02000000EC 0, "unknown reason", IL 1 (a 32-bit instruction), ISS 0
4CPSR ← EL1h, interrupts masked0x604003c5flags kept, low bits 0x3c5, plus PAN (privileged access never, bit 22)
5PC ← VBAR_EL1 + 0x2000x40080a00VBAR_EL1 is 0x40080800 (from the handler's printout), plus 0x200: synchronous, current EL with SP_EL1

PAN (bit 22 of the CPSR, chapter 06's Aside) is set because exception entry sets it unless the guest's SCTLR_EL1.SPAN bit is 1; Under the hood, below, has the details.

The handler's printout matches steps 1 to 3 to the bit, and it printed at all, so step 5 reached the table. The handler then moves ELR_EL1 past the mrs and returns: the guest decides whether to skip a faulting instruction, not us.

vector_offset picks the table's row from the mode bits of the CPSR (step 5's 0x200) and refuses any mode our vCPUs never run; entry_pstate builds step 4's value:

crates/vmm/src/arch/inject.rslines 141-171
/// The synchronous-exception vector offset for an exception taken from `cpsr` (module docs/// table). Total over every `u64`: no/// guest-controlled CPSR can make it panic.pub const fn vector_offset(cpsr: u64) -> Result<u64, InjectError> {    match cpsr & pstate_ext::MODE {        0b00100 => Ok(offset::CURRENT_SP0),        0b00101 => Ok(offset::CURRENT_SPX),        0b00000 => Ok(offset::LOWER_A64),        _ => Err(InjectError::UnsupportedMode { cpsr }),    }}/// True if an exception from `cpsr` is taken from EL0 (a "lower EL"). Only meaningful when/// [`vector_offset`] accepted `cpsr`.pub const fn from_lower_el(cpsr: u64) -> bool {    cpsr & pstate_ext::MODE == 0}/// PSTATE on entry to the EL1h handler (module docs table).pub const fn entry_pstate(old: u64, sctlr_el1: u64) -> u64 {    let mut p = pstate::EL1H_MASKED | (old & (pstate_ext::NZCV | pstate_ext::DIT));    p |= if sctlr_el1 & sctlr_ext::SPAN == 0 {        pstate_ext::PAN    } else {        old & pstate_ext::PAN    };    if sctlr_el1 & sctlr_ext::DSSBS != 0 {        p |= pstate_ext::SSBS;    }    p}

sync_exception computes steps 1 to 5 as pure data, with no vCPU in sight, which is how the contract tests check it:

crates/vmm/src/arch/inject.rslines 175-200
/// Compute the register writes that make the guest take a synchronous exception with/// exception class `ec` and syndrome `iss` (25 bits; higher bits are dropped) to EL1. `far`/// is the faulting VA for aborts. Pure: the caller writes the result to the vCPU.pub fn sync_exception(    st: &VcpuState,    ec: u8,    iss: u32,    far: Option<u64>,) -> Result<Injection, InjectError> {    let off = vector_offset(st.cpsr)?;    let pc = st        .vbar_el1        .checked_add(off)        .ok_or(InjectError::VectorOverflow {            vbar: st.vbar_el1,            offset: off,        })?;    Ok(Injection {        elr_el1: st.pc, // the faulting instruction itself: the handler decides whether to skip it        spsr_el1: st.cpsr,        esr_el1: (u64::from(ec & 0x3f) << 26) | ESR_IL | u64::from(iss & 0x01ff_ffff),        far_el1: far,        cpsr: entry_pstate(st.cpsr, st.sctlr_el1),        pc,    })}

undef fills in step 3's syndrome: EC 0 and ISS 0.

crates/vmm/src/arch/inject.rslines 204-208
/// An UNDEFINED-instruction exception: EC `0x00` ("unknown reason"), ISS 0, IL 1, so/// `ESR_EL1 = 0x0200_0000`. What a guest sees for a register that does not exist.pub fn undef(st: &VcpuState) -> Result<Injection, InjectError> {    sync_exception(st, ec::UNKNOWN, 0, None)}

apply_injection writes the result into the vCPU, and inject_undef is what the policy's UNDEF calls. It returns advance_pc: false, which is why the PC lands on the vector instead of being stepped past the mrs:

crates/vmm/src/vcpu/exit.rslines 332-375
/// Write an [`Injection`] into the vCPU: the exception-entry registers, then `CPSR` and `PC`.fn apply_injection(regs: &mut dyn VcpuRegs, inj: &Injection) -> Result<()> {    regs.set_sys_reg(SysReg::ELR_EL1, inj.elr_el1)?;    regs.set_sys_reg(SysReg::SPSR_EL1, inj.spsr_el1)?;    regs.set_sys_reg(SysReg::ESR_EL1, inj.esr_el1)?;    if let Some(far) = inj.far_el1 {        regs.set_sys_reg(SysReg::FAR_EL1, far)?;    }    regs.set_cpsr(inj.cpsr)?;    regs.set_pc(inj.pc)}/// The state [`inject`] needs, read from the vCPU at the trap.fn inject_state(regs: &dyn VcpuRegs) -> Result<VcpuState> {    Ok(VcpuState {        pc: regs.pc()?,        cpsr: regs.cpsr()?,        vbar_el1: regs.sys_reg(SysReg::VBAR_EL1)?,        sctlr_el1: regs.sys_reg(SysReg::SCTLR_EL1)?,    })}/// Inject an UNDEF for the instruction at the PC and resume at the guest's vector (the PC is/// not advanced). A mode the injector refuses stops the VM.pub fn inject_undef(    regs: &mut dyn VcpuRegs,    env: &ExitEnv<'_>,    exit: &Exit,    raw: &hvf::VcpuExit,    rec: &mut ExitRecord,) -> Result<ExitAction> {    let st = inject_state(regs)?;    match inject::undef(&st) {        Ok(inj) => {            apply_injection(regs, &inj)?;            rec.action = Some(Action::InjectUndef);            Ok(ExitAction::Resume { advance_pc: false })        }        Err(e) => {            let why = format!("{e} at pc {:#x}", st.pc);            fatal(regs, env, exit, raw, rec, why)        }    }}

Now the exit handler for class 0x18 can apply the policy's outcome. An emulated access steps over the trapped instruction, which has not executed (chapter 07's PC rule); an UNDEF calls inject_undef, which sends the PC to the guest's vector table instead:

crates/vmm/src/vcpu/exit.rslines 405-450
/// A trapped `MSR`/`MRS` (EC 0x18). The policy (`arch::sysreg`) decides;/// an emulated access steps over the instruction, anything else becomes an UNDEF in the guest/// with a rate-limited warning naming the register (at most a few/// lines per call site, so a guest cannot flood the log).fn sysreg_trap(    regs: &mut dyn VcpuRegs,    env: &ExitEnv<'_>,    exit: &Exit,    raw: &hvf::VcpuExit,    access: &SysRegAccess,    rec: &mut ExitRecord,) -> Result<ExitAction> {    let reg = access.encoding();    rec.sysreg = sysreg::static_name(reg);    // Always the number too: the trap log must identify registers that have no name.    rec.sysreg_enc = Some(reg.0);    let value = if access.read { 0 } else { regs.x(access.rt)? };    let mut fallback = SysRegState::default();    let state = match regs.sysreg_state() {        Some(st) => st,        None => &mut fallback,    };    match sysreg::handle(state, access, value) {        SysRegOutcome::Read(v) => {            regs.set_x(access.rt, v)?; // XZR (rt = 31) discards it            rec.value = Some(v);            rec.action = Some(Action::Sysreg);            Ok(ExitAction::Resume { advance_pc: true })        }        SysRegOutcome::Written => {            rec.value = Some(value);            rec.action = Some(Action::Sysreg);            Ok(ExitAction::Resume { advance_pc: true })        }        SysRegOutcome::Undef => {            crate::guest_warn!(                "vcpu{}: {} {} at pc {:#x}: injecting UNDEF",                regs.index(),                if access.read { "MRS" } else { "MSR" },                sysreg::display_name(reg),                regs.pc()?            );            inject_undef(regs, env, exit, raw, rec)        }    }}

Under the hood

Step 4 is more than 0x3c5. The ARM ARM's exception-entry pseudocode (AArch64.TakeException) keeps the N, Z, C and V flags, clears a few execution bits, and sets PAN unless SCTLR_EL1.SPAN, bit 23, is 1. Our vCPUs come up with SCTLR_EL1 = 0x30000180 (only its RES1 bits, since chapter 06's reset clears M, C and I), whose SPAN is 0, so this guest enters its handler with PAN set: the handler read PAN=0x400000. The contract tests check both settings of SPAN.

Now the same instrumented copy in the default configuration, where HVF raises the UNDEF for PMCR_EL0 itself, with no exit, and our VMM injects only for MDCCSR_EL0:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --timeout 10exit: 0--- stdout ---sysreg-probe: undef count=1 ec=0x0sysreg-probe: handler saw ELR_EL1=0x400812e8 SPSR_EL1=0x600003c5 ESR_EL1=0x2000000 VBAR_EL1=0x40080800sysreg-probe: in the handler PAN=0x400000 SCTLR_EL1=0x30000180sysreg-probe: elr ok (the mrs at 0x400812e8; Rt untouched)sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=1 ec=0x0sysreg-probe: mdccsr handler saw ELR_EL1=0x40081048 SPSR_EL1=0x800003c5 ESR_EL1=0x2000000 VBAR_EL1=0x40080800sysreg-probe: mdccsr in the handler PAN=0x400000 SCTLR_EL1=0x30000180sysreg-probe: mdccsr elr ok (the mrs at 0x40081048; Rt untouched)sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok--- stderr ---inject: SCTLR_EL1=0x30000180; CPSR 0x800003c5 -> 0x804003c5; PC 0x40081048 -> 0x40080a00macvmm: warn: [vcpu0] guest: vcpu0: MRS MDCCSR_EL0 at pc 0x40081048: injecting UNDEF
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The same instrumented sysreg-probe and VMM as 08-inject-nogic.txt, now in the default configuration (with the in-kernel interrupt controller). Run in a copy of the reference with those edits.
course/captures/08-inject-gic.txt

The PMCR_EL0 lines are identical: the same ELR_EL1, SPSR_EL1, ESR_EL1 and PAN. Yet there is only one inject: line, for MDCCSR_EL0; HVF did the first one. The guest cannot tell whether HVF or our VMM raised its UNDEF: an injected exception must be built exactly as the hardware builds one. Building it faithfully is a separate question from deciding to raise it. For MDCCSR_EL0 the decision is ours, not what silicon would do, which is why the reference records it as an open question.

Deliberate breakage 1: answer 0 instead of UNDEF. In your workspace, add a first arm to sysreg::handle that returns SysRegOutcome::Read(0) for any read whose policy is Undef; undo it afterwards. Check your Predict entry, then run the probe without the interrupt controller, so that PMCR_EL0 reaches you, with the trace:

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/sysreg-probe.bin@0x40080000 --irqchip none --trace exits:/tmp/z.jsonl:sysreg --timeout 10cat /tmp/z.jsonl
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --irqchip none --trace exits:/tmp/z.jsonl:sysreg --timeout 10; cat /tmp/z.jsonlexit: 0--- stdout ---sysreg-probe: undef count=0 ec=0xffffffffffffffffsysreg-probe: FAILED: elr=0x0 want 0x400811ec, Rt=0x0sysreg-probe: lo=1 lorid=0x0 undef count=0sysreg-probe: lorid oksysreg-probe: mdccsr undef count=0 ec=0xffffffffffffffffsysreg-probe: mdccsr FAILED: elr=0x0 want 0x40081048, Rt=0x0sysreg-probe: oslsr after lock=0xa after unlock=0x8sysreg-probe: oslsr ok{"t_ns":927875,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400811ec","value":"0x0","sysreg":"PMCR_EL0","sysreg_enc":"0xdce0","action":"sysreg"}{"t_ns":1250875,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081244","value":"0x0","sysreg":"LORID_EL1","sysreg_enc":"0xc527","action":"sysreg"}{"t_ns":1755791,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812ec","value":"0x1","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}{"t_ns":1761166,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812f4","value":"0xa","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}{"t_ns":1765375,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081304","value":"0x0","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}{"t_ns":1769500,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x4008131c","value":"0x8","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: in sysreg::handle (crates/vmm/src/arch/sysreg.rs) a new first arm answers every read whose policy is Undef (the PMU rows and every register in no row) with 0 instead of injecting UNDEF; the guest is the reference sysreg-probe.
  • Run without the in-kernel interrupt controller (--irqchip none), so that PMCR_EL0 reaches the VMM. Run in a copy of the reference with that one edit; the trace file is printed after the run, and the exit status is macvmm's.
course/captures/08-zero-unknown.txt

Read it in three parts:

  1. The probe's first line says undef count=0, then FAILED: no exception arrived, so no ELR_EL1 was recorded (elr=0x0). Only this probe notices, because it was written to expect one.
  2. mdccsr FAILED is the HVF effect seen earlier with --irqchip none, not the break.
  3. The VMM reports nothing: exit code 0, no warning, no crash. Yet the trace's first record reads PMCR_EL0, "value":"0x0", "action":"sysreg": the guest was told there is no PMU, and now its control register answers. A kernel that trusted the value would carry on.

The checkpoint is less polite. We ran it against a copy of the reference with this one edit, in the default configuration:

TerminalReal output
scripts/checkpoint.sh 08exit: 1--- stdout ---checkpoint: implementation <tree>[FAIL] contract tests   sysreg_policy: 2 failed: pmu_is_undef, unknown_is_undef_sweep    ---- pmu_is_undef stdout ----        thread 'pmu_is_undef' (126666786) panicked at tests/sysreg_policy.rs:85:13:    assertion `left == right` failed      left: Read(0)     right: Undef    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace        ---- unknown_is_undef_sweep stdout ----        thread 'unknown_is_undef_sweep' (126666787) panicked at tests/sysreg_policy.rs:129:13:    assertion `left == right` failed: S0_0_C0_C0_0(0x0000)[FAIL] runs on your Mac sysreg-probe: expected/sysreg-probe.txt:5: stdout marker "sysreg-probe: mdccsr undef count=1 ec=0x0" missing (in order) (4/9 serial markers matched before it)    expected/sysreg-probe.trace.txt:2: trace marker "\"ec\":\"0x18\",*\"sysreg\":\"MDCCSR_EL0\",\"sysreg_enc\":\"0x9808\",\"action\":\"inject_undef\"" missing (in order) (1/4 trace markers matched before it)    last 20 trace records:      {"t_ns":592458,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081244","value":"0x0","sysreg":"LORID_EL1","sysreg_enc":"0xc527","action":"sysreg"}      {"t_ns":826166,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081048","value":"0x0","sysreg":"MDCCSR_EL0","sysreg_enc":"0x9808","action":"sysreg"}      {"t_ns":1277250,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812ec","value":"0x1","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}      {"t_ns":1282916,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x400812f4","value":"0xa","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}      {"t_ns":1287083,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x40081304","value":"0x0","sysreg":"OSLAR_EL1","sysreg_enc":"0x8084","action":"sysreg"}      {"t_ns":1290958,"vcpu":0,"reason":"exception","ec":"0x18","pc":"0x4008131c","value":"0x8","sysreg":"OSLSR_EL1","sysreg_enc":"0x808c","action":"sysreg"}    stderr (last lines):[PASS] runs on your Mac psci-probe: 11/11 serial markers, exit 0 in 0.01s[PASS] runs on your Mac psci-probe-exit: 4/4 serial markers, exit 4 in 0.01s[INFO] journal          not checked (not a learner tree)CHECKPOINT 08 FAIL
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1 (every read whose policy is Undef answers 0), checked by the real checkpoint run against a copy of the reference with that one edit (scripts/checkpoint.sh 08 --impl <tree>).
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/08-zero-unknown-checkpoint.txt

The contract tests catch it (pmu_is_undef, and the sweep over unlisted encodings), though HVF never forwards PMCR_EL0 here. The run fails too, because the checkpoint pins the reference's choice for MDCCSR_EL0.

What you saw: a run that "passes" while the guest is told something false.

The misconception: "no crash means no harm"; silence is a decision, and here a wrong one.

The tool that found it: the contract sweep and the trace's "action" field, not a guest that trusts the value; only a probe written to expect an exception notices.

Sitting A ends in a state that builds. In learner/, cargo build -p vmm succeeds and cargo test -p vmm passes your own tests. Then, from the repository root, scripts/checkpoint.sh 08 reports each contract file by name on its first line: inject and sysreg_policy should pass, while smccc_dispatch, psci_state and the runs fail until sitting B is done.

Good place to stop. Sitting B needs about 2 hours, your Mac and the smccc primer fresh in mind.

A power button nobody wired

Starting sitting B. Two things first. If this is a new terminal, set G again, exactly as in sitting A, from learner/:

Shell
G=../target/guests/aarch64-unknown-none/release

Then borrow the CPU power table, from the repository root: scripts/learner lifeline vmm::psci. Your dispatcher calls into it for CPU_ON, CPU_OFF and AFFINITY_INFO, which chapter 20 teaches.

A kernel that wants to power off does not poke a power chip; it asks the platform: the firmware from the os-basics primer, which ran first and stays behind to answer a few requests such as "power off". Our machine has no firmware, so the VMM plays its part.

We could invent a power-controller device and write a driver for it into every guest, or answer the call real Arm firmware already answers, so stock kernels work unchanged. That standard is PSCI: a set of numbered calls to power off, reset, and start or stop CPUs. It is carried by SMCCC, the calling convention named after SMC (secure monitor call) that you reviewed in the smccc primer.

Take SYSTEM_OFF, function ID 0x84000008. Bit 31 is 1: a fast call, one that runs to completion without interruption (a yielding call may be paused and resumed; every call in this course is fast). Bit 30 is 0: the 32-bit convention. Bits 29 to 24 are the owning entity number (OEN), 4, "standard secure service", PSCI's home. The low 16 bits are the function number, 8.

The registers are the API: the function ID goes in w0, arguments in x1 onwards (PSCI needs at most three, x1 to x3, and only their low halves, w1 to w3, for a 32-bit call such as this one), and results come back in x0 to x3.

Lab

System registers and SMCCC IDs

Take two 32-bit numbers apart field by field: build or decode an SMCCC function ID and see what macvmm answers, and decode an mrs or msr word (or its trap syndrome) into a register name and macvmm's policy for it.

Runs in browserOpen full page: System registers and SMCCC IDs
Two numbers, taken apart by field Top: the SMCCC function ID 0x8400_0008 split into its fields. Bit 31 is 1, a fast call; bit 30 is 0, the 32-bit convention; bits 29 to 24 are 4, the owner "standard secure service calls"; bits 23 to 16 are zero, as they must be; bits 15 to 0 are 8. Owner 4, function 8 is PSCI SYSTEM_OFF, and macvmm powers the VM off with exit code 0. Bottom: the instruction word 0xD53B_9C00 split into its fields: L is 1 (mrs), op0 3, op1 3, CRn 9, CRm 12, op2 0, Rt 0. The coordinates (3, 3, 9, 12, 0) name PMCR_EL0, so the word is mrs x0, PMCR_EL0; if it traps, its syndrome is 0x6230_E419 and macvmm injects UNDEF, because the guest was told it has no performance monitor. SMCCC function ID 0x8400_0008 bit 31 bit 30 29..24 23..16 15..0 1 0 4 0x00 0x0008 fast 32-bit owner zero function owner 4, function 8 = PSCI_SYSTEM_OFF: the VM powers off, exit code 0 Instruction word 0xD53B_9C00 L op0 op1 CRn CRm op2 Rt 1 3 3 9 12 0 0 (3, 3, 9, 12, 0) = PMCR_EL0: mrs x0, PMCR_EL0 trap syndrome 0x6230_E419; macvmm injects UNDEF (no PMU)

If the lab does not load: it decodes an mrs/msr instruction word into the register's coordinates and name, and builds an SMCCC function ID from its four fields (fast or yielding, 32 or 64, owner, number) and back.

The IDs and return values we answer, in crates/vmm/src/smccc.rs:

crates/vmm/src/smccc.rslines 67-107
/// PSCI_VERSION (DEN 0022 §5.1.1).pub const PSCI_VERSION: u32 = 0x8400_0000;/// CPU_SUSPEND (DEN 0022 §5.1.2), SMC32 and SMC64.pub const PSCI_CPU_SUSPEND_32: u32 = 0x8400_0001;pub const PSCI_CPU_SUSPEND_64: u32 = 0xC400_0001;/// CPU_OFF (DEN 0022 §5.1.3).pub const PSCI_CPU_OFF: u32 = 0x8400_0002;/// CPU_ON(target, entry, ctx) (DEN 0022 §5.1.4), SMC32 and SMC64.pub const PSCI_CPU_ON_32: u32 = 0x8400_0003;pub const PSCI_CPU_ON_64: u32 = 0xC400_0003;/// AFFINITY_INFO(target, level) (DEN 0022 §5.1.5), SMC32 and SMC64.pub const PSCI_AFFINITY_INFO_32: u32 = 0x8400_0004;pub const PSCI_AFFINITY_INFO_64: u32 = 0xC400_0004;/// MIGRATE_INFO_TYPE (DEN 0022 §5.1.7).pub const PSCI_MIGRATE_INFO_TYPE: u32 = 0x8400_0006;/// PSCI SYSTEM_OFF (SMC32 fast call, DEN 0022 §5.1.9).pub const PSCI_SYSTEM_OFF: u32 = 0x8400_0008;/// PSCI SYSTEM_RESET (SMC32 fast call, DEN 0022 §5.1.10).pub const PSCI_SYSTEM_RESET: u32 = 0x8400_0009;/// PSCI_FEATURES(fn) (DEN 0022 §5.1.14).pub const PSCI_FEATURES: u32 = 0x8400_000A;/// TRNG_VERSION (Arm DEN 0098 "True Random Number Generator Firmware Interface" §2.1).pub const TRNG_VERSION: u32 = 0x8400_0050;/// The vendor-specific hypervisor service's `Call UID` query (DEN 0028 §6.2: OEN 6, function/// `0xFF01`; Linux `ARM_SMCCC_VENDOR_HYP_CALL_UID_FUNC_ID`).pub const VENDOR_HYP_CALL_UID: u32 = 0x8600_FF01;/// SMCCC 1.1 and PSCI 1.1: major in bits 30:16, minor in 15:0.pub const VERSION_1_1: u64 = 0x0001_0001;/// MIGRATE_INFO_TYPE 2: "Trusted OS is either not present or does not require migration".pub const MIGRATE_NO_TRUSTED_OS: u64 = 2;/// SMCCC / PSCI `SUCCESS`.pub const SUCCESS: u64 = 0;/// SMCCC `NOT_SUPPORTED` (-1) as the register value.pub const NOT_SUPPORTED: u64 = u64::MAX;/// SMCCC / PSCI `INVALID_PARAMETERS` (-2) as the register value.pub const INVALID_PARAMETERS: u64 = u64::MAX - 1;/// PSCI `DENIED` (-3) as the register value.pub const DENIED: u64 = u64::MAX - 2;

The dispatcher

A call arrives as an Exit::Hvc or Exit::Smc (chapter 07). Three small types describe it: which conduit it came through (hvc or smc, the two instructions that can make a call; the next section compares them), what the guest passed, and what to do next.

crates/vmm/src/smccc.rslines 168-195
/// How the guest made the call.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Conduit {    /// `hvc #imm`: the hardware has already advanced the PC (checked on a real Mac).    Hvc,    /// `smc #imm`: the PC still points at the SMC (checked on a real Mac); the caller adds 4.    Smc,}/// One call: the conduit, its immediate and `x0..x3` at the trap.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct Call {    pub conduit: Conduit,    pub imm: u16,    pub x: [u64; 4],}/// What to do after a call.#[derive(Debug)]pub enum Outcome {    /// Write each `Some` into `x0..x3` and resume the guest.    Return([Option<u64>; 4]),    /// Stop the VM.    Stop(StopReason),    /// PSCI CPU_OFF succeeded: the calling vCPU is now `Off` and parks until a CPU_ON (or the    /// stop). Nothing is written back: CPU_OFF never returns on success (DEN 0022 §5.1.3).    CpuOff,}
crates/vmm/src/smccc.rslines 217-232
/// `W0`: the function ID is the low 32 bits of `x0` (DEN 0028 §2).fn function_id(x0: u64) -> u32 {    let [b0, b1, b2, b3, ..] = x0.to_le_bytes();    u32::from_le_bytes([b0, b1, b2, b3])}/// The three arguments as the call sees them: `x1..x3`, truncated to `W1..W3` for an SMC32/// call (bit 30 of the ID clear; DEN 0028 §3.1).fn args(fid: u32, x: [u64; 4]) -> [u64; 3] {    let [_, x1, x2, x3] = x;    if fid & (1 << 30) == 0 {        [x1, x2, x3].map(|v| v & 0xffff_ffff)    } else {        [x1, x2, x3]    }}

The dispatcher is one match that has an answer for every possible 64-bit input. The immediate is the number written after the instruction (the 0 in hvc #0), which the syndrome reports; an immediate other than 0 is not SMCCC. An ID nobody expected gets NOT_SUPPORTED with a warning (rate-limited so a guest cannot flood your terminal). Two IDs a stock Linux boot asks about get a quiet "no", through is_known_probe: TRNG_VERSION (does the firmware offer a true random number generator, TRNG?) and VENDOR_HYP_CALL_UID (which hypervisor is this? UID is unique identifier). The CPU_ON, CPU_OFF and AFFINITY_INFO rows act on a per-CPU power table that chapter 20 explains.

crates/vmm/src/smccc.rslines 257-312
/// Dispatch one SMCCC call (module docs). Total over every input: any `x0` a guest passes gets/// an answer, never a panic.pub fn dispatch(ctx: &Ctx<'_>, call: &Call) -> Outcome {    if call.imm != 0 {        crate::guest_warn!(            "hvc/smc with immediate {:#x} is not SMCCC; returning -1",            call.imm        );        return ret(NOT_SUPPORTED);    }    let [x0, ..] = call.x;    let fid = function_id(x0);    let [a1, a2, a3] = args(fid, call.x);    let psci = ctx.ctl.psci();    match fid {        SMCCC_VERSION | PSCI_VERSION => ret(VERSION_1_1),        // Only SMCCC_VERSION is advertised: no ARCH_WORKAROUND_1/2/3 (the host handles them).        SMCCC_ARCH_FEATURES => ret(if function_id(a1) == SMCCC_VERSION {            SUCCESS        } else {            NOT_SUPPORTED        }),        PSCI_CPU_SUSPEND_32 | PSCI_CPU_SUSPEND_64 => ret(SUCCESS), // standby: wake at once        PSCI_CPU_OFF => {            if psci.cpu_off(ctx.vcpu) {                Outcome::CpuOff            } else {                ret(DENIED)            }        }        PSCI_CPU_ON_32 | PSCI_CPU_ON_64 => match psci.cpu_on(a1, a2, a3, entry_valid(ctx, a2)) {            Ok(_) => ret(SUCCESS),            Err(e) => psci_err(e),        },        PSCI_AFFINITY_INFO_32 | PSCI_AFFINITY_INFO_64 => match psci.affinity_info(a1, a2) {            Ok(state) => ret(state.affinity_info()),            Err(e) => psci_err(e),        },        PSCI_MIGRATE_INFO_TYPE => ret(MIGRATE_NO_TRUSTED_OS),        PSCI_SYSTEM_OFF => Outcome::Stop(StopReason::PowerOff),        PSCI_SYSTEM_RESET => Outcome::Stop(StopReason::Reset),        PSCI_FEATURES => ret(if implemented(ctx, function_id(a1)) {            SUCCESS        } else {            NOT_SUPPORTED        }),        DEBUG_PUTC | DEBUG_EXIT | DEBUG_MEMHASH | DEBUG_BOOT_COUNT if ctx.debug_calls => {            debug_call(ctx, fid, call.x)        }        _ if is_known_probe(fid) => ret(NOT_SUPPORTED),        _ => {            crate::guest_warn!("unknown SMCCC function {fid:#x}; returning -1");            ret(NOT_SUPPORTED)        }    }}

SYSTEM_OFF and SYSTEM_RESET return nothing: they stop the VM with a reason. From now on every test guest ends with SYSTEM_OFF, exit code 0.

Two doors: hvc and smc

SMCCC has two conduits, and both reach us, by different routes. hvc (hypervisor call) is an exception call aimed at EL2 by design: it completes, the exception is taken, and the PC has already moved past it. smc would go to EL3, the firmware's level, which Apple's chips do not have, so HVF traps it before it runs and the PC still points at it. Chapter 02 showed the two PCs. So the dispatch result is written back the same way for both, and only an smc needs its PC advanced:

crates/vmm/src/vcpu/exit.rslines 272-309
fn smccc_call(    regs: &mut dyn VcpuRegs,    env: &ExitEnv<'_>,    conduit: Conduit,    imm: u16,    rec: &mut ExitRecord,) -> Result<ExitAction> {    let x = [regs.x(0)?, regs.x(1)?, regs.x(2)?, regs.x(3)?];    let [x0, ..] = x;    rec.func = smccc::function_name(x0);    rec.action = Some(if smccc::is_psci(x0) {        Action::Psci    } else {        Action::Smccc    });    let ctx = smccc::Ctx {        mem: env.mem,        serial: env.serial,        ctl: env.ctl,        vcpu: regs.index(),        generation: env.generation,        debug_calls: env.debug_calls,    };    match smccc::dispatch(&ctx, &smccc::Call { conduit, imm, x }) {        smccc::Outcome::Stop(r) => Ok(ExitAction::Stop(r)),        smccc::Outcome::CpuOff => Ok(ExitAction::CpuOff),        smccc::Outcome::Return(values) => {            for (n, v) in (0u8..).zip(values) {                if let Some(v) = v {                    regs.set_x(n, v)?;                }            }            Ok(ExitAction::Resume {                advance_pc: conduit == Conduit::Smc,            })        }    }}

Here is the reference psci-probe, which calls through hvc #0, with its first three trace records:

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/psci-probe.bin@0x40080000 --on-reset exit --trace exits:/tmp/h.jsonl:psci --timeout 10head -n 3 /tmp/h.jsonl
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/psci-probe.bin@0x40080000 --on-reset exit --trace exits:/tmp/h.jsonl:psci --timeout 10; head -n 3 /tmp/h.jsonlexit: 4--- stdout ---psci-probe: version=0x10001 okpsci-probe: smccc_version=0x10001 okpsci-probe: features(CPU_ON)=0 okpsci-probe: features(0x84000099)=-1 okpsci-probe: sip(0x82000000)=-1 okpsci-probe: affinity_info(0,0)=0 okpsci-probe: cpu_on(1)=-2 okpsci-probe: migrate_info_type=2 okpsci-probe: boot 0{"t_ns":197583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008137c","imm":0,"fn":"PSCI_VERSION","action":"psci"}{"t_ns":402708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081398","imm":0,"fn":"PSCI_FEATURES","action":"psci"}{"t_ns":519958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081398","imm":0,"fn":"PSCI_FEATURES","action":"psci"}--- stderr ---macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: guest requested a reset (exit code 4)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference psci-probe and VMM (calls through hvc #0), for comparison with 08-smc-conduit.txt.
  • The first three trace records are printed after the run; the exit status is macvmm's.
course/captures/08-hvc-conduit.txt

In the trace, an hvc arrives as exception class 0x16, an exit like any other. A hypercall is not a special CPU mode; it is an ordinary exception-generating instruction plus an agreed meaning for the registers.

Each guest line is one call and the x0 it got back:

  • version=0x10001: major 1 in the top half, minor 1 in the bottom, so PSCI 1.1 (and SMCCC 1.1 on the next line).
  • features(CPU_ON)=0 and features(0x84000099)=-1: the second sets w0 = 0x8400000A (PSCI_FEATURES) and w1 = 0x84000099, a function that does not exist, and reads -1 back in x0.
  • sip(0x82000000)=-1: a deliberate unknown ID in the silicon-provider range (owner 2). It is there to trigger the rate-limited warning, so the unknown SMCCC function line on standard error is expected.
  • affinity_info(0,0)=0 and cpu_on(1)=-2: CPU 0 is on, and -2 is INVALID_PARAMETERS because there is no CPU 1 yet (chapter 20).
  • migrate_info_type=2: "no trusted OS to migrate". A trusted OS is a small separate operating system that some machines run in EL3's secure world; we have none.

Try it

The test guests are shared by every chapter: they live in the repository's guests/ directory, not in your learner/ workspace. In guests/common/hvc.rs, inside the asm! call of hvc_call (the SMCCC helper), change the string "hvc #0" to "smc #0"; the other mentions of hvc #0 in that file are comments. From the repository root, run scripts/build-guests.sh; then, back in learner/, run the same command as above. Compare the class and the PC of the first record with the run above before you read ours. Afterwards restore and rebuild, or every later run and checkpoint uses smc: git restore guests/, then scripts/build-guests.sh.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/psci-probe.bin@0x40080000 --on-reset exit --trace exits:/tmp/p.jsonl:psci --timeout 10; head -n 3 /tmp/p.jsonlexit: 4--- stdout ---psci-probe: version=0x10001 okpsci-probe: smccc_version=0x10001 okpsci-probe: features(CPU_ON)=0 okpsci-probe: features(0x84000099)=-1 okpsci-probe: sip(0x82000000)=-1 okpsci-probe: affinity_info(0,0)=0 okpsci-probe: cpu_on(1)=-2 okpsci-probe: migrate_info_type=2 okpsci-probe: boot 0{"t_ns":319333,"vcpu":0,"reason":"exception","ec":"0x17","pc":"0x40081378","imm":0,"fn":"PSCI_VERSION","action":"psci"}{"t_ns":527250,"vcpu":0,"reason":"exception","ec":"0x17","pc":"0x40081394","imm":0,"fn":"PSCI_FEATURES","action":"psci"}{"t_ns":635166,"vcpu":0,"reason":"exception","ec":"0x17","pc":"0x40081394","imm":0,"fn":"PSCI_FEATURES","action":"psci"}--- stderr ---macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: guest requested a reset (exit code 4)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Try it: every guest call made through smc #0 instead of hvc #0 (one word in guests/common/hvc.rs, guests rebuilt); the VMM is the reference. Run in a copy of the reference with that edit.
  • The first three trace records are printed after the run; the exit status is macvmm's.
course/captures/08-smc-conduit.txt

Same answers, class 0x17 instead of 0x16, and the first call's PC is 0x40081378 instead of 0x4008137c: four bytes earlier, at the smc. We accept both doors, but a guest learns which one to use from the device tree, a description of the machine that chapter 10 generates, where our PSCI node says method = "hvc". Serving smc too is a policy choice, not an obligation.

Stopping for a reason: exit codes

A stop's reason picks the exit code, so scripts can tell a power-off from a crash:

crates/vmm/src/control.rslines 118-136
/// Why a VM stopped.#[derive(Debug)]pub enum StopReason {    /// PSCI SYSTEM_OFF.    PowerOff,    /// PSCI SYSTEM_RESET. With `--on-reset reboot` (the default) `vmm::run` rebuilds the    /// machine instead of returning it; with `--on-reset exit` it ends the process (exit 4).    Reset,    /// The guest called DEBUG_EXIT with this code.    DebugExit(u32),    /// The guest did something fatal (exit 3).    GuestFatal(Box<GuestFatal>),    /// `--timeout` expired (exit 5).    Timeout,    /// SIGINT, SIGTERM or Ctrl-A x (exit 130).    UserQuit,    /// The VMM or the host failed (exit 1, or 2 for a configuration error).    Vmm(Error),}
crates/vmm/src/control.rslines 140-156
impl StopReason {    /// The process exit code: 0 clean power-off, 1 VMM or host failure, 2 bad configuration,    /// 3 fatal guest error, 4 reset, 5 timeout, 6 debug exit with a nonzero code, 130 user quit.    pub fn exit_code(&self) -> i32 {        match self {            StopReason::PowerOff | StopReason::DebugExit(0) => 0,            StopReason::Vmm(e) => e.exit_code(),            StopReason::GuestFatal(_) => 3,            StopReason::Reset => 4,            StopReason::Timeout => 5,            StopReason::DebugExit(_) => 6,            StopReason::UserQuit => 130,        }    }}
CodeCauseIntroduced
0the guest powered off (DEBUG_EXIT(0), now also SYSTEM_OFF)chapter 03
1an error in the VMM or from HVF, such as HV_DENIEDchapter 01
2a usage or configuration error, such as an unknown flagchapter 03
3guest fatal: unhandled memory-mapped I/O (MMIO), an instruction abort, an exit we cannot handle, now a reset storm (below)chapter 05
4the guest asked for a reset and --on-reset exit was giventhis chapter
5--timeout expiredchapter 03
6DEBUG_EXIT with a non-zero code, such as a guest panicchapter 03
130you quit, for example with Ctrl-Ccoming in chapter 09

The same table is on the reference card.

SYSTEM_RESET asks for a system reset: the whole machine restarts, not one CPU as in chapter 06's reset state. With --on-reset reboot, the default, the VMM rebuilds the machine from the same inputs and boots it again; with --on-reset exit, the process ends with code 4. The loop counts boots in generation and caps resets per short window, so a guest that resets forever ends with exit 3:

crates/vmm/src/lib.rslines 89-128
/// The reboot loop with its two seams injected: `boot` builds and runs boot `generation` of/// the machine from `host` alone until it stops or the absolute `deadline` passes, and `now`/// is the clock of both the reset-storm limit and the `--timeout` deadline. `run` passes/// `Machine::build` + `Machine::run` and `Instant::now`; host tests pass fakes.pub fn run_with(    cfg: &VmConfig,    host: &HostIo,    mut now: impl FnMut() -> std::time::Instant,    mut boot: impl FnMut(&VmConfig, &HostIo, u64, Option<std::time::Instant>) -> Result<StopReason>,) -> Result<StopReason> {    // Once per process (doc comment above). `checked_add`: `--timeout` is capped    // (config::MAX_TIMEOUT), but never trust it in deadline arithmetic.    let deadline = cfg.timeout.and_then(|t| now().checked_add(t));    let mut storm = control::ResetStorm::new();    let mut generation: u64 = 0;    loop {        let reason = boot(cfg, host, generation, deadline)?; // Err: never reboot (teardown may have failed)        match reason {            StopReason::Reset if cfg.on_reset == config::ResetAction::Reboot => {                let at = now();                // The run's time is up: do not build another machine just to time it out.                if deadline.is_some_and(|d| at >= d) {                    return Ok(StopReason::Timeout);                }                if storm.record(at) {                    return Ok(StopReason::GuestFatal(Box::new(                        control::GuestFatal::machine(format!(                            "reset storm: more than {} resets within {} s",                            control::RESET_STORM_MAX,                            control::RESET_STORM_WINDOW.as_secs()                        )),                    )));                }                generation = generation.saturating_add(1);                crate::info!("guest reset: rebooting (boot {generation})");            }            other => return Ok(other),        }    }}

psci-probe prints boot 0, asks for a reset, and on its second boot powers off. Its RAM is fresh after a rebuild, so it asks the VMM which boot this is through DEBUG_BOOT_COUNT, a test-only debug hypercall of the same family as chapter 03's, and the answer is the loop's generation. The hvc run above used --on-reset exit, so it stopped after boot 0 with code 4.

Deliberate breakage 2: ignore SYSTEM_OFF. In your workspace, make the dispatcher answer PSCI_SYSTEM_OFF with ret(SUCCESS) instead of stopping; undo it afterwards. Predict: what does a guest do after a power-off that returned? Then run:

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/psci-probe.bin@0x40080000 --timeout 10
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/psci-probe.bin@0x40080000 --timeout 10exit: 5--- stdout ---psci-probe: version=0x10001 okpsci-probe: smccc_version=0x10001 okpsci-probe: features(CPU_ON)=0 okpsci-probe: features(0x84000099)=-1 okpsci-probe: sip(0x82000000)=-1 okpsci-probe: affinity_info(0,0)=0 okpsci-probe: cpu_on(1)=-2 okpsci-probe: migrate_info_type=2 okpsci-probe: boot 0psci-probe: version=0x10001 okpsci-probe: smccc_version=0x10001 okpsci-probe: features(CPU_ON)=0 okpsci-probe: features(0x84000099)=-1 okpsci-probe: sip(0x82000000)=-1 okpsci-probe: affinity_info(0,0)=0 okpsci-probe: cpu_on(1)=-2 okpsci-probe: migrate_info_type=2 okpsci-probe: boot 1--- stderr ---macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: 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 2: in smccc::dispatch (crates/vmm/src/smccc.rs) PSCI_SYSTEM_OFF returns SUCCESS to the guest instead of stopping the VM; the guest is the reference psci-probe.
course/captures/08-ignore-system-off.txt

The probe's output appears twice before the hang. Boot 0 asked for a reset, which still works, so the machine was rebuilt; boot 1 then asked to power off, got SUCCESS back, and is now parked. The process never exits on its own; --timeout ends it with code 5. Our guest's power_off falls into a loop of wfi (wait for interrupt) instructions, the only sane thing to do after a call that must not return.

What you saw: a hang after the last line.

The misconception: "the guest stops when it is done"; it stops only if both sides agree on how to say "done".

The tool that found it: the timeout and its exit code.

Security

The guest chooses everything a call carries: x0 to x3, the immediate, the conduit. Our dispatch answers every possible input (never a panic) and writes only x0 to x3, as each call defines. The debug calls answer only test guests, meaning anything loaded with --raw or as an ELF file; a Linux kernel image or firmware gets NOT_SUPPORTED, like any unknown ID. --no-debug-hvc and --debug-hvc turn them off or on for every guest.

Your turn

Check your workspace before the checkpoint:

  1. Your decoder turns 0x6230e419 into PMCR_EL0, x0, read, and your policy injects UNDEF for it.
  2. Your injection reproduces the table above for those numbers: ELR_EL1, SPSR_EL1, ESR_EL1, the new CPSR and the new PC.
  3. Your dispatcher answers PSCI_VERSION with 0x10001, PSCI_FEATURES of 0x84000099 with -1, and stops on SYSTEM_OFF and SYSTEM_RESET.
  4. Chapter 07's ExitEnv now bundles guest memory, the serial output, the stop control (ctl, the control.rs value through which a handler asks the VMM to stop with a reason) and the device bus. From now on build it only through ExitEnv::new, so the contract tests keep compiling when chapters 21 and 24 add fields:
crates/vmm/src/vcpu/exit.rslines 130-155
impl<'a> ExitEnv<'a> {    /// The environment as chapter 08 knows it: memory, the serial sink, the VM control block    /// and the device bus, with generation 0, the debug hypercalls off and the default    /// `--unhandled-mmio fatal` policy. Every field a later chapter adds (`rom`,    /// `watch`) starts as `None` here, so code (and the frozen checkpoint contracts) that    /// builds an `ExitEnv` with `ExitEnv { debug_calls: true, ..ExitEnv::new(..) }` keeps    /// compiling at every chapter, whatever fields the struct has grown since.    pub fn new(        mem: &'a dyn GuestMemory,        serial: &'a Sink,        ctl: &'a VmControl,        bus: &'a Bus,    ) -> Self {        Self {            mem,            serial,            ctl,            bus,            generation: 0,            debug_calls: false,            unhandled_mmio: MmioPolicy::Fatal,            watch: None,            rom: None,        }    }}

The checkpoint's PSCI contracts also exercise the CPU_ON power table that chapter 20 teaches, which you borrowed at the start of sitting B with scripts/learner lifeline vmm::psci; the checkpoint passes marked as borrowed. Stuck? scripts/learner hint 08 gives four hints, from a nudge to the exact reference file.

Checkpoint

From the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 08

You should see, as the last line:

CHECKPOINT 08 PASS

It runs the contract tests (vector offsets, the registers after injection, the policy sweep, one case per SMCCC function and the PSCI state table), then three runs on your Mac: sysreg-probe with its trace (the first capture on this page), psci-probe rebooting once and powering off, and psci-probe with --on-reset exit; the runs check two exit codes, 0 and 4. It ends with CHECKPOINT 08 PASS once your journal has an answer under every heading. Here it is against an unmodified copy of the reference, where there is no learner journal to check:

TerminalReal output
scripts/checkpoint.sh 08exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   inject (7 tests), sysreg_policy (6 tests), smccc_dispatch (8 tests), psci_state (7 tests)[PASS] runs on your Mac sysreg-probe: 9/9 serial markers, 4/4 trace markers, exit 0 in 0.06s[PASS] runs on your Mac psci-probe: 11/11 serial markers, exit 0 in 0.01s[PASS] runs on your Mac psci-probe-exit: 4/4 serial markers, exit 4 in 0.01s[INFO] journal          not checked (not a learner tree)CHECKPOINT 08 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 08 --impl <tree>): what a finished chapter 08 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/08-checkpoint.txt

Its contract tests are the first line, the three runs the next three, and your journal the last. One of the three runs, psci-probe rebooting once and powering off, looks like this when you run it by hand:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/psci-probe.bin@0x40080000 --timeout 10exit: 0--- stdout ---psci-probe: version=0x10001 okpsci-probe: smccc_version=0x10001 okpsci-probe: features(CPU_ON)=0 okpsci-probe: features(0x84000099)=-1 okpsci-probe: sip(0x82000000)=-1 okpsci-probe: affinity_info(0,0)=0 okpsci-probe: cpu_on(1)=-2 okpsci-probe: migrate_info_type=2 okpsci-probe: boot 0psci-probe: version=0x10001 okpsci-probe: smccc_version=0x10001 okpsci-probe: features(CPU_ON)=0 okpsci-probe: features(0x84000099)=-1 okpsci-probe: sip(0x82000000)=-1 okpsci-probe: affinity_info(0,0)=0 okpsci-probe: cpu_on(1)=-2 okpsci-probe: migrate_info_type=2 okpsci-probe: boot 1--- stderr ---macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference psci-probe and VMM under the default --on-reset reboot, the same run the checkpoint makes.
course/captures/08-psci-reboot.txt

What now works:

  • every system-register access that reaches your VMM is decoded, named and answered by a policy with a written reason;
  • your VMM can make the guest take an UNDEF built exactly as the hardware builds one;
  • guests power off and reset through PSCI over either conduit, and every stop maps to one exit code.

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

What's next

Chapter 09 builds the first real devices: the PL011 serial port, a state machine behind registers whose reads have side effects, and a PL031 clock beside it; it also turns chapter 07's one-entry bus into a checked one. Test guests stop printing through a debug hypercall and talk to a UART (universal asynchronous receiver-transmitter), the way Linux will.

Before you start it, close Part III with an explain-back. Below is the exit trace of a guest you have not been told about, with only macvmm's exit code; its own output was thrown away, and so were its one-byte DEBUG_PUTC print calls. In about 200 words, say what the guest was doing and why macvmm stopped it. Score yourself on three points: the mechanism is right, every claim cites a record or field from the trace, and you name one experiment that would test your explanation.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/mystery.bin@0x40080000 --trace exits:x.jsonl:psci,hvc --timeout 10 >/dev/null 2>&1; echo "macvmm exit code: $?"; grep -v DEBUG_PUTC x.jsonlexit: 0--- stdout ---macvmm exit code: 3{"t_ns":362500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc"}{"t_ns":552166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci"}{"t_ns":245458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":1}{"t_ns":349250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":1}{"t_ns":1464083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":2}{"t_ns":1569708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":2}{"t_ns":178291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":3}{"t_ns":337333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":3}{"t_ns":294083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":4}{"t_ns":399083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":4}{"t_ns":185500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":5}{"t_ns":282166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":5}{"t_ns":428333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":6}{"t_ns":526291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":6}{"t_ns":459083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":7}{"t_ns":580791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":7}{"t_ns":183708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":8}{"t_ns":297625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":8}{"t_ns":1184916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":9}{"t_ns":1288583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":9}{"t_ns":240541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081094","imm":0,"fn":"DEBUG_BOOT_COUNT","action":"smccc","boot":10}{"t_ns":348916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810b4","imm":0,"fn":"PSCI_SYSTEM_RESET","action":"psci","boot":10}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Part III explain-back: one of the repository's test guests, renamed mystery.bin so its name does not give it away; the VMM is the reference. The guest's own output and macvmm's messages are discarded; only the exit code and the trace (without its one-byte DEBUG_PUTC print records) are shown.
course/captures/08-explain-back.txt

Open question

Our psci-probe powered off because it knew 0x84000008 means "off", and we answered it. Why is PSCI a standard? What would Linux need if every VMM invented its own way to power off and start CPUs?

Spec hunt

  • ARM ARM, register page ESR_EL2, "ISS encoding for an exception from MSR, MRS, or System instruction execution in AArch64 state": which field would tell you the access was to xzr, and what must your emulation do then?
  • ARM ARM, the AArch64.TakeException() pseudocode and the section on exception vectors: which PSTATE bits does exception entry change, which does it keep, and where does it choose among the four rows of the vector table?
  • Arm DEN 0022, the PSCI specification, the sections on SYSTEM_OFF and PSCI_FEATURES: what may a caller assume about a SYSTEM_OFF that returns, and what must PSCI_FEATURES answer for a function that does not exist?
Progress is stored only in this browser.