indicogniBuild a VMM

Contents

Chapter 11 · Part V

Getting the CPU back: the timer and a bare interrupt

Needs a Mac Runs in browser ~4.5 h Lab: Timer timeline · Lab: Interrupt lifecycle
12 of 26

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.

  1. 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's reg describes two ranges. How many bytes long is the reg property?

    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.

  2. 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 trapped msr or mrs. The ISS 0x280520 gives Op0 2, Op2 4, Op1 0, CRn 1, Rt 9, CRm 0, direction 0: an msr (a write) from x9 to the register at (2, 0, 1, 0, 4), which is OSLAR_EL1.

  3. 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 is 0x4000_0000..0x4400_0000. Compute addr + len in 64-bit wrapping arithmetic, and say whether the check addr >= 0x4000_0000 && addr + len <= 0x4400_0000 accepts the access.

    Show answer

    The true sum is 0x1_0000_0000_0000_0004, which needs 65 bits; wrapped to 64 bits it is 0x4. Both halves of the check pass (0xFFFF_FFFF_FFFF_FFFC is above the base, 0x4 is below the end), so a wrapping check accepts an access that starts 4 bytes below the top of the address space. checked_add returns None instead, and the access is refused.

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) and WFE; 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_exit and the CANCELED exit (chapters 03 and 09); PSTATE's DAIF bits (chapter 06); the Exit enum and the exit handler (chapter 07); the vector table (chapter 08); the PL011's RIS, MIS and IMSC, 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_time and 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_EL0 and CNTV_CTL_EL0; derive the offset rule CNTVCT = 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, once CNTV_CTL_EL0 shows 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:

RegisterWhat it isWho writes it
CNTFRQ_EL0the counter's frequency in Hz: 24,000,000 as Hypervisor.framework presents it to the guest, so one tick is about 41.7 nsfirmware; here Hypervisor.framework
CNTVCT_EL0the virtual count: a number that goes up by one every ticknobody; it counts
CNTV_CVAL_EL0the compare value: "wake me when the count reaches this"the kernel
CNTV_CTL_EL0the 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):

guests/common/timer.rslines 32-58
/// 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:

crates/vmm/src/timer.rslines 77-95
/// 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):

crates/vmm/src/vcpu/manager.rslines 123-126
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:

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --timeout 10exit: 0--- stdout ---timer-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 ms
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Experiment: the guest reads CNTVCT_EL0 as its very first action and prints it as 'first cntvct'. The VMM is the reference (offset = the host count at boot).
  • Run in a copy of the reference with that one guest edit.
course/captures/11-first-cntvct.txt

133,166 ticks: 5.5 ms, the time it took to build the machine after the offset was taken. With the offset forced to 0:

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --timeout 10exit: 0--- stdout ---timer-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 ms
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Experiment: the same guest edit as 11-first-cntvct.txt (print CNTVCT_EL0 first), and the VMM's boot_offset() in crates/vmm/src/timer.rs returns 0 instead of mach_absolute_time().
  • Run in a copy of the reference with those two edits.
course/captures/11-offset-zero.txt

3,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, not IMASK, 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, #2 clears it (the immediate's bits are D, A, I, F from 8 down to 1, so 2 is I); msr daifset, #2 sets 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:

Lab

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 lifecycle
The life of one interrupt Top: with IRQs masked, a level line stays pending until the CPU unmasks, an edge with no latch is lost, and a latched edge waits in its latch. Bottom: the four GIC states of INTID 33. Raising the line makes it pending; reading the IAR makes it active, or active and pending while a level line is still high; lowering the line removes the pending half; writing the EOI makes it inactive, or pending again if a level line is still high, which is an interrupt storm. CPU masked, then unmasks level line: pending ... still pending ... handler runs edge, no latch: pulse, gone ... nothing pending ... nothing happens edge, latched: latch set ... still pending ... handler runs GIC state of INTID 33 inactive pending active and pending active raise IAR lower line EOI EOI, line still high: storm An edge: the IAR clears pending even with the line high, so the EOI ends it.

If 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, done

No 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:

