indicogniBuild a VMM

Contents

Chapter 12 · Part V

Why an interrupt controller, and why in the kernel

Needs a Mac Runs in browser ~4.5 h Lab: Interrupt lifecycle
13 of 26

Course progress: chapter 12 is 13 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 11: Getting the CPU back: the timer and a bare interrupt

    A guest reads CNTV_CTL_EL0 and gets 0b101. Is its timer raising its interrupt output right now? What about 0b111?

    Show answer

    0b101 is ENABLE (bit 0) and ISTATUS (bit 2) with IMASK (bit 1) clear: enabled, not masked, count reached, so yes, the output is up. 0b111 has IMASK set as well: the condition still holds, but the interrupt is masked at the timer, so the output is down.

  2. From chapter 09: A device is a state machine: the bus, PL011 and PL031

    A guest reads the PL011's flag register FR and gets 0x90. May it write a byte to DR now, and is there a byte for it to read?

    Show answer

    0x90 is bit 7 (TXFE, transmit FIFO empty) plus bit 4 (RXFE, receive FIFO empty). It may send: the transmit side is empty, so TXFF (full) is clear. There is nothing to read: RXFE says the receive FIFO is empty, and a DR read now would return 0.

  3. From chapter 05: Two stages, one map: holes in stage 2 on purpose

    A guest stores a byte to 0x0900_0000, where its UART should be, but your VMM has mapped an ordinary page of RAM there. What does the guest see, and what does your VMM see?

    Show answer

    The guest sees a store that worked: the byte sits in RAM, and a load from the same address returns it. Nothing is printed. Your VMM sees nothing at all: a mapped address never causes a VM exit, so the VMM never learns the store happened. A device register needs a stage-2 hole, so each access stops the guest.

Concepts you'll need

