Chapter 08 · Part III
System registers, injection, hypercalls and PSCI
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.
From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A data-abort exit carries the syndrome
0x93820046. Without looking at guest memory, say the direction, the size and the register of the access, and name one instruction that fits.Show answer
EC is
0x93820046 >> 26 = 0x24, a data abort from the guest. Bit 24 (ISV) is 1, so the note is valid. SAS (bits 23:22) is 2, so 4 bytes; SSE is 0; SRT (bits 20:16) is 2; SF is 0, so a 32-bitwregister; WnR (bit 6) is 1, a write. A 4-byte store fromw2, such asstr w2, [x1].From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A trapped store has SRT = 31. What value does the VMM send to the device, and why must it never pass 31 to
hv_vcpu_get_reg?Show answer
Zero: in the data-register field of a load or store, 31 means
xzr, which reads as 0. In Hypervisor.framework's register numbering, 31 isHV_REG_PC, so passing it through would send the guest's PC to the device (and a load intoxzrwould overwrite the PC).From chapter 07: The exit loop: decoding syndromes and emulating MMIO
The test device holds
0x8001at some offset. What ends up in the destination register forldrh w3,ldrsh w3andldrsh x3from that offset?Show answer
ldrh w3gives0x8001(zero-extended).ldrsh w3gives0xffff8001: sign-extended to 32 bits, and writing awregister clears the upper half.ldrsh x3gives0xffffffffffff8001, sign-extended to 64 bits. SSE says whether to sign-extend; SF says to which width.From chapter 07: The exit loop: decoding syndromes and emulating MMIO
After your VMM handles each of these exits, where must the PC point before the next run: an
hvc, ansmc, and a data abort it emulated?Show answer
hvc: leave it, the hardware already moved it past the call.smc: add 4, it was intercepted before it executed. Data abort: add 4, the saved PC is the faulting instruction (a fault retries), and the VMM has now done its work.From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A guest runs
ldp x0, x1, [x2]withx2pointing into a device window. What is ISV in the syndrome, why, and what does this chapter's VMM do?Show answer
ISV is 0. The note has room for one register number (SRT) and one size, and a pair load moves two registers, so the hardware cannot describe it. The other syndrome fields are then UNKNOWN, so the VMM stops the VM with a fatal error that prints the instruction word, instead of guessing.
From chapter 07: The exit loop: decoding syndromes and emulating MMIO
The guest runs
strb w5, [x1]to a device, withx5 = 0x12345678. What value must reach the device, and which field tells you?Show answer
0x78. SAS is 0, so the access is 1 byte, and the VMM masks the register's value to that size before writing. Sending all ofx5would let the guest write bytes it never stored.From chapter 07: The exit loop: decoding syndromes and emulating MMIO
Why must
Exit::decodereturn a value for every possible 64-bit input instead of panicking on a value it does not expect?Show answer
The syndrome is the hardware's description of what a possibly hostile guest did. If some value made the decoder panic, the guest could crash the VMM on purpose by producing it. The checkpoint feeds the decoder a million random values to check this.
From chapter 07: The exit loop: decoding syndromes and emulating MMIO
Your VMM forgets to advance the PC after an emulated store. What does the exit trace look like, and how does the run end?
Show answer
The same record over and over: same
pc, sameipa, samevalue, onlyt_nsgrowing, hundreds of thousands per second. The guest retries the store forever, and the run ends only when--timeoutstops it (exit code 5).From chapter 07: The exit loop: decoding syndromes and emulating MMIO
A guest stops with a fatal error after a long run. Where do you look first to see what led up to it, and what does it hold?
Show answer
The
last exits:part of the dump: the vCPU's ring of recent exits, oldest first, with the fatal one last. The ring keeps the last 256 exits of each vCPU whether or not--traceis on, and the dump prints the last 32.From chapter 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.
From chapter 05: Two stages, one map: holes in stage 2 on purpose
With its MMU on, a guest stores to the virtual address
0x0b10_0000, which its own page tables translate to0x0b00_0000. Nothing is mapped at0x0b00_0000in stage 2. Which address does the VM exit report, and why that one?Show answer
0x0b00_0000, the IPA. Stage 2 is the stage that failed, and by then the hardware had already translated the virtual address through the guest's stage 1, so it records the IPA's page number (inHPFAR_EL2, with the offset fromFAR_EL2) and the VMM never has to read the guest's tables. The virtual address means something only inside the guest's current address space.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A data-abort exit has the syndrome
0x93890046. Is it a load or a store, how wide, and what kind of fault?Show answer
The class is
0x93890046 >> 26 = 0x24, a data abort from the guest. Bit 6 (WnR) is 1, so a write. Bits 23:22 (SAS) are0b10, so1 << 2 = 4bytes. The low six bits (DFSC) are0x06: a translation fault at level 2, meaning stage 2 found no entry for the address.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Your machine has 512 MiB of RAM from
0x4000_0000, so RAM ends at0x6000_0000. How many IPA bits does the address space need, and what doesipa_bits_needed(0x6000_0000)return?Show answer
31 bits would be enough:
1 << 30 = 0x4000_0000is too small,1 << 31 = 0x8000_0000covers0x6000_0000. The function returns 36, because it never asks for less than HVF's default size, so a small machine gets the same VM it would get without the setting.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Where does virtio slot 5 live, and which INTID does it use?
Show answer
At
0x0a00_0000 + 5 × 0x200 = 0x0a00_0a00, with INTID48 + 5 = 53. QEMU'svirtboard wires slot i to shared interrupt line (SPI)16 + i, and SPIs are numbered from INTID 32, so slot i is INTID32 + 16 + i.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A layout puts a trapped device window of
0x200bytes at0x0a00_0200and RAM at0x4000_0000. Which of the two must be 16 KiB-aligned, and why only that one?Show answer
Only RAM. A mapped region goes through
hv_vm_map, which works in whole 16 KiB host pages. A trapped window is never mapped: it is the absence of a mapping, so it can have any size and alignment.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A guest stores to
0x10_0000_0000(1 << 36) in a VM with a 36-bit IPA space. What does the exit's DFSC say?Show answer
0x04: a translation fault at level 0. The address is outside the input range of the stage-2 tables, so the hardware does not look it up at all. We checked this on a real Mac; it is not an address-size fault.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Your VMM hard-codes a 31-bit IPA space and you start a guest with
--mem 2G. What happens, and before or after the guest runs its first instruction?Show answer
Before: RAM from
0x4000_0000would end at0xC000_0000, past1 << 31 = 0x8000_0000, sohv_vm_maprefuses the RAM withHV_BAD_ARGUMENTand the VM never starts. The width of the map has to cover the layout, which is whatipa_bits_neededcomputes.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Without a second translation stage, how would a VMM keep a guest from reaching host memory it does not own, and what would it cost?
Show answer
With shadow page tables: the VMM keeps its own tables that map guest virtual addresses straight to host memory, write-protects the guest's tables, and updates the shadow copy on every trapped write. Every guest page-table write becomes a VM exit, which is why hardware added stage 2.
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
Vmis still alive, or was dropped withoutDropcallinghv_vm_destroy.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
hv_vm_createreturns0xfae94009, a code yourHvErrordoes not list. What shouldHvError::from_codereturn, and why not a generic "unknown error"?Show answer
HvError::Unknown(0xfae94009). The exact value is the evidence a bug report needs, and a newer macOS may add codes;Displaystill prints it in full.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A freshly built
macvmm, run without the signing runner, getsHV_DENIED (0xfae94007). Is that a link problem? What fixes it?Show answer
No: the program linked and started; the kernel refused at the call because the signature has no
com.apple.security.hypervisor. Run it throughcargo run(the runner signs a copy first) or sign it withscripts/sign.sh.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest stores a byte to
0x0900_0000, where nothing is mapped. Which layer decides that this access leaves the guest, and which decides what it means?Show answer
The macOS kernel's EL2 part decides it stops the guest and forwards it (a VM exit); our VMM, an ordinary EL0 process, decides what it means, by playing the device at that address.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Inside an
unsafeblock you index a slice out of bounds. What happens, and what does that tell you aboutunsafe?Show answer
It still panics: bounds checks on safe indexing stay on, as do type and borrow checks.
unsafeonly allows a few extra operations (such as calling an FFI function); the invariants those operations need become yours.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
The header declares
hv_return_t hv_vm_get_max_vcpu_count(uint32_t *max_vcpu_count);. What is the Rust parameter type, and who owns the memory it points to?Show answer
*mut u32. It is an out-pointer: the caller owns a live, writableu32(for example a local variable) and passes its address; the function writes the answer there and returns only an error code.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Why does
hv_vm_destroytake no argument at all?Show answer
There is no handle to pass: the VM belongs to the whole process, and there can be only one, so "destroy the VM" is unambiguous.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
At which exception level does
macvmmitself run, and at which does the guest kernel run?Show answer
macvmmruns at EL0, like any app. The guest kernel runs natively at EL1. The level above both, EL2, belongs to part of the macOS kernel.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest reads the clock counter with
mrs x0, CNTVCT_EL0a million times. How many of those reads reach our VMM?Show answer
None: the hardware virtualizes the counter, so the read completes inside the guest without any exit.
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_OFFandSYSTEM_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_EL1and the reset state (chapter 06); theExitenum, itsSysRegvariant, 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,msrand system-register names). - Pointers: ID registers and feature discovery; the trap-control registers
HCR_EL2andMDCR_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'smethod = "hvc"(chapter 10);CPU_ONand 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
0x18syndrome into Op0, Op1, CRn, CRm, Op2, Rt and direction, and name the register (OSLAR_EL1,PMCR_EL0, orS3_0_C15_C0_0for 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_OFFandSYSTEM_RESET, returningNOT_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 rebootand--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:
- 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); - reads
LORID_EL1, a register that does exist, and expects no exception (thelo=andloridlines); - reads
MDCCSR_EL0, a debug status register, and expects one exception (themdccsrlines); - sets and then clears the operating system's debug lock (the OS lock, explained below), and reads its status after each (the
oslsrlines).
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:
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.jsonlOur 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:
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.jsonlsysreg-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"}macvmm: warn: [vcpu0] guest: vcpu0: MRS MDCCSR_EL0 at pc 0x40081048: injecting UNDEFSix 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.
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.jsonlsysreg-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"}macvmm: warn: [vcpu0] guest: vcpu0: MRS PMCR_EL0 at pc 0x400811ec: injecting UNDEFWe checked both on a real Mac, and they disagree:
| Guest access | Default configuration | With --irqchip none |
|---|---|---|
mrs PMCR_EL0 (performance monitor control) | HVF raises the UNDEF itself; no exit | reaches us |
mrs LORID_EL1 | reaches us | reaches us |
mrs MDCCSR_EL0 (debug channel status) | reaches us | HVF returns 0 itself; no exit |
msr OSLAR_EL1, mrs OSLSR_EL1 (the OS lock, explained below) | reach us | reach 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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --timeout 10sysreg-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 okmacvmm: warn: [vcpu0] guest: vcpu0: MRS MDCCSR_EL0 at pc 0x40081048: injecting UNDEFPMUVer=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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --irqchip none --timeout 10sysreg-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 oksysreg 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=0x4008131cTake 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 x0The 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:
/// 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) }}/// 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_EL1writes it,OSLSR_EL1reads it, andOSDLR_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_EL1andMDSCR_EL1. Every Armv8 CPU has the two control registers and at least two breakpoints and two watchpoints;ID_AA64DFR0_EL1says how many (its BRPs and WRPs fields, 5 and 3 in thePMUVercapture 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), exceptLORID_EL1, which is read-only, so a write to it is UNDEF (RazRoin the code). - Inject UNDEF for the PMU and for every register in no row. The default is never "let it through".
/// 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:
/// 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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --irqchip none --timeout 10sysreg-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 okinject: SCTLR_EL1=0x30000180; CPSR 0x600003c5 -> 0x604003c5; PC 0x400812e8 -> 0x40080a00macvmm: warn: [vcpu0] guest: vcpu0: MRS PMCR_EL0 at pc 0x400812e8: injecting UNDEFAddresses 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:
| Step | Register | Value | Why |
|---|---|---|---|
| 1 | ELR_EL1 (exception link register: where to return) ← PC | 0x400812e8 | an UNDEF is a fault, so the saved PC points at the instruction |
| 2 | SPSR_EL1 (saved program status register) ← CPSR | 0x600003c5 | the state to return to, flags and all |
| 3 | ESR_EL1 ← EC << 26 | IL << 25 | ISS | 0x02000000 | EC 0, "unknown reason", IL 1 (a 32-bit instruction), ISS 0 |
| 4 | CPSR ← EL1h, interrupts masked | 0x604003c5 | flags kept, low bits 0x3c5, plus PAN (privileged access never, bit 22) |
| 5 | PC ← VBAR_EL1 + 0x200 | 0x40080a00 | VBAR_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:
/// 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:
/// 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.
/// 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:
/// 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:
/// 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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/sysreg-probe.bin@0x40080000 --timeout 10sysreg-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 okinject: SCTLR_EL1=0x30000180; CPSR 0x800003c5 -> 0x804003c5; PC 0x40081048 -> 0x40080a00macvmm: warn: [vcpu0] guest: vcpu0: MRS MDCCSR_EL0 at pc 0x40081048: injecting UNDEFThe 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:
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.jsonlcargo 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.jsonlsysreg-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"}Read it in three parts:
- The probe's first line says
undef count=0, thenFAILED: no exception arrived, so noELR_EL1was recorded (elr=0x0). Only this probe notices, because it was written to expect one. mdccsr FAILEDis the HVF effect seen earlier with--irqchip none, not the break.- 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:
scripts/checkpoint.sh 08checkpoint: 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 FAILThe 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/:
G=../target/guests/aarch64-unknown-none/releaseThen 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.
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 IDsIf 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:
/// 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.
/// 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,}/// `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.
/// 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:
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:
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.jsonlcargo 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.jsonlpsci-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"}macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: guest requested a reset (exit code 4)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)=0andfeatures(0x84000099)=-1: the second setsw0 = 0x8400000A(PSCI_FEATURES) andw1 = 0x84000099, a function that does not exist, and reads -1 back inx0.sip(0x82000000)=-1: a deliberate unknown ID in the silicon-provider range (owner 2). It is there to trigger the rate-limited warning, so theunknown SMCCC functionline on standard error is expected.affinity_info(0,0)=0andcpu_on(1)=-2: CPU 0 is on, and -2 isINVALID_PARAMETERSbecause 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.
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.jsonlpsci-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"}macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: guest requested a reset (exit code 4)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:
/// 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),}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, } }}| Code | Cause | Introduced |
|---|---|---|
| 0 | the guest powered off (DEBUG_EXIT(0), now also SYSTEM_OFF) | chapter 03 |
| 1 | an error in the VMM or from HVF, such as HV_DENIED | chapter 01 |
| 2 | a usage or configuration error, such as an unknown flag | chapter 03 |
| 3 | guest fatal: unhandled memory-mapped I/O (MMIO), an instruction abort, an exit we cannot handle, now a reset storm (below) | chapter 05 |
| 4 | the guest asked for a reset and --on-reset exit was given | this chapter |
| 5 | --timeout expired | chapter 03 |
| 6 | DEBUG_EXIT with a non-zero code, such as a guest panic | chapter 03 |
| 130 | you quit, for example with Ctrl-C | coming 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:
/// 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:
cargo run -q -p macvmm -- run --mem 64M --raw $G/psci-probe.bin@0x40080000 --timeout 10cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/psci-probe.bin@0x40080000 --timeout 10psci-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 1macvmm: 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 10sThe 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:
- Your decoder turns
0x6230e419intoPMCR_EL0,x0, read, and your policy injects UNDEF for it. - Your injection reproduces the table above for those numbers:
ELR_EL1,SPSR_EL1,ESR_EL1, the new CPSR and the new PC. - Your dispatcher answers
PSCI_VERSIONwith0x10001,PSCI_FEATURESof0x84000099with -1, and stops onSYSTEM_OFFandSYSTEM_RESET. - Chapter 07's
ExitEnvnow bundles guest memory, the serial output, the stop control (ctl, thecontrol.rsvalue through which a handler asks the VMM to stop with a reason) and the device bus. From now on build it only throughExitEnv::new, so the contract tests keep compiling when chapters 21 and 24 add fields:
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 MacRun this from the repository root:
scripts/checkpoint.sh 08You should see, as the last line:
CHECKPOINT 08 PASSIt 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:
scripts/checkpoint.sh 08checkpoint: 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 PASSIts 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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/psci-probe.bin@0x40080000 --timeout 10psci-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 1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0x82000000; returning -1What 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.
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.jsonlmacvmm 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}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_OFFandPSCI_FEATURES: what may a caller assume about aSYSTEM_OFFthat returns, and what mustPSCI_FEATURESanswer for a function that does not exist?