Chapter 05 · Part II
Two stages, one map: holes in stage 2 on purpose
Course progress: chapter 05 is 6 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 04: Guest memory: the only safe access is a copy
A guest asks the VMM to read 8 bytes at address
0xFFFF_FFFF_FFFF_FFFC. Guest RAM is0x4000_0000..0x4400_0000. Computeaddr + lenin 64-bit wrapping arithmetic, and say whether the checkaddr >= 0x4000_0000 && addr + len <= 0x4400_0000accepts the access.Show answer
The true sum is
0x1_0000_0000_0000_0004, which needs 65 bits; wrapped to 64 bits it is0x4. Both halves of the check pass (0xFFFF_FFFF_FFFF_FFFCis above the base,0x4is below the end), so a wrapping check accepts an access that starts 4 bytes below the top of the address space.checked_addreturnsNoneinstead, and the access is refused.From chapter 04: Guest memory: the only safe access is a copy
hv_vm_mapis asked to map 4 KiB of host memory at guest address0x4000_0000, which is 16 KiB-aligned. What does it answer on a Mac with the default configuration?Show answer
HV_BAD_ARGUMENT. The address is fine, but the size must be a whole number of 16 KiB host pages, because HVF's stage-2 table, the one that maps guest memory to ours, uses the Mac's 16 KiB page size by default.From chapter 04: Guest memory: the only safe access is a copy
A guest RAM made of two adjacent regions,
0x4000_0000(64 KiB) and0x4001_0000(64 KiB). Is an 8-byte read at0x4000_FFFCvalid, and why?Show answer
No. The range crosses from the first region into the second. The two regions are separate host allocations that only look contiguous to the guest, so one copy from a single host pointer would run off the end of the first allocation. An access must lie inside one region.
From chapter 04: Guest memory: the only safe access is a copy
Why does the
GuestMemorycontract have noget_slicethat returns a&[u8]into guest RAM?Show answer
A
&[u8]promises the compiler that nobody changes those bytes while the reference lives, and the compiler uses that promise (it may load a byte once and reuse the value, or load it twice and assume both loads agree). The guest, another vCPU or a device thread can change guest RAM at any moment, so the promise would be false. The contract hands out copies instead, and the VMM checks its own copy.From chapter 04: Guest memory: the only safe access is a copy
check_range(GuestAddress(0x4000_0000), 0)on a valid RAM region: true or false, and why does the contract choose that answer?Show answer
False. A zero-length range is never a valid access, so
readandwriterefuse an empty buffer too, andcheck_rangeis true exactly when the matchingreadwould succeed.From chapter 04: Guest memory: the only safe access is a copy
Name two things a volatile load guarantees and two things it does not.
Show answer
It guarantees that the compiler performs the load, at its size, every time the program says so, in program order relative to other volatile accesses, and never assumes the value is unchanged. It does not make an access of several elements atomic, and it gives no ordering or visibility guarantee towards other threads or the guest (that needs atomics and barriers, chapter 16). Volatile does not mean thread-safe.
From chapter 04: Guest memory: the only safe access is a copy
write_u32(GuestAddress(0x4000_0010), 0xdead_beef)succeeds. Which byte doesread_u8(GuestAddress(0x4000_0010))return, and why?Show answer
0xef. The helpers are little-endian, like the guest: the least significant byte of the value goes to the lowest address, so the bytes in memory areef be ad de.From chapter 04: Guest memory: the only safe access is a copy
A region table is given the region
base = 0xFFFF_FFFF_FFFF_C000, size = 0x8000. Both are 16 KiB multiples. Which construction rule rejects it, and what would go wrong without that rule?Show answer
The overflow rule:
base + sizepassesu64::MAX. Without it, the region's end would wrap to0x4000, and a test of the formaddr < endwould place the region's end in low memory, so the table would answer nonsense for addresses near zero.From chapter 04: Guest memory: the only safe access is a copy
Your VMM's bounds check uses
addr + lenwith Rust's default release settings, where overflow is not checked. A guest calls the memory-hash debug call withaddr = 0xFFFF_FFFF_FFFF_FFF0, len = 0x20. What happens, and what changes if overflow checks are on?Show answer
Without overflow checks the sum wraps to
0x10, the range test passes, and the VMM forms a host pointer far outside the RAM allocation: a guest-chosen read of host memory, unless a second check catches it. With overflow checks on, the addition panics, and the guest has crashed the VMM. Both are wrong: onlychecked_add, which turns the overflow into an ordinary error, keeps the VMM running and safe.From chapter 02: An exception, one level up: your first VM exit
A VM exit reports the syndrome
0x5a00002a. Which instruction stopped the guest, and what number did it carry?Show answer
The exception class is
0x5a00002a >> 26 = 0x16: anhvcfrom 64-bit code. For anhvc, the low 16 bits of the syndrome hold its immediate, so the guest ranhvc #0x2a.From chapter 02: An exception, one level up: your first VM exit
An exit shows exception class
0x17with the guest's PC at0x40001000. Before you run the vCPU again, where must the PC point, and why?Show answer
At
0x40001004. That class is ansmc, which the level above intercepts before it executes, so the saved PC still points at thesmcitself, as for a fault; run it again unchanged and the guest repeats the same call forever.From chapter 02: An exception, one level up: your first VM exit
An app at EL0 runs
svc #0at address0x1000. Which exception level handles it, and which register holds0x1004when the handler starts?Show answer
EL1, the kernel's level.
ELR_EL1holds0x1004, the preferred return address: a call continues after itself.From chapter 02: An exception, one level up: your first VM exit
You set the starting PSTATE to
0x3c4instead of0x3c5. What is different about how the guest starts?Show answer
The low four bits change from
0b0101to0b0100: still EL1, but using the stack pointer of EL0 (SP_EL0, "EL1t") instead of EL1's own (SP_EL1, "EL1h"). The four DAIF mask bits are still all set.From chapter 02: An exception, one level up: your first VM exit
A timer interrupt arrives while a guest is in the middle of a loop. Is that a synchronous or an asynchronous exception, and where does the saved return address point?
Show answer
Asynchronous: no instruction caused it. The saved address is the first instruction that had not run yet, so the loop carries on as if nothing happened when the handler returns.
From chapter 02: An exception, one level up: your first VM exit
A guest's first instruction is at
0x40000000, but your VMM mapped its 16 KiB of RAM at0x40004000. What comes back from the firsthv_vcpu_run?Show answer
A VM exit for an instruction abort (exception class
0x20) at PC0x40000000: the CPU could not fetch the first instruction, because no stage-2 mapping covers that guest address. Nothing in the guest ran.From chapter 02: An exception, one level up: your first VM exit
hv_vm_mapis asked to map 16 KiB of host memory at guest address0x40002000. What does it answer on a Mac with the default configuration, and why?Show answer
An error (
HV_BAD_ARGUMENT). Mappings come in host pages of 16 KiB, so the guest address, the host address and the size must all be multiples of 16 KiB, and0x40002000is not.From chapter 02: An exception, one level up: your first VM exit
The instruction word
0x14000000sits after thehvcin chapter 02's guest. What does it do, and why is it there?Show answer
It is
b ., a branch to itself with offset 0: an endless loop. If the VMM ever resumes the guest past thehvc, the vCPU parks there harmlessly instead of running into whatever bytes follow.From chapter 02: An exception, one level up: your first VM exit
Why does the saved PC point after an
hvcbut at a load that faulted?Show answer
A call wants to continue after itself once it is answered; a fault must be retried once its cause is fixed, so the faulting instruction runs again.
From chapter 02: An exception, one level up: your first VM exit
Your VMM creates a vCPU on one thread and reads one of its registers with
hv_vcpu_get_regfrom another. What happens, and why?Show answer
The call fails (the framework answers
HV_BAD_ARGUMENT), because a vCPU belongs to the thread that created it: the header says its calls "must be called by the owning thread". In our Rust wrapper it does not even compile, because theVcputype cannot be sent to another thread.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 04, Guest memory: the only safe access is a copy.
- Core, taught here: stage-2 translation and the IPA (intermediate physical address); the stage-2 hole; memory-mapped I/O (MMIO); data abort and the data fault status code (DFSC); why an exit reports an IPA; the IPA size;
layout.rsand its invariants; the unhandled-MMIO policy. - Core, from earlier: the IPA and the stage-2 mapping (chapter 02); the exit record and the call-versus-retry rule (chapter 02); test guests, the run loop, exit codes and the address size fault (chapter 03);
hv_vm_map's 16 KiB rule and the region table (chapter 04). - Primers (read first):
page-tables(the walk, descriptors, Device memory, the second lookup);page-granules. - Primers (review):
os-basics(virtual memory);aarch64-reading(loads, stores, bit fields);reading-arm-specs(RAZ/WI). - Pointers: shadow page tables (chapter 00); port I/O (an Aside); dirty tracking (chapter 26); the QEMU
virtboard (chapter 21). - Forward definitions: INTID; SPI (shared peripheral interrupt) and PPI (private peripheral interrupt); virtio slot; the GIC (Generic Interrupt Controller) distributor and redistributors (chapter 12); the bus (chapters 07 and 09); the device tree (chapter 10). Each is defined where it first appears.
A guest wants to say "hi". On the machine it was written for, a UART (universal asynchronous receiver-transmitter), the simplest serial port, sits at 0x0900_0000: write a byte to its data register and it goes out to your terminal; read it and you get the next byte received (chapter 09 builds one). So the guest stores h, i and a newline to 0x0900_0000, one 32-bit store each, then loads the same address back.
Your virtual machine monitor (VMM) has no UART yet. Suppose you make the address exist the quickest way: hv_vm_map an ordinary 16 KiB page of RAM there.
Predict Does hi appear in your terminal, and what value does the guest's load read back?
Write your answer under ## Predict in your journal, with one sentence of reasoning.
This chapter finishes row 2 of chapter 00's problem ledger, memory, and opens row 3, devices. Both are answered by the same table: stage 2 maps what is there and, on purpose, leaves out what is not. Sitting A is on paper (1.5 hours); sitting B is at your Mac (2 hours).
Objectives: by the end you can
- (Sitting A) Explain with the UART example why a device register cannot be RAM, so device windows are stage-2 holes.
- (Sitting A) Explain what stage 2 saves over shadow page tables, in two sentences.
- (Sitting A) Walk a guest virtual address through a three-level stage-1 table to an IPA, predicting each level's index first, then say whether stage 2 maps it.
- (Sitting B) Write
arch/layout.rsas the single source of truth for the memory map and test its invariants. Compute the IPA size withipa_bits_needed, and refuse a machine that needs more than the host's maximum. - (Sitting B) Make a store to a never-populated hole produce a data-abort exit with its IPA, and stop cleanly with exit code 3.
Before you start. From the repository root, run scripts/learner start 05 to copy this chapter's journal to learner/journal/05.md. In sitting B, type each code block into your workspace, learner/, and run from inside it.
Two lookups, two owners
The page-tables primer ended with this picture:
guest (untrusted) | host: HVF and our VMM | VA --[stage 1: the guest's tables]--> IPA -|-[stage 2: HVF's tables]--> host memory written by the guest kernel | filled by our hv_vm_map calls a failure goes to the guest kernel | a failure becomes a VM exit for usEvery guest memory access is translated twice, by two owners; the trust boundary runs between them.
Inside a virtual machine (VM), a program uses a virtual address (VA). Stage 1 is the guest kernel's own page tables, rooted at TTBR0_EL1 and TTBR1_EL1. Its output is an IPA (intermediate physical address), the address the guest believes is physical. Stage 2 is a second set of tables, owned by Hypervisor.framework (HVF) and filled by our hv_vm_map calls; its output is real memory in our process.
Each stage has its own granule, the page size its tables use (chapter 04): arm64 Linux usually uses 4 KiB for stage 1; HVF's stage 2 uses the Mac's 16 KiB by default.
The problem stage 2 solves
Why two walks? A guest kernel writes page-table descriptors thousands of times a second, without asking anyone. With a single stage, whatever the guest's tables output is the address the hardware uses, so those descriptors would hold real host addresses, which the guest must never choose.
The classic answer, from chapter 00, was shadow page tables: the VMM keeps its own tables mapping guest VAs straight to host memory, and write-protects the guest's tables so every write to them traps: one VM exit each (Adams and Agesen, ASPLOS 2006).
Stage 2 removes the problem. The guest edits stage 1 with no traps; the VMM touches stage 2 only when the machine changes. On a miss the hardware walks both tables, up to 24 memory reads (the primer's "Under the hood"), but no exits; the TLB (translation lookaside buffer, the primer's translation cache) makes misses rare.
Journal question 3 asks for this in two sentences of your own; write it now.
A device cannot be RAM
Back to the puzzle. The UART's data register is not storage: writing sends a byte, reading removes one from the input queue. RAM read twice gives the same value.
A kernel with its MMU (memory management unit, the hardware that walks the translation tables, both stages) on marks the UART page as a Device memory type (the primer's section on MAIR_EL1): Linux uses Device-nGnRE, our test guests the stricter Device-nGnRnE. With the MMU off, every data access is treated as Device anyway. But Device memory changes only how the CPU performs the access; where it goes is stage 2's decision, and if stage 2 says "RAM", the store lands in RAM.
We checked on a real Mac, with one page of RAM at 0x0900_0000 and a guest that does what the puzzle describes. uart-ram, and va-alias below, are throwaway experiment guests, not shipped in guests/; read their captures. These runs use the reference monitor from the repository root; --stats is its flag, not yours. {guests} stands for target/guests/aarch64-unknown-none/release:
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/uart-ram.bin@0x40080000 --timeout 10 --statsuart-ram: storing 'h', 'i', '\n' to 0x9000000uart-ram: read back 0xamacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=70 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 71: hvc 71macvmm: stats: vcpu0 time: exec 0.000 s, wfi 0.000 smacvmm: stats: host cpu 0.000 s over 0.000 s wall (109%)macvmm: stats: rlimit core=0 nofile=1048576No hi. The load returned 0xa, the last byte stored: the "UART" is a word of memory. And 71 exits, all hvc (debug output and power-off), none for the four accesses. A mapped address never stops the guest, so the VMM never learns of the store.
So we leave the device's addresses out of stage 2. Every access there fails stage 2, the CPU takes an exception to exception level 2 (EL2, where Apple's hypervisor runs), HVF forwards it to us as a VM exit, and our VMM plays the device. That gap is a stage-2 hole, and talking to a device by loading and storing at its addresses is memory-mapped I/O (MMIO). The same guest on the finished reference, with chapter 09's UART behind the hole:
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/uart-ram.bin@0x40080000 --timeout 10 --statsuart-ram: storing 'h', 'i', '\n' to 0x9000000hiuart-ram: read back 0x0macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=73 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 75: hvc 71, data abort 4macvmm: stats: vcpu0 time: exec 0.000 s, wfi 0.000 smacvmm: stats: host cpu 0.000 s over 0.000 s wall (118%)macvmm: stats: rlimit core=0 nofile=1048576hi appears, the load returns 0 (nothing typed), and the stats show four data aborts, each an exit.
Aside
x86 PCs also have I/O ports, a separate device address space (Intel's Software Developer's Manual, volume 1). Arm has none.
What the exit tells us: an IPA
You have half met this exception in chapter 02. A failed instruction fetch is an instruction abort (class 0x20 from the guest); a failed load or store is a data abort, class 0x24. The low six bits of its ESR (Exception Syndrome Register) value are the DFSC (Data Fault Status Code): which kind of fault it was.
Our VMM never reads the guest's page tables. When stage 2 fails, the hardware has already translated the VA through stage 1. It reports the IPA's page number in HPFAR_EL2 (Hypervisor IPA Fault Address Register) and the VA in FAR_EL2 (Fault Address Register). The page offset is the same in both, so the IPA can be rebuilt from HPFAR_EL2 plus the low 12 bits of FAR_EL2; HVF hands us the result in the exit record.
Chapter 02's exit record carries both: the VA (its FAR field) and the IPA. We use only the IPA. The VA means something only inside the guest's current address space; the same VA can point to a different IPA a moment later. The IPA belongs to our map.
With the MMU off, as in every guest so far, VA and IPA are equal. This guest turns the MMU on with the tables in guests/common/mmu.rs and stores to VA 0x0b10_0000, which those tables send to IPA 0x0b00_0000. That is a window our map reserves for a test device, which a later chapter adds; today nothing is behind it, so it is a hole:
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/va-alias.bin@0x40080000 --timeout 10va-alias: MMU on; storing 0x4d to VA 0xb100000macvmm: guest fatal: unhandled MMIO write at 0xb000000 size 4 pc 0x4008108cvcpu0: data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) SSE=0 SRT=9 SF=0 AR=0 FnV=0 S1PTW=0 WnR=1 DFSC=0x6 (translation fault) esr=0x93890046 ipa=0xb000000 x0=0x0000000040082b24 x1=0x0000000000000025 x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x0000000000000007 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x000000000b100000 x9=0x000000000000004d x10=0x0000000000000078 x11=0x0000000040082da0 x12=0x0000000000000062 x13=0x0000000040096f4a x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040096f60 x19=0x0000000000000000 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x0000000040081078 sp_el0=0x0 sp_el1=0x40096ff0 pc=0x4008108c cpsr=0x800003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0 VBAR_EL1=0x40080800 SCTLR_EL1=0x30001185 TCR_EL1=0x100803519 TTBR0_EL1=0x40084000 TTBR1_EL1=0x0 insn at pc: 0xb9000109last exits: 32 (oldest first) {"t_ns":228458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":230333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":232041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":233583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":235375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":237041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":238666,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":240250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":241791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":243375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":244916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":246583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":260250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":264708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":266750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":269666,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":271291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":273875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":276833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":278416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":280708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":283041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":284625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":286333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":288500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":290041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":291750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":294375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":295958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":298791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008123c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":301708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811bc","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":305833,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008108c","ipa":"0xb000000","wnr":true,"size":4,"reg":9,"action":"stop","isv":true}The VMM printed the IPA, 0xb000000. The VA shows up only in x8=0x000000000b100000, the base register of the faulting str w9, [x8] (the word at the PC, 0xb9000109). The VMM sees IPAs, not guest virtual addresses.
How do we know stage 2 failed and not stage 1? A stage-1 fault is the guest kernel's own page fault, delivered through VBAR_EL1 to the guest (chapter 02's routing); that is why ESR_EL1 stays zero here. Only a stage-2 failure reaches EL2 and us, so an exit's DFSC describes the stage-2 walk.
DFSC=0x6 needs a table. For a data abort the ARM ARM (Arm Architecture Reference Manual) defines, among others:
| DFSC | Meaning |
|---|---|
0x00 to 0x03 | address size fault, level 0 to 3: a table address or the final output address is wider than the configured output size |
0x04 to 0x07 | translation fault, level 0 to 3: the walk found no valid entry at that level |
0x0d to 0x0f | permission fault, level 1 to 3: an entry exists but forbids this access |
The level says where the walk failed. With the default 16 KiB granule, stage 2 here starts at level 2: a 36-bit IPA needs only levels 2 and 3. An input too large for the walk at all is reported at level 0, because no table was read.
0x6 is a translation fault at level 2: stage 2's first lookup found no entry, because we never mapped anything there. That is the signature of a hole.
Walk one by hand
The va-alias store, as the hardware did it. First the geometry, from the dump: TCR_EL1 is 0x1_0080_3519. Its low six bits are T0SZ = 0x19 = 25, so addresses are 64 - 25 = 39 bits (the primer's T0SZ table), and TG0 (bits 15 and 14) is 0, so pages are 4 KiB. That makes three levels, each taking 9 bits of the VA: bits 38 to 30 at level 1, 29 to 21 at level 2, 20 to 12 at level 3; the low 12 bits are the offset.
Compute the three indices of 0x0b10_0000 before reading the table (the primer's printf one-liner does it in the shell). TTBR0_EL1 is 0x40084000, as the dump shows; the other table addresses come from our build of that guest:
| Level | Table base | Index | Descriptor read at | Descriptor | Meaning |
|---|---|---|---|---|---|
| 1 | 0x4008_4000 | 0 | 0x4008_4000 | 0x0000_0000_4008_5003 | table at 0x4008_5000 |
| 2 | 0x4008_5000 | 0x58 | 0x4008_52c0 | 0x0000_0000_4008_6003 | table at 0x4008_6000 |
| 3 | 0x4008_6000 | 0x100 | 0x4008_6800 | 0x0060_0000_0b00_0403 | page at 0x0b00_0000, Device memory |
Three reads, each at the table base plus eight times the index; the last one is a leaf.
The leaf's low bits 0x403 read, with the primer's section "What a descriptor says", as access flag set, AttrIndx = 0 and "page"; bits 53 and 54 forbid execution. Our guest sets MAIR_EL1 byte 0 to 0x00, Device-nGnRnE, in guests/common/mmu.rs. So stage 1 says: IPA 0x0b00_0000.
Now stage 2, with its own 16 KiB pages: is the page holding 0x0b00_0000 mapped? We mapped only RAM, from 0x4000_0000. No: stage 2 fails, and the exit carries 0x0b00_0000.
Now walk VA 0x0b10_1000 on paper. Which level-3 index, and at which address is its descriptor read? The descriptor there is 0x0060_0000_0900_0403. Decode it: which IPA, which memory type, and does stage 2 map that IPA? (Check your walk: index 0x101, read at 0x4008_6808.)
The two-stage-walker lab walks a VA through both stages, each with its own granule. It opens on the store above:
Two-stage translation walker
Walk a guest virtual address through the guest's page tables to an IPA, then through HVF's stage 2, with each stage's granule set separately, and see the exact fault registers when a walk fails.
Runs in browserOpen full page: Two-stage translation walkerStep through it and compare each read with the table and the capture. Then, with Predict on, walk 0x0b10_1000, then 0x4000_1234 (a 1 GiB block, so the IPA equals the VA). Set the stage-2 granule to 4 KiB: stage 2 needs one more level. Last, map RAM at 0x0900_0000 and walk 0x0b10_1000 again: no exit.
Good place to stop. Sitting B needs your Mac, your learner workspace and about 2 hours.
One map, one file
If holes are deliberate, someone decides where they are: one file, crates/vmm/src/arch/layout.rs. Mappings, devices, checks and the device tree (chapter 10's description of the machine for the kernel) are all built from it, because two copies of an address would one day disagree.
We copy QEMU's virt board, QEMU's standard Arm machine, whose map stock firmware and kernels already know. The reference's --dry-run prints the whole board without creating a VM (run it from the repository root; your VMM does not have the flag):
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/mmio-poke.bin@0x40080000 --dry-runmacvmm boot plan (dry run, no VM created)ram 0x40000000..0x44000000 64 MiBdtb 0x40000000..0x40000697 device tree (1687 bytes)raw 0x40080000..0x40082dba --raw blob 0 (11706 bytes)entry pc=0x40080000 x0=0x40000000 cpsr=0x3c5memory map (Virt): 0x00000000..0x04000000 flash0 Rom 0x04000000..0x08000000 flash1 Rom 0x08000000..0x08010000 gicd GicDist 0x08010000..0x08020000 gicv2-cpu Reserved 0x08020000..0x08030000 gic-v2m GicMsi 0x08080000..0x080a0000 gic-its Reserved 0x080a0000..0x09000000 gicr GicRedist 0x09000000..0x09001000 pl011 Mmio intid 33 0x09010000..0x09011000 pl031 Mmio intid 34 0x09020000..0x09020018 fw-cfg Reserved 0x09030000..0x09031000 pl061 Reserved intid 39 0x0a000000..0x0a004000 virtio-mmio Mmio 0x0b000000..0x0b001000 testdev Mmio 0x0c000000..0x0e000000 probe-hole Reserved 0x10000000..0x3eff0000 pcie-mmio Reserved 0x3eff0000..0x3f000000 pcie-pio Reserved 0x3f000000..0x40000000 pcie-ecam Reserved 0x40000000..0x44000000 ram Ramdevice tree: 1687 bytes at 0x40000000 (limit 524288), 1 vCPU(s), irqchip InKernelGicV3, rng-seed 64 bytes and kaslr-seed (values not shown)debug hypercalls: onTwo rows are ours, not QEMU's: testdev, a window for a small test device we add later, and probe-hole, where QEMU puts a platform bus we never populate. pl011 is the UART and pl031 a clock; the other names are QEMU devices we do not build. Some rows carry an INTID, the number that will name the device's interrupt line (chapters 11 and 12).
Every region has a kind, which decides what the VMM does with an access there. In learner/crates/vmm/src/arch/layout.rs:
/// What a region is, which decides how the VMM treats an access to it.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum RegionKind { /// Guest RAM, mapped RWX at stage 2. Not in [`VIRT_REGIONS`]: its size comes from `--mem`. Ram, /// Flash: mapped RX with `--bios` (bank 0 the image, bank 1 empty; chapter 21), else unmapped. Rom, /// In-kernel GIC distributor (HVF services it, no exits). GicDist, /// In-kernel GIC redistributors, `ncpus` frames of 128 KiB; the rest of the window is RAZ/WI. GicRedist, /// GICv2m MSI frame (in-kernel, used only with PCI, which this machine does not have). GicMsi, /// Trapped device window: every access exits to the VMM. Mmio, /// Reserved or never populated: an access is unhandled MMIO. Reserved,}Flash, the board's read-only firmware storage, is mapped only when you boot firmware with --bios (chapter 21). The GIC (Generic Interrupt Controller) routes device interrupts to CPUs. It has a shared part, the distributor, which decides where each device's interrupt goes, and one private part per CPU, a redistributor (chapter 12): the gicd and gicr rows.
impl RegionKind { /// True for the kinds that are not trapped to us: RAM and flash are mapped with `hv_vm_map`, /// and HVF's in-kernel GIC claims its own windows. All keep 16 KiB alignment (the GIC's /// bases need 64 KiB, `hv_gic_get_*_base_alignment`, checked separately). pub const fn may_be_mapped(self) -> bool { matches!( self, RegionKind::Ram | RegionKind::Rom | RegionKind::GicDist | RegionKind::GicRedist | RegionKind::GicMsi ) }}may_be_mapped marks the kinds something other than a VMM exit may serve: RAM, flash with --bios, and the GIC windows HVF can claim. From chapter 12, HVF services the distributor and one redistributor frame per vCPU; the unused rest of gicr comes back to us and reads as zero. We do not enable the gic-v2m frame, so it is a hole today despite its kind.
Today only RAM is mapped; everything else is a hole that exits to us.
A row of the map, and its helpers:
/// One row of the map.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct Region { pub name: &'static str, pub base: u64, pub size: u64, pub kind: RegionKind, /// The region's interrupt as an INTID, where it has one. pub intid: Option<u32>,}impl Region { /// One past the last byte. `layout_invariants.rs` proves no row overflows, so the /// saturation never triggers for the static table. pub const fn end(&self) -> u64 { self.base.saturating_add(self.size) } /// True if `ipa` lies in this region. pub const fn contains(&self, ipa: u64) -> bool { ipa >= self.base && ipa < self.end() } /// The DT unit address of a node for this region: the base in lowercase hex without a /// prefix or leading zeros (DT spec v0.4 section 2.2.1 "Node names": `node-name@unit-address`, /// where the unit address matches the first address in `reg`). Derived from `base` so the /// node name and `reg` can never disagree. pub fn unit_address(&self) -> String { format!("{:x}", self.base) }}unit_address names the region's device-tree node, as in pl011@9000000; derived from base, it cannot disagree with it. The bases other modules need get names:
pub const FLASH0_BASE: u64 = 0x0000_0000;pub const FLASH1_BASE: u64 = 0x0400_0000;pub const FLASH_BANK_SIZE: u64 = 0x0400_0000;/// Both flash banks: one read+execute `RomRegion` from `FLASH0_BASE` (chapter 21). Bank 1 must/// be readable because U-Boot `qemu_arm64` reads its environment memory-mapped from/// `CONFIG_ENV_ADDR = 0x0400_0000` before any driver probes.pub const FLASH_SIZE: u64 = 0x0800_0000;pub const GICD_BASE: u64 = 0x0800_0000;pub const GICD_SIZE: u64 = 0x0001_0000;pub const GIC_MSI_BASE: u64 = 0x0802_0000;pub const GICR_BASE: u64 = 0x080A_0000;pub const PL011_BASE: u64 = 0x0900_0000;pub const PL011_INTID: u32 = 33; // SPI 1pub const PL031_BASE: u64 = 0x0901_0000;pub const PL031_INTID: u32 = 34; // SPI 2pub const VIRTIO_MMIO_BASE: u64 = 0x0a00_0000;pub const TESTDEV_BASE: u64 = 0x0b00_0000;/// The never-populated hole that `guests/mmio-poke` stores into.pub const PROBE_HOLE_BASE: u64 = 0x0c00_0000;pub const RAM_BASE: u64 = 0x4000_0000;The table, sorted by base:
use RegionKind::*;/// Every region of the `virt` board except RAM, sorted by base (QEMU `hw/arm/virt.c`,/// `base_memmap[]`; one row per line).#[rustfmt::skip]pub const VIRT_REGIONS: &[Region] = &[ Region { name: "flash0", base: FLASH0_BASE, size: FLASH_BANK_SIZE, kind: Rom, intid: None }, Region { name: "flash1", base: FLASH1_BASE, size: FLASH_BANK_SIZE, kind: Rom, intid: None }, Region { name: "gicd", base: GICD_BASE, size: GICD_SIZE, kind: GicDist, intid: None }, Region { name: "gicv2-cpu", base: 0x0801_0000, size: 0x0001_0000, kind: Reserved, intid: None }, Region { name: "gic-v2m", base: GIC_MSI_BASE, size: 0x0001_0000, kind: GicMsi, intid: None }, Region { name: "gic-its", base: 0x0808_0000, size: 0x0002_0000, kind: Reserved, intid: None }, Region { name: "gicr", base: GICR_BASE, size: 0x00F6_0000, kind: GicRedist, intid: None }, Region { name: "pl011", base: PL011_BASE, size: 0x1000, kind: Mmio, intid: Some(PL011_INTID) }, Region { name: "pl031", base: PL031_BASE, size: 0x1000, kind: Mmio, intid: Some(PL031_INTID) }, Region { name: "fw-cfg", base: 0x0902_0000, size: 0x18, kind: Reserved, intid: None }, Region { name: "pl061", base: 0x0903_0000, size: 0x1000, kind: Reserved, intid: Some(39) }, Region { name: "virtio-mmio", base: VIRTIO_MMIO_BASE, size: 0x4000, kind: Mmio, intid: None }, Region { name: "testdev", base: TESTDEV_BASE, size: 0x1000, kind: Mmio, intid: None }, Region { name: "probe-hole", base: PROBE_HOLE_BASE, size: 0x0200_0000, kind: Reserved, intid: None }, Region { name: "pcie-mmio", base: 0x1000_0000, size: 0x2eff_0000, kind: Reserved, intid: None }, Region { name: "pcie-pio", base: 0x3eff_0000, size: 0x0001_0000, kind: Reserved, intid: None }, Region { name: "pcie-ecam", base: 0x3f00_0000, size: 0x0100_0000, kind: Reserved, intid: None },];Reserved rows mark devices QEMU has and we do not. They stop us from ever placing one of our own devices there, and they let the VMM name the device a stray access was aimed at. RAM has no row; chapter 04's region table holds it. The sizes --mem accepts:
/// RAM limits: 64 MiB ≤ size ≤ 255 GiB, a multiple of 2 MiB (so the Linux Image's 2 MiB-aligned/// placement, booting.rst section 4, always fits whole blocks).pub const RAM_MIN: u64 = 64 << 20;/// The top of the RAM window: 255 GiB of RAM ends at `0x40_0000_0000` (2^38).pub const RAM_MAX_END: u64 = 0x40_0000_0000;pub const RAM_MAX: u64 = RAM_MAX_END - RAM_BASE;pub const RAM_ALIGN: u64 = 2 << 20;pub const RAM_DEFAULT: u64 = 512 << 20;2 MiB steps keep RAM whole 16 KiB pages and a Linux kernel 2 MiB-aligned; 255 GiB from 1 GiB ends at exactly 1 << 38. A refused size says why (write use std::fmt; where the reference has core::fmt):
/// Why a `--mem` size was refused.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum RamSizeError { TooSmall { size: u64 }, TooLarge { size: u64 }, Unaligned { size: u64 },}impl fmt::Display for RamSizeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { RamSizeError::TooSmall { size } => { write!( f, "RAM size {size:#x} is below the minimum {RAM_MIN:#x} (64 MiB)" ) } RamSizeError::TooLarge { size } => { write!( f, "RAM size {size:#x} is above the maximum {RAM_MAX:#x} (255 GiB)" ) } RamSizeError::Unaligned { size } => { write!(f, "RAM size {size:#x} is not a multiple of 2 MiB") } } }}impl std::error::Error for RamSizeError {}Test guests are linked 512 KiB into RAM, after the device tree's slot:
pub const DTB_MAX_TEST_GUEST: u64 = 512 << 10;/// Where test guests are linked (chapter 03).pub const TEST_GUEST_BASE: u64 = RAM_BASE + DTB_MAX_TEST_GUEST;Finally the board, which owns the table (profile is optional). The methods below go in its impl Layout block:
/// A board: its profile and its static regions.#[derive(Debug)]pub struct Layout { pub profile: MachineProfile, pub regions: &'static [Region],}static VIRT: Layout = Layout { profile: MachineProfile::Virt, regions: VIRT_REGIONS,};impl Layout { /// The QEMU-`virt`-compatible board. pub fn virt() -> &'static Layout { &VIRT }cargo build -p vmm should compile now; the tests come after the next section.
Slots and interrupt numbers
A virtio slot is one of 32 MMIO windows for paravirtual devices, designed for virtual machines (chapter 15). QEMU wires slot i to SPI (shared peripheral interrupt) 16 + i, and SPIs are numbered from INTID 32, so slot i is INTID 48 + i:
pub const VIRTIO_MMIO_STRIDE: u64 = 0x200;pub const VIRTIO_MMIO_SLOTS: usize = 32;/// SPI 16 → INTID 48 for slot 0.pub const VIRTIO_FIRST_INTID: u32 = 48;/// Base address and INTID of virtio-mmio slot `i` (0..32); `None` past the last slot.pub fn virtio_slot(&self, i: usize) -> Option<(u64, u32)> { if i >= VIRTIO_MMIO_SLOTS { return None; } let base = VIRTIO_MMIO_STRIDE .checked_mul(u64::try_from(i).ok()?)? .checked_add(VIRTIO_MMIO_BASE)?; Some(( base, VIRTIO_FIRST_INTID.checked_add(u32::try_from(i).ok()?)?, ))}/// The non-RAM region containing `ipa`, if any.pub fn find(&self, ipa: u64) -> Option<&Region> { self.regions.iter().find(|r| r.contains(ipa))}Slot 31 is at 0x0a00_3e00 with INTID 79. A slot is only 0x200 bytes: RAM comes in 16 KiB pieces because hv_vm_map maps it, but a hole is the absence of a mapping, so it can be any size. find, at the end of that block, names the region holding an IPA.
The UART and clock carry INTIDs 33 and 34. QEMU hands some lines out in blocks to devices we do not build; we reserve each block whole so nothing collides with it later:
/// A block of consecutive INTIDs, `first..=last`, that the board reserves for a group of lines/// rather than for one device (QEMU `hw/arm/virt.c`, `a15irqmap[]`).#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct IntidRange { pub name: &'static str, pub first: u32, pub last: u32,}impl IntidRange { /// True if `intid` lies in `first..=last`. pub const fn contains(&self, intid: u32) -> bool { intid >= self.first && intid <= self.last }}/// PCIe legacy INTA..INTD: SPI 3–6 → INTID 35–38 (QEMU's PCIe host bridge).pub const PCIE_INTX_INTIDS: IntidRange = IntidRange { name: "pcie-intx", first: 35, last: 38,};/// The SPIs the GICv2m frame turns MSIs into: SPI 48–111 → INTID 80–143. It sits/// directly above the virtio block (INTID 48–79), so a 33rd virtio slot would collide with it.pub const GIC_V2M_INTIDS: IntidRange = IntidRange { name: "gic-v2m", first: 80, last: 143,};/// Every reserved INTID block, sorted by `first`. No device line may fall inside one.pub const RESERVED_INTIDS: &[IntidRange] = &[PCIE_INTX_INTIDS, GIC_V2M_INTIDS];Not every interrupt is shared. A PPI (private peripheral interrupt, INTIDs 16 to 31) belongs to one CPU, and each CPU's virtual timer uses 27 (chapter 11):
/// The EL1 virtual timer's interrupt: a PPI (INTIDs 16 to 31, private to one CPU), INTID 27/// on every Arm board (the device tree's timer node lists it).pub const VTIMER_INTID: u32 = 27;The redistributor window holds one 128 KiB frame per vCPU, at most 64; gicr_size gives their total, and ram_end checks a --mem size:
/// One redistributor (RD_base + SGI_base frames), 128 KiB (GICv3 spec IHI 0069, section/// 12.10 "The GIC Redistributor register map").pub const GICR_FRAME_SIZE: u64 = 0x0002_0000;/// The redistributor window ends where the PL011 begins; unclaimed frames are RAZ/WI.pub const GICR_WINDOW_END: u64 = PL011_BASE;/// The most vCPUs the `virt` board describes: 64 × 128 KiB = 8 MiB of redistributors, well/// inside the 0xF6_0000-byte window.pub const MAX_CPUS: u32 = 64;/// Bytes of redistributor frames for `ncpus` vCPUs (`1..=MAX_CPUS`); the rest of the/// window up to [`GICR_WINDOW_END`] is the RAZ/WI remainder.pub fn gicr_size(&self, ncpus: u32) -> Option<u64> { if ncpus == 0 || ncpus > MAX_CPUS { return None; } GICR_FRAME_SIZE.checked_mul(u64::from(ncpus))}/// Check a `--mem` size and return where RAM ends (`RAM_BASE + size`).pub fn ram_end(&self, size: u64) -> Result<u64, RamSizeError> { if size < RAM_MIN { return Err(RamSizeError::TooSmall { size }); } if size > RAM_MAX { return Err(RamSizeError::TooLarge { size }); } if !size.is_multiple_of(RAM_ALIGN) { return Err(RamSizeError::Unaligned { size }); } RAM_BASE .checked_add(size) .ok_or(RamSizeError::TooLarge { size })}The invariants, as tests
Write tests of what a correct map is, in learner/crates/vmm/tests/layout_invariants.rs; the checkpoint runs its own copy:
- No overlaps, no overflow, with
checked_add. - Mapped regions are 16 KiB-aligned, base and size, for every kind where
may_be_mapped()is true. - Everything ends at or below
1 << 40, the largest IPA size on our Apple M5 Pro (create_vmchecks the real host). - INTIDs are unique SPIs, inside 32 to 1019, counting the region lines, the slot lines and every reserved block; the timer's INTID is a PPI.
virtio_slot(0) == Some((0x0a00_0000, 48)),virtio_slot(31) == Some((0x0a00_3e00, 79)),virtio_slot(32) == None.- The GIC fits: 64 KiB-aligned bases, as HVF's in-kernel GIC requires, and 64 redistributor frames end below the UART.
- RAM sizes from 64 MiB to 255 GiB in 2 MiB steps are accepted, the rest refused.
How many address bits: the IPA size
Chapter 01's doctor printed max IPA: 40 bits (default 36) on a Mac with far less than a terabyte of RAM. The 40 is how many address bits stage 2 accepts as input. A VM with an IPA size of n bits can address [0, 2^n), and nothing above. HVF uses 36 bits (64 GiB) unless told otherwise. The function that picks ours:
/// The smallest IPA width the VMM asks for: HVF's default, 36/// (`hv_vm_config_get_default_ipa_size`).pub const MIN_IPA_BITS: u32 = 36;/// The smallest IPA width ≥ 36 that covers `max(ram_end, highest region end)`: a VM with/// `n` IPA bits can address `[0, 2^n)` (ARM ARM D8.1: the stage-2 input size,/// VTCR_EL2.T0SZ, which HVF derives from `hv_vm_config_set_ipa_size`). Asking for no more/// than needed keeps the stage-2 tables shallow. The caller refuses a result above the/// host's `max_ipa_bits` (`vm::create_vm`).pub fn ipa_bits_needed(&self, ram_end: u64) -> u32 { let top = self.regions.iter().map(Region::end).fold(ram_end, u64::max); let mut bits = MIN_IPA_BITS; while bits < 64 && 1u64.checked_shl(bits).is_some_and(|limit| limit < top) { bits = bits.saturating_add(1); } bits}Compute one before reading on. The default 512 MiB of RAM ends at 0x6000_0000. What does ipa_bits_needed(0x6000_0000) return?
31 bits would do (1 << 31 is 0x8000_0000), yet the function returns 36: the loop starts at MIN_IPA_BITS, HVF's default, so a small machine gets the VM it would get with no setting. 255 GiB of RAM gives 38.
The answer reaches HVF through a configuration object, an hv_vm_config_t, a reference-counted Apple "OS object": we must drop our reference with os_release when done, or it leaks. Declare the calls from hv_vm_config.h, and the release:
pub fn hv_vm_config_create() -> hv_vm_config_t;pub fn hv_vm_config_get_max_ipa_size(ipa_bit_length: *mut u32) -> hv_return_t;pub fn hv_vm_config_get_default_ipa_size(ipa_bit_length: *mut u32) -> hv_return_t;pub fn hv_vm_config_set_ipa_size(config: hv_vm_config_t, ipa_bit_length: u32) -> hv_return_t;pub fn hv_vm_config_get_ipa_size( config: hv_vm_config_t, ipa_bit_length: *mut u32,) -> hv_return_t;/// `<os/object.h>`: the C entry point behind the `os_release` macro when Objective-C is not/// in use (our situation). Releases `hv_vm_config_t` and the other OS objects.pub fn os_release(object: *mut c_void);The reference wraps it in OsObject (crates/hvf/src/host.rs), the RAII (resource acquisition is initialization) pattern of chapter 01's Vm: it releases the object once, on drop:
/// Owns one retained OS object (`hv_*_config_t`, `hv_gic_state_t`) and releases it on drop.pub(crate) struct OsObject { ptr: NonNull<c_void>,}impl OsObject { /// Wrap a freshly created object; NULL (the `*_create` functions' only failure) becomes an /// error attributed to `call`. pub(crate) fn new(call: &'static str, ptr: *mut c_void) -> Result<OsObject, CallError> { NonNull::new(ptr) .map(|ptr| OsObject { ptr }) .ok_or(CallError { call, error: HvError::NoResources, }) } /// The raw object, valid for as long as `self` lives. pub(crate) fn as_ptr(&self) -> *mut c_void { self.ptr.as_ptr() }}impl Drop for OsObject { fn drop(&mut self) { // SAFETY: `ptr` is a non-NULL object returned retained by an `hv_*_create` function, // owned solely by this wrapper, and released exactly once here. unsafe { ffi::os_release(self.ptr.as_ptr()) } }}The reference's VM builder sets the size only if asked:
// SAFETY: no preconditions; the result is checked for NULL by `OsObject::new`.let config = OsObject::new("hv_vm_config_create", unsafe { ffi::hv_vm_config_create() })?;if let Some(bits) = self.ipa_bits { // SAFETY: `config` is a live `hv_vm_config_t` owned by `config`. check("hv_vm_config_set_ipa_size", unsafe { ffi::hv_vm_config_set_ipa_size(config.as_ptr(), bits) })?;}Give your own Vm::new (chapter 01) an ipa_bits: Option<u32> parameter, add the lines above, and pass config.as_ptr() to hv_vm_create in place of the null pointer:
// SAFETY: `config` is a live configuration; the framework copies what it needs, so// releasing `config` afterwards is allowed (`hv_vm.h`).check("hv_vm_create", unsafe { ffi::hv_vm_create(config.as_ptr())})?;The host's limits come from two queries that need no VM:
let mut max_ipa_bits = 0u32;// SAFETY: as above, a local `u32` out-parameter.check("hv_vm_config_get_max_ipa_size", unsafe { ffi::hv_vm_config_get_max_ipa_size(&mut max_ipa_bits)})?;let mut default_ipa_bits = 0u32;// SAFETY: as above, a local `u32` out-parameter.check("hv_vm_config_get_default_ipa_size", unsafe { ffi::hv_vm_config_get_default_ipa_size(&mut default_ipa_bits)})?;The VMM refuses a machine the host cannot hold before creating anything. These lines open the reference's create_vm; put them right before your Vm::new(Some(bits)):
let bits = layout.ipa_bits_needed(ram_end);if bits > caps.max_ipa_bits { return Err(Error::Config(format!( "the machine needs a {bits}-bit IPA space; this host supports {}", caps.max_ipa_bits )));}caps.max_ipa_bits is the first query's answer (the reference's hvf::Capabilities::probe()); ram_end is Layout::virt().ram_end(mem_size)?. If your error enum has no Config variant, add one that maps to exit code 2, like chapter 03's usage errors. Compute bits once and pass it to your GuestRam::new too, in place of chapter 04's literal 36.
Here the largest legal machine needs 38 bits and the host allows 40, so you will not see the refusal. On a Mac with a smaller maximum, a large --mem should stop with exit code 2; we have no such host to check.
When the guest touches a hole
Now the trap: a branch for class 0x24 in your run loop that decodes the syndrome, decides what lives at the IPA and applies a policy. This chapter reads three syndrome fields: WnR (bit 6, write not read), SAS (bits 23 and 22, the access size as 1 << SAS bytes) and the DFSC. SAS is meaningful only when ISV (bit 24, "instruction syndrome valid") is 1, as it is here; chapter 07 handles ISV = 0. In learner/crates/vmm/src/arch/esr.rs, the bit-field helpers (field cuts width bits out of a value from bit lo; bit is the one-bit case):
/// The value of `width` bits of `v` starting at bit `lo` (`width ≤ 16`). Total: the mask is/// built with a checked shift and the result fits by construction.const fn field(v: u64, lo: u32, width: u32) -> u64 { let mask = match 1u64.checked_shl(width) { Some(m) => m.wrapping_sub(1), None => u64::MAX, }; match v.checked_shr(lo) { Some(s) => s & mask, None => 0, }}/// `field` narrowed to `u8` (callers pass `width ≤ 8`, so nothing is lost).#[allow(clippy::cast_possible_truncation)] // masked to 8 bits firstconst fn field8(v: u64, lo: u32, width: u32) -> u8 { (field(v, lo, width) & 0xff) as u8}/// `field` narrowed to `u16` (callers pass `width ≤ 16`).#[allow(clippy::cast_possible_truncation)] // masked to 16 bits firstconst fn field16(v: u64, lo: u32, width: u32) -> u16 { (field(v, lo, width) & 0xffff) as u16}const fn bit(v: u64, n: u32) -> bool { field(v, n, 1) != 0}With them, the syndrome's class, its instruction-length bit, and the ISS (instruction specific syndrome) that holds everything else:
/// `ESR.EC`, bits 31:26.pub const fn esr_ec(esr: u64) -> u8 { field8(esr, 26, 6)}/// `ESR.IL`, bit 25: the trapped instruction was 32 bits long (always 1 for A64).pub const fn esr_il(esr: u64) -> bool { bit(esr, 25)}/// `ESR.ISS`, bits 24:0.#[allow(clippy::cast_possible_truncation)] // masked to 25 bits firstpub const fn esr_iss(esr: u64) -> u32 { (field(esr, 0, 25) & 0x01ff_ffff) as u32}Then the whole decoded syndrome (chapter 07 keeps this shape), its size helper and the decoder:
/// A data abort's syndrome (the module docs table). Frozen: later chapters use this shape.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct DataAbort { pub isv: bool, /// Access size as `log2(bytes)`: 0..=3. pub sas: u8, pub sse: bool, /// Register number 0..=31; 31 is XZR. pub srt: u8, pub sf: bool, pub ar: bool, pub fnv: bool, pub s1ptw: bool, pub wnr: bool, pub dfsc: u8,}impl DataAbort { /// The access size in bytes, `1 << SAS` (1, 2, 4 or 8; SAS is two bits, so always valid). pub const fn size_bytes(&self) -> u8 { match 1u8.checked_shl((self.sas & 3) as u32) { Some(n) => n, None => 8, // unreachable: the shift is at most 3 } }}/// Decode a data-abort ISS (module docs table). Every field is masked to its width, so any/// `esr` gives a value; with ISV = 0 bits 23:14 are RES0, so those fields carry nothing.pub const fn decode_data_abort(esr: u64) -> DataAbort { DataAbort { isv: bit(esr, 24), sas: field8(esr, 22, 2), sse: bit(esr, 21), srt: field8(esr, 16, 5), sf: bit(esr, 15), ar: bit(esr, 14), fnv: bit(esr, 10), s1ptw: bit(esr, 7), wnr: bit(esr, 6), dfsc: field8(esr, 0, 6), }}Classification asks: RAM, a device on the bus, or which board region? The bus is the VMM's list of emulated devices by address window (chapters 07 and 09). The reference's classifier:
/// What an IPA is, by our own map.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum IpaClass { /// Guest RAM (always mapped: a fault here is a VMM bug). Ram, /// A device window on the bus, at this offset. Device { name: &'static str, offset: u64 }, /// The flash region with no device on the bus (no `--bios`). Rom, /// Nothing: a reserved region (named) or a hole. Unmapped { region: Option<&'static str> },}/// Classify `ipa` against RAM, the bus and the board layout, in that order. DFSC is/// never consulted: it says *how* stage 2 failed, not *what* lives at the address.pub fn classify_ipa(ipa: u64, mem: &dyn GuestMemory, bus: &Bus) -> IpaClass { if mem.check_range(GuestAddress(ipa), 1) { return IpaClass::Ram; } if let Some((name, offset)) = bus.device_at(ipa) { return IpaClass::Device { name, offset }; } match Layout::virt().find(ipa) { Some(r) if r.kind == RegionKind::Rom => IpaClass::Rom, Some(r) => IpaClass::Unmapped { region: Some(r.name), }, None => IpaClass::Unmapped { region: None }, }}You have no bus yet, so drop the bus parameter and the Device arm: check RAM with chapter 04's check_range, then ask Layout::virt().find. Keep the Rom arm: without firmware, flash is a hole.
Then the unhandled-MMIO policy, from --unhandled-mmio fatal|log. Parse it into an enum MmioPolicy with unit variants Fatal and Log, deriving Clone, Copy, Debug, Default, PartialEq and Eq, with Fatal marked #[default]. log makes reads return zero and ignores writes, the convention Arm calls RAZ/WI (read as zero, writes ignored). The policy's answer, in learner/crates/vmm/src/vcpu/exit.rs:
/// What [`unhandled_mmio_policy`] decided.#[derive(Clone, Debug, PartialEq, Eq)]pub enum MmioVerdict { /// Stop with this message (exit code 3). Fatal(String), /// Read as zero / ignore the write, and resume. RazWi,}/// A guest access to an IPA that is neither RAM nor a device. `fatal` (the default) stops the/// VM with a message only the VMM prints; `log` makes the access RAZ/WI and warns, rate-limited,/// because the guest decides how often it happens.pub fn unhandled_mmio_policy(policy: MmioPolicy, ipa: u64, da: &DataAbort, pc: u64) -> MmioVerdict { let dir = if da.wnr { "write" } else { "read" }; let what = format!( "unhandled MMIO {dir} at {ipa:#x} size {} pc {pc:#x}", da.size_bytes() ); match policy { MmioPolicy::Fatal => MmioVerdict::Fatal(what), MmioPolicy::Log => { crate::guest_warn!("{what} (ignored: --unhandled-mmio log)"); MmioVerdict::RazWi } }}For the reference's rate-limited crate::guest_warn!, write a plain eprintln!. To resume, the VMM must write the zero into the load's register and advance the PC, which a data abort leaves at the instruction; chapter 07 does both. For now, accept --unhandled-mmio log, but treat RazWi as a fatal stop with the message log policy needs chapter 07.
Now the branch, in your chapter 03 loop:
- For class
0x24, calldecode_data_aborton the exit'sesr; the IPA is the exit record'sipafield. - Read the guest's PC, as your trace does.
- Classify the IPA.
Ramnever faults (it is mapped), so stop with a VMM-bug message; for every other class callunhandled_mmio_policy. - On
Fatal(msg), or for nowRazWi, printmacvmm: guest fatal:and the message to standard error and exit with code 3, new: the guest broke the machine's rules.
From inside learner/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/mmio-poke.bin@0x40080000 --timeout 10The reference's run:
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/mmio-poke.bin@0x40080000 --timeout 10mmio-poke: storing 0x4d to 0xc000000macvmm: guest fatal: unhandled MMIO write at 0xc000000 size 4 pc 0x40081088vcpu0: data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) SSE=0 SRT=9 SF=0 AR=0 FnV=0 S1PTW=0 WnR=1 DFSC=0x6 (translation fault) esr=0x93890046 ipa=0xc000000 x0=0x0000000040082a6a x1=0x0000000000000027 x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x0000000000000007 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x000000000c000000 x9=0x000000000000004d x10=0x0000000000000078 x11=0x0000000040082ce0 x12=0x0000000000000063 x13=0x0000000040092d1a x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040092d30 x19=0x0000000000000000 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x0000000040081074 sp_el0=0x0 sp_el1=0x40092dc0 pc=0x40081088 cpsr=0x800003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0 VBAR_EL1=0x40080800 SCTLR_EL1=0x30000180 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0 insn at pc: 0xb9000109last exits: 32 (oldest first) {"t_ns":213375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":215708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":218500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":220416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":222625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":225458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":228750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":230416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":237583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":239458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":242583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":244458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":246708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":248291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":249875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":253250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":254916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":257166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":258750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":283541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":296166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":323541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":326000,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":328375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":330041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":332250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":333875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":336458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":338666,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":340250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":347000,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008110c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":349833,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081088","ipa":"0xc000000","wnr":true,"size":4,"reg":9,"action":"stop","isv":true}Yours prints only the first line of standard error. The second reads: class 0x24, WnR=1 (a store), SAS=2 (4 bytes), DFSC=0x6 (a hole).
Deliberate breakage 1: hard-code the IPA size. In your VMM, pass Some(31) to Vm::new in place of Some(bits), and leave GuestRam alone (our runs made the same change in the reference's create_vm).
Predict Two runs of mmio-poke: with --mem 64M, and with --mem 2G. What happens in each?
Write both predictions before reading on.
First 64 MiB:
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/mmio-poke.bin@0x40080000 --timeout 10mmio-poke: storing 0x4d to 0xc000000macvmm: guest fatal: unhandled MMIO write at 0xc000000 size 4 pc 0x40081088vcpu0: data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) SSE=0 SRT=9 SF=0 AR=0 FnV=0 S1PTW=0 WnR=1 DFSC=0x6 (translation fault) esr=0x93890046 ipa=0xc000000 x0=0x0000000040082a6a x1=0x0000000000000027 x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x0000000000000007 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x000000000c000000 x9=0x000000000000004d x10=0x0000000000000078 x11=0x0000000040082ce0 x12=0x0000000000000063 x13=0x0000000040092d1a x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040092d30 x19=0x0000000000000000 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x0000000040081074 sp_el0=0x0 sp_el1=0x40092dc0 pc=0x40081088 cpsr=0x800003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0 VBAR_EL1=0x40080800 SCTLR_EL1=0x30000180 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0 insn at pc: 0xb9000109last exits: 32 (oldest first) {"t_ns":226791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":228416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":230041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":231833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":233375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":238958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":240541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":242416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":245458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":247125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":251375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":253541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":255125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":256708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":259875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":261500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":264500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":266125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":296916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":302250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":303875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":305625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":307208,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":309166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":310791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":313833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":315458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":317583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":319125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":321083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":324125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008110c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":326916,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081088","ipa":"0xc000000","wnr":true,"size":4,"reg":9,"action":"stop","isv":true}The same exit as above: 31 bits cover RAM ending at 0x4400_0000. Now 2 GiB, which ends at 0xC000_0000:
cargo run -q -p macvmm -- run --mem 2G --raw {guests}/mmio-poke.bin@0x40080000 --timeout 10macvmm: map guest memory: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)What you saw: the guest never ran; hv_vm_map refused the RAM, exit code 1 (a host failure). The misconception: "the IPA size is a detail; smaller only wastes less". The tools: ipa_bits_needed, and the invariant "everything ends below the limit". Undo the edit.
Chapter 04's RegionTable::new, inside your GuestRam, could have caught this first: it refuses a region that ends above 1 << ipa_bits. Pass it 31 too and it refuses before hv_vm_map is called, even for 64 MiB, because it accepts only widths 32 to 52.
Try it
What if the address is outside the IPA space altogether? Predict the DFSC for a store to 1 << 36 in our 36-bit VM: translation or address size fault, and at which level? To run it, set HOLE in guests/mmio-poke/main.rs to 1 << 36 and run scripts/build-guests.sh; afterwards git restore guests/ and rebuild. Our run used a renamed copy, ipa-poke. This is journal question 2.
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/ipa-poke.bin@0x40080000 --timeout 10ipa-poke: storing 0x4d to 0x1000000000macvmm: guest fatal: unhandled MMIO write at 0x1000000000 size 4 pc 0x40081088vcpu0: data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) SSE=0 SRT=9 SF=0 AR=0 FnV=0 S1PTW=0 WnR=1 DFSC=0x4 (translation fault) esr=0x93890044 ipa=0x1000000000 x0=0x0000000040082a69 x1=0x0000000000000025 x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x000000000000000a x6=0x0000000000000000 x7=0x0000000000000000 x8=0x0000001000000000 x9=0x000000000000004d x10=0x0000000000000078 x11=0x0000000040082ce0 x12=0x0000000000000031 x13=0x0000000040092d17 x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040092d30 x19=0x0000000000000000 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x0000000040081074 sp_el0=0x0 sp_el1=0x40092dc0 pc=0x40081088 cpsr=0x800003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0 VBAR_EL1=0x40080800 SCTLR_EL1=0x30000180 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0 insn at pc: 0xb9000109last exits: 32 (oldest first) {"t_ns":234083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":236250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":238875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":240458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":242041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":248000,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":249583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":252916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":254708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":257083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":258666,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":260791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":267291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":268875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":270416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":271958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":276041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":278208,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":280541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":282083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":283791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":286041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":287583,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":289958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":291666,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":295375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":301708,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":303291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":304916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":316375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008118c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":318083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008110c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":320291,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081088","ipa":"0x1000000000","wnr":true,"size":4,"reg":9,"action":"stop","isv":true}What to look for: DFSC=0x4, a translation fault at level 0, though our walk starts at level 2: an input outside the IPA size is never looked up. Chapter 03's address size fault was a different check: with the MMU off, the guest's address is stage 1's output, so being too wide was an output problem, taken at EL1. Here the address is too wide as an input to stage 2.
Security
The guest chooses the IPA in every data-abort exit. Classify it against the map, never index anything with it. The default stops loudly, so probing is noticed; with log the guest decides how often a warning fires, so the reference rate-limits them.
Production note
Real hypervisors also map RAM read-only on purpose (hv_vm_protect): the first write to each page exits once, telling the VMM which pages changed, for live migration and snapshots (chapter 26).
Your turn
The checkpoint's tests compile against these public names in vmm::arch::layout, so spell them exactly:
- the table:
Region(withend,contains,unit_address),RegionKind(withmay_be_mapped),VIRT_REGIONS,Layout(withvirt,find,virtio_slot,gicr_size,ram_end,ipa_bits_needed); - addresses:
RAM_BASE,GICD_BASE,GICR_BASE,GICR_FRAME_SIZE,GICR_WINDOW_END,MAX_CPUS,VIRTIO_MMIO_SLOTS,VIRTIO_MMIO_STRIDE,TEST_GUEST_BASE,DTB_MAX_TEST_GUEST; - RAM:
RAM_MIN,RAM_MAX,RAM_DEFAULT,RAM_ALIGN,RAM_MAX_END; - interrupts:
PL011_INTID,PL031_INTID,VTIMER_INTID,RESERVED_INTIDS,PCIE_INTX_INTIDS,GIC_V2M_INTIDS(anIntidRangehasname,first,lastandcontains).
They also use chapter 04's REGION_ALIGN, GuestAddress and RegionTable. Then check:
cargo test -p vmmpasses your layout tests, andipa_bits_needed(0x6000_0000)is 36 for the reason above, not by luck.- The
mmio-pokerun, from insidelearner/, ends with exit code 3 and the linemacvmm: guest fatal: unhandled MMIO write at 0xc000000 size 4 pc 0x4008…(your PC may differ in the last digits). - Your journal has the Predict entry, written before you read its run.
Stuck? scripts/learner hint 05 gives four hints, from a nudge to the reference file.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 05You should see, as the last line:
CHECKPOINT 05 PASSIts three result lines are, in order: the contract tests against your layout; mmio-poke on your Mac, which expects the guest's storing line, our stop message and exit code 3, and fails if survived appears; and the journal check:
scripts/checkpoint.sh 05checkpoint: implementation <tree>[PASS] contract tests layout_invariants (10 tests)[PASS] runs on your Mac mmio-poke: 2/2 serial markers, exit 3 in 0.06s[INFO] journal not checked (not a learner tree)CHECKPOINT 05 PASSWhat now works: the board is one tested table, the IPA size follows from it, and a store to a hole stops cleanly with exit code 3.
The next chapter starts from this state (the reference at the end of chapter 05).
What's next
Chapter 06 turns to the CPU: which registers must hold what before it runs someone else's code, and how does a register dump expose a fault the guest took inside itself?
Open question
Our default stops at the first touch of a hole. The reference with --unhandled-mmio log (yours, after chapter 07):
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/mmio-poke.bin@0x40080000 --timeout 10 --unhandled-mmio logmmio-poke: storing 0x4d to 0xc000000mmio-poke: survivedmacvmm: warn: [vcpu0] guest: unhandled MMIO write at 0xc000000 size 4 pc 0x40081088 (ignored: --unhandled-mmio log)The guest carried on and printed survived; only our warning knows. From the guest's point of view, what is the difference between "no device here" and "a device that ignores you"?
Spec hunt
- ARM ARM (DDI 0487), register page ESR_EL2, data-abort field DFSC: which code means a permission fault at level 3?
- ARM ARM, register page HPFAR_EL2: which IPA bits does it hold, and for which faults is it valid?
- QEMU's
hw/arm/virt.c,base_memmap[]anda15irqmap[]: which regions did we leave out or resize?