MaskWho sets itWhat it stops
IMASK, bit 1 of CNTV_CTL_EL0the guest kernelthe timer's output, at the timer
PSTATE.Ithe 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 VMMthe 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:

EventOur VMM doesPC afterwards
VTIMER_ACTIVATED exitraise our line; leave the vtimer maskedunchanged: an asynchronous exit points at the next instruction not yet run (chapter 02)
before every entryour 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:

Lab

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 timeline

Loading 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 round

Three 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:

crates/vmm/src/timer.rslines 104-114
/// `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:

crates/vmm/src/timer.rslines 171-200
/// 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):

crates/vmm/src/timer.rslines 203-230
/// 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:

crates/vmm/src/timer.rslines 131-166
/// 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:

crates/hvf/src/host.rslines 46-81
/// 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/:

Shell
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):

TerminalReal output
cargo test -p vmm --lib timer::exit: 0--- stdout ---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--- stderr ---    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)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run in a copy of the reference whose crates/ are unmodified (only one test guest differs, for the 250 Hz experiment), so the shared target/ was not touched. Learners run it from inside learner/.
course/captures/11-timer-tests.txt

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.

crates/vmm/src/config.rslines 416-425
/// 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:

Shell
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:

crates/hvf/src/ffi.rslines 247-250
/// `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;
crates/hvf/src/ffi.rslines 526-535
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;
crates/hvf/src/ffi.rslines 551-554
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):

crates/hvf/src/ffi.rslines 677-683
/// `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,}
crates/hvf/src/ffi.rslines 695-699
/// `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;
crates/hvf/src/ffi.rsline 548
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:

crates/hvf/src/vcpu.rslines 202-214
/// 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)        }    };}
crates/hvf/src/vcpu.rslines 335-360
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)    })}
crates/hvf/src/vcpu.rslines 434-445
/// 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/:

Shell
cargo build -p hvf
TerminalReal output
cargo build -p hvfexit: 0--- stderr ---   Compiling hvf v0.1.0 (<tree>/crates/hvf)    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run in a copy of the reference whose crates/ are unmodified, after touching crates/hvf/src/lib.rs so cargo rebuilds the crate. Learners run it from inside learner/.
course/captures/11-hvf-build.txt

Wiring 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:

crates/vmm/src/vcpu/mod.rslines 138-175
/// 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(())}
crates/vmm/src/vcpu/mod.rslines 251-255
/// 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:

crates/vmm/src/vcpu/exit.rslines 518-526
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:

crates/vmm/src/vcpu/exit.rslines 460-488
/// 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:

crates/vmm/src/control.rslines 290-303
/// 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:

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10exit: 5--- stdout ---timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Experiment: nogic_before_entry in crates/vmm/src/vcpu/mod.rs never arms the line kicker, so nothing forces an exit while the IRQ line is up.
  • Run in a copy of the reference with that one edit.
course/captures/11-no-kick.txt

After 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:

crates/vmm/src/timer.rslines 254-300
/// 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:

crates/vmm/src/vcpu/mod.rslines 100-114
/// 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:

guests/timer-nogic/main.rslines 44-58
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:

guests/common/timer.rslines 70-83
/// 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:

guests/timer-nogic/main.rslines 67-83
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:

