Chapter 06 · Part III
vCPU state: registers, PSTATE and reset
Course progress: chapter 06 is 7 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 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 03: A guest of your own, and what an exit costs
A guest prints
okand a newline through DEBUG_PUTC, then powers off. How many records with"ec":"0x16"does--trace exits:t.jsonl:hvcwrite, and why?Show answer
Four. Each printed byte is one
hvc(three bytes:o,k, newline), and the power-off call is one morehvc. Every one is an exception of class0x16.From chapter 03: A guest of your own, and what an exit costs
Decode the hypercall ID
0xC600_4D02field by field.Show answer
Bit 31 = 1, a fast call; bit 30 = 1, the 64-bit convention; bits 29 to 24 =
0x06, owner 6, vendor-specific hypervisor service; low 16 bits =0x4D02, the function. In macvmm that is DEBUG_EXIT, with the exit code inx1.From chapter 03: A guest of your own, and what an exit costs
A guest calls DEBUG_EXIT with
x1 = 3. What exit status doesmacvmmreturn to the shell, and what would it return forx1 = 0?Show answer
6 for any non-zero guest code (and it prints
guest exit code 3); 0 for code 0. The guest's own number and the monitor's exit status are different things.From chapter 03: A guest of your own, and what an exit costs
The flat binary of a guest is 11,866 bytes, and its linker map puts
__bss_startat0x40082e60with the image linked at0x40080000. After--raw guest.bin@0x40080000, what does a zero-initialised static at0x40082e60contain before_startruns?Show answer
Whatever that RAM held before: the file ends at offset 11,866 and
0x2e60is 11,872, so no byte of the file lands there. It reads 0 only if the monitor happened to hand over fresh, zeroed memory;_startmust zero the BSS itself.From chapter 03: A guest of your own, and what an exit costs
Your loader checks
addr + len <= ram_endwith a plain+. A user passes a 0x2000-byte file at address0xffff_ffff_ffff_f000. What goes wrong, and what is the fix?Show answer
With Rust's default release settings the sum wraps to
0x1000, which is below the end of RAM, so the check passes and the copy runs off the top of memory (withoverflow-checkson, as in our workspace, it panics instead: a crash, still not a clean refusal). Usechecked_addand refuse the file, exit code 2, when it returnsNone.From chapter 03: A guest of your own, and what an exit costs
exit-benchreports 3,600,000 ticks for 100,000 calls on a 24 MHz counter. What is one round trip in nanoseconds?Show answer
3,600,000 / 24,000,000 s = 0.15 s; divided by 100,000 that is 1.5 µs, 1,500 ns per round trip.
From chapter 03: A guest of your own, and what an exit costs
Why can a single store instruction not be timed with
CNTVCT_EL0, and what doesexit-bench's method do instead?Show answer
The counter ticks at 24 MHz, once every 41.7 ns, while a store takes a fraction of a nanosecond, so one store almost never spans a tick. Timing a loop of a million stores and dividing by a million gives the average.
From chapter 03: A guest of your own, and what an exit costs
A guest spins in
b .and you run it with--timeout 1. Why can the vCPU's own thread not notice the timeout, and what exit status do you get?Show answer
The thread is blocked inside
hv_vcpu_run, which does not return while the guest runs without exiting, so it cannot look at a clock. Another thread must notice the deadline and stop it (the reference kicks the vCPU; ending the process also works). The exit status is 5.From chapter 03: A guest of your own, and what an exit costs
After a DEBUG_PUTC exit, your run loop adds 4 to the PC before resuming. What happens to the guest?
Show answer
It skips the instruction after the
hvc. The hardware already saved the PC past thehvc(a call continues after itself), so the extra 4 jumps over code the guest meant to run; anhvcexit must resume with the PC unchanged.From chapter 03: A guest of your own, and what an exit costs
You delete
mov sp, x10from_start. The run prints nothing and the trace's only record iscanceledatpc=0x40080a00, with the guest's vectors at0x40080800. Where was the CPU, and why did no exit report the fault?Show answer
In the guest's own vector entry at
VBAR_EL1 + 0x200, for an exception taken at EL1 itself. Withsp= 0, the first stack store used an address no memory could have, so the fault was taken by the guest's own level, not forwarded to EL2; the handler then faulted on the same bad stack, again and again, until the timeout's kick stopped it.From chapter 00: Two kernels, one Mac: what a virtual machine is
A guest runs 1,000 instructions under trap-and-emulate; 6 of them are privileged or touch the console. Roughly how many instructions does the VMM handle for it, and what does the processor do with the rest?
Show answer
About 6, one per trap. The other 994 run natively on the real processor, unseen by the VMM; only an emulator handles every instruction.
From chapter 00: Two kernels, one Mac: what a virtual machine is
An instruction reads the current privilege mode and, in user mode, answers "user" without trapping. Is it sensitive, privileged, both or neither, and why does that break trap-and-emulate?
Show answer
Sensitive (it reads state the VMM must control) but not privileged (it does not trap). Nothing traps, so the VMM never gets a turn to supply the virtual answer "kernel", and the guest kernel acts on the truth: it is in user mode.
From chapter 00: Two kernels, one Mac: what a virtual machine is
You must run an unmodified guest on a processor that has sensitive, unprivileged instructions and no hardware assist. Which strategies are open to you, and which is not?
Show answer
Interpretation (slow but correct) and binary translation (rewrite the bad instructions just before they run). Paravirtualization is not: it needs the guest's source changed.
From chapter 00: Two kernels, one Mac: what a virtual machine is
A kernel copied into an ordinary process stores to the console's address. Which ledger row is that, and what does a VMM using trap-and-emulate do to make it work?
Show answer
Row 3, devices at fixed addresses. The VMM leaves the address unmapped, so the store traps; the VMM plays the device's part (prints the character) and resumes the guest after the store.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Under hardware assist, why does the guest kernel's "am I in kernel mode?" check pass, when it failed under plain trap-and-emulate?
Show answer
The guest kernel now runs in a real kernel mode, below a new, more privileged level that the VMM's side controls, so the honest answer is "kernel". The level above traps only what it was told to watch.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Before hardware help for memory, how did a VMM stop a guest kernel from mapping memory that is not its own, and what did that cost?
Show answer
With shadow page tables: real tables the VMM keeps, mapping guest addresses straight to host memory, kept in step by trapping every guest write to its own page tables. Every such write cost a trap; a second hardware translation stage removed them.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Someone says "QEMU is a hypervisor". How does this course say the same thing, and which part of a Mac is the course's "hypervisor"?
Show answer
QEMU is a VMM (with its own emulator when no hardware assist is used). In this course the hypervisor is only the part at a level more privileged than the kernel's that controls the processor's support for virtual machines; on a Mac, a part of macOS, not our program.
From chapter 00: Two kernels, one Mac: what a virtual machine is
scripts/doctor.shprintsdoctor: hv_vm_create: OK. What has this proved about the Mac and the probe process?Show answer
The processor has the hardware-assisted level, macOS offers it, and this process (signed with the one permission it needs) was allowed to create a virtual machine.
Concepts you'll need
Chapters before this one: chapter 05, Two stages, one map: holes in stage 2 on purpose.
- Core, taught here: PSTATE and SPSR (saved program status register) in full (
M[3:0]with the stack-pointer select bit, the DAIF mask bits, the condition flags);SCTLR_EL1(its M, C, I and A bits);MPIDR_EL1and why bit 31 is set; alignment faults; the reset state of a CPU versus a system reset; the register dump as a diagnostic tool, and reading a first fault behind a second one. - Core, from earlier: the exception model, the vector table and routing to EL1 versus EL2 (chapter 02); reading
0x3c5with a field table (chapter 02); the run loop,--raw,--timeoutand the address size fault (chapter 03); instruction aborts, data aborts, the fault status code and stage-2 holes (chapter 05). - Primers (read first):
arm64-boot-protocol(only the CPU state at entry: the registers, DAIF, the MMU (memory management unit) and the caches). - Primers (review):
page-tables(what turning the MMU on means). - Pointers: two PSTATE flags we never use, PAN (privileged access never) and TCO (an Aside); the caches primer, before chapter 13.
- Forward definitions: the device tree address in
x0(chapter 10); the virtual counter offset (chapter 11); the ring of last exits (chapter 07); a system reset requested through PSCI, the power state coordination interface (chapter 08); the interrupt controller's per-CPU part, the redistributor (chapter 12). Each is defined in a sentence where it first appears.
Your test guest lives at 0x4008_0000. It never jumps anywhere near address 0x200. Yet in this chapter your virtual machine monitor (VMM) will stop it with "instruction abort at pc 0x200", and every word of that report will be true. Chapter 02's guest died the same way, and there we reasoned the cause out by hand; this time the VMM will print the evidence. First, an older question: what has to be true about a CPU before it starts running someone else's code correctly?
Predict At the end of this chapter you run a guest called self-fault. It turns on alignment checking and then loads 8 bytes from an address that is not a multiple of 8. Will your VMM report (a) an alignment fault, or (b) something else?
Write your choice and one sentence of reasoning under ## Predict in your journal. The section "A guest that faults inside itself" runs it.
This chapter applies row 1 of the problem ledger, the CPU: chapter 02's exception model now explains a crash that happens inside the guest, where we cannot see it directly.
Objectives: by the end you can
- Build PSTATE and SPSR values bit by bit (
M[3:0], DAIF, the stack-pointer select bit) and name the mode that0x3c5,0x3c4and0x3c9encode. - Implement
Vcpu::create, which writesMPIDR_EL1, andVcpu::reset(&BootParams), which sets the PC (program counter),x0tox3, CPSR, andSCTLR_EL1with the MMU (memory management unit) and caches off. - Print a register dump when the guest stops on a fatal exit, and use it to find the first fault of a guest that faulted inside itself and then faulted again on its missing vector table.
Before you start. Run scripts/learner start 06, which copies this chapter's journal to learner/journal/06.md. This chapter has no starter files: you create vcpu/regs.rs and vcpu/dump.rs yourself. The lesson shows the reference's code for most of the chapter and explains each piece; you write the PSTATE Display, the extra SysRegs and the fatal stop on your own. scripts/learner hint 06 is there when you are stuck.
What a CPU needs to know before it runs
You are handing a CPU to a stranger's program. Before reading on, list what you must decide first.
Most lists hold four things, each a register on Arm:
| Question | Register | Our answer for virtual CPU (vCPU) 0 |
|---|---|---|
| Which instruction runs first? | the PC | the guest's entry, 0x4008_0000 |
| At which level, on which stack, with what masked? | PSTATE (Hypervisor.framework, HVF, calls it CPSR) | 0x3c5: EL1, its own stack, everything masked |
| Which CPU am I? | MPIDR_EL1 | 0x8000_0000 |
| Is address translation on? Are the caches on? | SCTLR_EL1 | both off |
Together these values are the CPU's reset state: the register values a CPU has when it is powered on or restarted. Vcpu::reset recreates it for a vCPU. Do not confuse it with a system reset, which a guest requests through PSCI, the power state coordination interface (chapter 08), and which leads to a reset state on every vCPU. Ours is always a cold start, as if from power-on.
PSTATE, bit by bit
Chapter 02 read 0x3c5 from a table. Now you build such values yourself. PSTATE (processor state) is the CPU's current mode and flags. When an exception is taken, the CPU saves a snapshot of it in an SPSR (saved program status register), in this layout, and HVF shows the current value to us in the same layout under the name CPSR (current program status register):
31 30 29 28 9 8 7 6 5 4 3 2 1 0+--+--+--+--+ ... +---+---+---+---+---+---+------+---+---+| N| Z| C| V| | D | A | I | F | 0 |nRW| EL | 0 |SP |+--+--+--+--+ ... +---+---+---+---+---+---+------+---+---+ condition flags the DAIF masks M[3:0]: modePSTATE in SPSR layout. The low four bits, M[3:0], say where the CPU runs; bits 9 to 6 say which exceptions it holds off.
| Bits | Field | Meaning |
|---|---|---|
| 31 to 28 | N, Z, C, V | condition flags set by comparisons (negative, zero, carry, overflow) |
| 9 to 6 | D, A, I, F | 1 masks that kind of exception: hardware debug exceptions (D: breakpoints and watchpoints set in the debug registers, and single-step; the brk instruction is never masked), and three asynchronous ones: SError (system error, A), IRQ (interrupt request, I), FIQ (fast interrupt request, F) |
| 4 | nRW | 0 means 64-bit execution (AArch64); we never run 32-bit guests |
| 3 to 2 | EL | the exception level, 0 to 3 |
| 0 | SP | the stack-pointer select bit (SPSel in the Arm manual): 0 uses SP_EL0, 1 uses the current level's own stack pointer |
Build 0x3c5 from the fields, one step at a time:
- Mask all four kinds: D, A, I and F are bits 9, 8, 7 and 6, so
0x200 + 0x100 + 0x80 + 0x40 = 0x3c0. - Run at EL1: 1 shifted into bits 3 to 2 is
1 << 2 = 0x4. - Use EL1's own stack pointer,
SP_EL1: bit 0,0x1.
So 0x3c0 | 0x4 | 0x1 = 0x3c5, written EL1h ("h" for handler stack). Change only step 3 and you get 0x3c4, EL1t ("t" for thread): still EL1, but sp in the guest's code now means SP_EL0, the stack EL0 apps use. Put 2 in the EL field instead and you get 0x3c8 | 0x1 = 0x3c9, EL2h, a level our guests are not offered (chapter 02's Aside); hv_vcpu_run refuses that state with HV_ILLEGAL_GUEST_STATE before the CPU sees it. You will run the 0x3c4 mistake later in this chapter.
Two facts make the guest's own view match ours. mrs x0, daif (mrs reads a system register into a general register; the aarch64-reading primer) reads the same bits 9 to 6, so a guest started with 0x3c5 reads DAIF = 0x3c0. And mrs x0, CurrentEL puts the level in bits 3 to 2, so EL1 reads 0x4.
Toggle the bits yourself in the builder:
PSTATE builder
Build the boot value 0x3c5 from its fields, find the one bit that makes the EL1t mistake 0x3c4, and see why HVF refuses EL2 (0x3c9).
Runs in browserOpen full page: PSTATE builderLoading the lab. If nothing appears, your browser may have JavaScript turned off or the lab failed to load.
If the lab does not load, three rows carry the idea:
value M[3:0] mode stack pointer masked0x3c5 0101 EL1h SP_EL1 D A I F0x3c4 0100 EL1t SP_EL0 D A I F0x3c9 1001 EL2h SP_EL2 D A I FWrite the bit constants in your learner/crates/vmm/src/arch/regs.rs, checking each against the table above. The reference's:
/// PSTATE bits (SPSR format, module docs).pub mod pstate { pub const N: u64 = 1 << 31; pub const Z: u64 = 1 << 30; pub const C: u64 = 1 << 29; pub const V: u64 = 1 << 28; pub const D: u64 = 1 << 9; pub const A: u64 = 1 << 8; pub const I: u64 = 1 << 7; pub const F: u64 = 1 << 6; pub const DAIF: u64 = D | A | I | F; /// `nRW`: set means AArch32 (we never run AArch32 guests). pub const NRW: u64 = 1 << 4; pub const SP: u64 = 1 << 0; /// The boot state: EL1h, DAIF masked (`0x3c5`). pub const EL1H_MASKED: u64 = DAIF | (1 << 2) | SP;}Decoding reads the table backwards; the dump uses this decoder to print (EL1h, DAIF, nzcv) after a CPSR value:
/// A PSTATE value in SPSR format, with decoders for the dump.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct Pstate(pub u64);impl Pstate { /// The exception level, bits 3:2. pub const fn el(self) -> u8 { ((self.0 >> 2) & 3) as u8 } /// `SPSel`: true = SP_ELx (`h`), false = SP_EL0 (`t`). pub const fn sp_elx(self) -> bool { self.0 & pstate::SP != 0 } /// True if the state is AArch32 (`nRW = 1`). pub const fn aarch32(self) -> bool { self.0 & pstate::NRW != 0 } /// The D, A, I, F mask bits as they read in `mrs x, daif` (bits 9:6). pub const fn daif(self) -> u64 { self.0 & pstate::DAIF } /// The mode name: `EL0t`, `EL1t`, `EL1h`, `EL2t`, `EL2h`, ... or `AArch32` (unsupported). pub const fn mode_name(self) -> &'static str { if self.aarch32() { return "AArch32"; } match (self.el(), self.sp_elx()) { (0, _) => "EL0t", (1, false) => "EL1t", (1, true) => "EL1h", (2, false) => "EL2t", (2, true) => "EL2h", (_, false) => "EL3t", (_, true) => "EL3h", } }}The Display implementation below it prints MODE, DAIF, NZCV, each letter upper case when its bit is set: 0x3c5 prints EL1h, DAIF, nzcv and 0xf0000004 prints EL1t, daif, NZCV. Write your own; the contract tests check the mode names EL0t, EL1t, EL1h, EL2h and AArch32 (bit 4 set) and three exact Display strings.
Which CPU am I: MPIDR_EL1
An operating system tells its CPUs apart by one number each, MPIDR_EL1, the Multiprocessor Affinity Register: a kernel says "start CPU 2" with it, and the interrupt controller routes by it. Our guests' start code reads it first thing, to pick a stack.
The low bits hold affinity fields, a CPU's address in a hierarchy: Aff0 (bits 7 to 0) numbers CPUs within a cluster, Aff1 (bits 15 to 8) numbers clusters (a cluster is a group of cores that share hardware such as a cache). Bit 31 is defined as always 1 by the architecture, which the Arm manual writes as RES1 (reserved, reads as one). So vCPU 0 gets 0x8000_0000: bit 31 set, every affinity field 0. The reference puts sixteen CPUs in each cluster, as QEMU's virt machine (the emulated board whose memory map ours copies) does, because the interrupt controller can address at most sixteen CPUs of one cluster in one message (chapter 12):
/// `MPIDR_EL1` for vCPU `index` (ARM ARM, register page `MPIDR_EL1`): bit 31 is RES1,/// Aff1 (the cluster) = index / 16, Aff0 (the CPU in the cluster) = index % 16. Sixteen CPUs/// per cluster, like QEMU `virt`, because the interrupt controller's CPU-to-CPU interrupt/// message names at most 16 CPUs of one cluster (GICv3 spec, register `ICC_SGI1R_EL1`,/// field `TargetList`; chapter 12).pub fn mpidr(index: usize) -> u64 { let i = u64::try_from(index).unwrap_or(u64::MAX); (1 << 31) | (((i / 16) & 0xff) << 8) | (i % 16)}Translation and caches off: SCTLR_EL1
SCTLR_EL1, the System Control Register for EL1, holds the switches a kernel flips as it brings itself up. Four of its bits matter now:
| Bit | Name | 1 means |
|---|---|---|
| 0 | M | the MMU translates the guest's addresses through its own page tables, stage 1 |
| 1 | A | alignment checking: an access to an address that is not a multiple of its size faults |
| 2 | C | data accesses may be cached |
| 12 | I | instruction fetches may be cached |
With M = 0 and C = 0, translation and data caching are off, as a kernel expects at entry: it turns them on itself, in an order it controls. Why caches need that care is the caches primer, before chapter 13. The arm64-boot-protocol primer shows where Linux writes this rule down; journal question 2 asks why.
An alignment fault is the exception a load or store takes when its address is not a multiple of the access size and the CPU checks alignment: with A = 1, an 8-byte load from an address ending in 1 faults. While translation is off, a second rule applies as well: every data access is treated as an access to Device memory (the memory type for device registers), where unaligned accesses fault even with A = 0 (we checked this on our Mac). self-fault sets A = 1 anyway, so that its fault has a cause you can see in a register.
/// `SCTLR_EL1` bits used by the VMM and its test guests (ARM ARM D19.2.118 `SCTLR_EL1`).pub mod sctlr { /// Stage-1 MMU enable. pub const M: u64 = 1 << 0; /// Alignment check enable. pub const A: u64 = 1 << 1; /// Data cache enable (cacheability of data accesses). pub const C: u64 = 1 << 2; /// Instruction cache enable. pub const I: u64 = 1 << 12;}System registers through HVF
MPIDR_EL1 and SCTLR_EL1 are system registers, read with mrs and written with msr. From outside, the VMM uses a second pair of calls. Declare them from hv_vcpu.h beside chapter 02's hv_vcpu_get_reg, with their id type type hv_sys_reg_t = u16 (16 bits, unlike the 32-bit hv_reg_t):
pub fn hv_vcpu_get_sys_reg(vcpu: hv_vcpu_t, reg: hv_sys_reg_t, value: *mut u64) -> hv_return_t;pub fn hv_vcpu_set_sys_reg(vcpu: hv_vcpu_t, reg: hv_sys_reg_t, value: u64) -> hv_return_t;The safe wrappers in crates/hvf/src/vcpu.rs follow chapter 02's get_reg exactly:
/// Read a system register. HVF reaches only the registers `hv_vcpu_types.h` lists (our/// copy of that list: [`SysReg::HV_ACCESSIBLE`]).pub fn get_sys_reg(&self, reg: SysReg) -> Result<u64, CallError> { let mut v = 0u64; // SAFETY: owning thread; live out-parameter. check("hv_vcpu_get_sys_reg", unsafe { ffi::hv_vcpu_get_sys_reg(self.id, reg.0, &mut v) })?; Ok(v)}/// Write a system register.pub fn set_sys_reg(&self, reg: SysReg, value: u64) -> Result<(), CallError> { // SAFETY: owning thread; plain values. check("hv_vcpu_set_sys_reg", unsafe { ffi::hv_vcpu_set_sys_reg(self.id, reg.0, value) })}A system register's id packs five small numbers that the Arm manual prints on each register's page: Op0, Op1, CRn, CRm and Op2 (chapter 08 decodes them from traps). The reference's SysReg type builds an id from them, and names the registers we use, such as SysReg::MPIDR_EL1 = new(3, 0, 0, 0, 5) and SysReg::SCTLR_EL1 = new(3, 0, 1, 0, 0):
/// Pack ARM ARM coordinates. Out-of-range fields are masked to their architectural widths/// (op0 2 bits, op1 3, CRn 4, CRm 4, op2 3), so the result is always a 16-bit encoding.pub const fn new(op0: u8, op1: u8, crn: u8, crm: u8, op2: u8) -> SysReg { let v = ((op0 as u16 & 0x3) << 14) | ((op1 as u16 & 0x7) << 11) | ((crn as u16 & 0xf) << 7) | ((crm as u16 & 0xf) << 3) | (op2 as u16 & 0x7); SysReg(v)}Check your packing against HVF's hv_vcpu_types.h: HV_SYS_REG_MPIDR_EL1 is 0xc005 and HV_SYS_REG_SCTLR_EL1 is 0xc080.
Reset, in one function
The library crate gets its own Vcpu now, in learner/crates/vmm/src/vcpu/mod.rs. It owns chapter 02's hvf::Vcpu, and with it the rule that only the creating thread may touch it, and adds which CPU it is and how to reset it. First the boot parameters, the bits to clear, and the MPIDR rule:
/// The architectural state a vCPU starts from: its entry point, boot arguments and mode.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct BootParams { pub pc: u64, /// `x0..x3` (booting.rst §4: x0 = DTB, x1..x3 = 0). pub x: [u64; 4], pub cpsr: u64,}/// `SCTLR_EL1` bits cleared at reset: M (bit 0, stage-1 MMU), C (bit 2, data cache), I/// (bit 12, instruction cache) (ARM ARM D19.2.118 SCTLR_EL1; booting.rst §4 "MMU off").pub const SCTLR_MMU_CACHES: u64 = sctlr::M | sctlr::C | sctlr::I;/// `MPIDR_EL1` for vCPU `index` (the rule lives in `arch::regs::mpidr`).pub fn mpidr_for(index: usize) -> u64 { crate::arch::regs::mpidr(index)}x[0] will carry the address of the device tree, the machine description a kernel reads at boot (chapter 10); until then, keep passing 0x4000_0000. Then the struct, and hv, which turns a failed HVF call into the library's error, naming the failed step. If your chapter 04 Error lacks them, add Hv { op: &'static str, err: hvf::CallError }, displayed as op: err, and Internal(&'static str) for a VMM bug. Leave out nogic_kick, sysregs and nogic here and below; chapters 08 and 11 add them:
fn hv(op: &'static str) -> impl FnOnce(hvf::CallError) -> Error { move |err| Error::Hv { op, err }}/// One vCPU, owned by its thread.pub struct Vcpu<'vm> { /// The no-GIC stale-line kick (`timer::LineKicker`, `--irqchip none` only). Declared /// first so it is dropped (its thread joined) before `inner` destroys the vCPU it kicks. nogic_kick: Option<LineKicker>, inner: hvf::Vcpu<'vm>, pub index: usize, pub mpidr: u64, /// The emulated OS-lock registers (`arch::sysreg`), one set per vCPU. sysregs: SysRegState, /// The VMM-side timer interrupt line, only in the `--irqchip none` teaching mode /// (`timer.rs`). `None` with the in-kernel GIC. nogic: Option<NoGicTimer>,}Creating the vCPU writes its MPIDR once, because it never changes:
/// Create vCPU `index` on the calling thread and give it its MPIDR. The MPIDR must be/// written explicitly: HVF's own copy reads 0 until we do (the guest still reads/// `0x80000000` on vCPU 0), and `hv_gic_get_redistributor_base` (chapter 12) refuses/// until the vCPU's affinity has been set by this write (`hv_gic.h`). The redistributor/// slot it returns follows creation order, not the value written.pub fn create(vm: &'vm Vm, index: usize) -> Result<Vcpu<'vm>> { let inner = hvf::Vcpu::create(vm).map_err(hv("create vCPU"))?; let mpidr = mpidr_for(index); inner .set_sys_reg(SysReg::MPIDR_EL1, mpidr) .map_err(hv("set MPIDR_EL1"))?; Ok(Vcpu { nogic_kick: None, inner, index, mpidr, sysregs: SysRegState::default(), nogic: None, })}Then reset. Through the API a fresh vCPU's SCTLR_EL1 reads 0, yet our dumps show 0x30000180 plus whatever bits the guest set: its RES1 bits (7, 8, 28 and 29 on this CPU) read as 1 whatever you write, as we checked by writing 0 and reading it back from inside a guest. So clearing M, C and I equals writing 0; reset clears only those bits anyway: change only what you mean to change. Leave out vtimer_offset and its call (where the guest's clock starts); chapter 11 adds both.
/// Put the vCPU in its boot state (chapter 06: the CPU's *reset state*, as opposed to a/// system reset the guest asks for through PSCI). Only what a guest relies on is set:/// - `PC` = the entry point and `x0..x3` = the boot arguments (booting.rst section 4:/// x0 = the device tree address);/// - `CPSR` = `0x3c5` by default: EL1h, D/A/I/F masked (`arch::regs::Pstate`);/// - `SCTLR_EL1.{M,C,I} = 0`: translation and caches off, the state booting.rst requires;/// - the VM-wide virtual-counter offset (chapter 11: the same value on every vCPU, so the/// guest's counter starts near 0 and agrees across CPUs).////// `MPIDR_EL1` was set by [`Vcpu::create`]. Every other register keeps HVF's default,/// which reads 0 through the API, `SCTLR_EL1` included. A dump still shows `SCTLR_EL1 =/// 0x30000180`: its RES1 bits (7, 8, 28, 29 on this CPU) read as 1 whatever is written/// (verified on a real Mac). Clearing only M, C and I is a defensive habit: change only/// the bits you mean to change.pub fn reset(&self, boot: &BootParams, vtimer_offset: u64) -> Result<()> { let v = &self.inner; v.set_reg(Reg::PC, boot.pc).map_err(hv("set PC"))?; for (i, value) in boot.x.iter().enumerate() { let reg = u8::try_from(i) .ok() .and_then(Reg::x) .ok_or(Error::Internal("x index"))?; v.set_reg(reg, *value).map_err(hv("set x0..x3"))?; } v.set_reg(Reg::CPSR, boot.cpsr).map_err(hv("set CPSR"))?; let sctlr = v .get_sys_reg(SysReg::SCTLR_EL1) .map_err(hv("get SCTLR_EL1"))?; v.set_sys_reg(SysReg::SCTLR_EL1, sctlr & !SCTLR_MMU_CACHES) .map_err(hv("set SCTLR_EL1"))?; v.set_vtimer_offset(vtimer_offset) .map_err(hv("set vtimer offset"))?; Ok(())}Call create, then reset, on the vCPU's thread, where chapter 03 set the PC and CPSR directly. Give Vcpu a regs_dump(&self) that calls RegDump::capture(&self.inner) (the dump comes below); the loop calls that, since inner is private.
Production note
A real CPU's reset state covers hundreds of registers. On Linux's KVM (Kernel-based Virtual Machine), initialising a vCPU resets the system, timer, debug and floating-point state and presents sanitised feature identification registers the VMM may adjust. With HVF we set only what our guests rely on.
Checking the reset from inside
The regcheck guest checks the reset from the guest's side, with the instructions a kernel would use: mrs from CurrentEL, MPIDR_EL1, SCTLR_EL1 and DAIF. From the repository root, build the guests (scripts/build-guests.sh, as in chapter 03), then cd learner and run:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/regcheck.bin@0x40080000 --timeout 10Our run, of the reference from the repository root:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10regcheck: CurrentEL=0x4regcheck: MPIDR_EL1=0x80000000regcheck: SCTLR_EL1.M=0regcheck: DAIF=0x3c0regcheck: x0=0x40000000regcheck: vectors ok (svc caught at EL1, esr=0x5600004d)Each line is a row of the opening table, read from inside. The checkpoint accepts any value on the x0 line.
Look again at the last line. Our guests' start code installs its own vector table in VBAR_EL1 (vector base address register, chapter 02), and regcheck runs svc #0x4d on purpose: syndrome 0x5600004d is class 0x15, an svc, carrying 0x4d. The guest caught it at EL1 and carried on. Did our VMM see it? The reference's --stats flag (yours gains it later) counts VM exits, the times the virtual machine (VM) handed control back to us. From the repository root:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10 --statscargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10 --statsregcheck: CurrentEL=0x4regcheck: MPIDR_EL1=0x80000000regcheck: SCTLR_EL1.M=0regcheck: DAIF=0x3c0regcheck: x0=0x40000000regcheck: vectors ok (svc caught at EL1, esr=0x5600004d)macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=181 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 182: hvc 182macvmm: stats: vcpu0 time: exec 0.000 s, wfi 0.000 smacvmm: stats: host cpu 0.001 s over 0.001 s wall (133%)macvmm: stats: rlimit core=0 nofile=1048576182 exits, every one an hvc: 181 debug calls, one per printed character, and one to stop. The svc never left the guest; remember that when you meet self-fault.
Try it
Delete the line in your Vcpu::create that writes MPIDR_EL1, and run regcheck again. Predict its second line before you look.
Your VMM has no interrupt controller yet, so we ran a copy of the reference without one, which behaves like yours:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10 --irqchip noneregcheck: CurrentEL=0x4regcheck: MPIDR_EL1=0x80000000regcheck: SCTLR_EL1.M=0regcheck: DAIF=0x3c0regcheck: x0=0x40000000regcheck: vectors ok (svc caught at EL1, esr=0x5600004d)Nothing changed. So HVF keeps two values: the one the guest's mrs sees, which HVF fills in by itself, and its own copy, which we read and write with hv_vcpu_get_sys_reg and hv_vcpu_set_sys_reg and which reads 0 until we write it. We have not been able to check why HVF splits them; what matters is that HVF's other features use its own copy, as the finished reference, with chapter 12's interrupt controller, shows:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10macvmm: error: get the GIC redistributor base: hv_gic_get_redistributor_base: HV_BAD_ARGUMENT (0xfae94003)The VM never started. Before the first run, the reference asks HVF for this vCPU's redistributor, the per-CPU part of the interrupt controller (chapter 12). HVF refuses until the vCPU's affinity has been set by writing MPIDR_EL1 (its header hv_gic.h says so), so without our write the lookup fails with HV_BAD_ARGUMENT. A missing write that no one-CPU test can see is the worst kind. Chapter 20 finds two places where the value itself must be right; journal question 3 asks you to find them first.
Breaking the reset
Deliberate breakage 1: start in EL1t. Change the cpsr field of the BootParams your run command builds from 0x3c5 to 0x3c4, rebuild, and run regcheck again. Predict: which of its six lines will change?
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10regcheck: CurrentEL=0x4regcheck: MPIDR_EL1=0x80000000regcheck: SCTLR_EL1.M=0regcheck: DAIF=0x3c0regcheck: x0=0x40000000macvmm: timeout: the guest was still running after --timeout 10sOnly the sixth line, vectors ok, is missing: nothing the first five read depends on bit 0. Then the guest hung until --timeout stopped it (exit code 5). What you saw: a hang after five lines. The register dump explains it, in "When the handler faults on itself". Undo the change.
The register dump
When a guest dies, its registers are our only witness. A register dump is a snapshot of them, printed in the order a reader asks questions:
- Where was it? The PC and CPSR.
- What was it computing?
x0tox30and both stack pointers. - Did it take an exception of its own first?
ELR_EL1(exception link register: where that exception happened),SPSR_EL1(the PSTATE saved with it),ESR_EL1(exception syndrome register: why) andFAR_EL1(fault address register: which data address). - Where would its handler be, and was translation on?
VBAR_EL1,SCTLR_EL1, andTCR_EL1,TTBR0_EL1andTTBR1_EL1, the guest's own page-table setup (0 while translation is off; chapter 21 reads them).
Write it in learner/crates/vmm/src/vcpu/regs.rs:
/// The register snapshot (module docs). Numbers only, so nothing a guest wrote can reach the/// terminal as text.#[derive(Clone, Debug, Default, PartialEq, Eq)]pub struct RegDump { /// `X0..X30` (X30 is the link register). pub x: [u64; 31], pub sp_el0: u64, pub sp_el1: u64, pub pc: u64, pub cpsr: u64, pub elr_el1: u64, pub spsr_el1: u64, pub esr_el1: u64, pub far_el1: u64, pub vbar_el1: u64, pub sctlr_el1: u64, pub tcr_el1: u64, pub ttbr0_el1: u64, pub ttbr1_el1: u64,}The snapshot is taken once, on the vCPU's own thread, at the moment the guest is stopped for good:
/// Read every register of `v` (module docs). Called on the vCPU's thread.pub fn capture(v: &hvf::Vcpu<'_>) -> Result<RegDump, CallError> { let mut d = RegDump::default(); for (n, slot) in (0u8..).zip(d.x.iter_mut()) { if let Some(r) = Reg::x(n) { *slot = v.get_reg(r)?; } } d.pc = v.get_reg(Reg::PC)?; d.cpsr = v.get_reg(Reg::CPSR)?; let sys = |r: SysReg| v.get_sys_reg(r); d.sp_el0 = sys(SysReg::SP_EL0)?; d.sp_el1 = sys(SysReg::SP_EL1)?; d.elr_el1 = sys(SysReg::ELR_EL1)?; d.spsr_el1 = sys(SysReg::SPSR_EL1)?; d.esr_el1 = sys(SysReg::ESR_EL1)?; d.far_el1 = sys(SysReg::FAR_EL1)?; d.vbar_el1 = sys(SysReg::VBAR_EL1)?; d.sctlr_el1 = sys(SysReg::SCTLR_EL1)?; d.tcr_el1 = sys(SysReg::TCR_EL1)?; d.ttbr0_el1 = sys(SysReg::TTBR0_EL1)?; d.ttbr1_el1 = sys(SysReg::TTBR1_EL1)?; Ok(d)}The dump must notice when the PC sits on a vector entry, so here is the whole table; chapter 02 used two of its entries:
VBAR_EL1 + ... synchronous IRQ FIQ SError0x000 current level, using SP_EL0 0x000 0x080 0x100 0x1800x200 current level, using SP_ELx 0x200 0x280 0x300 0x3800x400 lower level, AArch64 0x400 0x480 0x500 0x5800x600 lower level, AArch32 0x600 0x680 0x700 0x780The vector table: four groups of 0x200 bytes, by where the exception came from (SP_ELx is the current level's own stack pointer); in each, four 0x80-byte entries, by kind. 16 × 0x80 = 0x800 bytes. Chapter 08 uses all of them.
The checkpoint compares the formatter, in learner/crates/vmm/src/vcpu/dump.rs, byte for byte, so copy its layout exactly: general-purpose registers padded to 16 digits, four per line; named registers unpadded, so a marker can match a prefix such as pc=0x200; and a note: line when the PC is VBAR_EL1 plus a multiple of VECTOR_ENTRY (0x80) below VECTOR_TABLE_SIZE (0x800). The contract tests check that VBAR_EL1 + 0x80 gets the note and VBAR_EL1 + 0x10 does not.
/// The register block of the dump (module docs), each line indented by two spaces.pub fn format_regs(d: &RegDump) -> String { let mut s = String::with_capacity(1024); for (row, chunk) in d.x.chunks(4).enumerate() { s.push(' '); for (col, v) in chunk.iter().enumerate() { let n = row.saturating_mul(4).saturating_add(col); let _ = write!(s, " x{n}={v:#018x}"); } s.push('\n'); } let _ = writeln!(s, " sp_el0={:#x} sp_el1={:#x}", d.sp_el0, d.sp_el1); let _ = writeln!( s, " pc={:#x} cpsr={:#x} ({})", d.pc, d.cpsr, Pstate(d.cpsr) ); let _ = writeln!( s, " ELR_EL1={:#x} SPSR_EL1={:#x} ESR_EL1={:#x}{} FAR_EL1={:#x}", d.elr_el1, d.spsr_el1, d.esr_el1, ec_suffix(d.esr_el1), d.far_el1 ); let _ = writeln!( s, " VBAR_EL1={:#x} SCTLR_EL1={:#x} TCR_EL1={:#x} TTBR0_EL1={:#x} TTBR1_EL1={:#x}", d.vbar_el1, d.sctlr_el1, d.tcr_el1, d.ttbr0_el1, d.ttbr1_el1 ); let off = d.pc.wrapping_sub(d.vbar_el1); if off < VECTOR_TABLE_SIZE && off.is_multiple_of(VECTOR_ENTRY) { let _ = writeln!( s, " note: pc is VBAR_EL1 + {off:#x}, an exception vector: the guest took an \ exception at EL1 first, so ELR_EL1 and ESR_EL1 describe the first fault" ); } s}After ESR_EL1 the dump names the exception class in words. ec_suffix, above the formatter, prints the class in hex, then its name if it has one. It calls esr::esr_ec, the helper from chapter 05's esr_header_fields (bits 31 to 26 of the syndrome).
/// ` (EC 0x25: data abort, same EL)`: the exception class of `esr` in hex, then its name when/// [`esr::ec_name`] knows one.fn ec_suffix(esr: u64) -> String { let ec = esr::esr_ec(esr); match esr::ec_name(ec) { Some(n) => format!(" (EC {ec:#04x}: {n})"), None => format!(" (EC {ec:#04x})"), }}The names live in arch/esr.rs. For now the rows 0x15, 0x20, 0x24 and 0x25 are enough, and the golden dump checks the 0x25 text exactly; a class without a row prints (EC 0xNN) alone.
/// A static name for an exception class, for dumps (ARM ARM, register page `ESR_EL1`, the EC/// table). `None` for a class we never expect to see.pub const fn ec_name(ec: u8) -> Option<&'static str> { Some(match ec { 0x00 => "unknown reason", 0x01 => "WFI/WFE", 0x07 => "SVE/SIMD/FP access", 0x0e => "illegal execution state", 0x15 => "SVC (AArch64)", 0x16 => "HVC (AArch64)", 0x17 => "SMC (AArch64)", 0x18 => "MSR/MRS/system instruction", 0x19 => "SVE access", 0x20 => "instruction abort from a lower EL", 0x21 => "instruction abort, same EL", 0x22 => "PC alignment fault", 0x24 => "data abort from a lower EL", 0x25 => "data abort, same EL", 0x26 => "SP alignment fault", 0x2c => "floating-point exception", 0x2f => "SError", 0x30 | 0x31 => "breakpoint", 0x32 | 0x33 => "software step", 0x34 | 0x35 => "watchpoint", 0x3c => "BRK (AArch64)", _ => return None, })}Now wire it into your run loop, learner/crates/vmm/src/vcpu/run_loop.rs, beside chapter 05's class-0x24 branch. So far exit code 3 means one thing: chapter 05's fatal stop for an unhandled memory-mapped I/O (MMIO) data abort. The self-fault run ends in an instruction abort, class 0x20, which your loop does not stop on yet. When esr_ec of the exit's syndrome is 0x20:
- capture the dump with
regs_dump, first; - print
macvmm: guest fatal: instruction abort at pc 0x…to standard error; - print a line naming the vCPU and the exit, at least
vcpu0: instruction abort (EC 0x20); - print
format_regsof the dump; - exit with code 3.
Do the same on chapter 05's 0x24 path: capture first, then its guest fatal: line, a vcpu0: line and the dump. The checkpoint matches the words instruction abort and checks exit code 3.
Security
Every value in the dump comes from a possibly hostile guest and lands on your terminal. Print only numbers and fixed names, never guest bytes as text, so a guest cannot smuggle terminal control sequences through it.
A guest that faults inside itself
Time for the Predict entry. The self-fault guest sets SCTLR_EL1.A = 1, writes 0 into VBAR_EL1 (so it has no vector table), and loads 8 bytes from an address ending in 1. Run it from inside learner/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/self-fault.bin@0x40080000 --timeout 10cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/self-fault.bin@0x40080000 --timeout 10self-fault: SCTLR_EL1.A=1, VBAR_EL1=0, loading 8 bytes from 0x40082a51macvmm: guest fatal: instruction abort at pc 0x200: translation fault at IPA 0x200 (ifsc 0x6)vcpu0: instruction abort (EC 0x20): IFSC=0x6 S1PTW=0 (translation fault) esr=0x82000006 ipa=0x200 x0=0x0000000000000000 x1=0x000000000000000a x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x0000000000000008 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x0000000030000182 x9=0x0000000000000000 x10=0x0000000000000078 x11=0x0000000040082d40 x12=0x0000000000000034 x13=0x0000000040092d69 x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040092d80 x19=0x0000000040082a51 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x000000004008107c sp_el0=0x0 sp_el1=0x40092e10 pc=0x200 cpsr=0x824003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x40081094 SPSR_EL1=0x800003c5 ESR_EL1=0x96000021 (EC 0x25: data abort, same EL) FAR_EL1=0x40082a51 VBAR_EL1=0x0 SCTLR_EL1=0x30000182 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0 note: pc is VBAR_EL1 + 0x200, an exception vector: the guest took an exception at EL1 first, so ELR_EL1 and ESR_EL1 describe the first fault insn at pc: not readable (the pc does not translate to RAM)last exits: 32 (oldest first) {"t_ns":446833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":448500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":450041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":452208,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":453916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":455541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":457750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":459333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":461000,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":462541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":464750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":466291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":467916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":470125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":471708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":473250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":475500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":477083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":478625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":480791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":482625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":484166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":485791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":489208,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":490750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":495333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":497083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":510833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":514583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":516458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":518291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081124","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":526583,"vcpu":0,"reason":"exception","ec":"0x20","pc":"0x200","ipa":"0x200","action":"stop"}No alignment fault in sight: an instruction abort at pc 0x200. There is the report from the top of the page: every word true, and the guest never jumped to 0x200. The six links below show who did.
Yours will be shorter: the rest of the vcpu0: line (two fault fields chapter 07 decodes), the esr=/ipa= line (the IPA, intermediate physical address, from chapter 05), insn at pc: and last exits: (both chapter 07) can wait. The checkpoint matches the guest's own first line, then guest fatal: instruction abort, pc=0x200, ELR_EL1=0x4008… and ESR_EL1=0x96… (five markers), plus exit code 3; addresses may differ by a few bytes.
Six links connect the load to this report, each leaving register values behind:
- With
SCTLR_EL1.A = 1, the guest loads 8 bytes from0x40082a51, not a multiple of 8: an alignment fault. - That fault is routed to EL1, the guest's own level, so we see nothing yet. The CPU saves
ELR_EL1 = 0x40081094, the faulting load's address (a fault retries, chapter 02),ESR_EL1 = 0x96000021andFAR_EL1 = 0x40082a51. - The CPU jumps to the guest's vector table entry for "current level, using
SP_EL1, synchronous" (the second row of the vector table above):VBAR_EL1 + 0x200.VBAR_EL1is 0, so the PC becomes0x200. - Nothing is mapped at IPA
0x200(chapter 05's map has flash there, and we loaded no firmware), so fetching the handler's first instruction fails in stage 2. - That instruction abort is routed to EL2, and HVF forwards it to us: PC
0x200, syndrome0x82000006(class0x20, an instruction abort from a lower level; fault status0x6, a translation fault). - Our dump shows the second fault and, in
ELR_EL1andESR_EL1, the first one, as itsnote:line says.
The rule to keep: when the PC is a synchronous vector entry (0x000 or 0x200 from the current level, 0x400 or 0x600 from a lower one), ELR_EL1 and ESR_EL1 describe the exception the guest took before it got there; if ELR_EL1 itself points into the vector table, the handler is faulting on itself and the original cause is gone. An IRQ or FIQ entry writes only ELR_EL1 and SPSR_EL1, leaving ESR_EL1 stale; our note: line does not yet tell them apart, which matters once chapter 11 unmasks interrupts. Here ELR_EL1 points at the guest's code, so it is the first fault. Decode it as in chapter 05:
Field of 0x96000021 | Bits | Value | Meaning |
|---|---|---|---|
| EC, the exception class | 31 to 26 | 0x25 | data abort taken without a change of level: the guest's EL1 faulted and EL1 took it. Chapter 05's stage-2 hole gave 0x24, "from a lower level" |
| IL | 25 | 1 | a 32-bit instruction |
| WnR | 6 | 0 | a read (a load) |
| DFSC | 5 to 0 | 0x21 | data fault status code: alignment fault |
SPSR_EL1 = 0x800003c5 and cpsr=0x824003c5 share their low bits: the guest faulted in EL1h and landed in EL1h. The 8 at the top is the N flag.
Aside
The extra bits in cpsr (0x02400000) are set by the CPU itself on an exception to EL1: bit 22 is PAN (privileged access never, which stops a kernel touching app memory by accident) and bit 25 is TCO (tag check override, for memory tagging). Neither matters to our guests.
What you saw: an instruction abort at an address the guest never jumped to. The misconception: "every guest exception becomes a VM exit". The tool that found the first fault: the dump's ELR_EL1 and ESR_EL1.
Exceptions routed to EL1 are handled by the guest's own vector table, as regcheck's svc was. Only what is routed to EL2, and forwarded by HVF, reaches us.
When the handler faults on itself
Back to breakage 1. We added a probe that is not part of the course: with CPSR still 0x3c4, the loop prints the dump's register block when the timeout stops it.
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 3regcheck: CurrentEL=0x4regcheck: MPIDR_EL1=0x80000000regcheck: SCTLR_EL1.M=0regcheck: DAIF=0x3c0regcheck: x0=0x40000000 x0=0x0000000040081040 x1=0x000000000000000a x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x0000000000000008 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x0000000040082f90 x9=0x0000000000000000 x10=0x0000000000000078 x11=0x0000000040082ea0 x12=0x0000000000000034 x13=0x0000000040092ec9 x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040092ee0 x19=0x0000000040092f98 x20=0x0000000040082988 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x0000000040081150 sp_el0=0x40092f70 sp_el1=0xffffffed2081bf60 pc=0x40080a00 cpsr=0x824003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x40080a04 SPSR_EL1=0x824003c5 ESR_EL1=0x96000040 (EC 0x25: data abort, same EL) FAR_EL1=0xffffffed2081bf60 VBAR_EL1=0x40080800 SCTLR_EL1=0x30000180 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0 note: pc is VBAR_EL1 + 0x200, an exception vector: the guest took an exception at EL1 first, so ELR_EL1 and ESR_EL1 describe the first faultmacvmm: timeout: the guest was still running after --timeout 3sThe PC is VBAR_EL1 + 0x200, a synchronous entry, so by the rule above look at ELR_EL1: 0x40080a04, inside the vector table itself. The handler is faulting on itself:
- In EL1t,
spmeansSP_EL0, so_start'smov sp, x10setSP_EL0; the dump shows the guest's stack there (sp_el0=0x40092f70).SP_EL1kept its reset value, 0. regcheckran itssvc. Taken from EL1t, it entered atVBAR_EL1 + 0x000(the first row of the vector table: current level, usingSP_EL0). Taking an exception to EL1 always switches toSP_EL1.- The handler's first instruction,
sub sp, sp, #0x120, subtracted 288 from 0, and the store after it wrote far above any memory: an address size fault, a data abort at EL1 (ESR_EL1 = 0x96000040,FAR_EL1equal tosp_el1). - That fault was taken from EL1h, so it entered at
VBAR_EL1 + 0x200, where the dump caught it, and the same two instructions faulted again, and again, all inside the guest.
So ELR_EL1 and ESR_EL1 describe the latest fault, the note: line was wrong here, and the first cause, the svc on a bad stack, is gone from every register.
sp_el1 moved 288 bytes per fault, from 0 down to 0xffffffed2081bf60 in the probe's three seconds: about 280 million faults, none routed to EL2. Giving SP_EL1 a valid value at reset, with CPSR still 0x3c4, makes the same run pass, which confirms the chain:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/regcheck.bin@0x40080000 --timeout 10regcheck: CurrentEL=0x4regcheck: MPIDR_EL1=0x80000000regcheck: SCTLR_EL1.M=0regcheck: DAIF=0x3c0regcheck: x0=0x40000000regcheck: vectors ok (svc caught at EL1, esr=0x5600004d)What you saw: a guest that hung after printing everything it could. The misconception it exposes: "bit 0 only picks a stack; if the program sets sp, nothing else depends on it". The tool that found it: the register dump, whose sp_el1 and ELR_EL1 named the cause.
Your turn
Your workspace now needs, and the checkpoint tests:
- In
arch/regs.rs:Pstate(el,sp_elx,aarch32,daif,mode_nameand theMODE, DAIF, NZCVDisplay), thepstateandsctlrconstants, andmpidr. hv_sys_reg_t,hv_vcpu_get_sys_regandhv_vcpu_set_sys_regdeclared and wrapped, and aSysRegfor each register the dump reads.Vcpu::createwritingMPIDR_EL1, andVcpu::reset(&BootParams)setting the PC,x0tox3, CPSR andSCTLR_EL1.RegDumpwithcapture,ec_suffixwith the fourec_namerows,format_regs, and the class-0x20fatal stop:guest fatal:line,vcpu0:line, dump, exit code 3.- Your journal: the Predict entry, written before you ran
self-fault, and the four questions.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 06You should see, as the last line:
CHECKPOINT 06 PASSIt runs the contract tests (the dump's exact layout and the PSTATE decoder), runs regcheck and self-fault against your VMM and matches their output, and checks your journal. A finished chapter looks like this:
scripts/checkpoint.sh 06checkpoint: implementation <tree>[PASS] contract tests dump_format (4 tests)[PASS] runs on your Mac regcheck: 6/6 serial markers, exit 0 in 0.05s[PASS] runs on your Mac self-fault: 5/5 serial markers, exit 3 in 0.01s[INFO] journal not checked (not a learner tree)CHECKPOINT 06 PASSWhat now works:
- your vCPU starts in a defined state (EL1h, everything masked, its own MPIDR, translation and caches off), and a guest can check it from inside;
- you can build and read any PSTATE value, and know which bit picks the stack;
- a dying guest prints a register dump, and you can tell our fault from the guest's first one, and know when that one is gone.
The next chapter starts from this state (the reference at the end of chapter 06).
What's next
The dump told you where a guest died, but our loop still stops at the first exit it does not understand. Chapter 07 decodes every syndrome, emulates a guest's loads and stores to device addresses, and adds the ring of last exits you saw at the bottom of the self-fault run.
Open question
Your dump is the only window into a crashed guest. Which five registers would you add to it, and what question does each one answer?
Spec hunt
- The Arm Architecture Reference Manual (ARM ARM, DDI 0487), register page SPSR_EL1, Saved Program Status Register (EL1): which
M[3:0]values are legal for an exception taken to EL1, and why is there no "EL0h"? - ARM ARM, register page MPIDR_EL1, Multiprocessor Affinity Register: what do the
UandMTbits mean, and where does the fourth affinity field,Aff3, live? - Linux
Documentation/arch/arm64/booting.rst, section 4, "Call the kernel image": which registers andSCTLR_EL1bits must hold at entry, and which of them does yourresetnot set yet?