Chapter 11 · Part V
Getting the CPU back: the timer and a bare interrupt
Course progress: chapter 11 is 12 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 10: The Device Tree: the VMM's promise to the guest
A node's parent says
#address-cells = <2>and#size-cells = <1>. The node'sregdescribes two ranges. How many bytes long is theregproperty?Show answer
Each range is 2 + 1 = 3 cells, and a cell is 4 bytes, so one range is 12 bytes and two ranges are 24. The counts come from the parent, not from the node itself.
From chapter 10: The Device Tree: the VMM's promise to the guest
The first eight bytes of a blob are
d0 0d fe ed 00 00 04 f7. What is it, and how big is it?Show answer
A flattened device tree:
0xd00dfeedis its magic number. The next big-endian 32-bit word istotalsize,0x4f7= 1271 bytes. Read little-endian, the same bytes would give0xf7040000, which is why the byte order matters.From chapter 10: The Device Tree: the VMM's promise to the guest
Why can an arm64 kernel not find the PL011 by reading every address in the first 4 GiB and looking for a UART?
Show answer
Nothing on that bus answers "who is here?", and an address with no device behind it does not return a polite "nothing" either: on real hardware it can fault or hang, and in our VMM it is an unhandled access that stops the guest (exit code 3 by default). Even the PrimeCell ID registers help only once you know where the device is. So somebody has to tell the kernel: the DTB.
From chapter 10: The Device Tree: the VMM's promise to the guest
Two nodes each have a
compatibleproperty. How many times does the wordcompatibleappear in the blob, and where?Show answer
Once, in the strings block: property names are stored there once and referred to by offset (
nameoff). The values ("arm,pl011","arm,pl031") are not names; they sit in the structure block after eachFDT_PROPtoken.From chapter 10: The Device Tree: the VMM's promise to the guest
Your writer opens
/cpus, openscpu@0, closes it, and then adds#size-cellsto/cpus. What should happen, and why?Show answer
An error. The format requires every property of a node to come before its first child node, because a reader walks the token stream once and attaches each property to the node it is in. The reference writer refuses it as
PropAfterChildinstead of writing a tree a kernel would misread.From chapter 10: The Device Tree: the VMM's promise to the guest
A guest's first instruction runs with
x0 = 0x40000000. What does an arm64 kernel expect to find there, and what two rules does the address obey?Show answer
The device tree blob: Linux's boot protocol says
x0holds its physical address. It must be 8-byte aligned and the blob at most 2 MiB long, in RAM. Our VMM puts it at the start of RAM.From chapter 10: The Device Tree: the VMM's promise to the guest
You add a node
pl031@9050000to the DTB but no device to the bus. Linux boots. With the default unhandled-access policy, what doesmacvmmprint, and why at that address?Show answer
unhandled MMIO read at 0x9050fe0, then exit code 3. The AMBA bus code reads a PrimeCell's ID registers, at offsets0xFE0to0xFFC, before it picks a driver, so the first access to the phantom device is the ID read. With--unhandled-mmio logthe reads return zero and the device is left unbound ("deferred probe pending").From chapter 10: The Device Tree: the VMM's promise to the guest
A node says
compatible = "arm,pl011", "arm,primecell". Why two strings, and in which order are they tried?Show answer
Most specific first. A kernel looks for a driver that knows
arm,pl011; the second string says what family the device belongs to (an Arm PrimeCell, with ID registers), which a more general driver or bus can use.From chapter 10: The Device Tree: the VMM's promise to the guest
/cpussays#address-cells = <1>and#size-cells = <0>. How long iscpu@0'sreg, and what does it hold?Show answer
4 bytes: one address cell and no size. It holds the CPU's identity (its MPIDR affinity, here 0), which is why the node is called
cpu@0.From chapter 08: System registers, injection, hypercalls and PSCI
A VM exit reports the syndrome
0x62280520. Which instruction stopped the guest, and on which register?Show answer
0x62280520 >> 26 = 0x18: a trappedmsrormrs. The ISS0x280520gives Op0 2, Op2 4, Op1 0, CRn 1, Rt 9, CRm 0, direction 0: anmsr(a write) fromx9to the register at (2, 0, 1, 0, 4), which isOSLAR_EL1.From chapter 08: System registers, injection, hypercalls and PSCI
The guest is at EL1h with
VBAR_EL1 = 0x40080800when your VMM injects an UNDEF. Where does the guest's PC go, and what is inESR_EL1?Show answer
To
0x40080800 + 0x200 = 0x40080a00, the synchronous entry for "current EL, usingSP_EL1".ESR_EL1holds0x02000000: exception class 0 ("unknown reason"), IL 1, ISS 0.From chapter 08: System registers, injection, hypercalls and PSCI
After injecting an UNDEF for an
mrsat0x4008126c, should your VMM also add 4 to the PC it saved inELR_EL1?Show answer
No. An UNDEF is a fault, so
ELR_EL1must hold the address of themrsitself, as real hardware would leave it. Whether to skip the instruction is the guest handler's decision, not the VMM's.From chapter 08: System registers, injection, hypercalls and PSCI
A guest that ran in EL0 makes an access your VMM must answer with an UNDEF. Which vector table offset does the injection use, and why not
0x200?Show answer
0x400: the exception comes from a lower level (EL0) running 64-bit code.0x200is for an exception taken at the same level, EL1, usingSP_EL1.From chapter 08: System registers, injection, hypercalls and PSCI
The guest calls
hvc #0withx0 = 0x84000008. What does it ask for, and what doesmacvmmreturn to the shell?Show answer
0x84000008is a fast, 32-bit-convention call of owner 4 (standard secure service), function 8: PSCISYSTEM_OFF. The VM stops andmacvmmexits with code 0.From chapter 08: System registers, injection, hypercalls and PSCI
A guest calls PSCI
SYSTEM_RESET, andmacvmmwas started with--on-reset exit. What happens, and what changes with the default setting?Show answer
The process ends with exit code 4. With the default
--on-reset reboot, the VMM rebuilds the machine from the same inputs and boots it again, unless the guest resets too often in a short window, which ends with exit code 3.From chapter 08: System registers, injection, hypercalls and PSCI
Your VMM handles a PSCI call that arrived through
smc #0at0x40081378. Where must the guest resume?Show answer
At
0x4008137c. Ansmcis intercepted before it executes, so the saved PC points at it, and the VMM advances it by 4. After anhvc, the PC already points past the call.From chapter 08: System registers, injection, hypercalls and PSCI
The guest reads a system register that no row of your policy table names. What does the reference VMM do, and why that default?
Show answer
It injects an UNDEF, with a rate-limited warning naming the register. A real CPU raises UNDEFINED for a register it does not have; answering 0 would let the guest believe something false without anyone noticing.
From chapter 08: System registers, injection, hypercalls and PSCI
The guest calls
hvc #0withx0 = 0x84000099. What comes back, and in which register?Show answer
NOT_SUPPORTED, -1 (all ones), inx0, with a warning on the VMM's standard error. An unknown function ID is never silent and never a crash.From chapter 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.
Concepts you'll need
Chapters before this one: chapter 10, The Device Tree: the VMM's promise to the guest.
- Core, taught here: interrupts as state (pending, mask, vector); level versus edge; the generic timer (
CNTVCT_EL0,CNTV_CVAL_EL0,CNTV_CTL_EL0,CNTFRQ_EL0) and the counter offset;WFI(closing chapter 01's definition) andWFE; the vtimer, the VTIMER exit and the vCPU's IRQ input; exits per tick as a cost (--stats). - Core, from earlier: the PC after an exit (chapter 02); exit cost and the exit trace (chapter 03); the kick,
hv_vcpus_exitand theCANCELEDexit (chapters 03 and 09); PSTATE's DAIF bits (chapter 06); theExitenum and the exit handler (chapter 07); the vector table (chapter 08); the PL011'sRIS,MISandIMSC, and the stop flag (chapter 09). - Primers (read first):
os-basics(what an interrupt is; why a kernel needs a timer to get the CPU back). - Primers (review):
host-concurrency(a condition variable's timed wait, for the WFI sleep; timer-driven preemption). - Pointers: Linux's Arm timer driver;
mach_absolute_timeand the host timebase (both Asides). - Forward definitions: the interrupt controller (chapter 12). It is defined at first use.
Here is a guest that wants to sleep for 100 milliseconds, ten times. Each round it sets an alarm, then runs wfi, "wait for interrupt", and the CPU idles until something knocks: on a real board, a wire from the timer. Our virtual machine has no such wire yet: nothing between the timer and the CPU, no interrupt controller (the hardware that routes such wires to CPUs; chapter 12). So who wakes the guest, and what does each wake-up cost the monitor you are building, in VM exits?
Predict How many timer-related VM exits (not counting the guest's printing) will ten 100 ms sleeps produce: (a) about zero, because the timer is hardware; (b) about 20 to 30; (c) thousands?
The answer is in "The run", after we count the exits.
This chapter works on rows 6 and 7 of chapter 00's problem ledger: interrupts from devices, and an alarm clock. By its end a guest is woken by its timer, with your virtual machine monitor (VMM) as the wiring; chapter 12 finishes both rows. Sitting A is ideas, in the browser (about 1.5 hours); sitting B is code and measurement at your Mac (about 3 hours).
Write your choice and one sentence of reasoning under ## Predict in learner/journal/11.md (created by scripts/learner start 11, below) before reading on.
Objectives: by the end you can
- (Sitting A) Explain why a kernel needs an alarm that interrupts, not only a counter; name the job of
CNTVCT_EL0,CNTV_CVAL_EL0andCNTV_CTL_EL0; derive the offset ruleCNTVCT = mach_absolute_time() - offset. - (Sitting A) Explain with an example why a level-triggered line is state that cannot be lost while masked, and an edge is an event that needs latching.
- (Sitting B) With no interrupt controller, handle
VTIMER_ACTIVATED: raise the vCPU's IRQ (interrupt request) input, keep the vtimer (the guest's virtual timer) masked, and before every entry raise the IRQ again or, onceCNTV_CTL_EL0shows the timer quiet, drop it and unmask. Observe that the exit arrives even while the guest masks IRQs. - (Sitting B) Handle WFI exits by sleeping the vCPU thread until the alarm's deadline or a stop, and measure idle host CPU under 10% with
--stats. - (Sitting B) Turn exits per second at 10 Hz (ten ticks per second) and 250 Hz into host CPU cost with your chapter 03 number, and compare with the measured cost.
Before you start. From the repository root, run scripts/learner start 11. It copies this chapter's journal to learner/journal/11.md. The code goes into your learner/ workspace, in the files named above each block; the checkpoint tests your crates through the same public names.
Why reading a clock is not enough
Picture a guest kernel with one CPU and an app that runs loop {}. The app never makes a system call, so the kernel never runs again, and a clock it could read does not help. The way out, from the os-basics primer: an alarm that makes the CPU take an interrupt into the kernel. A kernel needs it to preempt a program that would keep the CPU (the host-concurrency primer), to wake a sleeper whose 100 ms are up, and to time out I/O that never answers.
Arm's generic timer: a counter and an alarm
Every Arm CPU core has one, the generic timer. Three registers matter to a guest kernel, plus one that says how fast it ticks:
| Register | What it is | Who writes it |
|---|---|---|
CNTFRQ_EL0 | the counter's frequency in Hz: 24,000,000 as Hypervisor.framework presents it to the guest, so one tick is about 41.7 ns | firmware; here Hypervisor.framework |
CNTVCT_EL0 | the virtual count: a number that goes up by one every tick | nobody; it counts |
CNTV_CVAL_EL0 | the compare value: "wake me when the count reaches this" | the kernel |
CNTV_CTL_EL0 | the control bits: ENABLE (bit 0), IMASK (bit 1, mask the interrupt), ISTATUS (bit 2, read-only: the count has reached the compare value) | the kernel, except ISTATUS |
One counter, one alarm.
The _EL0 suffix means even apps (EL0) may read these if the kernel allows it; the kernel at EL1 can always write them.
The timer raises its interrupt output when ENABLE = 1, IMASK = 0 and ISTATUS = 1. Our test guest arms it like this (guest code, inside the virtual machine):
/// Write `CNTV_CVAL_EL0`.pub fn set_cval(v: u64) { // SAFETY: an EL1-accessible timer register; only arms the comparator. unsafe { asm!("msr cntv_cval_el0, {}", "isb", in(reg) v, options(nostack)) };}/// Write `CNTV_CTL_EL0`.pub fn set_ctl(v: u64) { // SAFETY: an EL1-accessible timer register. unsafe { asm!("msr cntv_ctl_el0, {}", "isb", in(reg) v, options(nostack)) };}/// Read `CNTV_CTL_EL0`.pub fn ctl() -> u64 { let v: u64; // SAFETY: reads a timer register; no side effects. unsafe { asm!("mrs {}, cntv_ctl_el0", out(reg) v, options(nomem, nostack)) }; v}/// Arm the timer `ticks` counter ticks from now, interrupt unmasked. Returns the start count.pub fn arm_in(ticks: u64) -> u64 { let now = crate::cntvct(); set_cval(now.wrapping_add(ticks)); set_ctl(ENABLE); now}For 100 ms it adds CNTFRQ / 10 (2,400,000 ticks). To silence the timer, a kernel clears ENABLE, sets IMASK, or moves the compare value ahead; ours clears ENABLE.
The counter offset
Why "virtual" count? Arm gives every core a physical count and a virtual one, the physical minus an offset that only the hypervisor level (EL2) can set, for exactly this. Hypervisor.framework's hv_vcpu.h states its version: CNTVCT_EL0 = mach_absolute_time() - vtimer_offset, where mach_absolute_time() is the Mac's own tick count and the VMM chooses the offset.
A guest expects its counter to start near zero, as after power-on, and to never go backwards, the same on every CPU. So the offset is the host's count at boot, given to every vCPU before its first run:
/// The virtual-counter offset of a new boot: the host tick count now, so the guest's/// `CNTVCT_EL0 = mach_absolute_time() - offset` starts at 0. `Machine::build` captures it once/// and every vCPU of the boot gets the same value before its first run, so all CPUs agree.pub fn boot_offset() -> u64 { hvf::host::mach_absolute_time()}/// The guest's counter at host tick `mach` under `offset` (modulo 2^64, as the hardware/// subtracts the offset).pub const fn guest_counter(mach: u64, offset: u64) -> u64 { mach.wrapping_sub(offset)}/// The offset that makes the guest's counter read `saved_cntvct` at host tick `mach_now`, so a/// paused or restored guest continues where it stopped and never sees time run backwards/// (the restore rule).pub const fn restore_offset(mach_now: u64, saved_cntvct: u64) -> u64 { mach_now.wrapping_sub(saved_cntvct)}The subtraction wraps around at 2^64, as the hardware's does, so restore_offset, used after a pause or a restored snapshot (chapter 26), works even when the saved count is larger than the host's current one. Every vCPU gets the offset as it is set up (the second call switches on this chapter's no-controller mode; sitting B builds it):
vcpu.reset(setup.boot, setup.vtimer_offset)?;if setup.irqchip == IrqChip::None { vcpu.enable_nogic(setup.vtimer_offset)?;}Give chapter 06's reset the vtimer_offset parameter and closing set_vtimer_offset call it left out. A guest whose first act is to read CNTVCT_EL0, with the reference's offset:
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --timeout 10timer-nogic: first cntvct=133166timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 108 ms oktimer-nogic: interval 1 = 101 ms oktimer-nogic: interval 2 = 101 ms oktimer-nogic: interval 3 = 105 ms oktimer-nogic: interval 4 = 102 ms oktimer-nogic: interval 5 = 104 ms oktimer-nogic: interval 6 = 105 ms oktimer-nogic: interval 7 = 103 ms oktimer-nogic: interval 8 = 105 ms oktimer-nogic: interval 9 = 102 ms oktimer-nogic: irqs=10 stale=302824timer-nogic: 10/10 intervals within 95..150 ms133,166 ticks: 5.5 ms, the time it took to build the machine after the offset was taken. With the offset forced to 0:
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --timeout 10timer-nogic: first cntvct=3583539855220timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 105 ms oktimer-nogic: interval 1 = 105 ms oktimer-nogic: interval 2 = 100 ms oktimer-nogic: interval 3 = 101 ms oktimer-nogic: interval 4 = 101 ms oktimer-nogic: interval 5 = 105 ms oktimer-nogic: interval 6 = 100 ms oktimer-nogic: interval 7 = 105 ms oktimer-nogic: interval 8 = 100 ms oktimer-nogic: interval 9 = 101 ms oktimer-nogic: irqs=10 stale=274782timer-nogic: 10/10 intervals within 95..150 ms3,583,539,855,220 ticks at 24 MHz is about 149,300 seconds, or 41.5 hours: how long this Mac had been awake since it booted (the count pauses during sleep, see the Aside). Journal question 1 asks what that tells a guest.
Aside
On Apple silicon mach_absolute_time also ticks at 24 MHz (mach_timebase_info reports 125/3 ns per tick), but the VMM converts with the timebase instead of assuming it. It does not advance while the Mac sleeps.
An interrupt is state, not a call
It is tempting to picture an interrupt as a function call. This chapter's breaks come from that picture. An interrupt is three pieces of state:
- pending: a source wants attention. For the timer, that is the output above (
ENABLE, notIMASK,ISTATUS). - mask: whether the CPU is listening. That is the I bit of PSTATE (processor state), one of the four DAIF bits from chapter 06.
msr daifclr, #2clears it (the immediate's bits are D, A, I, F from 8 down to 1, so 2 is I);msr daifset, #2sets it. - vector: where the CPU goes. An IRQ (interrupt request, the ordinary kind) taken at EL1 on EL1's own stack enters at
VBAR_EL1 + 0x280(group+0x200, IRQ slot+0x80, chapter 08's table).
The CPU takes the interrupt only when it is pending and unmasked, between two instructions. The handler must make the source stop asking, or the CPU takes it again at once.
That depends on how the source asks. Our timer's output is level-triggered: high for as long as the condition holds. Mask IRQs for an hour and the line is still high when you unmask; it drops only when someone removes the cause.
The other kind is edge-triggered: the source signals one event ("a key was pressed"), and then the signal is gone. If the CPU was not listening, the event is lost, unless something latches it, remembering it until it is handled. You built such a latch: the PL011's RIS remembers that a byte arrived, and MIS (RIS and IMSC combined) is a level output (chapter 09).
The lab plays both kinds against a mask, with and without a latch:
Interrupt lifecycle
See an interrupt as state, not a call: a level line, an edge and a latched edge played against a masked CPU, and, from chapter 12, one interrupt inside the GIC, when the source stops asking early, late or never.
Runs in browserOpen full page: Interrupt lifecycleIf the lab does not load, here is what it shows:
step level line edge, no latch edge, latchedsource raises pending pulse, gone latch set, pendingCPU masked, waits still pending nothing pending still pendingCPU unmasks handler runs nothing happens handler runshandler returns, cause kept runs again at once - runs again at oncehandler clears the cause line drops, done - latch cleared, doneNo interrupt controller: Hypervisor.framework hands us the timer
On a real board the timer's line goes into an interrupt controller, a device that collects every source's line, ranks them and delivers one IRQ to a CPU. Arm's is the GIC (Generic Interrupt Controller), so in our code "nogic" means "no interrupt controller". Here we run without one, in a teaching mode, --irqchip none, hidden from --help because a real kernel expects a controller.
Without a controller, Hypervisor.framework gives the timer to us. It calls the CNTV_* timer the vtimer. When the vtimer raises its output, hv_vcpu_run returns with HV_EXIT_REASON_VTIMER_ACTIVATED, and "the timer is masked automatically" until we clear the mask (the header's words): the framework's own mask, not the guest's IMASK. The vCPU's IRQ input, hv_vcpu_set_pending_interrupt, is "automatically cleared after hv_vcpu_run returns", so we set it "before every hv_vcpu_run".
That makes three masks, with three owners. Keep them apart; the breaks depend on it:
| Mask | Who sets it | What it stops |
|---|---|---|
IMASK, bit 1 of CNTV_CTL_EL0 | the guest kernel | the timer's output, at the timer |
PSTATE.I | the guest CPU (msr daifset) | the CPU taking IRQs |
the vtimer mask (hv_vcpu_set_vtimer_mask) | the framework, at each VTIMER exit; cleared only by our VMM | the timer causing another VTIMER exit |
Three masks, three owners.
So our VMM is the wiring for one line. A source asserts its line when it drives it high. We keep one boolean, our line, up from the VTIMER exit until the guest is done, and copy it into the one-run pending IRQ before every entry.
Derive the rules. A level line unmasked while still high fires again at once, so unmask only once the timer stops asking. The guest silences it with a register write that causes no exit, so we learn of it only by reading CNTV_CTL_EL0 before the next entry:
| Event | Our VMM does | PC afterwards |
|---|---|---|
VTIMER_ACTIVATED exit | raise our line; leave the vtimer masked | unchanged: an asynchronous exit points at the next instruction not yet run (chapter 02) |
| before every entry | our line is up and the timer still asserts: set the pending IRQ for this run. Timer quiet (ENABLE = 0, IMASK = 1 or ISTATUS = 0): drop our line and unmask the vtimer | |
WFI exit, class 0x01 (next section) | if no IRQ is pending, sleep until the alarm's deadline | + 4 |
The whole of our "interrupt controller" for one line.
WFI: idling without burning a core
WFI, wait for interrupt, tells the CPU "nothing to do until something happens". Its sibling WFE, wait for event, is a lighter wait used in spin locks (locks a waiting core polls in a loop), ended by an interrupt or an event such as another core releasing the lock. The fine print to chapter 01's definition: the Arm Architecture Reference Manual (the ARM ARM) lets either end early for no visible reason, so a guest always re-checks its condition after a WFI.
Here, with no controller, a guest's WFI reaches us as an exit with exception class (EC) 0x01; a two-bit syndrome field, TI, says which wait it was: 0 for WFI, 1 for WFE (2 and 3 are their timed variants, WFIT and WFET). It leaves the PC at the WFI, so we add 4 when we resume (chapter 02's rule). In between, we could resume at once (correct, but an idle guest would keep a host core busy), or sleep the vCPU's thread until the alarm is due. In host ticks, CNTVCT = host − offset reaches CVAL when host = CVAL + offset.
While our thread sleeps, the vCPU is outside hv_vcpu_run, so we are the alarm clock; the VTIMER exit comes as soon as we re-enter.
The timeline lab puts one round of the test guest on one time axis:
Timer timeline
Step through one 100 ms sleep of chapter 11's test guest with no interrupt controller: the counter and its offset, the alarm, the WFI sleep, the VTIMER exit and the three masks, on one time axis.
Runs in browserOpen full page: Timer timelineLoading the lab. If nothing appears, your browser may have JavaScript turned off or the lab failed to load.
If the lab does not load, this is one round, in order:
guest arms CVAL = now + 2,400,000 ticks, ENABLE = 1; unmasks IRQs; runs WFIexit 1 WFI (class 0x01), PC at the wfi -> VMM sleeps until CVAL + offset ... about 100 ms of nothing, on both sides ...VMM wakes, PC + 4, enters the guestexit 2 VTIMER_ACTIVATED, PC unchanged -> VMM raises our line (vtimer stays masked)VMM before entry: timer still asserts -> pending IRQ for this runguest takes the IRQ at VBAR_EL1 + 0x280, handler clears ENABLE, returnsexit 3 (sitting B explains this one) -> before entry: timer quiet: drop line, unmaskguest prints the interval, arms the next roundThree exits per round. Sitting B finds out why there is a third.
Good place to stop. Sitting B needs your Mac, your learner workspace and about 3 hours.
The rules, as functions you can test
Sitting A's table becomes small functions, testable on the host. Create learner/crates/vmm/src/timer.rs and declare it in your lib.rs. The contract tests use: guest_counter, restore_offset and boot_offset (above); cntv_ctl (a module of the three bit constants) and timer_asserted; NoGicTimer with new, line, vtimer_activated, before_entry and irq_pending; nogic_wfi_wait, its answer WfiWait (Wake or Sleep(Duration)) and NOGIC_WFI_SLICE; and hvf::host::Timebase. The register bits and the "does it assert" rule:
/// `CNTV_CTL_EL0` bits (ARM ARM D19.11.15).pub mod cntv_ctl { pub const ENABLE: u64 = 1 << 0; pub const IMASK: u64 = 1 << 1; pub const ISTATUS: u64 = 1 << 2;}/// True if the timer is asserting its interrupt: enabled, not masked, condition met.pub const fn timer_asserted(ctl: u64) -> bool { ctl & cntv_ctl::ENABLE != 0 && ctl & cntv_ctl::IMASK == 0 && ctl & cntv_ctl::ISTATUS != 0}Our line. First the answer the rule gives and the state it keeps:
/// What to do before entering the guest in the no-GIC mode.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct EntryAction { /// Call `hv_vcpu_set_vtimer_mask(false)`. pub unmask: bool, /// Call `hv_vcpu_set_pending_interrupt(IRQ, true)` for this run. pub assert_irq: bool,}/// One vCPU's interrupt line in the no-GIC mode: raised by a VTIMER exit, re-asserted before/// each entry, dropped (and the vtimer unmasked) once the guest's timer stops asserting.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct NoGicTimer { /// The boot's counter offset (for WFI deadlines). pub offset: u64, /// The host timebase (`None` only if the kernel would not say). pub timebase: Option<hvf::host::Timebase>, /// The VMM's model of the vCPU's IRQ input: raised by `VTIMER_ACTIVATED`, dropped when the /// guest has handled or disarmed the timer. line: bool,}impl NoGicTimer { pub fn new(offset: u64, timebase: Option<hvf::host::Timebase>) -> NoGicTimer { NoGicTimer { offset, timebase, line: false, } }Then the rule. before_entry is the table's middle row; masked is the framework's vtimer mask (not IMASK):
/// Is the IRQ line up?pub fn line(&self) -> bool { self.line}/// `VTIMER_ACTIVATED`: the framework masked the vtimer; raise the line.pub fn vtimer_activated(&mut self) { self.line = true;}/// The before-entry rule, given whether the framework currently masks the vtimer and the/// guest's `CNTV_CTL`: drop the line and unmask once the timer no longer asserts, otherwise/// keep re-asserting the (per-run) pending IRQ.pub fn before_entry(&mut self, masked: bool, ctl: u64) -> EntryAction { let mut a = EntryAction::default(); if masked && !timer_asserted(ctl) { self.line = false; a.unmask = true; } a.assert_irq = self.line; a}/// Whether an IRQ is pending for a WFI: the line is up and the timer still asserts it.pub fn irq_pending(&self, ctl: u64) -> bool { self.line && timer_asserted(ctl)}The WFI deadline. Both registers are guest-written, so every case ends in a bounded answer. We never sleep more than 100 ms at a time (a slice), then re-read the guest's timer and the stop flag, so a hostile or missing deadline cannot hold up --timeout:
/// How long a WFI may sleep in the no-GIC mode, from the guest's `CNTV_CTL` and `CNTV_CVAL`,/// the boot's counter `offset`, the host tick count `now` and the host timebase. Both registers/// are guest-written, so every input, however hostile, ends in a bounded answer.////// - timer disabled or masked: there is no deadline; sleep one slice (only a stop ends it);/// - condition already met, or `CVAL` in the past: wake;/// - deadline beyond `u64::MAX` host ticks, or an unknown timebase: sleep one slice;/// - otherwise sleep until the deadline, at most one slice.pub fn nogic_wfi_wait( ctl: u64, cval: u64, offset: u64, now: u64, timebase: Option<hvf::host::Timebase>,) -> WfiWait { if ctl & cntv_ctl::ENABLE == 0 || ctl & cntv_ctl::IMASK != 0 { return WfiWait::Sleep(NOGIC_WFI_SLICE); } if ctl & cntv_ctl::ISTATUS != 0 { return WfiWait::Wake; } // CNTVCT = mach - offset reaches CVAL at host tick CVAL + offset. let Some(deadline) = cval.checked_add(offset) else { return WfiWait::Sleep(NOGIC_WFI_SLICE); }; let Some(left) = deadline.checked_sub(now).filter(|t| *t > 0) else { return WfiWait::Wake; }; match timebase { Some(tb) => { let d = Duration::from_nanos(tb.ticks_to_nanos(left)); WfiWait::Sleep(d.min(NOGIC_WFI_SLICE)) } None => WfiWait::Sleep(NOGIC_WFI_SLICE), }}Ticks become nanoseconds here, in learner/crates/hvf/src/host.rs:
/// The host tick counter (`mach_absolute_time`). Monotonic; never fails.pub fn mach_absolute_time() -> u64 { // SAFETY: no arguments, no preconditions; it only reads the system clock. unsafe { ffi::mach_absolute_time() }}/// `mach_timebase_info`: `nanoseconds = ticks * numer / denom`.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct Timebase { pub numer: u32, pub denom: u32,}impl Timebase { /// Convert host ticks to nanoseconds, saturating instead of overflowing. pub fn ticks_to_nanos(self, ticks: u64) -> u64 { if self.denom == 0 { return 0; } let n = u128::from(ticks) * u128::from(self.numer) / u128::from(self.denom); u64::try_from(n).unwrap_or(u64::MAX) }}/// The host timebase. `None` if the kernel call fails (it does not in practice) or reports a/// zero denominator, which would make every conversion meaningless.pub fn timebase() -> Option<Timebase> { let mut info = ffi::mach_timebase_info_data_t::default(); // SAFETY: `info` is a live, writable `mach_timebase_info_data_t` with the C layout // (checked by `check-ffi.sh`). let kr = unsafe { ffi::mach_timebase_info(&mut info) }; (kr == 0 && info.denom != 0).then_some(Timebase { numer: info.numer, denom: info.denom, })}Test them in a #[cfg(test)] mod tests in your timer.rs: a past compare value wakes, u64::MAX and a disabled timer sleep one slice, and our line follows the table. From inside learner/:
cargo test -p vmm --lib timer::The reference's tests (line_kicker_fires_once_and_disarms tests a piece you meet in "The surprise"; your count may differ):
cargo test -p vmm --lib timer::running 5 teststest timer::tests::boot_counter_starts_near_zero ... oktest timer::tests::nogic_line_follows_the_table ... oktest timer::tests::restore_offset_keeps_the_counter_monotonic ... oktest timer::tests::nogic_wfi_deadline ... oktest timer::tests::line_kicker_fires_once_and_disarms ... oktest result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 145 filtered out; finished in 0.29s Blocking waiting for file lock on package cache Compiling vmm v0.1.0 (<tree>/crates/vmm) Finished `test` profile [unoptimized + debuginfo] target(s) in 0.88s Running unittests src/lib.rs (target/debug/deps/vmm-53adcdad9026fed4)Security
The guest chooses CNTV_CVAL_EL0, say u64::MAX, so CVAL + offset can overflow. A naive sleep(cval + offset - now) would panic, or sleep for centuries and hold up --timeout, Ctrl-A x and SIGTERM. Hence checked_add, checked_sub and the slice. The mode itself is fenced: --irqchip none is refused (exit code 2) for anything but a test guest on one vCPU.
/// The `--irqchip none` restriction: the teaching mode exists only for our own test guests/// on one vCPU. A real operating system expects an interrupt controller, so anything else/// is refused with exit code 2 before any Hypervisor.framework call. `test_guest` says/// whether the loaded bytes are one of our test guests.pub fn validate_irqchip(&self, test_guest: bool) -> Result<()> { if self.irqchip == IrqChip::None && (!test_guest || self.cpus != 1) { return Err(Error::Config(IRQCHIP_NONE_RESTRICTION.into())); } Ok(())}Declaring the vtimer and IRQ calls
The headers, as in chapter 01:
ls "$(xcrun --show-sdk-path)/System/Library/Frameworks/Hypervisor.framework/Headers/"From hv_vcpu.h and hv_vcpu_types.h, declare in learner/crates/hvf/src/ffi.rs, checking each line against the header, the interrupt type, the pending-interrupt pair and the vtimer calls:
/// `hv_interrupt_type_t`: the vCPU's IRQ/FIQ lines (only without an in-kernel GIC).pub type hv_interrupt_type_t = u32;pub const HV_INTERRUPT_TYPE_IRQ: hv_interrupt_type_t = 0;pub const HV_INTERRUPT_TYPE_FIQ: hv_interrupt_type_t = 1;pub fn hv_vcpu_get_pending_interrupt( vcpu: hv_vcpu_t, type_: hv_interrupt_type_t, pending: *mut bool,) -> hv_return_t;pub fn hv_vcpu_set_pending_interrupt( vcpu: hv_vcpu_t, type_: hv_interrupt_type_t, pending: bool,) -> hv_return_t;pub fn hv_vcpu_get_vtimer_mask(vcpu: hv_vcpu_t, vtimer_is_masked: *mut bool) -> hv_return_t;pub fn hv_vcpu_set_vtimer_mask(vcpu: hv_vcpu_t, vtimer_is_masked: bool) -> hv_return_t;pub fn hv_vcpu_get_vtimer_offset(vcpu: hv_vcpu_t, vtimer_offset: *mut u64) -> hv_return_t;pub fn hv_vcpu_set_vtimer_offset(vcpu: hv_vcpu_t, vtimer_offset: u64) -> hv_return_t;Three more calls: the host clock and its timebase (mach/mach_time.h, in the C library every program links) and the vCPU's run time (hv_vcpu.h):
/// `mach_timebase_info_data_t` (`mach/mach_time.h`): ticks × numer / denom = nanoseconds.#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct mach_timebase_info_data_t { pub numer: u32, pub denom: u32,}/// `mach/mach_time.h`: the host tick counter that the guest's CNTVCT_EL0 follows/// (`CNTVCT = mach_absolute_time() - vtimer_offset`, `hv_vcpu.h`).pub fn mach_absolute_time() -> u64;/// `mach/mach_time.h`. Returns a `kern_return_t`.pub fn mach_timebase_info(info: *mut mach_timebase_info_data_t) -> c_int;pub fn hv_vcpu_get_exec_time(vcpu: hv_vcpu_t, time: *mut u64) -> hv_return_t;The safe wrappers follow chapter 02's pattern. The getters use get_via_out!, a small macro that wraps a "get through an out-pointer" call with its // SAFETY: comment:
/// Generate an owner-thread getter that reads one value through an out-pointer.macro_rules! get_via_out { ($(#[$m:meta])* $fname:ident, $call:ident, $ty:ty, $($arg:expr),*) => { $(#[$m])* pub fn $fname(&self) -> Result<$ty, CallError> { let mut v: $ty = Default::default(); // SAFETY: called on the owning thread (`Vcpu` is `!Send`); `v` is a live local of // the C out-parameter's type. check(stringify!($call), unsafe { ffi::$call(self.id, $($arg,)* &mut v) })?; Ok(v) } };}get_via_out!( /// `CNTVCT_EL0 = mach_absolute_time() - offset` for this vCPU. vtimer_offset, hv_vcpu_get_vtimer_offset, u64,);/// Set the virtual counter offset (the same value on every vCPU, before its first run).pub fn set_vtimer_offset(&self, offset: u64) -> Result<(), CallError> { // SAFETY: owning thread; plain values. check("hv_vcpu_set_vtimer_offset", unsafe { ffi::hv_vcpu_set_vtimer_offset(self.id, offset) })}get_via_out!( /// Whether the framework currently masks the vtimer (no-GIC mode; it sets the mask /// itself on every VTIMER exit). vtimer_mask, hv_vcpu_get_vtimer_mask, bool,);/// Mask or unmask the vtimer exit (no-GIC mode).pub fn set_vtimer_mask(&self, masked: bool) -> Result<(), CallError> { // SAFETY: owning thread; plain values. check("hv_vcpu_set_vtimer_mask", unsafe { ffi::hv_vcpu_set_vtimer_mask(self.id, masked) })}/// Assert or clear the IRQ/FIQ line; auto-cleared after each `run` (`hv_vcpu.h`).pub fn set_pending_interrupt(&self, fiq: bool, pending: bool) -> Result<(), CallError> { let ty = if fiq { ffi::HV_INTERRUPT_TYPE_FIQ } else { ffi::HV_INTERRUPT_TYPE_IRQ }; // SAFETY: owning thread; plain values. check("hv_vcpu_set_pending_interrupt", unsafe { ffi::hv_vcpu_set_pending_interrupt(self.id, ty, pending) })}Build it from inside learner/:
cargo build -p hvfcargo build -p hvf Compiling hvf v0.1.0 (<tree>/crates/hvf) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19sWiring the rules into the vCPU
Now the glue in learner/crates/vmm/src/vcpu/. Before every entry, read the vtimer mask and CNTV_CTL_EL0, ask the rule, and act. set_pending_interrupt(false, true) reads "not FIQ (fast interrupt request, the other kind), so IRQ; pending". Ignore the final nogic_kick block until the next section:
/// The no-GIC before-entry rule: drop the line and unmask the vtimer once the guest handled/// or disarmed it; while the line is up, assert the IRQ for this run (the framework clears/// it after every run, `hv_vcpu.h`) and arm the kick that ends the run within/// `timer::NOGIC_LINE_RECHECK`: the guest silences the timer without an exit, and the/// pending IRQ would otherwise outlive it for the whole run.fn nogic_before_entry(&mut self) -> Result<()> { let Some(t) = self.nogic.as_mut() else { return Ok(()); }; let masked = self.inner.vtimer_mask().map_err(hv("get vtimer mask"))?; let ctl = if masked || t.line() { self.inner .get_sys_reg(SysReg::CNTV_CTL_EL0) .map_err(hv("get CNTV_CTL_EL0"))? } else { 0 }; let action = t.before_entry(masked, ctl); if action.unmask { self.inner .set_vtimer_mask(false) .map_err(hv("unmask vtimer"))?; } if action.assert_irq { // Verified on a real Mac: this call succeeds when there is no GIC. self.inner .set_pending_interrupt(false, true) .map_err(hv("set pending IRQ"))?; } if let Some(k) = &self.nogic_kick { if action.assert_irq { k.arm(NOGIC_LINE_RECHECK); } else { k.disarm(); } } Ok(())}/// Enter the guest until the next exit (in the no-GIC mode, after the before-entry rule).pub fn run(&mut self) -> Result<hvf::VcpuExit> { self.nogic_before_entry()?; self.inner.run().map_err(hv("run vCPU"))}Two new arms in chapter 07's exit handler:
Exit::Wfx { .. } if regs.nogic().is_some() => nogic_wfi(regs, env),Exit::VtimerActivated if regs.nogic().is_some() => { // The framework has masked the vtimer; the line stays up until the guest handles // or disarms the timer (`Vcpu::run`'s before-entry rule). if let Some(t) = regs.nogic() { t.vtimer_activated(); } Ok(ExitAction::Resume { advance_pc: false })}The sleep re-reads the guest's registers every slice and ends at once on a stop:
/// A WFI in the `--irqchip none` mode: if no IRQ is pending, sleep until/// the guest's `CNTV_CVAL` deadline, in slices of at most `timer::NOGIC_WFI_SLICE`, each one/// woken early by a stop, so a guest that never arms its timer cannot hold up `--timeout` or a/// quit. `CNTV_CTL`/`CNTV_CVAL` are re-read every slice (they are guest-controlled; their/// handling is total, `timer::nogic_wfi_wait`). Then step over the WFI.pub fn nogic_wfi(regs: &mut dyn VcpuRegs, env: &ExitEnv<'_>) -> Result<ExitAction> { loop { if env.ctl.is_stopping() { break; } let ctl = regs.sys_reg(SysReg::CNTV_CTL_EL0)?; let cval = regs.sys_reg(SysReg::CNTV_CVAL_EL0)?; let Some(t) = regs.nogic() else { break }; if t.irq_pending(ctl) { break; // the pending IRQ ends the WFI at once } let (offset, tb) = (t.offset, t.timebase); let now = hvf::host::mach_absolute_time(); match timer::nogic_wfi_wait(ctl, cval, offset, now, tb) { WfiWait::Wake => break, WfiWait::Sleep(d) => { if env.ctl.sleep_unless_stopped(d) { break; } } } } Ok(ExitAction::Resume { advance_pc: true })}It is the host-concurrency primer's timed wait, on the condition variable a stop notifies, checking the stop under the lock:
/// Sleep up to `d` on this VM's condition variable, waking early when a stop is requested/// (the no-GIC WFI sleep: bounded by the caller's slice and never able to delay a stop)./// Returns true if the VM is stopping.pub fn sleep_unless_stopped(&self, d: Duration) -> bool { let slot = lock(&self.reason); if slot.is_some() || self.is_stopping() { return true; } let slot = match self.changed.wait_timeout(slot, d) { Ok((guard, _)) => guard, Err(poisoned) => poisoned.into_inner().0, }; slot.is_some() || self.is_stopping()}The surprise: a pending IRQ outlives the guest's answer
Sitting A's table has a gap. The pending IRQ we set stays pending for the whole hv_vcpu_run. The guest's handler clears ENABLE and returns, but that caused no exit, so we could not drop our line, and the CPU takes the same IRQ again and again. The reference with the fix below removed:
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0macvmm: timeout: the guest was still running after --timeout 10smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=53 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 1, wfx 1, total 56: canceled 1, vtimer 1, wfx 1, hvc 53macvmm: stats: vcpu0 time: exec 9.819 s, wfi n/amacvmm: stats: host cpu 9.846 s over 10.004 s wall (99%)macvmm: stats: rlimit core=0 nofile=1048576After its first tick the guest made no progress, yet exec says it ran 9.8 of ten seconds, re-taking an interrupt it had handled: an interrupt storm, from a level line nobody lowered.
A real interrupt controller marks a taken interrupt active, so it is not taken again, until the guest says it is done (chapter 12). We have neither, so we bound the damage: while our line is up, a helper thread forces the vCPU out after 1 ms with chapter 09's kick (hv_vcpus_exit, a CANCELED exit), and the before-entry rule then drops our line. LineKicker is plumbing: copy LineKicker, the small types it uses (KickState, KickShared), kicker_loop and NOGIC_LINE_RECHECK (1 ms) from ../crates/vmm/src/timer.rs, and read them:
/// A one-shot deadline on a helper thread: [`LineKicker::arm`] makes `fire` run once, `after`/// from now, unless [`LineKicker::disarm`] comes first. In the no-GIC mode `fire` is/// `hv_vcpus_exit` for the vCPU, so a stale pending IRQ lasts at most one/// [`NOGIC_LINE_RECHECK`]: the guest silences its timer without an exit, and only an exit lets/// us drop the line. A kick that lands while the vCPU is outside `hv_vcpu_run` is sticky and/// costs one spurious `CANCELED` exit, which the run loop already tolerates (verified on a real/// Mac). Dropping the kicker stops and joins the thread.#[derive(Debug)]pub struct LineKicker { shared: Arc<KickShared>, thread: Option<JoinHandle<()>>,}impl LineKicker { /// Start the helper thread (named `name`); `fire` runs on it. pub fn spawn<F>(name: String, fire: F) -> std::io::Result<LineKicker> where F: Fn() + Send + 'static, { let shared = Arc::new(KickShared::default()); let sh = Arc::clone(&shared); let thread = std::thread::Builder::new() .name(name) .spawn(move || kicker_loop(&sh, &fire))?; Ok(LineKicker { shared, thread: Some(thread), }) } /// Fire `after` from now. An earlier pending deadline is kept (the line has been up since /// then), so re-arming on every entry cannot postpone the kick forever. pub fn arm(&self, after: Duration) { let now = Instant::now(); let at = now.checked_add(after).unwrap_or(now); let mut st = lock(&self.shared.state); if st.at.is_none() { st.at = Some(at); self.shared.cv.notify_one(); } } /// Cancel a pending deadline (the line dropped). pub fn disarm(&self) { lock(&self.shared.state).at = None; }}Each vCPU in this mode gets its line and its kicker, whose kick is hv_vcpus_exit on this vCPU's handle:
/// Switch this vCPU to the no-GIC teaching mode (`--irqchip none`): the VMM delivers the/// timer interrupt itself (`timer.rs` module docs). Call before the first run. Starts the/// helper thread that bounds a stale pending IRQ (`timer::LineKicker`).pub fn enable_nogic(&mut self, offset: u64) -> Result<()> { let h = self.inner.handle(); let kick = LineKicker::spawn(format!("vcpu{}-irqkick", self.index), move || { // A stale handle after the vCPU is gone is harmless (`hvf::vcpus_exit` docs); the // kicker is joined before the vCPU is destroyed anyway. let _ = hvf::vcpus_exit(&[h]); }) .map_err(|_| Error::Internal("cannot spawn the no-GIC line kicker thread"))?; self.nogic_kick = Some(kick); self.nogic = Some(NoGicTimer::new(offset, hvf::host::timebase())); Ok(())}Until the kick the guest still sees the stale pending IRQ, so its handler tolerates finding the timer quiet, and counts those as stale:
static FIRED_AT: AtomicU64 = AtomicU64::new(0);static IRQS: AtomicU32 = AtomicU32::new(0);static STALE: AtomicU32 = AtomicU32::new(0);fn on_irq(_frame: &mut ExceptionFrame) { // No PSTATE games: return as taken. A stale re-take finds the timer quiet: count it only. let ctl = timer::ctl(); if ctl & timer::ENABLE != 0 && ctl & timer::ISTATUS != 0 { timer::set_ctl(0); FIRED_AT.store(guest::cntvct(), Ordering::Relaxed); bump(&IRQS); } else { bump(&STALE); }}The guest and the count
The guest unmasks IRQs only around its WFI:
/// Unmask IRQs, wait in WFI, mask them again. A pending interrupt is taken between the/// unmask and the re-mask, so the handler has run (or WFI woke spuriously) when this returns.pub fn wait_for_interrupt() { // SAFETY: changes only PSTATE.I and waits; the handler that may run in between is ours, // and `clobber_abi("C")` tells the compiler every caller-saved register may change. unsafe { asm!( "msr daifclr, #2", "wfi", "msr daifset, #2", clobber_abi("C") ) };}and measures ten sleeps with the counter:
let mut ok = 0;for i in 0..10 { FIRED_AT.store(0, Ordering::Relaxed); let start = timer::arm_in(freq / 10); while FIRED_AT.load(Ordering::Relaxed) == 0 { timer::wait_for_interrupt(); } let ms = timer::ticks_to_ms(FIRED_AT.load(Ordering::Relaxed).wrapping_sub(start), freq); let good = (95..150).contains(&ms); if good { ok += 1; } println!( "timer-nogic: interval {i} = {ms} ms {}", if good { "ok" } else { "OUT OF RANGE" } );}To count without a trace, the VMM gets --stats, in a new learner/crates/vmm/src/stats.rs. Exits by kind: put back the log.stats line chapter 07's run loop left out, which counts each decoded Exit by kind. exec, the guest's run time: hv_vcpu_get_exec_time, in host ticks, read when the vCPU thread ends:
get_via_out!( /// Cumulative guest run time in mach ticks. exec_time, hv_vcpu_get_exec_time, u64,);let to_ns = |ticks: u64| hvf::host::timebase().map(|tb| tb.ticks_to_nanos(ticks));lock(setup.stats).push(VcpuStats { index, exits: log.stats.clone(), exec_ns: vcpu.exec_time().ok().and_then(to_ns), wfi_ns: vcpu.wfi_time().and_then(to_ns),});Host CPU: the process's user plus system time from getrusage, before and after the run, against the wall clock:
/// `getrusage(RUSAGE_SELF)`: user + system CPU time of the whole process (every thread,/// including the vCPU threads while they are inside `hv_vcpu_run`). `None` if the call fails.pub fn process_cpu_time() -> Option<std::time::Duration> { // SAFETY: an all-zero `struct rusage` is a valid value of that plain-data C struct. let mut ru: libc::rusage = unsafe { core::mem::zeroed() }; // SAFETY: `ru` is a live, writable `struct rusage`; `RUSAGE_SELF` is a valid selector. if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut ru) } != 0 { return None; } let tv = |t: libc::timeval| { let secs = u64::try_from(t.tv_sec).ok()?; let micros = u32::try_from(t.tv_usec).ok()?; Some(std::time::Duration::from_secs(secs) + std::time::Duration::from_micros(micros.into())) }; Some(tv(ru.ru_utime)? + tv(ru.ru_stime)?)}let cpu0 = hvf::host::process_cpu_time();let t0 = Instant::now();let reason = manager::run_vcpus(&self.vm, &setup, &env, &obs, deadline);let wall = t0.elapsed();let cpu1 = hvf::host::process_cpu_time();drop(attached);self.serial_input.set_hook(None);if self.stats { let mut vcpus = crate::sync::lock(&per_vcpu).clone(); vcpus.sort_by_key(|v| v.index); let stats = BootStats { vcpus, wall, host_cpu: cpu0.zip(cpu1).map(|(a, b)| b.saturating_sub(a)), };The report prints them:
/// The `--stats` lines (without the `macvmm: stats: ` prefix): numbers and fixed names/// only, never guest-chosen text. `wfi` reads `n/a` when the framework does not report it/// (no in-kernel GIC):/// ```text/// vcpu0 exits: vtimer 0, wfx 0, total 41: hvc 38, data abort 3/// vcpu0 time: exec 0.006 s, wfi 1.010 s/// host cpu 0.012 s over 1.031 s wall (2%)/// ```pub fn report(&self) -> Vec<String> { let mut out = Vec::new(); for v in &self.vcpus { out.push(format!( "vcpu{} exits: vtimer {}, wfx {}, {}", v.index, v.exits.kind("vtimer"), v.exits.kind("wfx"), v.exits.summary() )); out.push(format!( "vcpu{} time: exec {}, wfi {}", v.index, ns(v.exec_ns), ns(v.wfi_ns) )); } out.push(match (self.host_cpu, self.host_cpu_percent()) { (Some(cpu), Some(p)) => format!( "host cpu {} over {} wall ({p}%)", secs(cpu), secs(self.wall) ), _ => format!("host cpu n/a over {} wall", secs(self.wall)), }); out}The run
Build the test guests if you have not since chapter 03 (scripts/build-guests.sh from the repository root), then, from inside learner/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --irqchip none --mem 64M --raw $G/timer-nogic.bin@0x40080000 --stats --trace exits:t.jsonl:all --timeout 10Check your Predict entry first. The reference's run ({guests} and {out} stand for directories):
macvmm run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --trace exits:{out}/t.jsonl:all --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 102 ms oktimer-nogic: interval 1 = 110 ms oktimer-nogic: interval 2 = 102 ms oktimer-nogic: interval 3 = 102 ms oktimer-nogic: interval 4 = 106 ms oktimer-nogic: interval 5 = 107 ms oktimer-nogic: interval 6 = 109 ms oktimer-nogic: interval 7 = 110 ms oktimer-nogic: interval 8 = 101 ms oktimer-nogic: interval 9 = 101 ms oktimer-nogic: irqs=10 stale=362066timer-nogic: 10/10 intervals within 95..150 msmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=494 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 10, wfx 10, total 525: canceled 10, vtimer 10, wfx 10, hvc 495macvmm: stats: vcpu0 time: exec 0.016 s, wfi n/amacvmm: stats: host cpu 0.020 s over 1.079 s wall (2%)macvmm: stats: rlimit core=0 nofile=1048576Ten intervals of 100 to 110 ms. The exits: line says total 525, but 495 are hvc: printing, one per character, and the power-off. The timer's own are vtimer 10, wfx 10, canceled 10: thirty, three per round, answer (b). pfr0.gic=0 is the guest reading its CPU feature register ID_AA64PFR0_EL1: no GIC interface, because there is no controller.
stale=362066: before each kick the guest re-took the stale IRQ about 36,000 times. Harmless at 10 Hz; at 250 Hz it is the whole story.
wfi n/a is expected: the framework reports WFI waiting only with its own interrupt controller (chapter 12). Ignore the serial_* line (bytes printed) and the rlimit line (chapter 25).
The trace, with the printing filtered out, shows the timer exits in order:
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --trace exits:t.jsonl:all --timeout 10 > /dev/null; grep -v DEBUG_PUTC t.jsonl | head -7{"t_ns":1065541,"vcpu":0,"reason":"exception","ec":"0x1","pc":"0x40081188"}{"t_ns":106099666,"vcpu":0,"reason":"vtimer","pc":"0x4008118c"}{"t_ns":107359083,"vcpu":0,"reason":"canceled","pc":"0x40081044"}{"t_ns":107512291,"vcpu":0,"reason":"exception","ec":"0x1","pc":"0x40081188"}{"t_ns":212565000,"vcpu":0,"reason":"vtimer","pc":"0x4008118c"}{"t_ns":213832875,"vcpu":0,"reason":"canceled","pc":"0x4008118c"}{"t_ns":214044250,"vcpu":0,"reason":"exception","ec":"0x1","pc":"0x40081188"}Second round: a WFI exit at 107.5 ms with the PC at the wfi (0x40081188); 105 ms later, the VTIMER exit with the PC at the next instruction; 1.3 ms after that, the kick's canceled. Sitting A's timeline, with real times.
Level behaviour, seen from the outside
First, journal question 3: what if the timer fires while the guest has IRQs masked? We changed the guest so that, in its first round only, it spins for 300 ms with PSTATE.I still set, then unmasks for one instruction:
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --trace exits:t.jsonl:all --timeout 10; grep -m 3 -v DEBUG_PUTC t.jsonltimer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 300 ms OUT OF RANGEtimer-nogic: interval 1 = 103 ms oktimer-nogic: interval 2 = 104 ms oktimer-nogic: interval 3 = 105 ms oktimer-nogic: interval 4 = 101 ms oktimer-nogic: interval 5 = 104 ms oktimer-nogic: interval 6 = 105 ms oktimer-nogic: interval 7 = 105 ms oktimer-nogic: interval 8 = 105 ms oktimer-nogic: interval 9 = 105 ms oktimer-nogic: irqs=10 stale=253683timer-nogic: 9/10 intervals within 95..150 ms{"t_ns":101876000,"vcpu":0,"reason":"vtimer","pc":"0x40081184"}{"t_ns":103169500,"vcpu":0,"reason":"canceled","pc":"0x40081188"}{"t_ns":104441458,"vcpu":0,"reason":"canceled","pc":"0x40081188"}macvmm: guest exit code 1macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=503 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 10, wfx 9, total 691: canceled 168, vtimer 10, wfx 9, hvc 504macvmm: stats: vcpu0 time: exec 0.307 s, wfi n/amacvmm: stats: host cpu 0.316 s over 1.254 s wall (26%)macvmm: stats: rlimit core=0 nofile=1048576The VTIMER exit came at 101.9 ms, while the guest spun with IRQs masked: the exit does not wait for the guest. Then a canceled every 1.3 ms, as each entry set the pending IRQ and armed the kick.
Interval 0 reads 300 ms (exit code 6), because the handler ran only when the guest unmasked. For 200 ms the interrupt existed only as state: ISTATUS, our line, and the pending IRQ. (Round 0 had no WFI exit: the handler ran during the one-instruction unmask, so FIRED_AT was already set and the loop never called wait_for_interrupt, hence wfx 9.)
To repeat it: in round 0 of guests/timer-nogic/main.rs, after arm_in, spin until guest::cntvct() passes start + 3 * freq / 10, then run msr daifclr, #2, isb, msr daifset, #2 once; run scripts/build-guests.sh, and undo it afterwards.
Try it
In your nogic_before_entry, unmask the vtimer whenever it is masked, instead of waiting until the timer stops asserting (if action.unmask || masked). Predict the vtimer count after ten seconds, then compare with our run in the next block. Look at what the guest printed.
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0macvmm: timeout: the guest was still running after --timeout 10smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=53 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 8379518, wfx 1, total 8387052: canceled 7480, vtimer 8379518, wfx 1, hvc 53macvmm: stats: vcpu0 time: exec 2.798 s, wfi n/amacvmm: stats: host cpu 9.500 s over 10.004 s wall (95%)macvmm: stats: rlimit core=0 nofile=10485768,379,518 VTIMER exits in ten seconds, and no interval printed: unmasked while ISTATUS = 1, the vtimer exits again at once. That is why the header says to unmask only once the guest "has completed servicing" the interrupt.
What a tick costs
Now turn exits into cost, with your own chapter 03 figure from learner/journal/03.md; ours was 1.43 µs per exit. At 10 Hz, 30 timer exits per second cost about 43 µs of host CPU per second: 0.004% of one core. The run measured 2% (0.020 s over 1.08 s): the timer exits are a sliver; the rest is starting the VMM, 495 printing exits and the stale re-takes before each kick. Linux commonly ticks at 250 Hz.
Predict At 250 Hz, a tick every 4 ms, how many timer exits per second do you expect, how much host CPU should they cost by your exit-bench arithmetic, and will the guest still keep good time?
We ran the guest changed to 250 rounds of 4 ms each, printing one summary: total time, ticks per second achieved, and the mean, smallest and largest interval.
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: 250 Hz asked: 250 ticks took 1656 ms, 150 ticks per secondtimer-nogic: interval mean 5138 us, min 4031 us, max 12355 ustimer-nogic: irqs=250 stale=8580120timer-nogic: 64/250 intervals within 3..5 msmacvmm: guest exit code 1macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=268 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 250, wfx 250, total 1019: canceled 250, vtimer 250, wfx 250, hvc 269macvmm: stats: vcpu0 time: exec 0.358 s, wfi n/amacvmm: stats: host cpu 0.369 s over 1.660 s wall (23%)macvmm: stats: rlimit core=0 nofile=1048576Three exits per tick: vtimer 250, wfx 250, canceled 250. But the 250 ticks took 1,656 ms, 150 ticks per second. The guest did not keep good time: mean interval 5.1 ms against 4 asked, worst 12.4 ms, only 64 of 250 within 3 to 5 ms (hence exit code 6).
Where did the time go? The guest's interval runs from arming to its handler: 4 ms plus about 1.1 ms of lateness (our wake-up and two exits), 5.1 ms. The stale re-takes come after the handler and before the next arm: about 1.4 ms per round (0.358 s of exec / 250, stale=8580120). So a round is 4 + 1.1 + 1.4, about 6.5 ms, close to the 6.6 ms measured (1,656 / 250).
Exit-bench arithmetic predicted about 0.1% of a core (750 × 1.43 µs, about 1.1 ms per second); we measured 23% (0.369 s). The gap is the stale re-takes, not the exits.
To repeat it, in guests/timer-nogic/main.rs change 0..10 to 0..250 and freq / 10 to freq / 250, run scripts/build-guests.sh and the command from "The run", and undo it afterwards. Your guest prints 250 interval lines instead of our summary, but the --stats lines compare directly.
Aside
Linux's driver for this timer, drivers/clocksource/arm_arch_timer.c, makes our guest's moves (read CNTFRQ_EL0, program the compare value, silence the timer in its handler), with a controller in between.
Breaking it on purpose
Edit, predict, run, undo.
Deliberate breakage 1: WFI returns at once. Make your nogic_wfi return Resume { advance_pc: true } immediately, without sleeping. Predict: do the ten intervals still pass, and what does --stats say?
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 100 ms oktimer-nogic: interval 1 = 100 ms oktimer-nogic: interval 2 = 100 ms oktimer-nogic: interval 3 = 100 ms oktimer-nogic: interval 4 = 100 ms oktimer-nogic: interval 5 = 100 ms oktimer-nogic: interval 6 = 100 ms oktimer-nogic: interval 7 = 100 ms oktimer-nogic: interval 8 = 100 ms oktimer-nogic: interval 9 = 100 ms oktimer-nogic: irqs=10 stale=301944timer-nogic: 10/10 intervals within 95..150 msmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=494 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 10, wfx 900973, total 901488: canceled 10, vtimer 10, wfx 900973, hvc 495macvmm: stats: vcpu0 time: exec 0.310 s, wfi n/amacvmm: stats: host cpu 0.909 s over 1.021 s wall (90%)macvmm: stats: rlimit core=0 nofile=1048576Every interval passed. But 900,973 WFI exits and 90% host CPU: the guest's WFI and our handler bounced off each other. The checkpoint refuses it twice: the trace of almost half a million WFI exits outgrows its 32 MiB cap, and host CPU is 93%, not under 10%:
scripts/checkpoint.sh 11checkpoint: implementation <tree>[PASS] contract tests timer_rules (7 tests)[FAIL] runs on your Mac timer-nogic: trace <repo>/target/checkpoint/11/159b2fef888f7503/out/10951/timer-nogic/t.jsonl: 37751023 bytes is over the 33554432-byte cap host cpu 99% is not under 10% stderr (last lines): macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=494 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0 macvmm: stats: vcpu0 exits: vtimer 10, wfx 483783, total 484298: canceled 10, vtimer 10, wfx 483783, hvc 495 macvmm: stats: vcpu0 time: exec 0.183 s, wfi n/a macvmm: stats: host cpu 0.999 s over 1.018 s wall (99%) macvmm: stats: rlimit core=0 nofile=1048576[INFO] journal not checked (not a learner tree)CHECKPOINT 11 FAILWhat you saw: a correct guest, a busy core. The misconception: "a WFI handler must wait, or the guest breaks"; returning at once is correct, only expensive. The tool: --stats.
Deliberate breakage 2: never clear the vtimer mask. Restore the sleep. In your nogic_before_entry, never call set_vtimer_mask(false). Predict how many intervals print:
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 104 ms okmacvmm: timeout: the guest was still running after --timeout 10smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=89 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 1, wfx 9435272, total 9435363: canceled 1, vtimer 1, wfx 9435272, hvc 89macvmm: stats: vcpu0 time: exec 3.106 s, wfi n/amacvmm: stats: host cpu 9.687 s over 10.001 s wall (97%)macvmm: stats: rlimit core=0 nofile=1048576One interval, then nothing until the timeout (exit code 5): vtimer 1 against 9.4 million WFI exits, at 97% CPU. The guest re-armed its timer and it fired, but the vtimer was still masked, so no VTIMER exit came and our line stayed down; our WFI handler found the deadline past and woke at once, every time.
What you saw: one tick, then a hang that burns a core. The misconception: "the guest forgot to re-arm"; the mask was ours to clear. The tool: --stats (one VTIMER exit against millions of WFI exits).
Your turn
Check:
- Your run prints
10/10 intervals within 95..150 msand astats:line under 10% host CPU. - Your trace has VTIMER and WFI records. Each of these prints 10:
grep -c '"reason":"vtimer"' t.jsonlgrep -c '"ec":"0x1"' t.jsonl- Your journal has the Predict entry, written before your first run, and answers for questions 1 to 5.
Stuck? scripts/learner hint 11 gives four hints, up to the exact reference anchor.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 11You should see, as the last line:
CHECKPOINT 11 PASSIt runs the contract tests (offset, deadline and unmask rules, hostile timer values, the one-vCPU fence), runs timer-nogic with --stats and the trace, and checks your journal. Ours shows the journal skipped because it ran on the reference:
scripts/checkpoint.sh 11checkpoint: implementation <tree>[PASS] contract tests timer_rules (7 tests)[PASS] runs on your Mac timer-nogic: 8/8 serial markers, 2/2 trace markers, host cpu 3% < 10%, exit 0 in 1.15s[INFO] journal not checked (not a learner tree)CHECKPOINT 11 PASSWhat now works:
- a guest counter that starts near zero, and an alarm that interrupts, with your VMM as the wire;
- a guest waiting in
WFIcosts about 2% of a core, not 90%; --statssplits a cost into exits and guest time.
Chapter 12 starts from this state (the reference at the end of chapter 11).
What's next
Chapter 12 builds the interrupt controller this chapter did without, then hands the job to Hypervisor.framework's own, inside the macOS kernel. The same ten sleeps will run with no VTIMER or WFI exits at all.
Open question
Our one line served one source. The UART (universal asynchronous receiver-transmitter, our PL011) also wants to interrupt when a byte arrives. With a single IRQ input per CPU, how would a handler know which source fired, which one is more urgent, and which CPU should take it?
Spec hunt
- ARM ARM (DDI 0487), register page CNTV_CTL_EL0, Counter-timer Virtual Timer Control Register: which bit is read-only, what sets it, and what does
IMASKdo to the interrupt output while the condition holds? - ARM ARM, the description of the WFI instruction and the section on wait-for-interrupt wake-up events in the AArch64 power management chapter: which events end a
WFI, and where does the manual allow it to end for no reason at all? - The SDK (software development kit) header
hv_vcpu.h, onhv_vcpu_set_vtimer_maskandhv_vcpu_set_pending_interrupt: what must a VMM detect before it clears the mask, and how long does a pending interrupt you set stay pending?