Chapters before this one: chapter 11, Getting the CPU back: the timer and a bare interrupt.

  • Core, taught here: why many interrupt sources need a controller; the GIC (Generic Interrupt Controller) version 3: distributor, redistributors, CPU interface, INTIDs of three kinds, SGI (software-generated interrupt), PPI (private peripheral interrupt) and SPI (shared peripheral interrupt), the IAR (interrupt acknowledge register) and EOI (end of interrupt), affinity routing; the device tree interrupt binding; GicSpi; freezing IrqLine; the in-kernel GIC as a trade you measure.
  • Core, from earlier: interrupts as state, level and edge lines, the virtual timer, WFI (wait for interrupt) and VTIMER exits, interrupt storms, --stats (chapter 11); INTIDs and the memory map (chapter 05); MPIDR_EL1, mrs and msr (chapter 06); the PL011's IMSC and RIS, IrqLine, NullIrq, TestIrq, the kick and the stdin thread (chapter 09); the device tree, phandles and --dtb-out (chapter 10).
  • Primers (read first): reading-arm-specs (finding a register page in an Arm specification).
  • Primers (review): host-concurrency (which thread calls into the framework, and why a device's Mutex is held while it does).
  • Pointers: the GICv3 architecture specification, Arm document IHI 0069; redistributor frames follow vCPU (virtual CPU) creation order (an Aside); LPIs and message-signalled interrupts (an Aside).
  • Forward definitions: none.

At the end of chapter 11, ten 100 ms sleeps cost your virtual machine monitor (VMM) thirty exits: ten VTIMER exits, ten WFI (wait for interrupt) exits and ten kicks. That was one source. The UART (universal asynchronous receiver-transmitter, the serial port) wants to interrupt too, so do the clock chip and every disk, and the CPU has one IRQ (interrupt request) input. Who decides which source fired, which one goes first, and which CPU takes it? And does the VMM have to stand in the middle of every one of them?

Predict Run chapter 11's ten 100 ms sleeps again, with Hypervisor.framework's interrupt controller in the kernel. How many VTIMER and WFI exits will --stats count: (a) ten of each, as in chapter 11; (b) about half; (c) zero? And will the wake-ups be more punctual, less, or the same?

Write your answers and one sentence of reasoning under ## Predict in your journal.

This chapter closes rows 6 and 7 of chapter 00's problem ledger, interrupts and time: devices and the timer interrupt a guest through a real controller, and an idle guest costs almost nothing. Sitting A is the controller on paper and in the browser (1.5 hours); sitting B is the build, the measurement and three breaks (3 hours).

Objectives: by the end you can

  • (Sitting A) List what a controller must do for many interrupt sources, and match each job to the distributor, a redistributor or the CPU interface of a GICv3.
  • (Sitting A) Convert between device tree interrupt cells and INTIDs both ways (SPI n is INTID 32 + n, PPI n is 16 + n), and say why a timer interrupt is a PPI and a UART interrupt an SPI.
  • (Sitting A) Trace one level-triggered interrupt through pending, active and inactive, and predict what happens if the device never lowers its line.
  • (Sitting B) Create the in-kernel GIC after hv_vm_create and before any vCPU, at 0x0800_0000 and 0x080A_0000, and check the framework's sizes and timer INTIDs at start-up.
  • (Sitting B) Drive the PL011's interrupt as SPI 1 (INTID 33) through IrqLine, describe it in the device tree, and run a guest that takes three keystrokes as three interrupts.
  • (Sitting B) Measure chapter 11's timer workload with the GIC in the kernel, and state what was gained and what was given up.

Before you start. From the repository root, run scripts/learner start 12 to copy this chapter's journal to learner/journal/12.md. In sitting B, type the code into learner/ and run from inside it.

One input, many sources

Design the box between many sources and one IRQ input: write down its jobs before you read on.

Most lists arrive at five. Collect many lines into one input, and let the handler ask which line it was. Rank them, so the disk does not wait behind a chatty keyboard. Route each to a CPU, once there are several. Acknowledge and finish: the handler says "I am on it" (so the interrupt is not delivered twice at once) and later "I am done" (so the next one can come).

The fifth job: keep some lines private. Every CPU has its own timer, and CPU 0's timer must never interrupt CPU 1.

That box is an interrupt controller, and Arm's is the GIC (Generic Interrupt Controller). We use GICv3: Hypervisor.framework emulates it, and QEMU's virt board offers it, so stock kernels already drive it.

Every line has a number

Each line gets an INTID (chapter 05: the number naming an interrupt line). The GIC splits the numbers by who may receive the interrupt:

INTIDsKindBelongs toExamples on our board
0 to 15SGI (software-generated interrupt)one CPU; another CPU sends it by writing a registera kernel waking another CPU (chapter 20)
16 to 31PPI (private peripheral interrupt)one CPU; a device inside that CPUthe virtual timer, 27; the physical timer, 30
32 to 1019SPI (shared peripheral interrupt)any CPU; a device outside the CPUsPL011 (the UART) 33, PL031 (the real-time clock) 34, virtio devices (chapter 15) from 48
1023specialnobody"nothing pending"

Private interrupts repeat on every CPU: each CPU has its own INTID 27. Shared ones exist once.

Chapter 11's virtual timer is inside each CPU, so its line is a PPI; the UART sits outside every CPU, so its line is an SPI.

Three parts: distributor, redistributors, CPU interface

The five jobs split across three blocks: shared things live in one place, private things once per CPU.

 our VMM (devices)  |  macOS kernel: Hypervisor.framework's GICv3                    | PL011 raises 33 -+ |  distributor (GICD)          redistributor 0 (GICR)       CPU interface 0 PL031 raises 34 -+-+> one, for all SPIs: forwards> vCPU 0's SGIs, PPIs: signals> ICC_* registers: interrupts> vCPU 0 virtio raises 48+ +|  enable, priority,            (its timer: 27)              (IAR, EOI, mask)                    |  trigger, target CPU forwards> redistributor 1 ... signals ...................> vCPU 1

Our devices only raise and lower lines; everything right of the bar runs in the kernel. Shared lines go through the distributor; private ones start in a redistributor.

  • The distributor (GICD_* registers) holds, per SPI, enable, priority (a lower number is more urgent), level or edge trigger, and target CPU.
  • One redistributor per CPU (GICR_*) holds the same for that CPU's SGIs and PPIs, and forwards to its CPU: two 64 KiB frames, 128 KiB per vCPU.
  • The CPU interface, inside each CPU, is system registers (chapter 06's mrs and msr) named ICC_*: priority mask, acknowledge, end of interrupt.

The five jobs, each with its home:

JobWhereRegisters
Collect, and tell the handler which lineCPU interfaceICC_IAR1_EL1 returns the INTID
Rankdistributor (SPIs) or redistributor (SGIs, PPIs) holds each line's priority; the CPU interface holds the CPU's maskGICD_IPRIORITYR, GICR_IPRIORITYR; ICC_PMR_EL1
Route to a CPUdistributorGICD_IROUTER, one per SPI
Acknowledge and finishCPU interfaceICC_IAR1_EL1, then ICC_EOIR1_EL1
Keep lines privateone redistributor per CPUGICR_*

Routing names CPUs as chapter 06 did, by MPIDR_EL1's affinity fields: each SPI's GICD_IROUTER holds its target's affinity. That is affinity routing.

Check yourself. Without the table: which block holds the CPU's priority mask, which names INTID 33's target CPU, and which holds the timer's INTID 27 settings? Journal question 3 asks for these.

Aside

Redistributor frames follow vCPU creation order, not MPIDR_EL1, so a guest finds its own frame by walking them and reading each GICR_TYPER (IHI 0069, the redistributor registers); our guests and Linux do this. Our VMM checks at every boot that vCPU i's frame sits at the base plus i × 128 KiB.

The life of one interrupt

Chapter 11 taught that an interrupt is state. The GIC keeps four per INTID: inactive, pending (asked, not taken), active (being handled), and active and pending (being handled, and asking again). Follow the UART's line through one keystroke:

  1. A byte arrives, the PL011 raises its line, and INTID 33 becomes pending.
  2. The distributor forwards it, through the target CPU's redistributor, to that CPU's interface. If it is more urgent than the CPU's priority mask (ICC_PMR_EL1) and the CPU has IRQs unmasked in PSTATE, the CPU takes an IRQ exception through its vector table.
  3. The handler reads the IAR (interrupt acknowledge register, ICC_IAR1_EL1; the 1 is the interrupt group: 0 for firmware, 1 for kernels). It returns 33 and the interrupt becomes active; the line is still high, so active and pending.
  4. The handler removes the cause: it reads the byte from DR, the FIFO (first in, first out queue) empties, and the PL011 lowers its line. With the line low, the pending half goes away: the interrupt is only active.
  5. The handler writes 33 to the EOI (end of interrupt) register, ICC_EOIR1_EL1. The interrupt becomes inactive.

Step 5 holds the rule this chapter's breaks turn on. A level-triggered interrupt stays pending while its line is high, so if the line is still high at EOI, the CPU takes it again at once. Step 4 is not the GIC's job; it is the device's and the handler's.

If the IAR has nothing to give (another CPU took it, or the line dropped), it returns 1023, a spurious interrupt, and the handler returns without an EOI.

The lab steps one level line and one edge line through these states. Try never lowering the level line:

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 the lab steps through (a simulation from the lab's model, not a capture):

step                          line   state of INTID 33byte arrives                  high   pendingCPU reads IAR (returns 33)    high   active and pendinghandler reads DR (FIFO empty) low    activehandler writes EOI            low    inactive          one interrupt, done--- same, but the device never lowers the line ---CPU reads IAR (returns 33)    high   active and pendinghandler writes EOI            high   pending           taken again at once: a storm--- an edge-triggered line ---rising edge                   high   pendingCPU reads IAR, line held high high   active            active only: the IAR cleared pendinghandler writes EOI            high   inactive          no re-delivery

An edge line latches one event instead: holding the line high afterwards changes nothing, so an edge cannot storm this way. The price: two edges before the acknowledge become one pending interrupt, so a handler must check how much work is waiting, not count interrupts.

Telling the guest: the interrupt binding

A guest learns where the GIC lives and which INTID each device uses from the DTB (device tree blob) of chapter 10. The GIC node says interrupt-controller, gets a phandle, and declares #interrupt-cells = <3>. The root node's interrupt-parent points at that phandle, so every device uses the GIC. And each device lists its lines in interrupts, three cells per line, an interrupt specifier:

CellMeansPL011Virtual timer
1kind: 0 SPI, 1 PPI01
2number within that kind111
3trigger: 4 level-high, 1 rising edge44
INTIDSPI n = 32 + n; PPI n = 16 + n3327

The second cell is not the INTID.

Our VMM's device tree, decompiled by dtc (cells in hexadecimal). Find interrupt-parent, the intc@8000000 node with its two reg ranges (distributor, then one redistributor), the timer's four PPIs and the PL011's <0x00 0x01 0x04>:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/hello.bin@0x40080000 --dtb-out v.dtb --timeout 10 && dtc -I dtb -O dts v.dtbexit: 0--- stdout ---/dts-v1/;/ {	compatible = "linux,dummy-virt";	model = "macvmm-virt";	#address-cells = <0x02>;	#size-cells = <0x02>;	interrupt-parent = <0x01>;	dma-coherent;	chosen {		stdout-path = "/pl011@9000000";		rng-seed = <0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00>;		kaslr-seed = <0x00 0x00>;	};	memory@40000000 {		device_type = "memory";		reg = <0x00 0x40000000 0x00 0x4000000>;	};	cpus {		#address-cells = <0x01>;		#size-cells = <0x00>;		cpu@0 {			device_type = "cpu";			compatible = "arm,arm-v8";			reg = <0x00>;			enable-method = "psci";		};	};	psci {		compatible = "arm,psci-1.0", "arm,psci-0.2", "arm,psci";		method = "hvc";	};	timer {		compatible = "arm,armv8-timer", "arm,armv7-timer";		always-on;		interrupts = <0x01 0x0d 0x04 0x01 0x0e 0x04 0x01 0x0b 0x04 0x01 0x0a 0x04>;	};	intc@8000000 {		compatible = "arm,gic-v3";		#interrupt-cells = <0x03>;		interrupt-controller;		#address-cells = <0x02>;		#size-cells = <0x02>;		ranges;		#redistributor-regions = <0x01>;		reg = <0x00 0x8000000 0x00 0x10000 0x00 0x80a0000 0x00 0x20000>;		phandle = <0x01>;	};	apb-pclk {		compatible = "fixed-clock";		#clock-cells = <0x00>;		clock-frequency = <0x16e3600>;		clock-output-names = "clk24mhz";		phandle = <0x02>;	};	pl011@9000000 {		compatible = "arm,pl011", "arm,primecell";		reg = <0x00 0x9000000 0x00 0x1000>;		interrupts = <0x00 0x01 0x04>;		clocks = <0x02 0x02>;		clock-names = "uartclk", "apb_pclk";	};	pl031@9010000 {		compatible = "arm,pl031", "arm,primecell";		reg = <0x00 0x9010000 0x00 0x1000>;		interrupts = <0x00 0x02 0x04>;		clocks = <0x02>;		clock-names = "apb_pclk";	};};
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The hello guest only gives the VMM something to boot; --dtb-out writes the device tree the guest received (seeds zeroed). dtc's own warnings are discarded, as is the guest's output.
course/captures/12-dtb-gic.txt

The timer's four PPIs, 0x0d 0x0e 0x0b 0x0a (INTIDs 29, 30, 27, 26), are one timer per possible owner (secure firmware, the kernel's physical timer, the virtual timer, the hypervisor's), in the order Linux's timer binding fixes. Only the virtual one, 27, matters to us.

Good place to stop. Sitting B needs your Mac, your learner workspace and about 3 hours.

Declaring the GIC

Type each piece into learner/ as you read: the irq run at the end of "Three keystrokes" needs all of them. List the SDK (software development kit) headers as in chapter 01:

Shell
ls "$(xcrun --show-sdk-path)/System/Library/Frameworks/Hypervisor.framework/Headers/"

Add the functions of hv_gic_config.h, hv_gic.h and hv_gic_parameters.h to learner/crates/hvf/src/ffi.rs. A configuration object holds the two bases; hv_gic_create reads it:

crates/hvf/src/ffi.rslines 559-579
/// "Create the GIC configuration after the virtual machine has been created."pub fn hv_gic_config_create() -> hv_gic_config_t;pub fn hv_gic_config_set_distributor_base(    config: hv_gic_config_t,    distributor_base_address: hv_ipa_t,) -> hv_return_t;pub fn hv_gic_config_set_redistributor_base(    config: hv_gic_config_t,    redistributor_base_address: hv_ipa_t,) -> hv_return_t;pub fn hv_gic_config_set_msi_region_base(    config: hv_gic_config_t,    msi_region_base_address: hv_ipa_t,) -> hv_return_t;pub fn hv_gic_config_set_msi_interrupt_range(    config: hv_gic_config_t,    msi_intid_base: u32,    msi_intid_count: u32,) -> hv_return_t;/// Must be called after `hv_vm_create` and before any `hv_vcpu_create` (`hv_gic.h`).pub fn hv_gic_create(gic_config: hv_gic_config_t) -> hv_return_t;

The call devices need, and the geometry and INTID queries:

crates/hvf/src/ffi.rslines 584-585
/// Any thread. Asserts (`level = true`) or deasserts an SPI.pub fn hv_gic_set_spi(intid: u32, level: bool) -> hv_return_t;
crates/hvf/src/ffi.rslines 634-653
pub fn hv_gic_get_distributor_size(distributor_size: *mut usize) -> hv_return_t;pub fn hv_gic_get_distributor_base_alignment(    distributor_base_alignment: *mut usize,) -> hv_return_t;pub fn hv_gic_get_redistributor_region_size(    redistributor_region_size: *mut usize,) -> hv_return_t;pub fn hv_gic_get_redistributor_size(redistributor_size: *mut usize) -> hv_return_t;pub fn hv_gic_get_redistributor_base_alignment(    redistributor_base_alignment: *mut usize,) -> hv_return_t;pub fn hv_gic_get_msi_region_size(msi_region_size: *mut usize) -> hv_return_t;pub fn hv_gic_get_msi_region_base_alignment(    msi_region_base_alignment: *mut usize,) -> hv_return_t;pub fn hv_gic_get_spi_interrupt_range(    spi_intid_base: *mut u32,    spi_intid_count: *mut u32,) -> hv_return_t;pub fn hv_gic_get_intid(interrupt: hv_gic_intid_t, intid: *mut u32) -> hv_return_t;
crates/hvf/src/ffi.rslines 310-316
/// `hv_gic_intid_t`: the fixed PPIs the framework wires to its in-kernel redistributors.pub type hv_gic_intid_t = u16;pub const HV_GIC_INT_PERFORMANCE_MONITOR: hv_gic_intid_t = 23;pub const HV_GIC_INT_MAINTENANCE: hv_gic_intid_t = 25;pub const HV_GIC_INT_EL2_PHYSICAL_TIMER: hv_gic_intid_t = 26;pub const HV_GIC_INT_EL1_VIRTUAL_TIMER: hv_gic_intid_t = 27;pub const HV_GIC_INT_EL1_PHYSICAL_TIMER: hv_gic_intid_t = 30;

Read the comment above hv_gic_create in hv_gic.h. The GIC must be created after the virtual machine (VM) and before any vCPU, "so that GIC CPU system resources can be allocated"; otherwise "an error is returned". A vCPU is born with its redistributor and CPU interface, so their GIC must exist first.

Creating it in the only window that works

In learner/crates/hvf/src/gic.rs, the wrapper creates a configuration, sets the two bases and creates the GIC, checking each call with chapter 01's check:

crates/hvf/src/gic.rslines 59-92
/// `hv_gic_config_create` → set bases → `hv_gic_create`. Requires a live VM with no vCPUs.pub(crate) fn create(config: GicConfig, generation: u64) -> Result<Gic, CallError> {    // SAFETY: called by `VmBuilder::create` after `hv_vm_create` succeeded, as    // `hv_gic_config.h` requires; NULL is turned into an error by `OsObject::new`.    let cfg = OsObject::new("hv_gic_config_create", unsafe {        ffi::hv_gic_config_create()    })?;    // SAFETY: `cfg` is a live `hv_gic_config_t` owned by `cfg` for these calls.    check("hv_gic_config_set_distributor_base", unsafe {        ffi::hv_gic_config_set_distributor_base(cfg.as_ptr(), config.distributor_base)    })?;    // SAFETY: as above.    check("hv_gic_config_set_redistributor_base", unsafe {        ffi::hv_gic_config_set_redistributor_base(cfg.as_ptr(), config.redistributor_base)    })?;    if let Some(msi) = config.msi {        // SAFETY: as above.        check("hv_gic_config_set_msi_region_base", unsafe {            ffi::hv_gic_config_set_msi_region_base(cfg.as_ptr(), msi.base)        })?;        // SAFETY: as above.        check("hv_gic_config_set_msi_interrupt_range", unsafe {            ffi::hv_gic_config_set_msi_interrupt_range(                cfg.as_ptr(),                msi.intid_base,                msi.intid_count,            )        })?;    }    // SAFETY: a VM exists and no vCPU can exist yet (`Vcpu` borrows `Vm`, which the builder has    // not returned), satisfying `hv_gic.h`'s ordering rule. The framework copies the config.    check("hv_gic_create", unsafe { ffi::hv_gic_create(cfg.as_ptr()) })?;    Ok(Gic { generation })}

Skip the msi branch (message-signalled interrupts, an Aside below); our board passes None. generation counts VMs, so a handle kept from before a reboot (chapter 08's SYSTEM_RESET) cannot touch the next VM's GIC; the builder supplies it.

create is pub(crate) on purpose: the only caller is the VM builder in learner/crates/hvf/src/vm.rs. The builder records the request:

crates/hvf/src/vm.rslines 163-167
/// Create the in-kernel GICv3 at these addresses as part of `create`.pub fn with_gic(mut self, config: GicConfig) -> VmBuilder {    self.gic = Some(config);    self}

and create makes the GIC right after hv_vm_create, before the Vm value exists:

crates/hvf/src/vm.rslines 220-233
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);let gic = match self.gic.map(|c| gic::create(c, generation)).transpose() {    Ok(gic) => gic,    Err(e) => {        // Tear the half-built VM down directly rather than through `Vm::drop`, so the        // flag is released once, by `create`. The GIC error is the one worth reporting.        // SAFETY: `hv_vm_create` succeeded above, no vCPU exists, and no `Vm` value        // represents this VM, so it is destroyed exactly once, here.        let _ = unsafe { ffi::hv_vm_destroy() };        return Err(e);    }};// Publish last: no token of this generation works before the VM is complete.Ok((Vm::publish(generation), gic))

A Vcpu borrows a Vm, so no vCPU can exist yet: the compiler checks the ordering rule. One crate up, in learner/crates/vmm/src/vm.rs, the machine asks for a GIC at the board's addresses:

crates/vmm/src/vm.rslines 50-77
/// Create the process's VM, with an in-kernel GICv3 at the layout's GICD/GICR bases, for a/// machine whose RAM ends at `ram_end`.pub fn create_vm(layout: &Layout, ram_end: u64, caps: &Capabilities) -> Result<(Vm, Gic)> {    let bits = layout.ipa_bits_needed(ram_end);    if bits > caps.max_ipa_bits {        return Err(Error::Config(format!(            "the machine needs a {bits}-bit IPA space; this host supports {}",            caps.max_ipa_bits        )));    }    let gic = GicConfig {        distributor_base: GICD_BASE,        redistributor_base: GICR_BASE,        msi: None,    };    let (vm, gic) = VmBuilder::new()        .ipa_bits(bits)        .with_gic(gic)        .create()        .map_err(|err| Error::Hv {            op: "create VM",            err,        })?;    let gic = gic.ok_or(Error::Internal("VmBuilder::with_gic returned no GIC"))?;    Ok((vm, gic))}

Check what you assumed

Our layout, device tree and guests assume a 64 KiB distributor, 128 KiB per redistributor, an SPI range holding every wired line, and timers at 27 and 30. Those numbers are the framework's, so the VMM asks once per boot, before any vCPU exists, through queries on Gic in hvf/src/gic.rs (with handle, which the next section needs), gathered in learner/crates/vmm/src/vm.rs:

crates/hvf/src/gic.rslines 217-254
impl Gic {    /// A copyable handle for device threads (used by `vmm::irq::GicSpi`), bound to the same    /// VM as `self`.    pub fn handle(&self) -> GicHandle {        GicHandle {            generation: self.generation,        }    }    /// Size of the GICD frame in bytes (`hv_gic_get_distributor_size`; 64 KiB on the M5 Pro).    pub fn distributor_size(&self) -> Result<usize, CallError> {        size(            "hv_gic_get_distributor_size",            ffi::hv_gic_get_distributor_size,        )    }    /// Size of **one** vCPU's redistributor (RD_base + SGI_base frames;    /// `hv_gic_get_redistributor_size`, 128 KiB on the M5 Pro). The DT's GICR `reg` covers    /// `ncpus` of these (ADR-0003).    pub fn redistributor_size(&self) -> Result<usize, CallError> {        size(            "hv_gic_get_redistributor_size",            ffi::hv_gic_get_redistributor_size,        )    }    /// The SPI INTIDs the framework accepts in [`GicHandle::set_spi`], as a half-open range    /// (`32..1020` on the M5 Pro). An MSI range, if configured, lies inside it.    pub fn spi_range(&self) -> Result<Range<u32>, CallError> {        let (base, count) = spi_base_count()?;        // A framework answer that overflows is not something to build a range from.        let end = base.checked_add(count).ok_or(CallError {            call: "hv_gic_get_spi_interrupt_range",            error: crate::HvError::Error,        })?;        Ok(base..end)    }
crates/vmm/src/vm.rslines 124-142
impl GicFacts {    /// Ask the live framework.    pub fn query(gic: &Gic) -> Result<GicFacts> {        let hv = |err| Error::Hv {            op: "query the in-kernel GIC",            err,        };        let size = |r: core::result::Result<usize, CallError>| {            r.map_err(hv).map(|v| u64::try_from(v).unwrap_or(u64::MAX))        };        Ok(GicFacts {            distributor_size: size(gic.distributor_size())?,            redistributor_size: size(gic.redistributor_size())?,            spi: gic.spi_range().map_err(hv)?,            vtimer: gic.intid(GicInterrupt::El1VirtualTimer).map_err(hv)?,            ptimer: gic.intid(GicInterrupt::El1PhysicalTimer).map_err(hv)?,        })    }}

Every SPI the board wires, listed from the layout:

crates/vmm/src/vm.rslines 151-156
/// Every SPI INTID the `virt` layout wires: each region's line and the 32 virtio-mmio slots.pub fn layout_spis(layout: &Layout) -> Vec<u32> {    let mut v: Vec<u32> = layout.regions.iter().filter_map(|r| r.intid).collect();    v.extend((0..VIRTIO_MMIO_SLOTS).filter_map(|i| layout.virtio_slot(i).map(|(_, intid)| intid)));    v}

If a future macOS changes one, the VMM refuses to start, naming both values:

crates/vmm/src/vm.rslines 160-210
/// The start-up checks: the framework's GIC geometry and timer INTIDs must match what the/// layout and the device tree promise the guest. Each failure names the value the framework/// reported and the one macvmm needs.pub fn check_gic_facts(f: &GicFacts, layout: &Layout) -> Result<()> {    let mismatch = |what: &str, got: String, want: String| {        Err(Error::Config(format!(            "in-kernel GIC: {what} is {got}, but macvmm's machine layout needs {want}"        )))    };    if f.distributor_size != GICD_SIZE {        return mismatch(            "the distributor size",            format!("{:#x}", f.distributor_size),            format!("{GICD_SIZE:#x}"),        );    }    if f.redistributor_size != GICR_FRAME_SIZE {        return mismatch(            "the per-vCPU redistributor size",            format!("{:#x}", f.redistributor_size),            format!("{GICR_FRAME_SIZE:#x}"),        );    }    if let Some(intid) = layout_spis(layout).into_iter().find(|i| !f.spi.contains(i)) {        return mismatch(            "the SPI range",            format!("{}..{}", f.spi.start, f.spi.end),            format!("one containing INTID {intid}"),        );    }    if f.vtimer != EXPECTED_VTIMER_INTID {        return mismatch(            "the EL1 virtual timer INTID",            f.vtimer.to_string(),            EXPECTED_VTIMER_INTID.to_string(),        );    }    if f.ptimer != EXPECTED_PTIMER_INTID {        return mismatch(            "the EL1 physical timer INTID",            f.ptimer.to_string(),            EXPECTED_PTIMER_INTID.to_string(),        );    }    Ok(())}/// [`check_gic_facts`] on the live GIC (`Machine::build`, `hvf_gic_live`).pub fn check_gic(gic: &Gic, layout: &Layout) -> Result<()> {    check_gic_facts(&GicFacts::query(gic)?, layout)}

Machine::build in learner/crates/vmm/src/machine/mod.rs runs it right after creating the VM:

crates/vmm/src/machine/mod.rslines 335-339
// Startup assertions on the GIC layout, before any memory exists: on a mismatch, dropping// the VM destroys it and nothing else was built.if let Some(g) = &gic {    vm::check_gic(g, layout)?;}

The checkpoint's on-Mac test makes the same queries, on our Mac:

TerminalReal output
cargo test -q -p vmm --features hvf-tests --test hvf_gic_live -- --test-threads=1 --nocaptureexit: 0--- stdout ---running 2 tests..test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s--- stderr ---hvf_gic_live: GicFacts { distributor_size: 65536, redistributor_size: 131072, spi: 32..1020, vtimer: 27, ptimer: 30 }hvf_gic_live: spi range 32..1020hvf_gic_live: ID_AA64PFR0_EL1 (hv_vcpu_get_sys_reg) = 0x1101000011110011 (GIC field 1)hvf_gic_live: no GIC: ID_AA64PFR0_EL1 = 0x1101000010110011 (GIC field 0); hv_vcpu_set_pending_interrupt(IRQ) = Ok(())
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: the on-Mac test the checkpoint runs as gic-live, with its own output shown.
course/captures/12-gic-live.txt

As assumed. It also reads ID_AA64PFR0_EL1, the CPU feature register a kernel checks before touching ICC_* registers: its GIC field is 1 with the GIC, 0 without.

A line, not a call

In chapter 09 the PL011 drove an IrqLine, and the machine passed NullIrq, connected to nothing. The IrqLine trait itself does not change: from here on it is frozen (chapter 09's word: later chapters use it exactly as given). What is new is a line that reaches the GIC.

Why a line object and not a direct call to hv_gic_set_spi? Three reasons. The PL011 stays testable on any machine with TestIrq. The device never learns its INTID: the machine picks 33 and checks it once. And the device stays in the vmm crate, which forbids unsafe: only hvf makes the foreign call.

An IrqLine connected to the GIC is a GicSpi, in learner/crates/vmm/src/irq.rs. It sends its level through a backend trait:

crates/vmm/src/irq.rslines 123-134
/// Where a [`GicSpi`] sends its level: `hvf::GicHandle` on a real machine, a recorder in host/// tests. `Send + Sync` because every [`IrqLine`] is.pub trait SpiBackend: Send + Sync {    /// `hv_gic_set_spi(intid, level)`.    fn set_spi(&self, intid: u32, level: bool) -> Result<(), hvf::CallError>;}impl SpiBackend for hvf::GicHandle {    fn set_spi(&self, intid: u32, level: bool) -> Result<(), hvf::CallError> {        hvf::GicHandle::set_spi(self, intid, level)    }}

The real backend is GicHandle, from learner/crates/hvf/src/gic.rs:

crates/hvf/src/gic.rslines 370-392
/// `Copy + Send + Sync` capability to drive interrupt lines from any thread.////// It holds no pointer (the framework's GIC is per process), only the generation of the VM it/// was made for. Once that VM is destroyed every call returns `HV_BAD_ARGUMENT`, also after a/// new VM with its own GIC exists, so a handle that survives a reboot cannot raise lines in the/// next boot's guest (`vm::with_live_vm`; test `stale_gic_tokens_are_refused`).#[derive(Clone, Copy, Debug)]pub struct GicHandle {    generation: u64,}impl GicHandle {    /// Assert (`level = true`) or deassert an SPI. Any thread; wakes a vCPU sitting in    /// in-kernel WFI (checked on a real Mac). An INTID outside the SPI range, or inside the MSI    /// range, returns `HV_BAD_ARGUMENT` (`hv_gic.h`); `vmm::irq::GicSpi` validates first.    pub fn set_spi(&self, intid: u32, level: bool) -> Result<(), CallError> {        with_live_vm(self.generation, "hv_gic_set_spi", || {            // SAFETY: plain values; the framework validates `intid`.            check("hv_gic_set_spi", unsafe {                ffi::hv_gic_set_spi(intid, level)            })        })    }
crates/vmm/src/irq.rslines 204-242
/// A level-sensitive line wired to one SPI of the in-kernel GIC (`hv_gic_set_spi`, `hv_gic.h`).pub struct GicSpi<B: SpiBackend = hvf::GicHandle> {    intid: u32,    backend: B,    /// Set after the first `hv_gic_set_spi` failure, so it is logged once per line.    failed: AtomicBool,}impl<B: SpiBackend> GicSpi<B> {    /// Wire `intid` through `backend`, if `limits` allow it (module docs).    pub fn new(intid: u32, limits: &SpiLimits, backend: B) -> Result<GicSpi<B>, SpiError> {        limits.check(intid)?;        Ok(GicSpi {            intid,            backend,            failed: AtomicBool::new(false),        })    }    /// The INTID this line drives.    pub fn intid(&self) -> u32 {        self.intid    }}impl<B: SpiBackend> IrqLine for GicSpi<B> {    /// `hv_gic_set_spi(intid, high)`. Non-blocking and callable with a device mutex held. An    /// error is logged once for this line and otherwise ignored (module docs): never fatal.    fn set_level(&self, high: bool) {        if let Err(e) = self.backend.set_spi(self.intid, high)            && !self.failed.swap(true, Ordering::Relaxed)        {            crate::guest_warn!(                "interrupt line INTID {}: {e} (further errors on this line are not logged)",                self.intid            );        }    }}

B is the backend: the real GicHandle (a cheap copyable handle to the VM's GIC, from Gic::handle) by default, or a fake in contract tests. failed.swap(true) returns the old value, so only the first failure is logged.

Two threads move this line: the vCPU thread, and chapter 09's stdin thread when a byte arrives (Pl011::input_ready, with the PL011's Mutex held, so the level sent is the device's). The per-vCPU functions in hv_gic.h say "Must be called by the owning thread"; the header gives hv_gic_set_spi no such rule, and our irq run below shows it working, every keystroke reaching the GIC from the stdin thread.

GicSpi::new refuses an INTID that is not an SPI, or that falls in the block reserved for message-signalled interrupts:

crates/vmm/src/irq.rslines 175-200
impl SpiLimits {    /// The limits of the live in-kernel GIC: its SPI range, minus the board's GICv2m MSI block    /// (the board reserves INTIDs 80..143 for MSIs whether or not a frame is configured).    pub fn of(gic: &hvf::Gic) -> Result<SpiLimits, hvf::CallError> {        Ok(SpiLimits {            spi: gic.spi_range()?,            msi: Some(GIC_V2M_INTIDS),        })    }    /// Is `intid` a valid wired line?    pub fn check(&self, intid: u32) -> Result<(), SpiError> {        if !self.spi.contains(&intid) {            return Err(SpiError::NotAnSpi {                intid,                spi: self.spi.clone(),            });        }        if let Some(msi) = self.msi            && msi.contains(intid)        {            return Err(SpiError::InMsiRange { intid, msi });        }        Ok(())    }}

Aside

INTIDs from 8192 up are LPIs (locality-specific peripheral interrupts): messages a PCI (Peripheral Component Interconnect) device writes to memory instead of wires. Our board keeps INTIDs 80 to 143 for such message-signalled interrupts, which is why GicSpi refuses them; see IHI 0069's LPI chapter.

The machine wires the lines once, in learner/crates/vmm/src/machine/virt.rs; Machine::build passes them to chapter 09's register_platform:

crates/vmm/src/machine/virt.rslines 374-394
/// The platform lines for this boot: `GicSpi(33)` for the PL011 and `GicSpi(34)` for the PL031/// on the in-kernel GIC (each validated against the GIC's SPI range and the MSI block before/// the guest runs, so a wiring bug can never reach the framework), or `NullIrq` without a GIC.pub fn platform_irqs(gic: Option<&hvf::Gic>) -> Result<PlatformIrqs> {    let Some(gic) = gic else {        return Ok(PlatformIrqs::none());    };    let limits = SpiLimits::of(gic).map_err(|err| Error::Hv {        op: "query the GIC's SPI range",        err,    })?;    let line = |intid: u32| -> Result<Arc<dyn IrqLine>> {        let spi = GicSpi::new(intid, &limits, gic.handle())            .map_err(|e| Error::Config(format!("in-kernel GIC: {e}")))?;        Ok(Arc::new(spi))    };    Ok(PlatformIrqs {        pl011: line(PL011_INTID)?,        pl031: line(PL031_INTID)?,    })}

The PL031's alarm gets SPI 2, INTID 34, the same way; find its <0x00 0x02 0x04> in the device tree above. Chapter 09's helper thread for the alarm now has a line that reaches a guest.

Security

A hostile guest can make us call hv_gic_set_spi millions of times a second. So it never chooses an INTID: the machine fixes and checks it before the guest runs. And a failing call is logged once per line, never a crash or a log flood: a lost interrupt is the guest's problem, a crashed VMM is everyone's.

Telling the guest, in code

In learner/crates/vmm/src/fdt/machine.rs, the three cells get names, from Linux's arm-gic.h binding header:

crates/vmm/src/fdt/machine.rslines 66-74
/// Interrupt-specifier cells (`dt-bindings/interrupt-controller/arm-gic.h`, `irq.h`).pub const GIC_SPI: u32 = 0;pub const GIC_PPI: u32 = 1;pub const IRQ_TYPE_LEVEL_HIGH: u32 = 4;/// The four architected-timer PPIs in the order `arm,arch_timer.yaml` lists them: secure/// physical (13 → INTID 29), non-secure physical (14 → 30), **virtual** (11 → 27; delivered/// in-kernel by the GIC, or as `HV_EXIT_REASON_VTIMER_ACTIVATED` only with `--irqchip none`)/// and hypervisor physical (10 → 26).pub const TIMER_PPIS: [u32; 4] = [13, 14, 11, 10];

One function owns the SPI offset, so no node can forget it:

crates/vmm/src/fdt/machine.rslines 161-167
/// `<GIC_SPI n IRQ_TYPE_LEVEL_HIGH>` for an SPI INTID (32..=1019, GIC spec IHI 0069 §2.2).pub fn spi_cells(intid: u32) -> Result<[u32; 3], FdtError> {    match intid.checked_sub(32) {        Some(n) if intid <= 1019 => Ok([GIC_SPI, n, IRQ_TYPE_LEVEL_HIGH]),        _ => Err(bad(format!("INTID {intid} is not an SPI"))),    }}

The GIC node, with the redistributor range sized for the number of vCPUs, and the timer node with its PPIs:

crates/vmm/src/fdt/machine.rslines 313-334
/// `/intc@8000000` (`arm,gic-v3.yaml`): the in-kernel GICv3 HVF emulates at the layout bases/// (`vm::create_vm`). `reg[0]` is the distributor, `reg[1]` one redistributor region of/// `ncpus` 128 KiB frames (RD_base + SGI_base, IHI 0069 section 12.10). No ITS and no v2m frame: the/// virtio-mmio devices use wired SPIs.fn gic(w: &mut FdtWriter, layout: &Layout, d: &MachineDesc) -> Result<(), FdtError> {    let gicr = layout        .gicr_size(d.ncpus)        .ok_or_else(|| bad(format!("{} vCPUs (1..={MAX_CPUS})", d.ncpus)))?;    let n = w.begin_node(&format!("intc@{GICD_BASE:x}"))?;    w.prop_str("compatible", "arm,gic-v3")?;    w.prop_u32("#interrupt-cells", 3)?;    w.prop_null("interrupt-controller")?;    w.prop_u32("#address-cells", 2)?;    w.prop_u32("#size-cells", 2)?;    w.prop_null("ranges")?;    w.prop_u32("#redistributor-regions", 1)?;    let mut reg = reg64(GICD_BASE, GICD_SIZE).to_vec();    reg.extend_from_slice(&reg64(GICR_BASE, gicr));    w.prop_cells("reg", &reg)?;    w.prop_u32("phandle", GIC_PHANDLE)?;    w.end_node(n)}
crates/vmm/src/fdt/machine.rslines 295-309
/// `/timer` (`arm,arch_timer.yaml`). No `clock-frequency`: the binding says firmware should/// set `CNTFRQ_EL0` instead, and HVF does (24 MHz, measured on this Mac).fn timer(w: &mut FdtWriter, with_gic: bool) -> Result<(), FdtError> {    let n = w.begin_node("timer")?;    w.prop_strs("compatible", &["arm,armv8-timer", "arm,armv7-timer"])?;    w.prop_null("always-on")?;    if with_gic {        let cells: Vec<u32> = TIMER_PPIS            .iter()            .flat_map(|&ppi| [GIC_PPI, ppi, IRQ_TYPE_LEVEL_HIGH])            .collect();        w.prop_cells("interrupts", &cells)?;    }    w.end_node(n)}

Now put back the with_gic lines you left out in chapter 10: the root node's interrupt-parent and the gic call, and each PrimeCell's interrupts:

crates/vmm/src/fdt/machine.rslines 391-431
let mut w = FdtWriter::new();let root = w.begin_node("")?;w.prop_str("compatible", "linux,dummy-virt")?;w.prop_str("model", "macvmm-virt")?;w.prop_u32("#address-cells", 2)?;w.prop_u32("#size-cells", 2)?;if with_gic {    w.prop_u32("interrupt-parent", GIC_PHANDLE)?;}w.prop_null("dma-coherent")?;chosen(&mut w, layout, desc)?;memory(&mut w, layout, desc)?;cpus(&mut w, desc)?;psci(&mut w)?;timer(&mut w, with_gic)?;if with_gic {    gic(&mut w, layout, desc)?;}apb_pclk(&mut w)?;primecell(    &mut w,    row(layout, PL011_BASE)?,    &["arm,pl011", "arm,primecell"],    &["uartclk", "apb_pclk"],    with_gic,)?;primecell(    &mut w,    row(layout, PL031_BASE)?,    &["arm,pl031", "arm,primecell"],    &["apb_pclk"],    with_gic,)?;for slot in slots {    virtio_slot(&mut w, layout, slot)?;}w.end_node(root)?;// The boot CPU is vCPU 0, whose `reg` is 0.w.finish(0)
crates/vmm/src/fdt/machine.rslines 171-193
/// An AMBA PrimeCell node (`arm,primecell.yaml`) named from its layout row: `reg`, one/// level-high SPI, and the APB clock(s) the AMBA bus enables before probing.fn primecell(    w: &mut FdtWriter,    region: &Region,    compatible: &[&str],    clock_names: &[&str],    with_gic: bool,) -> Result<(), FdtError> {    let intid = region        .intid        .ok_or_else(|| bad(format!("{} has no interrupt", region.name)))?;    let n = w.begin_node(&format!("{}@{}", region.name, region.unit_address()))?;    w.prop_strs("compatible", compatible)?;    w.prop_cells("reg", &reg64(region.base, region.size))?;    if with_gic {        w.prop_cells("interrupts", &spi_cells(intid)?)?;    }    let clocks: Vec<u32> = clock_names.iter().map(|_| APB_PCLK_PHANDLE).collect();    w.prop_cells("clocks", &clocks)?;    w.prop_strs("clock-names", clock_names)?;    w.end_node(n)}

Three keystrokes, three interrupts

The irq test guest is given; you only read it. It finds its redistributor (by reading each frame's affinity in GICR_TYPER) and wakes it: after reset a redistributor assumes its CPU is powered down and delivers nothing until software clears its sleep bit, GICR_WAKER.ProcessorSleep. It opens its CPU interface with priority mask 0xff, the least restrictive value (any priority more urgent than 0xff gets through). Then it configures INTID 33:

guests/common/gic.rslines 231-245
/// Configure SPI `intid` (32..1019): Group 1, [`PRIORITY`], level-sensitive, routed to the CPU/// with MPIDR `target`, enabled (IHI 0069 §12.9: IGROUPR, IPRIORITYR, ICFGR, IROUTER,/// ISENABLER).pub fn enable_spi(intid: u32, target: u64) {    let n = intid as usize;    let bit = 1u32 << (intid % 32);    let g = GICD_BASE + GICD_IGROUPR + (n / 32) * 4;    wr32(g, rd32(g) | bit);    set_priority_byte(GICD_BASE + GICD_IPRIORITYR, intid, PRIORITY);    let cfg = GICD_BASE + GICD_ICFGR + (n / 16) * 4;    wr32(cfg, rd32(cfg) & !(2 << ((intid % 16) * 2))); // 0 = level-sensitive    wr64(GICD_BASE + GICD_IROUTER + n * 8, irouter_affinity(target));    wr32(GICD_BASE + GICD_ISENABLER + (n / 32) * 4, bit);    wait_rwp();}

Its handler is sitting A's five steps; it drains DR before the EOI:

guests/irq/main.rslines 43-59
fn on_irq(_frame: &mut ExceptionFrame) {    let intid = gic::ack();    if intid == gic::SPURIOUS {        bump(&SPURIOUS);        return;    }    if intid == PL011_INTID {        while uart::getc().is_some() {            bump(&BYTES);        }        bump(&IRQS);    } else {        bump(&OTHER);    }    LAST_INTID.store(intid, Ordering::Relaxed);    gic::eoi(intid);}
guests/common/gic.rslines 249-262
/// Acknowledge the highest-priority pending Group 1 interrupt (`ICC_IAR1_EL1`); [`SPURIOUS`]/// when there is none.pub fn ack() -> u32 {    let v: u64;    // SAFETY: reading IAR1 acknowledges an interrupt; it has no memory effects.    unsafe { asm!("mrs {}, icc_iar1_el1", out(reg) v, options(nomem, nostack)) };    (v & 0x00ff_ffff) as u32}/// End the interrupt `intid` returned by [`ack`] (`ICC_EOIR1_EL1`). Never for [`SPURIOUS`].pub fn eoi(intid: u32) {    // SAFETY: writing EOIR1 drops the running priority and deactivates `intid`.    unsafe { asm!("msr icc_eoir1_el1, {}", "isb", in(reg) u64::from(intid), options(nostack)) };}

Build the guests if irq.bin is missing (scripts/build-guests.sh from the repository root). From inside learner/, run it; when irq: ready appears, type a, b and c within ten seconds (no Enter), or --timeout ends the run with exit code 5:

Shell
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw "$G/irq.bin@0x40080000" --timeout 10 --stats

Our capture ran from the repository root with the keys piped in. In a terminal you will also see a first line, macvmm: console attached; Ctrl-A x quits…. Times will differ; counts should not.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsexit: 0--- stdout ---irq: pfr0.gic=1irq: readyirq: 3 irqs intid=33 spurious=0 other=0 bytes=3--- stderr ---macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=75 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 162: hvc 1, data abort 161macvmm: stats: vcpu0 time: exec 0.000 s, wfi 3.844 smacvmm: stats: host cpu 0.001 s over 3.845 s wall (1%)macvmm: stats: rlimit core=0 nofile=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The keystrokes a, b and c were piped to stdin 3 s after start, then 0.5 s apart (in a terminal, type them after irq: ready).
course/captures/12-irq-typed.txt

pfr0.gic=1 is the feature field the on-Mac test read. Three interrupts, all INTID 33, none spurious, three bytes, and 162 exits. We traced every exit and counted each guest-physical address:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --trace exits:t.jsonl:all > /dev/null; grep -o '"ipa":"[^"]*"' t.jsonl | sort | uniq -c; wc -l < t.jsonlexit: 0--- stdout ---  78 "ipa":"0x9000000"  81 "ipa":"0x9000018"   1 "ipa":"0x900002c"   1 "ipa":"0x9000038"     162
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The keystrokes a, b and c were piped to stdin 3 s after start, then 0.5 s apart. The trace has one line per VM exit; the grep counts the guest-physical address (IPA) of each MMIO exit.
course/captures/12-irq-exits.txt

The counts add to 161 MMIO (memory-mapped I/O) exits, all PL011 registers (--stats lists them as data abort, as in chapter 07), plus the power-off hypercall; most are the guest printing its own 75 characters. The guest also wrote dozens of GIC registers and read the IAR three times, and none of that exited: the kernel's GIC answered it.

The measurement

Chapter 11's run, with no interrupt controller:

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

And the same ten sleeps, through the in-kernel GIC:

TerminalReal output
macvmm run --mem 64M --raw {guests}/timer.bin@0x40080000 --stats --trace exits:{out}/t.jsonl:all --timeout 10exit: 0--- stdout ---timer: cntfrq=24000000timer: interval 0 = 105 ms oktimer: interval 1 = 105 ms oktimer: interval 2 = 103 ms oktimer: interval 3 = 105 ms oktimer: interval 4 = 105 ms oktimer: interval 5 = 105 ms oktimer: interval 6 = 105 ms oktimer: interval 7 = 105 ms oktimer: interval 8 = 105 ms oktimer: interval 9 = 104 ms oktimer: irqs=10 spurious=0timer: 10/10 intervals within 95..150 ms--- stderr ---macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=390 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 391: hvc 391macvmm: stats: vcpu0 time: exec 0.000 s, wfi 1.048 smacvmm: stats: host cpu 0.003 s over 1.050 s wall (1%)macvmm: stats: rlimit core=0 nofile=1048576
captured: run "timer" of checkpoint 12, captured from the reference on real hardwarecourse/captures/12-timer.txt

Check your Predict entry. The answer is (c): vtimer 0, wfx 0. All 391 exits are hvc: one debug hypercall per printed character (chapter 03), plus a PSCI (power state coordination interface) SYSTEM_OFF (chapter 08). Chapter 11 paid three exits per tick; we pay none, and 0.003 s of host CPU.

If you picked (a), you held a natural belief: that the VMM must see every interrupt. With the GIC in the kernel, the tick never reaches us.

Did we lose punctuality? Single runs vary (several of chapter 11's intervals above read 110 ms), so we ran each mode three times; the first three lines use the in-kernel GIC, the last three chapter 11's mode:

TerminalReal output
for i in 1 2 3; do cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/timer.bin@0x40080000 | sed -n 's/.*= \([0-9]*\) ms.*/\1/p' | tr '\n' ' '; echo; done; for i in 1 2 3; do cargo run -q -p macvmm -- run --irqchip none --mem 64M --raw target/guests/aarch64-unknown-none/release/timer-nogic.bin@0x40080000 | sed -n 's/.*= \([0-9]*\) ms.*/\1/p' | tr '\n' ' '; echo; doneexit: 0--- stdout ---101 105 105 105 105 104 103 105 104 105 105 105 105 105 105 103 105 105 103 105 101 105 105 102 105 105 104 105 101 105 105 102 105 104 104 104 105 104 105 105 102 105 105 105 105 103 101 100 105 100 100 101 105 103 105 101 105 105 103 101 
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. Each line is one run's ten intervals in ms: three runs with the in-kernel GIC (timer guest), then three with --irqchip none (chapter 11's timer-nogic guest).
course/captures/12-timer-repeat.txt

Most intervals woke 0 to 5 ms late in both modes; we could not see a difference on our Mac. What we gave up is control: the timer, the wake-up and the delivery happen where none of our code runs, so we cannot log a tick or tighten a wake-up. For a VMM whose job is to run kernels fast, that is a good trade.

Production note

Linux's KVM (its kernel-based virtual machine module, chapter 00) makes the same choice: its GIC for Arm guests, the vGIC, lives in the host kernel, and Firecracker and crosvm both use it, paying the same price in visibility.

Breaking it on purpose

Three breaks, each predicted first; undo each before the next.

Deliberate breakage 1: never lower the line. In learner/crates/vmm/src/devices/pl011.rs, change Pl011::update_irq to call set_level(true) when the masked status is non-zero, and do nothing otherwise. Predict: after you type a, how many interrupts will the guest count, and will it ever print its final line?

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsexit: 5--- stdout ---irq: pfr0.gic=1irq: ready--- stderr ---macvmm: timeout: the guest was still running after --timeout 10smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=27 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 4212050: data abort 4212050macvmm: stats: vcpu0 time: exec 1.633 s, wfi 2.699 smacvmm: stats: host cpu 6.849 s over 10.001 s wall (69%)macvmm: stats: rlimit core=0 nofile=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: Pl011::update_irq only ever raises the line (set_level(true) when RIS & IMSC != 0; never set_level(false)).
  • The keystrokes a, b and c were piped to stdin 3 s after start, then 0.5 s apart (in a terminal, type them after irq: ready).
course/captures/12-never-lower.txt

The guest printed irq: ready, then nothing. It made about 4.2 million exits in the seven seconds after the first key, a host core nearly saturated (69% averaged over the whole 10 s run). Every EOI found INTID 33 still high, so the handler ran again at once, reading FR (one exit) to find the FIFO empty. It counts without end, but the main loop, which would print once the count reached 3, never got to run.

What you saw: an interrupt storm with no progress. The misconception: "an interrupt is a message, sent once". It is a level, and a level is state. The tool: --stats, whose data-abort count exploded while the guest's output stood still.

For contrast, we broke the guest instead, PL011 back to normal: an irq handler that never reads DR, counts interrupts for one second, then masks the UART in IMSC and prints. It needs guest edits beyond this chapter, so read our run, with one key typed:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsexit: 0--- stdout ---irq: pfr0.gic=1irq: readyirq: 985326 irqs intid=33 spurious=0 other=0 bytes=0--- stderr ---macvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=80 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 164: hvc 1, data abort 163macvmm: stats: vcpu0 time: exec 0.396 s, wfi 2.824 smacvmm: stats: host cpu 0.941 s over 3.825 s wall (25%)macvmm: stats: rlimit core=0 nofile=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Our run of a modified guest (not a Try it): the irq guest's handler changed to never read DR (no drain). It counts interrupts for one second after the first, then writes 0 to UARTIMSC to stop them and prints. The VMM is the unmodified reference.
  • One keystroke, a, was piped to stdin 3 s after start.
course/captures/12-no-drain.txt

About a million interrupts for one byte, and only 164 exits: the handler touched only GIC registers, which never exit. The only VMM-side traces are the host CPU and vCPU exec time in --stats (0.941 s and 0.396 s, up from 0.001 s and 0.000 s in the normal run).

Deliberate breakage 2: create the GIC at the wrong time. Three edits. In learner/crates/hvf/src/gic.rs, change pub(crate) fn create to pub fn create. In learner/crates/hvf/src/lib.rs, add pub use gic::create; (GicConfig is already exported). Then in learner/crates/macvmm/src/first_exit.rs, chapter 02's first-exit, call hvf::create with a GicConfig holding the board's two bases and msi: None, and generation 0: once before VmBuilder::new().create() and once right after the vCPU is created, printing each Result with {:?}. Making it public removes the compiler's guarantee from earlier, which is why the experiment can break the rule; undo all three edits afterwards. Predict: errors, a crash, or a GIC without a vCPU interface?

TerminalReal output
cargo run -q -p macvmm -- first-exitexit: 0--- stdout ---first-exit: hv_gic_create before hv_vm_create: Err("hv_gic_create: HV_NO_DEVICE (0xfae94006)")first-exit: mapped 16 KiB at IPA 0x40000000first-exit: hv_gic_create after hv_vcpu_create: Err("hv_gic_create: HV_BUSY (0xfae94002)")first-exit: exit reason=EXCEPTION syndrome=0x5a000000 ec=0x16 (HVC64) imm=0x0first-exit: pc=0x40000008 x0=0x2a
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 2: chapter 02's first-exit, with two extra hv_gic_create calls (distributor 0x0800_0000, redistributors 0x080A_0000, no MSI frame): one before hv_vm_create and one right after hv_vcpu_create. Each prints the call's result.
course/captures/12-gic-order.txt

Two different clean errors: HV_NO_DEVICE with no VM yet, HV_BUSY once a vCPU exists. The guest still runs, without a GIC. The GIC hands out a redistributor and a CPU interface as each vCPU is created, so it must come first.

What you saw: the API refusing, as its header promised. The misconception: "the order in which you create objects does not matter". The tool: reading the header comment, and a wrapper whose types make the wrong order impossible.

Deliberate breakage 3: an SPI written as a PPI. In spi_cells, write GIC_PPI instead of GIC_SPI as the first cell. The VMM still drives INTID 33. Rebuild and dump the tree with the --dtb-out and dtc commands from chapter 10 (check 3 of "Your turn" below). Predict: which INTID will a guest that believes the device tree listen on?

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/hello.bin@0x40080000 --dtb-out v.dtb --timeout 10 && dtc -I dtb -O dts v.dtb | grep -A6 'pl011@9000000 {'exit: 0--- stdout ---	pl011@9000000 {		compatible = "arm,pl011", "arm,primecell";		reg = <0x00 0x9000000 0x00 0x1000>;		interrupts = <0x01 0x01 0x04>;		clocks = <0x02 0x02>;		clock-names = "uartclk", "apb_pclk";	};
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 3: in crates/vmm/src/fdt/machine.rs, spi_cells writes GIC_PPI (1) instead of GIC_SPI (0) as the first cell; the VMM still drives INTID 33.
  • dtc's own warnings are discarded, as is the guest's output.
course/captures/12-ppi-dtb.txt

<0x01 0x01 0x04> reads as PPI 1, that is INTID 17. The guest half needs guest edits beyond this chapter, so read our run: we changed the irq guest to do what such a guest would, enabling INTID 17 in its redistributor instead of SPI 33, and typed three keys:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsexit: 5--- stdout ---irq: pfr0.gic=1irq: ready--- stderr ---macvmm: timeout: the guest was still running after --timeout 10smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=27 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 57: canceled 1, data abort 56macvmm: stats: vcpu0 time: exec 0.000 s, wfi 10.003 smacvmm: stats: host cpu 0.000 s over 10.004 s wall (1%)macvmm: stats: rlimit core=0 nofile=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 3, the guest's side: the VMM from 12-ppi-dtb.txt, and the irq guest changed to enable INTID 17 as a private interrupt (rd.enable_ppi(17)) instead of SPI 33, which is what a guest that believes interrupts = <1 1 4> would do.
  • The keystrokes a, b and c were piped to stdin 3 s after start, then 0.5 s apart.
course/captures/12-ppi-guest.txt

Silence, then a timeout. The device raised INTID 33, which the guest never enabled; the guest enabled INTID 17, which nothing drives.

What you saw: a guest that waits forever with nothing wrong in either half on its own. The misconception: "the kind cell is a label; the number alone names the line". The tool: --dtb-out and dtc, reading the promise the VMM actually made, as chapter 10 taught.

Your turn

Check that you typed every piece: hvf/src/ffi.rs; hvf/src/gic.rs; the GIC step in hvf/src/vm.rs; GicFacts, layout_spis and the checks in vmm/src/vm.rs, called from Machine::build; vmm/src/irq.rs; platform_irqs; and the device tree nodes with with_gic restored. Then, from inside learner/ with G set as before, check:

  1. The irq run prints irq: 3 irqs intid=33 spurious=0 other=0 bytes=3 after you type three keys.

  2. The timer guest's --stats line shows vtimer 0, wfx 0:

    Shell
    cargo run -q -p macvmm -- run --mem 64M --raw "$G/timer.bin@0x40080000" --stats
  3. Your device tree shows the PL011 with <0x00 0x01 0x04> and the timer with interrupts = <0x01 0x0d 0x04 0x01 0x0e 0x04 0x01 0x0b 0x04 0x01 0x0a 0x04>, PPIs 13, 14, 11 and 10 in hexadecimal (dtc is installed with brew install dtc, chapter 10):

    Shell
    cargo run -q -p macvmm -- run --mem 64M --raw "$G/hello.bin@0x40080000" --dtb-out v.dtb --timeout 10dtc -I dtb -O dts v.dtb
  4. Your journal has the Predict entry, written before your first timer run.

Stuck? scripts/learner hint 12 gives four hints, from a nudge to the exact reference file.

Checkpoint

Back at the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 12

You should see, as the last line:

CHECKPOINT 12 PASS

It runs the contract tests (GicSpi refuses wrong INTIDs; the PL011's line drops on drain and on mask), the irq guest with a, b and c typed 200 ms apart, the timer guest (no VTIMER or WFI exits, host CPU under 10%) and the on-Mac GIC test, then checks your journal. On our Mac, against the reference:

TerminalReal output
scripts/checkpoint.sh 12exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   irq_lines (4 tests)[PASS] runs on your Mac irq: 3/3 serial markers, exit 0 in 0.49s[PASS] runs on your Mac timer: 7/7 serial markers, 1/1 trace markers, host cpu 2% < 10%, exit 0 in 1.09s[PASS] runs on your Mac gic-live: HVF contract hvf_gic_live (2 tests) in 0.42s[INFO] journal          not checked (not a learner tree)CHECKPOINT 12 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The chapter's checkpoint, run against an unmodified copy of the reference (scripts/checkpoint.sh 12 --impl <tree>): what a finished chapter 12 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/12-checkpoint.txt

The irq step compares against this run ({guests} is the guest directory, {out} the scratch folder); the timer step against the timer run in The measurement:

TerminalReal output
macvmm run --mem 64M --raw {guests}/irq.bin@0x40080000 --timeout 10exit: 0--- stdout ---irq: pfr0.gic=1irq: readyirq: 3 irqs intid=33 spurious=0 other=0 bytes=3
captured: run "irq" of checkpoint 12, captured from the reference on real hardwarecourse/captures/12-irq.txt

What now works: your VMM creates the GICv3 in the one window the API allows and refuses to boot if its geometry differs from what the guest is told; the PL011 interrupts a guest through INTID 33, described in the device tree; and the timer and idle cost zero exits, with the numbers to show it.

The next chapter starts from this state (the reference at the end of chapter 12).

What's next

Rows 1 to 7 of the ledger now work for one CPU (row 4's CPU_ON waits for chapter 20). That is everything a Linux kernel needs from the machine; what it still needs is to be loaded. Chapter 13 opens row 10, the boot chain: your VMM becomes the kernel's loader.

Open question

The irq run's --stats shows zero WFI exits and nearly four seconds of in-kernel WFI. In chapter 11 the vCPU slept on our condition variable, and we had to wake it. Who wakes a vCPU sleeping in WFI when a UART byte arrives now, and why does it no longer need a kick from us?

Spec hunt

  • GICv3 architecture specification (Arm IHI 0069), the section on INTIDs in the chapter "Distribution and routing of interrupts": which INTID ranges are reserved, and what are 1020 to 1023 used for besides 1023?
  • IHI 0069, the register page for ICC_EOIR1_EL1 (and ICC_CTLR_EL1.EOImode): what does an EOI write do in two steps (priority drop, then deactivation), and when would a kernel want them separated?
  • The SDK header hv_gic.h, the comment on hv_gic_set_spi: what does a level of false do to an edge-triggered interrupt, and which INTIDs make it return HV_BAD_ARGUMENT?
Progress is stored only in this browser.