Chapter 12 · Part V
Why an interrupt controller, and why in the kernel
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.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A guest reads
CNTV_CTL_EL0and gets0b101. Is its timer raising its interrupt output right now? What about0b111?Show answer
0b101isENABLE(bit 0) andISTATUS(bit 2) withIMASK(bit 1) clear: enabled, not masked, count reached, so yes, the output is up.0b111hasIMASKset as well: the condition still holds, but the interrupt is masked at the timer, so the output is down.From chapter 11: Getting the CPU back: the timer and a bare interrupt
The counter runs at 24 MHz. A guest wants an alarm 250 ms from now and reads
CNTVCT_EL0 = 1,000,000. What does it write toCNTV_CVAL_EL0?Show answer
250 ms is a quarter of 24,000,000 ticks, 6,000,000 ticks, so it writes 7,000,000. The compare value is an absolute count, not a delay.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A VMM sets the vtimer offset to the host's tick count when the VM boots. Ten minutes later the guest is paused for an hour and then resumed without changing anything. What does the guest's counter show on resume, and what offset would make it continue where it stopped?
Show answer
It jumps forward by an hour of ticks, because
CNTVCT = mach_absolute_time() - offsetand the host kept counting. To resume where it stopped, recompute the offset as the host count now minus the count the guest last saw (restore_offset(now, saved)); then the counter continues fromsaved.From chapter 11: Getting the CPU back: the timer and a bare interrupt
With no interrupt controller, your VMM got a
VTIMER_ACTIVATEDexit. Before the next entry the guest'sCNTV_CTL_EL0still readsENABLE = 1, IMASK = 0, ISTATUS = 1. Do you unmask the vtimer? What do you do instead?Show answer
No: the level line is still high, so an unmasked vtimer would exit again at once, before the guest could handle anything (a real Mac shows millions of VTIMER exits). Keep it masked and set the vCPU's IRQ pending for this run with
hv_vcpu_set_pending_interrupt; unmask only onceCNTV_CTL_EL0shows the timer quiet.From chapter 11: Getting the CPU back: the timer and a bare interrupt
A guest's timer fires while the guest has
PSTATE.Iset and is busy in a loop for another 200 ms. When does its IRQ handler run, and is the interrupt lost meanwhile?Show answer
When the guest clears the mask, about 200 ms later. It is not lost: the timer's output is a level, still high, and the VMM keeps the IRQ pending before every entry, so the interrupt waits as state until the CPU listens.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A WFI exit arrives with the PC at
0x40081188. Where must the PC point when you resume the guest, and is it a bug if you resume at once without sleeping?Show answer
At
0x4008118c: a trappedWFIleaves the PC at the instruction, so the VMM adds 4. Resuming at once is not a bug, becauseWFIis allowed to end early; it only costs a busy host core while the guest is idle.From chapter 11: Getting the CPU back: the timer and a bare interrupt
Your
--statsline readsvtimer 1, wfx 9435272after a 10-second timeout, and the guest printed one interval. What did your VMM most likely forget?Show answer
To unmask the vtimer once the guest silenced it. The framework masks the vtimer at the first VTIMER exit; if it stays masked, no further VTIMER exit comes, the WFI handler finds the deadline already past and wakes at once, and guest and VMM loop on WFI exits.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A tick handled with no interrupt controller costs three exits. Your exit costs 1.43 µs. What host CPU do the exits alone cost at 10 Hz and at 250 Hz, and why was the measured 250 Hz cost (23% of a core) so much higher?
Show answer
30 exits per second is about 43 µs per second (0.004%); 750 per second would be about 1 ms per second (0.1%). The measured cost was the guest's own time: after each tick it re-took the stale pending IRQ for over a millisecond until the kick let the VMM drop the line, because the VMM cannot see the guest finish with the interrupt. That lost time also slowed the guest to about 150 ticks per second.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A key press is signalled as a short pulse while the CPU has IRQs masked. With no latch, what happens to it? Which PL011 register is the latch?
Show answer
It is lost: an edge is an event, and nobody was listening. The PL011's
RISlatches it (it remembers that a byte arrived until the guest clears it), andMIS,RIScombined with the maskIMSC, turns that memory into a level output.From chapter 09: A device is a state machine: the bus, PL011 and PL031
A guest reads the PL011's flag register
FRand gets0x90. May it write a byte toDRnow, and is there a byte for it to read?Show answer
0x90is 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 aDRread now would return 0.From chapter 09: A device is a state machine: the bus, PL011 and PL031
The host typed one letter,
a(0x61), and the guest reads the PL011'sDRtwice in a row. What does each read return, and why do they differ?Show answer
0x61, then 0. ADRread pops the receive FIFO: the first read removes the byte it returns, so the second finds the FIFO empty. A register whose read changes the device cannot be modelled as a stored value.From chapter 09: A device is a state machine: the bus, PL011 and PL031
IMSCis 0 when a byte arrives at the PL011. What doRISandMISread, and is the interrupt line high or low?Show answer
RIShas the receive bit (bit 4,0x10) set, and in our model the receive-timeout bit (bit 6) too: the device remembers that it wants attention.MISisRIS & IMSC= 0 and the line stays low: the mask says not to say so. SettingIMSCbit 4 later raises the line at once, because the condition still holds.From chapter 09: A device is a state machine: the bus, PL011 and PL031
The bus holds the PL011 at
0x0900_0000with size0x1000. What doesBus::insertanswer for a device at0x0900_0ff8with size0x10, and for one at0x0900_1000with size0x1000?Show answer
The first is refused with
BusError::Overlap: its first eight bytes fall inside the PL011's window. The second is accepted: it starts exactly where the PL011 ends, so the two windows are adjacent, not overlapping.From chapter 09: A device is a state machine: the bus, PL011 and PL031
A guest makes a 4-byte read at
0x0900_0ffe, two bytes below the end of the PL011's window. Which register does the PL011 see?Show answer
None. The access starts inside the window but runs past its end, so the bus answers
BusError::Straddleand the VMM treats it like an access to no device at all. No device ever sees a partial access, so no device has to reason about one.From chapter 09: A device is a state machine: the bus, PL011 and PL031
The guest stops reading its UART, and you keep typing. Why must the stdin thread's push into
SerialInputdrop bytes instead of waiting for room?Show answer
The same thread reads Ctrl-A x. If it blocked waiting for the guest, a guest that never reads would also stop the host from seeing the quit keys, and the user would lose every in-band way out. So
SerialInputholds 4 KiB, drops and counts the rest, and the thread goes straight back toread.From chapter 09: A device is a state machine: the bus, PL011 and PL031
You press Ctrl-A x in a running
macvmm, and in another run you send it SIGTERM. Which exit code do you get each time, and why that number?Show answer
130 both times. 130 is the shell's code for "ended by SIGINT" (128 + 2), and macvmm uses it for every user quit. A program killed by SIGTERM would report 143, but macvmm catches the signal, stops the VM cleanly and chooses its own code.
From chapter 09: A device is a state machine: the bus, PL011 and PL031
A guest prints the four bytes
ESC [ 6 nto the UART. What would your terminal do with them, and what does macvmm's output filter do?Show answer
They ask the terminal for the cursor position, and the terminal types its answer into the program's input, where the guest, or after macvmm exits your shell, would read it. The default (
safe) filter drops the sequence, so it never reaches the terminal.From chapter 09: A device is a state machine: the bus, PL011 and PL031
Why does the PL031 read the host's wall clock on every
RTCDRaccess instead of storing the boot time and adding the time elapsed since?Show answer
A monotonic clock such as Rust's
Instantstops while the Mac sleeps, so "boot time + elapsed" would fall behind the real date by every hour of sleep. Reading the wall clock each time stays right; the reference also never lets the value go backwards if the host clock is stepped back.From chapter 09: A device is a state machine: the bus, PL011 and PL031
A driver makes an 8-byte read of the PL011's
FR(offset0x18), then a 1-byte read of the same register. What does each return?Show answer
The 8-byte read returns 0, with a rate-limited warning: the PL011's registers are at most 32 bits wide, so that access names no register and is read-as-zero, write-ignored. The 1-byte read returns the low byte of
FR,0x90after reset: a narrow access at a register's offset reaches the register.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A guest stores a byte to
0x0900_0000, where its UART should be, but your VMM has mapped an ordinary page of RAM there. What does the guest see, and what does your VMM see?Show answer
The guest sees a store that worked: the byte sits in RAM, and a load from the same address returns it. Nothing is printed. Your VMM sees nothing at all: a mapped address never causes a VM exit, so the VMM never learns the store happened. A device register needs a stage-2 hole, so each access stops the guest.
From chapter 05: Two stages, one map: holes in stage 2 on purpose
With its MMU on, a guest stores to the virtual address
0x0b10_0000, which its own page tables translate to0x0b00_0000. Nothing is mapped at0x0b00_0000in stage 2. Which address does the VM exit report, and why that one?Show answer
0x0b00_0000, the IPA. Stage 2 is the stage that failed, and by then the hardware had already translated the virtual address through the guest's stage 1, so it records the IPA's page number (inHPFAR_EL2, with the offset fromFAR_EL2) and the VMM never has to read the guest's tables. The virtual address means something only inside the guest's current address space.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A data-abort exit has the syndrome
0x93890046. Is it a load or a store, how wide, and what kind of fault?Show answer
The class is
0x93890046 >> 26 = 0x24, a data abort from the guest. Bit 6 (WnR) is 1, so a write. Bits 23:22 (SAS) are0b10, so1 << 2 = 4bytes. The low six bits (DFSC) are0x06: a translation fault at level 2, meaning stage 2 found no entry for the address.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Your machine has 512 MiB of RAM from
0x4000_0000, so RAM ends at0x6000_0000. How many IPA bits does the address space need, and what doesipa_bits_needed(0x6000_0000)return?Show answer
31 bits would be enough:
1 << 30 = 0x4000_0000is too small,1 << 31 = 0x8000_0000covers0x6000_0000. The function returns 36, because it never asks for less than HVF's default size, so a small machine gets the same VM it would get without the setting.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Where does virtio slot 5 live, and which INTID does it use?
Show answer
At
0x0a00_0000 + 5 × 0x200 = 0x0a00_0a00, with INTID48 + 5 = 53. QEMU'svirtboard wires slot i to shared interrupt line (SPI)16 + i, and SPIs are numbered from INTID 32, so slot i is INTID32 + 16 + i.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A layout puts a trapped device window of
0x200bytes at0x0a00_0200and RAM at0x4000_0000. Which of the two must be 16 KiB-aligned, and why only that one?Show answer
Only RAM. A mapped region goes through
hv_vm_map, which works in whole 16 KiB host pages. A trapped window is never mapped: it is the absence of a mapping, so it can have any size and alignment.From chapter 05: Two stages, one map: holes in stage 2 on purpose
A guest stores to
0x10_0000_0000(1 << 36) in a VM with a 36-bit IPA space. What does the exit's DFSC say?Show answer
0x04: a translation fault at level 0. The address is outside the input range of the stage-2 tables, so the hardware does not look it up at all. We checked this on a real Mac; it is not an address-size fault.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Your VMM hard-codes a 31-bit IPA space and you start a guest with
--mem 2G. What happens, and before or after the guest runs its first instruction?Show answer
Before: RAM from
0x4000_0000would end at0xC000_0000, past1 << 31 = 0x8000_0000, sohv_vm_maprefuses the RAM withHV_BAD_ARGUMENTand the VM never starts. The width of the map has to cover the layout, which is whatipa_bits_neededcomputes.From chapter 05: Two stages, one map: holes in stage 2 on purpose
Without a second translation stage, how would a VMM keep a guest from reaching host memory it does not own, and what would it cost?
Show answer
With shadow page tables: the VMM keeps its own tables that map guest virtual addresses straight to host memory, write-protects the guest's tables, and updates the shadow copy on every trapped write. Every guest page-table write becomes a VM exit, which is why hardware added stage 2.
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; freezingIrqLine; 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,mrsandmsr(chapter 06); the PL011'sIMSCandRIS,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'sMutexis 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_createand before any vCPU, at0x0800_0000and0x080A_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:
| INTIDs | Kind | Belongs to | Examples on our board |
|---|---|---|---|
| 0 to 15 | SGI (software-generated interrupt) | one CPU; another CPU sends it by writing a register | a kernel waking another CPU (chapter 20) |
| 16 to 31 | PPI (private peripheral interrupt) | one CPU; a device inside that CPU | the virtual timer, 27; the physical timer, 30 |
| 32 to 1019 | SPI (shared peripheral interrupt) | any CPU; a device outside the CPUs | PL011 (the UART) 33, PL031 (the real-time clock) 34, virtio devices (chapter 15) from 48 |
| 1023 | special | nobody | "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 1Our 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
mrsandmsr) namedICC_*: priority mask, acknowledge, end of interrupt.
The five jobs, each with its home:
| Job | Where | Registers |
|---|---|---|
| Collect, and tell the handler which line | CPU interface | ICC_IAR1_EL1 returns the INTID |
| Rank | distributor (SPIs) or redistributor (SGIs, PPIs) holds each line's priority; the CPU interface holds the CPU's mask | GICD_IPRIORITYR, GICR_IPRIORITYR; ICC_PMR_EL1 |
| Route to a CPU | distributor | GICD_IROUTER, one per SPI |
| Acknowledge and finish | CPU interface | ICC_IAR1_EL1, then ICC_EOIR1_EL1 |
| Keep lines private | one redistributor per CPU | GICR_* |
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:
- A byte arrives, the PL011 raises its line, and INTID 33 becomes pending.
- 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. - The handler reads the IAR (interrupt acknowledge register,
ICC_IAR1_EL1; the1is 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. - 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. - 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:
Interrupt lifecycle
See an interrupt as state, not a call: a level line, an edge and a latched edge played against a masked CPU, and, from chapter 12, one interrupt inside the GIC, when the source stops asking early, late or never.
Runs in browserOpen full page: Interrupt lifecycleIf the lab does not load, here is what 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-deliveryAn 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:
| Cell | Means | PL011 | Virtual timer |
|---|---|---|---|
| 1 | kind: 0 SPI, 1 PPI | 0 | 1 |
| 2 | number within that kind | 1 | 11 |
| 3 | trigger: 4 level-high, 1 rising edge | 4 | 4 |
| INTID | SPI n = 32 + n; PPI n = 16 + n | 33 | 27 |
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>:
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/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"; };};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:
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:
/// "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:
/// Any thread. Asserts (`level = true`) or deasserts an SPI.pub fn hv_gic_set_spi(intid: u32, level: bool) -> hv_return_t;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;/// `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:
/// `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:
/// 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:
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:
/// 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:
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) }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:
/// 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:
/// 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:
// 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:
cargo test -q -p vmm --features hvf-tests --test hvf_gic_live -- --test-threads=1 --nocapturerunning 2 tests..test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00shvf_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(())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:
/// 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:
/// `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) }) }) }/// 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:
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:
/// 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:
/// 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:
/// `<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:
/// `/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(®64(GICR_BASE, gicr)); w.prop_cells("reg", ®)?; w.prop_u32("phandle", GIC_PHANDLE)?; w.end_node(n)}/// `/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:
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)/// 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", ®64(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:
/// 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:
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);}/// 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:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw "$G/irq.bin@0x40080000" --timeout 10 --statsOur 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.
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsirq: pfr0.gic=1irq: readyirq: 3 irqs intid=33 spurious=0 other=0 bytes=3macvmm: 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=1048576pfr0.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:
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.jsonl 78 "ipa":"0x9000000" 81 "ipa":"0x9000018" 1 "ipa":"0x900002c" 1 "ipa":"0x9000038" 162The 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:
macvmm run --irqchip none --mem 64M --raw {guests}/timer-nogic.bin@0x40080000 --stats --trace exits:{out}/t.jsonl:all --timeout 10timer-nogic: cntfrq=24000000timer-nogic: pfr0.gic=0timer-nogic: interval 0 = 102 ms oktimer-nogic: interval 1 = 110 ms oktimer-nogic: interval 2 = 102 ms oktimer-nogic: interval 3 = 102 ms oktimer-nogic: interval 4 = 106 ms oktimer-nogic: interval 5 = 107 ms oktimer-nogic: interval 6 = 109 ms oktimer-nogic: interval 7 = 110 ms oktimer-nogic: interval 8 = 101 ms oktimer-nogic: interval 9 = 101 ms oktimer-nogic: irqs=10 stale=362066timer-nogic: 10/10 intervals within 95..150 msmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=494 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 10, wfx 10, total 525: canceled 10, vtimer 10, wfx 10, hvc 495macvmm: stats: vcpu0 time: exec 0.016 s, wfi n/amacvmm: stats: host cpu 0.020 s over 1.079 s wall (2%)macvmm: stats: rlimit core=0 nofile=1048576And the same ten sleeps, through the in-kernel GIC:
macvmm run --mem 64M --raw {guests}/timer.bin@0x40080000 --stats --trace exits:{out}/t.jsonl:all --timeout 10timer: 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 msmacvmm: 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=1048576Check 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:
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; done101 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 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?
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsirq: pfr0.gic=1irq: readymacvmm: 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=1048576The 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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsirq: pfr0.gic=1irq: readyirq: 985326 irqs intid=33 spurious=0 other=0 bytes=0macvmm: 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=1048576About 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?
cargo run -q -p macvmm -- first-exitfirst-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=0x2aTwo 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?
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 {' pl011@9000000 { compatible = "arm,pl011", "arm,primecell"; reg = <0x00 0x9000000 0x00 0x1000>; interrupts = <0x01 0x01 0x04>; clocks = <0x02 0x02>; clock-names = "uartclk", "apb_pclk"; };<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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/irq.bin@0x40080000 --timeout 10 --statsirq: pfr0.gic=1irq: readymacvmm: 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=1048576Silence, 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:
The
irqrun printsirq: 3 irqs intid=33 spurious=0 other=0 bytes=3after you type three keys.The timer guest's
--statsline showsvtimer 0, wfx 0:Shell cargo run -q -p macvmm -- run --mem 64M --raw "$G/timer.bin@0x40080000" --statsYour device tree shows the PL011 with
<0x00 0x01 0x04>and the timer withinterrupts = <0x01 0x0d 0x04 0x01 0x0e 0x04 0x01 0x0b 0x04 0x01 0x0a 0x04>, PPIs 13, 14, 11 and 10 in hexadecimal (dtcis installed withbrew 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.dtbYour 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 MacRun this from the repository root:
scripts/checkpoint.sh 12You should see, as the last line:
CHECKPOINT 12 PASSIt 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:
scripts/checkpoint.sh 12checkpoint: 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 PASSThe 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:
macvmm run --mem 64M --raw {guests}/irq.bin@0x40080000 --timeout 10irq: pfr0.gic=1irq: readyirq: 3 irqs intid=33 spurious=0 other=0 bytes=3What 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 aleveloffalsedo to an edge-triggered interrupt, and which INTIDs make it returnHV_BAD_ARGUMENT?