crates/hvf/src/vcpu.rslines 364-367
get_via_out!(    /// Cumulative guest run time in mach ticks.    exec_time, hv_vcpu_get_exec_time, u64,);
crates/vmm/src/vcpu/manager.rslines 193-199
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:

crates/hvf/src/host.rslines 760-775
/// `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)?)}
crates/vmm/src/machine/mod.rslines 508-510
let cpu0 = hvf::host::process_cpu_time();let t0 = Instant::now();let reason = manager::run_vcpus(&self.vm, &setup, &env, &obs, deadline);
crates/vmm/src/machine/mod.rslines 516-527
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:

crates/vmm/src/stats.rslines 163-197
/// 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/:

Shell
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 10

Check your Predict entry first. The reference's run ({guests} and {out} stand for directories):

TerminalReal output
macvmm run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --trace exits:{out}/t.jsonl:all --timeout 10exit: 0--- stdout ---timer-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 ms--- stderr ---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=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=1048576
captured: run "timer-nogic" of checkpoint 11, captured from the reference on real hardwarecourse/captures/11-timer-nogic.txt

Ten 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:

TerminalReal output
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 -7exit: 0--- stdout ---{"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"}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified (a copy of it); the guest's printing is sent to /dev/null and the trace's printing exits (DEBUG_PUTC hvc calls) are filtered out, leaving the first seven timer-related exits.
course/captures/11-trace-ticks.txt

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:

TerminalReal output
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.jsonlexit: 6--- stdout ---timer-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"}--- stderr ---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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Experiment: in its first interval only, the guest arms the timer for 100 ms, then spins for 300 ms with IRQs still masked (PSTATE.I = 1), then clears the mask for one instruction (msr daifclr, #2; isb; msr daifset, #2) before its usual wait. The VMM is the reference.
  • Run in a copy of the reference with that one guest edit; the trace's first three non-printing exits are shown at the end of stdout.
course/captures/11-masked-irq.txt

The 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.

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10exit: 5--- stdout ---timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Experiment: nogic_before_entry in crates/vmm/src/vcpu/mod.rs unmasks the vtimer before every entry whenever it is masked (if action.unmask || masked), instead of waiting until CNTV_CTL shows the timer no longer asserting.
  • Run in a copy of the reference with that one edit.
course/captures/11-unmask-early.txt

8,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.

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10exit: 6--- stdout ---timer-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 ms--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Experiment: the guest changed to arm its timer 250 times for 4 ms (freq / 250) instead of 10 times for 100 ms, and to print one summary: total time, achieved ticks per second, the mean, smallest and largest interval in microseconds, and how many intervals fell within 3..5 ms. The VMM is the unmodified reference binary.
  • The guest was built in a copy of the reference with that one edit; {guests} is that copy's guest directory.
course/captures/11-250hz.txt

Three 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?

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10exit: 0--- stdout ---timer-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 ms--- stderr ---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=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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: nogic_wfi in crates/vmm/src/vcpu/exit.rs returns Resume { advance_pc: true } at once, without sleeping until the CNTV_CVAL deadline.
  • Run in a copy of the reference with that one edit.
course/captures/11-wfi-spin.txt

Every 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%:

TerminalReal output
scripts/checkpoint.sh 11exit: 1--- stdout ---checkpoint: 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 FAIL
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: nogic_wfi in crates/vmm/src/vcpu/exit.rs returns Resume { advance_pc: true } at once (the same edit as 11-wfi-spin.txt).
  • Run as scripts/checkpoint.sh 11 --impl <tree>, a copy of the reference with that one edit; the journal step is skipped for such a tree.
course/captures/11-wfi-spin-checkpoint.txt

What 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:

TerminalReal output
cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --timeout 10exit: 5--- stdout ---timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 104 ms ok--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: nogic_before_entry in crates/vmm/src/vcpu/mod.rs never calls set_vtimer_mask(false), so the vtimer stays masked after the first VTIMER_ACTIVATED exit.
  • Run in a copy of the reference with that one edit.
course/captures/11-mask-forever.txt

One 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:

  1. Your run prints 10/10 intervals within 95..150 ms and a stats: line under 10% host CPU.
  2. Your trace has VTIMER and WFI records. Each of these prints 10:
Shell
grep -c '"reason":"vtimer"' t.jsonlgrep -c '"ec":"0x1"' t.jsonl
  1. 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 Mac

Run this from the repository root:

scripts/checkpoint.sh 11

You should see, as the last line:

CHECKPOINT 11 PASS

It 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:

TerminalReal output
scripts/checkpoint.sh 11exit: 0--- stdout ---checkpoint: 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 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run as scripts/checkpoint.sh 11 --impl <tree>, an unmodified copy of the reference, so the shared target/ binaries were not relinked; the journal step is skipped for such a tree.
course/captures/11-checkpoint.txt

What now works:

  • a guest counter that starts near zero, and an alarm that interrupts, with your VMM as the wire;
  • a guest waiting in WFI costs about 2% of a core, not 90%;
  • --stats splits 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 IMASK do 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, on hv_vcpu_set_vtimer_mask and hv_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?
Progress is stored only in this browser.