Chapter 17 · Part VII
virtio-rng (worked) and virtio-console (faded)
Course progress: chapter 17 is 18 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 16: Split virtqueues: shared memory with an adversary
A queue of size 8 last served up to
next_avail = 0xFFFE. The device now loadsavail.idx = 0x0002. How many new requests are there, and in which ring slots are their heads?Show answer
Four:
0x0002 - 0xFFFEin wrappingu16arithmetic is 4 (0x10002 - 0xFFFE). The slots are the indices modulo 8:0xFFFE & 7 = 6, then 7, 0 and 1. Nothing special happens at the wrap, because the indices are free-running counters and only the slot is reduced modulo the size.From chapter 16: Split virtqueues: shared memory with an adversary
Same queue,
next_avail = 0, and the device loadsavail.idx = 9. What does it do, and why is "serve 9 requests" wrong?Show answer
It refuses: the queue is marked broken and the transport sets
DEVICE_NEEDS_RESET. Only 8 slots exist, so an honest driver can never be more than 8 requests ahead; a jump of 9 (or 65535) is a broken or hostile driver, and looping over it would re-serve stale slots or burn time the guest chose.From chapter 16: Split virtqueues: shared memory with an adversary
The driver places a size-256 used ring at
0x4000_5002. Which check refuses it, and how many bytes would the ring have needed?Show answer
The alignment check: the used ring must be 4-byte aligned, and
0x...02is not. Had it been aligned, the ring needs6 + 8 × 256 = 2054bytes (flags, idx, 256 elements of{id, len}, andavail_event), all inside one RAM region, computed withchecked_mulandchecked_add.From chapter 16: Split virtqueues: shared memory with an adversary
Descriptor 0 of a size-8 queue is
{addr: 0x0900_0000, len: 8, flags: 0, next: 0}. Every number fits its field. Why does our walker refuse it, and what would a device that accepted it do?Show answer
0x0900_0000is the PL011's MMIO window, not RAM, socheck_rangefails and the walker returnsBufferOutOfRam. A device that accepted it would read or write its "buffer" through whatever lives at that address: a guest could aim the device's own memory accesses at device registers or firmware, the bug class our copy-only, RAM-only memory API exists to rule out.From chapter 16: Split virtqueues: shared memory with an adversary
A chain is
[0: writable, NEXT → 1],[1: readable]. Each descriptor passes its own checks. What doesinto_validatedreturn, and why does the order matter?Show answer
ReadableAfterWritable. The spec has the driver put every device-readable buffer before every device-writable one, so a device can read the whole request before it writes any reply. A device that accepted the mixed order would have to guess which part is the header and which the reply, and a naive one writes its reply into a buffer the guest meant only to be read.From chapter 16: Split virtqueues: shared memory with an adversary
Why can a walker stop a self-looping chain by counting hops instead of remembering which descriptors it visited, and what is the limit?
Show answer
A legal chain uses each descriptor at most once, so it can never be longer than the table: N hops for a queue of size N, or
len / 16inside an indirect table. A walk that wants hop N + 1 must have revisited something, which is a loop or a chain no driver may build. A counter needs no allocation whose size the guest chooses.From chapter 16: Split virtqueues: shared memory with an adversary
A device validates
desc.len, then later readsdesc.lenfrom guest memory again to decide how much to copy. Name the bug and the fix.Show answer
A double fetch, the TOCTOU (time of check to time of use) bug: another guest vCPU can change
lenbetween the check and the use, so the device uses a length it never checked. The fix is to copy the whole descriptor once withread_obj, validate the copy, and use only the copy.From chapter 16: Split virtqueues: shared memory with an adversary
Which two guest-memory accesses of the split ring are ordered, and what does each one order?
Show answer
The acquire load of
avail.idx, which keeps every later read (ring entries, descriptors, buffers) after it, so we see what the driver wrote before it published the index; and the release store ofused.idx, which keeps every earlier write (the used element and the buffer data) before it. Everything else is a plain copy. A fullSeqCstfence also sits between ourused.idxstore and our load ofavail.flags.From chapter 16: Split virtqueues: shared memory with an adversary
The device wrote 150 bytes into a request whose writable buffers total 200. What goes in the used element's
len, and what goes wrong if you put 200?Show answer
150, the bytes actually written. The driver trusts
len: with 200 it would treat 50 bytes the device never wrote, whatever was in that memory before, as data, for example as random numbers or as file contents.From chapter 14: Booting Linux to a shell
A Linux boot log ends with
timer_probe: no matching timers found, thenKernel panic - not syncing: Unable to initialise architected timer., andmacvmmexits 5 after--timeout. What is wrong with the machine, and why did the VMM not stop on its own?Show answer
The device tree has no
/timernode (or one whosecompatibleLinux does not match), so stage 4 of the boot cannot find a clock and panics. A panicked kernel spins inside the guest without touching anything that traps, so the run loop sees no exit; only--timeout(exit 5) ends the run.From chapter 14: Booting Linux to a shell
A boot log says
GICv3: No redistributor present, then shows an Oops and a panic, while the VMM prints no unhandled-MMIO error. Which two numbers do you compare to find the bug?Show answer
The redistributor base in the device tree's
/intcnode (its secondregpair) and the base where the interrupt controller really has its redistributors (GICR_BASE,0x080a_0000in our layout). Linux readGICR_PIDR2at offset0xFFE8of the frame it was told about; our read-as-zero region answered 0, which is not a GICv3 revision, so nothing looked broken to the VMM.From chapter 14: Booting Linux to a shell
A boot exits 0 and reaches
reboot: Power down, but the log has nottyAMA0 at MMIOline, saysWarning: unable to open an initial console., and the initramfs'sreadyline is missing. What did Linux fail to do, and which part of our machine do you check first?Show answer
It never bound a driver to the PL011 node, so no
ttyAMA0console exists and user-space output has nowhere to go (kernel messages still appear throughearlycon). Check what the AMBA bus matches on: the eight identification registers at0xFE0to0xFFC(expect0x11 0x10 0x14 0x00 0x0d 0xf0 0x05 0xb1), then the node'scompatibleand itsapb_pclkclock.From chapter 14: Booting Linux to a shell
A guest has panicked and
macvmmis still running. Without stopping it, how do you see what the vCPU last did, and how do you tell "spinning without exits" from "busy doing I/O"?Show answer
Press
Ctrl-Athentin its terminal, or send it SIGUSR1 from another (kill -USR1 <pid>). The last 256 exits of each vCPU are printed on standard error, oldest first. Compare the newest record'st_nswith how long the VM has been running: a last exit seconds ago means the vCPU is looping on something we do not trap.From chapter 14: Booting Linux to a shell
A Linux boot wrote 12,093 bytes to the PL011 and caused 32,811 data-abort exits. About how many exits per byte is that, and why more than one?
Show answer
About 2.7. Each byte is at least two device accesses, each its own VM exit: a read of the flag register
UARTFRto check there is room, the store toUARTDR, and often a further read ofUARTFR.From chapter 14: Booting Linux to a shell
Why does adding
panic=-1to the kernel command line turn a panicking kernel's run from exit status 5 into exit status 4 (with--on-reset exit)?Show answer
panic=-1makes Linux reboot immediately after a panic instead of spinning. On our machine a reboot is a PSCISYSTEM_RESEThypercall, which the VMM sees as an exit, and--on-reset exitmaps it to status 4. Without it the kernel spins forever and only the timeout (5) ends the run.From chapter 14: Booting Linux to a shell
You want a trace of a Linux boot that holds only the guest's hypercalls and trapped system registers, not the 32,000 console accesses. What do you pass, and roughly how many lines do you get?
Show answer
--trace exits:FILE:hvc,sysreg. The categories after the second colon select records by exception class (0x16forhvc,0x18for system registers); our boot gives 18 lines (16 PSCI and SMCCC calls, 2 debug-register writes) instead of 32,829.From chapter 14: Booting Linux to a shell
Linux reads
0x11 0x10 0x14 0x00from the four peripheral-ID registers of a PrimeCell. What part number, designer and revision is that?Show answer
The low byte of each register, assembled little-end first, gives
0x00141011: bits 11 to 0 are the part number0x011(a PL011), bits 19 to 12 the designer0x41(Arm), bits 23 to 20 the revision 1. Linux printed it as "PL011 rev1".From chapter 10: The Device Tree: the VMM's promise to the guest
A node's parent says
#address-cells = <2>and#size-cells = <1>. The node'sregdescribes two ranges. How many bytes long is theregproperty?Show answer
Each range is 2 + 1 = 3 cells, and a cell is 4 bytes, so one range is 12 bytes and two ranges are 24. The counts come from the parent, not from the node itself.
From chapter 10: The Device Tree: the VMM's promise to the guest
The first eight bytes of a blob are
d0 0d fe ed 00 00 04 f7. What is it, and how big is it?Show answer
A flattened device tree:
0xd00dfeedis its magic number. The next big-endian 32-bit word istotalsize,0x4f7= 1271 bytes. Read little-endian, the same bytes would give0xf7040000, which is why the byte order matters.From chapter 10: The Device Tree: the VMM's promise to the guest
Why can an arm64 kernel not find the PL011 by reading every address in the first 4 GiB and looking for a UART?
Show answer
Nothing on that bus answers "who is here?", and an address with no device behind it does not return a polite "nothing" either: on real hardware it can fault or hang, and in our VMM it is an unhandled access that stops the guest (exit code 3 by default). Even the PrimeCell ID registers help only once you know where the device is. So somebody has to tell the kernel: the DTB.
From chapter 10: The Device Tree: the VMM's promise to the guest
Two nodes each have a
compatibleproperty. How many times does the wordcompatibleappear in the blob, and where?Show answer
Once, in the strings block: property names are stored there once and referred to by offset (
nameoff). The values ("arm,pl011","arm,pl031") are not names; they sit in the structure block after eachFDT_PROPtoken.From chapter 10: The Device Tree: the VMM's promise to the guest
Your writer opens
/cpus, openscpu@0, closes it, and then adds#size-cellsto/cpus. What should happen, and why?Show answer
An error. The format requires every property of a node to come before its first child node, because a reader walks the token stream once and attaches each property to the node it is in. The reference writer refuses it as
PropAfterChildinstead of writing a tree a kernel would misread.From chapter 10: The Device Tree: the VMM's promise to the guest
A guest's first instruction runs with
x0 = 0x40000000. What does an arm64 kernel expect to find there, and what two rules does the address obey?Show answer
The device tree blob: Linux's boot protocol says
x0holds its physical address. It must be 8-byte aligned and the blob at most 2 MiB long, in RAM. Our VMM puts it at the start of RAM.From chapter 10: The Device Tree: the VMM's promise to the guest
You add a node
pl031@9050000to the DTB but no device to the bus. Linux boots. With the default unhandled-access policy, what doesmacvmmprint, and why at that address?Show answer
unhandled MMIO read at 0x9050fe0, then exit code 3. The AMBA bus code reads a PrimeCell's ID registers, at offsets0xFE0to0xFFC, before it picks a driver, so the first access to the phantom device is the ID read. With--unhandled-mmio logthe reads return zero and the device is left unbound ("deferred probe pending").From chapter 10: The Device Tree: the VMM's promise to the guest
A node says
compatible = "arm,pl011", "arm,primecell". Why two strings, and in which order are they tried?Show answer
Most specific first. A kernel looks for a driver that knows
arm,pl011; the second string says what family the device belongs to (an Arm PrimeCell, with ID registers), which a more general driver or bus can use.From chapter 10: The Device Tree: the VMM's promise to the guest
/cpussays#address-cells = <1>and#size-cells = <0>. How long iscpu@0'sreg, and what does it hold?Show answer
4 bytes: one address cell and no size. It holds the CPU's identity (its MPIDR affinity, here 0), which is why the node is called
cpu@0.
Concepts you'll need
Chapters before this one: chapter 16, Split virtqueues: shared memory with an adversary.
- Core, taught here: the device worker thread; the doorbell's happens-before chain; notify coalescing and the per-batch budget; virtio-rng and the exact used length; virtio-console and its two queues; exits per kilobyte.
- Core, from earlier: one exit's cost (chapter 03); the PL011 and its sinks (chapter 09); level-triggered interrupts and the GIC, the Generic Interrupt Controller (chapters 11 and 12);
--kernelfor ELF guests (chapter 13); the test initramfs (chapter 14); the virtio-mmio transport and theVirtioDevicetrait (chapter 15); split virtqueues and copy-then-validate (chapter 16); chapter 04's parked question. - Primers (read first):
memory-ordering(acquire and release, happens-before, and its section on the doorbell as a synchronisation point). - Primers (review):
host-concurrency(a mutex, a condition variable, joining a thread);tty-termios(raw mode). - Pointers:
getentropy(an Aside); Linux'shw_randomandhvclayers (linked); KVM'sioeventfd(a Production note). - Forward definitions: virtio-blk (chapter 18); a network card's receive thread (chapter 19); a second vCPU (chapter 20); the macOS sandbox (chapter 25). Each is defined at first use.
Here is one line to type at your guest's shell once your virtual machine monitor (VMM) has a random-number device: dd if=/dev/hwrng bs=1M count=1 | wc -c. It asks the device for one mebibyte (1 MiB, 1,048,576 bytes) of random bytes. When the guest's driver has new requests, it tells your VMM by ringing a doorbell, and a doorbell is one VM exit. So how many doorbells does a mebibyte cost?
Predict In the guest, dd if=/dev/hwrng bs=1M count=1 | wc -c reads 1 MiB from your virtio-rng. Does the number of QueueNotify doorbells grow with the bytes read or with the buffers the driver posts? Write a number.
Write your guess and one sentence of reasoning under ## Predict in your journal. The section "Bytes or buffers?" runs it and counts.
Chapters 15 and 16 built the transport and the rings for row 8 of chapter 00's problem ledger, bulk I/O at reasonable cost, with no real device behind them. This chapter puts the first two devices there, moves their work onto a thread of their own, and measures what row 8 is about: exits per kilobyte.
Objectives: by the end you can
- Implement virtio-rng (device ID 4) on a device worker thread woken through a mutex and a condition variable: fill only writable descriptors from
getentropy, at most 64 KiB per request, report the exact used length, and raise the interrupt. - Draw the doorbell's happens-before chain from the guest's barrier to the worker's acquire load of
avail.idx, and predict what breaks when one link is removed. - Give the
VirtioDevicetrait real bodies for virtio-rng, and implement virtio-console (device ID 3) against it from a specification and tests. - Measure exits per 4 KiB for the PL011 and for virtio-console with
--stats, and explain the ratio with chapter 03's cost per exit. - Explain with an example why chapter 04's parked question is now real with one vCPU.
Before you start. From the repository root, run scripts/learner start 17, which copies this chapter's journal to learner/journal/17.md. You need the kernel and test initramfs from chapter 14 in .cache/macvmm/.
Where should the work happen?
In chapter 15 a QueueNotify write processed the queue right there, on the thread of the virtual CPU (vCPU) that wrote it. While it handles the exit, the guest CPU is frozen. For 64 KiB of random bytes, or a disk read in chapter 18, it is time the guest cannot run.
Real hardware does not work like that: a disk controller's own engine reads the rings while the CPU goes back to work. We copy the shape: each virtio device gets a host thread of its own, and the vCPU only rings its bell. That thread is the device worker thread, the worker for short.
The bell is a mutex and a condition variable, exactly the pair the host-concurrency primer built in park.rs. The vCPU side sets one bit per queue and wakes the worker. It never touches the device itself, so it never waits behind a long batch:
/// The doorbell (on a vCPU thread): mark queue `queue` pending and wake the worker. Never/// blocks on the device: the state mutex is held only by the worker's bookkeeping, never/// across a batch.pub fn notify(&self, queue: usize) { let Some(bit) = u32::try_from(queue).ok().and_then(|q| 1u64.checked_shl(q)) else { crate::guest_warn!( "virtio worker {}: notify for queue {queue:?} ignored", self.name ); return; }; if queue >= self.queues { crate::guest_warn!( "virtio worker {}: notify for queue {queue:?} ignored", self.name ); return; } let mut s = lock(&self.shared.state); s.pending |= bit; // ten doorbells before the worker wakes are one bit (coalescing) self.shared.wake.notify_one();}The transport calls it from its QueueNotify handler, after the checks chapter 15 wrote (the device is live and the queue is ready). A slot without a worker still processes inline, which is what host tests use:
/// QueueNotify: only for an activated, healthy device and an existing ready queue.fn notify(&mut self, v: u32) { if self.status & st::DRIVER_OK == 0 || self.status & st::FAILED != 0 || self.interrupt.needs_reset() { crate::guest_warn!( "virtio-mmio: QueueNotify {v:?} ignored in status {:?}", self.status() ); return; } let Some(index) = usize::try_from(v) .ok() .filter(|i| self.queues.get(*i).is_some_and(Queue::ready)) else { crate::guest_warn!( "virtio-mmio: QueueNotify {v:?} ignored: no such ready queue ({:?} queues)", self.queues.len() ); return; }; match &self.notifier { Some(n) => n.notify(index), None => self.process_inline(index), }}The worker's loop
The worker sleeps on the condition variable inside the primer's predicate loop: it checks the state (any pending bit?) before every wait, so a bell rung before it fell asleep is not lost. When it wakes it takes all pending bits at once and marks itself busy:
/// Sleep until a queue is pending (and not paused); take every pending bit. `None` on stop.fn wait_for_work(&self) -> Option<u64> { let mut s = lock(&self.shared.state); loop { if s.stop { return None; } if !s.paused && s.pending != 0 { s.busy = true; return Some(core::mem::take(&mut s.pending)); } s = Shared::wait(&self.shared.wake, s); }}/// End of a pass: re-queue what ran out of budget (it goes round through the stop and/// pause checks first) and tell a waiting `pause()` that no batch is running.fn finish_pass(&self, requeue: u64) { let mut s = lock(&self.shared.state); s.pending |= requeue; s.busy = false; self.shared.idle.notify_all();}Taking every bit turns ten doorbells that arrived while the worker was busy into one pass. That is notify coalescing, and it is safe because a doorbell carries no data. It only says "look at the ring", and one look sees every buffer published before it. The virtio specification says as much: a driver may batch its notifications, so a device must not count on one per buffer.
Ignore paused, pause() and the idle wake-up in finish_pass: they let a test hold the worker at a batch boundary.
Then, for each pending queue, the worker locks the device, processes at most one batch, and unlocks:
while let Some(mask) = self.wait_for_work() { let mut requeue = 0u64; for (index, &budget) in self.budgets.iter().enumerate() { let bit = 1u64.checked_shl(u32::try_from(index).unwrap_or(u32::MAX)); let Some(bit) = bit.filter(|b| mask & b != 0) else { continue; }; if self.interrupt.needs_reset() { // The device already failed; nothing is processed until Status = 0 // resets it. The doorbell is dropped, not kept. continue; } // The device mutex is held for exactly one batch of at most `budget` chains, // and for the error report: a Status = 0 reset waiting on this mutex then runs // after NEEDS_RESET is latched and clears it (module docs, "Reset races"). let mut device = lock(&self.device); let progress = device.process_queue(index, budget); self.shared.batches.fetch_add(1, Ordering::SeqCst); match progress { Ok(QueueProgress::Drained) => {} Ok(QueueProgress::MoreWork) => requeue |= bit, // A reset raced the doorbell (module docs): not the guest's fault. Err(VirtioError::NotActivated) => {} Err(e) => report_error(&self.interrupt, index, &e), } drop(device); } self.finish_pass(requeue);}The short labels in these comments (letters, a dash and a number) are the reference's own test and threat-model labels; ignore them. Three details carry the design.
- The budget is the queue size: one call handles at most that many chains, so a guest that refills its ring as fast as we drain it cannot hold the device mutex forever.
MoreWorkputs the queue's bit back as pending, so the queue goes round again, through the stop check, andstopcan still win. - An error is the guest's fault. The device goes to
DEVICE_NEEDS_RESETwhile the lock is still held, and the worker keeps running for the next driver. A device already in that state drops further doorbells until the driver resets it. NotActivatedis ignored, because a driver that wroteStatus = 0while a bell was pending did nothing wrong.
Stopping is the last piece. stop sets a flag, wakes the worker, and joins it; the worker finishes its current batch and leaves. The machine stops every worker before it frees guest RAM. The companion lines belong to chapter 19, where a network card's receive thread (its own host thread for incoming packets) has to stop with its worker:
/// Stop the thread and wait for it: it finishes the batch in progress (at most `N` chains,/// its budget) and exits. Idempotent. Returns true if the thread panicked.pub fn stop(&self) -> bool { { let mut s = lock(&self.shared.state); s.stop = true; self.shared.wake.notify_all(); self.shared.idle.notify_all(); // a waiting `pause()` returns too } let handle = lock(&self.thread).take(); if let Some(h) = handle && h.join().is_err() { self.shared.panicked.store(true, Ordering::SeqCst); } // The companions (a NIC's RX thread) go with the worker. Every one is stopped, // even after one reports a panic. let companions: Vec<Arc<dyn Companion>> = lock(&self.companions).clone(); let companion_panicked = companions.iter().fold(false, |any, c| c.stop() | any); if companion_panicked { self.shared.panicked.store(true, Ordering::SeqCst); } self.panicked()}The doorbell's happens-before chain
The worker is a second thread reading memory the guest wrote. By the memory-ordering primer's rule, it may trust what it reads only if a chain of happens-before edges leads from the guest's writes to its reads:
guest vCPU (EL1) our vCPU thread our worker thread ---------------- --------------- ----------------- write descriptors, avail ring, avail.idx dmb (barrier) str QueueNotify --trap--> handle the MMIO exit lock state, set bit, notify_one, unlock -------> wake, lock state, take bits, unlock lock device acquire load avail.idx walk, copy, fill take the interrupt <---- line raised <--------------- release store used.idx, read InterruptStatus fence, should_interrupt?Every arrow is an edge: the guest's barrier, the trap itself, a mutex released by one thread and acquired by the next, then chapter 16's acquire and release pair on the ring indices.
The guest runs at exception level 1 (EL1, the kernel's level); its doorbell is a store to a memory-mapped I/O (MMIO) address. What goes wrong without each link:
- The barrier. Without the
dmb, the doorbell may become visible before the ring writes, and the worker on another core reads an unfinished ring. - The trap. The guest's stores and our handler run on the same core, one after the other, as if one thread wrote the ring and then rang. This link cannot be removed.
- The mutex. Unlock is a release and lock an acquire, so the waking worker sees an
avail.idxat least as new as the bell's. Replace it with a polledRelaxedflag and the primer's doorbell section shows a wake-up lost. - The acquire load. The guest keeps publishing while the worker walks; the acquire load of
avail.idxmakes those later descriptors safe to read.
At the bottom, should_interrupt is chapter 16's check: has the driver set its no-interrupt flag for this batch?
Deliberate breakage 1: forget to ring the bell. In notify, keep s.pending |= bit but delete self.shared.wake.notify_one(). Predict: does the guest still get its random bytes, perhaps late?
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 20 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet macvmm.test=rng"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virtmacvmm-rng: hw_random=virtio_rng.0macvmm: timeout: the guest was still running after --timeout 20smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=543 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 1662: canceled 1, hvc 15, sysreg 2, data abort 1644macvmm: stats: vcpu0 time: exec 0.112 s, wfi 19.818 smacvmm: stats: host cpu 0.137 s over 19.954 s wall (1%)macvmm: stats: rlimit core=0 nofile=1048576Never: the driver waits for this request before ringing again, so no second bell comes to rescue it. The bit was set and nobody looked until --timeout ended the run.
wfi 19.818 s is time the vCPU spent asleep in WFI (wait for interrupt, chapter 11), not exits: the in-kernel GIC handles WFI without an exit to us (chapter 12), hence wfx 0. Our worker slept too, and host CPU stayed at 1%.
What you saw: a hang where everyone is idle. The misconception: "the state is set, so someone will notice"; a bell nobody rings is a lost wake-up. The tool: --stats (all sleep, no work) and the contract test that sends ten notifies and waits for every buffer. Put the line back.
Chapter 04's question comes due
Chapter 04 asked when the guest could change memory while your VMM looks at it. Now: once notify returns, the guest runs while the worker walks its ring. A driver that rewrites a descriptor right after ringing races our worker, with one vCPU. This is why chapter 16 copies each descriptor once and validates only the copy. Chapter 20's second vCPU can do it from another core at full speed.
virtio-rng, the smallest real device
A freshly booted guest has almost no randomness of its own, yet it needs unpredictable numbers from its first second, for every key it will generate. The device tree's rng-seed (chapter 10) hands Linux one seed at boot; a random-number device hands it a source, which Linux exposes as /dev/hwrng through its hw_random layer.
The virtio-rng device is the smallest real virtio device: device ID 4, one queue (requestq), no feature bits of its own and no configuration space. The driver posts device-writable buffers; the device fills them with random bytes and returns each descriptor chain with the number of bytes it wrote. The specification allows fewer bytes than the buffer holds, but at least one.
Aside
The bytes come from getentropy, the Mac's system call for the kernel's cryptographically secure pseudo-random number generator (CSPRNG). It needs no file descriptor, so it keeps working inside chapter 25's sandbox, and it refuses more than 256 bytes per call. See man 2 getentropy, or the OpenBSD page where it began.
So the VMM's one entropy source fills large buffers in 256-byte calls:
/// Fill `buf` with random bytes, in ≤ 256-byte `getentropy(2)` calls.pub fn fill(&self, buf: &mut [u8]) -> std::io::Result<()> { for chunk in buf.chunks_mut(GETENTROPY_MAX) { hvf::host::getentropy(chunk)?; } Ok(())}In chapter 15 you gave read_config, write_config and process_queue trivial bodies. Rng is the first device that needs real ones: ID 4, one queue of at most 64, only VERSION_1, a zero-length config space the transport refuses, and activate keeping the memory, queue and interrupt that reset drops:
impl VirtioDevice for Rng { fn device_id(&self) -> u32 { DEVICE_ID_RNG } fn queue_max_sizes(&self) -> &[u16] { &[RNG_QUEUE_SIZE] } /// §5.4.3: "None currently defined"; only the transport-level `VERSION_1`. fn device_features(&self) -> u64 { features::VERSION_1 } fn ack_features(&mut self, _accepted: u64) {} /// §5.4.4: "None currently defined". `config_len` stays 0, so every config access is /// refused by the transport. fn read_config(&self, _offset: u32, data: &mut [u8]) { data.fill(0); } fn write_config(&mut self, _offset: u32, _data: &[u8]) {} fn activate( &mut self, mem: Arc<dyn GuestMemoryOrdered>, queues: Vec<Queue>, irq: Arc<VirtioInterrupt>, ) -> Result<(), VirtioError> { let queue = queues .into_iter() .next() .ok_or(VirtioError::NoSuchQueue(0))?; self.active = Some(Active { mem, queue, irq }); Ok(()) }Now the device's whole job, one batch per call, which the worker invokes with the device locked:
/// Fill up to `budget` posted chains with host randomness (module docs).fn process_queue(&mut self, index: usize, budget: u16) -> Result<QueueProgress, VirtioError> { if index != 0 { return Err(VirtioError::NoSuchQueue(index)); } let Some(a) = self.active.as_mut() else { return Err(VirtioError::NotActivated); }; let budget = budget.min(a.queue.size()); // one ring's worth at most let mem = &*a.mem; let mut used = false; let mut progress = QueueProgress::Drained; for n in 0..=budget { if n == budget { progress = QueueProgress::MoreWork; break; } let Some(chain) = a.queue.pop(mem)? else { break; }; // Every descriptor checked; the writable total capped at 64 KiB. let req = chain.into_validated(RNG_MAX_REQUEST)?; let want = usize::try_from(req.writable_len) .map_err(|_| VirtioError::Device("rng request larger than the address space"))?; // A fresh, zeroed buffer per request, never reused. let mut buf = vec![0u8; want]; self.entropy .fill(&mut buf) .map_err(|_| VirtioError::Device("the host entropy source failed"))?; // Only `req.writable` is written: readable descriptors are never touched. let written = req.write_writable(mem, &buf)?; a.queue.add_used(mem, req.head, written)?; // the bytes actually written self.requests = self.requests.saturating_add(1); self.bytes = self.bytes.saturating_add(u64::from(written)); used = true; } if used && a.queue.should_interrupt(mem)? { a.irq.signal_used(); } Ok(progress)}The budget is clamped to the driver's queue size. pop and into_validated are chapter 16's, with the writable total capped at 64 KiB.
A larger request is refused as TooLarge: DEVICE_NEEDS_RESET. Filling 64 KiB and reporting 65,536 would also be legal, and Linux never posts more than 64 bytes. The reference refuses so that every device has one limit, enforced in the shared validator before any byte moves.
Each request gets a fresh, zeroed buffer, so a short fill never leaks an earlier request's bytes. The used ring gets what chapter 16's write_writable returns: the count of bytes actually written into the writable descriptors, never the buffer's size.
After the batch, unless the driver set its no-interrupt flag, signal_used sets bit 0 of InterruptStatus and raises the slot's level-triggered line, which stays up until the guest writes InterruptACK.
Security
The used length is the device's reply, and the driver acts on it. A driver posting readable and writable descriptors together would take its own readable bytes as random if we reported the whole chain. Linux's driver trusts len as the valid bytes in its 64-byte buffer, so a larger len would make it copy past that buffer (see the spec hunt).
Deliberate breakage 2: report the buffer's length. In process_queue, replace written in the add_used call with u32::try_from(req.readable_len + req.writable_len).unwrap(), the chain's whole length. Predict: does Linux notice? Run the contract tests first:
cargo test -q -p vmm --test virtio_rngrunning 14 tests........ 8/14a_readable_only_chain_is_returned_with_len_0 --- FAILEDfills_only_writable_descriptors_and_ignores_readable_ones --- FAILED....failures:---- a_readable_only_chain_is_returned_with_len_0 stdout ----thread 'a_readable_only_chain_is_returned_with_len_0' (123013879) panicked at crates/vmm/tests/virtio_rng.rs:131:5:assertion `left == right` failed left: (0, 16) right: (0, 0)note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace---- fills_only_writable_descriptors_and_ignores_readable_ones stdout ----thread 'fills_only_writable_descriptors_and_ignores_readable_ones' (123013884) panicked at crates/vmm/tests/virtio_rng.rs:104:5:assertion `left == right` failed: len counts only the writable bytes left: (0, 96) right: (0, 32)failures: a_readable_only_chain_is_returned_with_len_0 fills_only_writable_descriptors_and_ignores_readable_onestest result: FAILED. 12 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04smacvmm: warn: [rings_out_of_ram_are_refused_at_driver_ok] guest: virtio-mmio: queue 0 refused at DRIVER_OK: virtqueue: RingOutOfRam { ring: Used, addr: 1074790396, len: 134 }macvmm: warn: [virtio-rng-test] guest: virtio: queue 0 failed, device needs reset: virtqueue: ChainTooLong { budget: 16 }macvmm: warn: [rings_out_of_ram_are_refused_at_driver_ok] guest: virtio-mmio: QueueNotify 0 ignored in status 79macvmm: warn: [a_hostile_chain_means_needs_reset_and_the_vmm_keeps_running] guest: virtio-mmio: QueueNotify 0 ignored in status 79macvmm: warn: [end_to_end_through_the_transport_and_the_worker] guest: virtio-mmio: config access of 4 bytes at 0x0 outside the 0-byte config space (RAZ/WI)error: test failed, to rerun pass `-p vmm --test virtio_rng`Two tests fail: a chain of 64 readable and 32 writable bytes came back with 96 instead of 32, and a readable-only chain claimed 16 random bytes that were the guest's own. Now Linux:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 60 --cmdline console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet macvmm.test=rng[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virtmacvmm-rng: hw_random=virtio_rng.0macvmm-rng: read 1048576 bytes ok[ 0.424842] reboot: Power downread 1048576 bytes ok: Linux posts writable-only buffers, so the lie never shows. What you saw: a broken device a real guest accepts. The misconception: "if the guest works, the device is right". The tool: contract tests with hostile shapes. Put written back.
Wiring it in: --rng and a slot
The machine puts each device in a virtio slot with its transport, its interrupt line and its worker, and makes the worker the transport's doorbell target. The Blk and Net arms and the nic lines belong to chapters 18 and 19; skip them:
/// One populated slot: the device model, its transport, and its worker thread, which/// is the transport's doorbell target (`QueueNotifier`), so a QueueNotify on a vCPU only sets/// a bit and returns. The worker's per-queue budget is the device's queue maximum, so one busy/// queue cannot starve the others.fn populated_slot( kind: VirtioKind, slot: usize, line: Arc<dyn IrqLine>, env: &VirtioEnv<'_>,) -> Result<(VirtioMmio, Arc<Worker>)> { // A NIC's typed handle, for its RX thread. let mut nic: Option<(usize, Arc<Mutex<crate::virtio::Net>>)> = None; let device: Arc<Mutex<dyn VirtioDevice>> = match kind { VirtioKind::Blk(n) => blk_device(env, n)?, VirtioKind::Rng => Arc::new(Mutex::new(Rng::new(env.entropy))), VirtioKind::Console => console_device(env)?, VirtioKind::Net(n) => { let host = env .nets .get(n) .ok_or(Error::Internal("--net without an open socket"))?; let dev = Arc::new(Mutex::new(crate::virtio::Net::new( host.mac, Arc::clone(&host.backend), ))); nic = Some((n, Arc::clone(&dev))); dev } }; let budgets = crate::sync::lock(&device).queue_max_sizes().to_vec(); let interrupt = Arc::new(VirtioInterrupt::new(line)); let mut transport = VirtioMmio::new( Arc::clone(&device), Arc::clone(&interrupt), Some(Arc::clone(&env.mem)), ) .map_err(Error::Internal)?; let worker = Worker::spawn( &format!("virtio-{}-{slot}", kind.name()), device, Arc::clone(&interrupt), budgets, Arc::clone(&env.ctl), ) .map_err(|_| Error::Internal("cannot spawn a virtio worker thread"))?; if let Some((n, dev)) = nic { attach_net_rx(&worker, slot, n, dev, interrupt, &env.ctl)?; } let notifier: Arc<dyn QueueNotifier> = worker.clone(); transport.set_notifier(Some(notifier)); Ok((transport, worker))}--rng asks for one in the slot after any disks (chapter 18 adds them), which with no disk is slot 0 at 0x0a00_0000, and the device tree lists it. Chapter 15 ran the bare-metal probe against 32 empty slots; the same ELF build, loaded with --kernel as before, now finds a device:
cargo run -q -p macvmm -- run --mem 64M --rng --kernel target/guests/aarch64-unknown-none/release/virtio-probe --timeout 10virtio-probe: slot 0 device 4 features okvirtio-probe: slot 0 device id 4 status 0xfvirtio-probe: rng 32 bytes nonzerovirtio-probe: 32 slots magic ok version 2virtio-probe: 31 empty (device id 0)virtio-probe: narrow read RAZ okvirtio-probe: dt lists 1 virtio_mmio nodes okmacvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)Slot 0 answers device 4, the handshake reaches status 0xf, and 32 random bytes came back through the worker. The warnings are the probe's deliberate reads of the wrong width (1, 2 and 8 bytes), refused as in chapter 15. Then Linux's driver, through the test initramfs's rng case:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 60 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet macvmm.test=rng"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virtmacvmm-rng: hw_random=virtio_rng.0macvmm-rng: read 1048576 bytes ok[ 0.367216] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=613 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 50967: hvc 16, sysreg 2, data abort 50949macvmm: stats: vcpu0 time: exec 0.152 s, wfi 0.102 smacvmm: stats: host cpu 0.379 s over 0.379 s wall (101%)macvmm: stats: rlimit core=0 nofile=1048576hw_random=virtio_rng.0 means Linux bound its driver to our device. The 50,967 exits are the cost we count next.
Bytes or buffers?
Time for the opening question. Boot with every MMIO exit traced and no macvmm.test= word, which gives chapter 14's shell case:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 30 --stats --trace exits:rng.jsonl:mmio --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"At the / # prompt, type this line; the modprobes are needed because the test initramfs loads drivers only for its named cases:
modprobe virtio_mmio; modprobe virtio-rng; sleep 1; dd if=/dev/hwrng bs=1M count=1 | wc -c; poweroff -fcargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 30 --stats --trace exits:rng.jsonl:mmio --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio-rng; sleep 1; dd if=/dev/hwrng bs=1M count=1 | wc -c; poweroff -f1+0 records in1+0 records out1048576 bytes (1.0MB) copied, 0.386095 seconds, 2.6MB/s1048576[ 3.184179] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=753 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=3macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 51684: hvc 16, sysreg 2, data abort 51666macvmm: stats: vcpu0 time: exec 0.159 s, wfi 2.813 smacvmm: stats: host cpu 0.536 s over 3.197 s wall (17%)macvmm: stats: rlimit core=0 nofile=1048576One mebibyte arrived, at 2.6 MB/s, and the run cost 51,684 exits. Count the doorbells, writes to 0x0a00_0050 (slot 0's base plus QueueNotify's offset):
grep -c '"ipa":"0xa000050"' rng.jsonl1638716,387. To see which of them are dd's, we repeated the run with count=0, which loads the driver and registers the device but reads nothing:
grep -c '"ipa":"0xa000050"' rng-0.jsonl2Two doorbells came from the kernel's own reads, with no dd at all; that baseline run cost 2,498 exits. So dd rang about 16,385 times (the count varies by one or two from run to run), and 1,048,576 / 16,384 = 64: Linux's driver posts one 64-byte buffer at a time. Here are three consecutive slot-0 records from the middle of the run:
grep '"ipa":"0xa0000[56]' rng.jsonl | sed -n '199,201p'{"t_ns":2810656500,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a0034","ipa":"0xa000050","wnr":true,"size":4,"reg":1,"value":"0x0","action":"mmio","isv":true}{"t_ns":2810672458,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a0884","ipa":"0xa000060","wnr":false,"size":4,"reg":19,"value":"0x1","action":"mmio","isv":true}{"t_ns":2810676583,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a08a4","ipa":"0xa000064","wnr":true,"size":4,"reg":19,"value":"0x1","action":"mmio","isv":true}The doorbell (0xa000050); 16 microseconds later the guest reads InterruptStatus (0xa000060) and acknowledges it (0xa000064) in its interrupt handler. Three exits per request, whatever the request holds: 16,385 × 3 = 49,155, and with the 2,498 of the baseline that makes 51,653, within a few dozen of the 51,684 we saw.
The rule: doorbells = bytes ÷ buffer size, and the driver picks the buffer size. Linux's virtio-rng always posts 64 bytes, so here the two lines run parallel, but the answer is buffers. The console runs below prove it: one doorbell per 2,048 bytes in one run, per 7 bytes in another.
Good place to stop. The second half is the console you write yourself, then the measurement.
virtio-console: your turn to build it
A virtio-console moves a whole buffer per doorbell, where the PL011 moved one byte per trapped access. Linux shows it as /dev/hvc0, through its hvc console layer. That hvc stands for "hypervisor virtual console" and has nothing to do with chapter 02's hvc instruction.
Rng's guest starts every exchange: it posts an empty writable buffer and the device answers into it. Keyboard input starts on the host, at any moment, and the device cannot allocate guest memory; it can only write into buffers handed over beforehand. So input needs a queue of empty writable buffers posted in advance, which sit until bytes arrive. Output buffers are readable and posted only when there is text, so they get a second queue. A universal asynchronous receiver-transmitter (UART) such as the PL011 needs no queue: each byte is its own register access.
Your device, from virtio 1.2's console section:
| Item | Value | What it means for you |
|---|---|---|
| device ID | 3 | device_id() |
queue 0, receiveq | host to guest, device-writable buffers | the guest posts empty buffers in advance; you fill them when the host has input |
queue 1, transmitq | guest to host, device-readable buffers | you read them and hand the bytes to a sink |
| features | none of its own | offer only VERSION_1, exactly one port |
| config space | 12 bytes, all zero, read-only | ignore writes |
You offer none of the three console features, SIZE (the terminal's rows and columns), MULTIPORT (several consoles) and EMERG_WRITE (panic output without queues), so their config fields stay zero.
The rules, each checked by the reference's virtio_console suite:
- Transmit. Validate each chain with a 64 KiB cap, copy its readable bytes once into a fresh buffer, hand them to the sink (which runs chapter 09's output filter, a file included), and return the chain with
len = 0. The sink's writer thread callswrite, never the worker. - Transmit never blocks. If the sink's queue is full, wait at most 10 ms per batch (the
FullWaitbelow), then drop and count the bytes. - Receive, nothing to say. With no input queued, pop nothing: a popped chain must go back, and an empty one reaches the guest as a zero-byte read, which a shell treats as end of file and quits. A console with no stdin bound never receives.
- Receive, input waiting. Fill
min(writable length, queued bytes)and report exactly that. Remove input only after the guest write succeeded, so no keystroke is lost. - Receive, nothing writable in a chain is a driver error:
DEVICE_NEEDS_RESET. - Budget and reset. At most
budgetchains per call, clamped to the queue size, thenMoreWork. Reset drops the queues but keeps queued input. - Who rings for input? The guest rings
QueueNotify 0when it posts buffers; the host rings the same bell when stdin has bytes.
The last rule is new, a doorbell rung by the host, through a hook:
/// The console input hook: bytes the stdin thread pushes into the console's input queue ring/// this boot's console worker for the receiveq, exactly as a guest QueueNotify would; the/// worker fills whatever RX buffers are posted (`virtio::console`, anchor `console_rx`). The/// hook holds a `Weak`, so it never keeps a torn-down boot's worker alive, and a doorbell for/// a stopped worker is a no-op; the next boot installs its own hook.fn connect_console_input(input: &Arc<SerialInput>, worker: &Arc<Worker>) { let weak = Arc::downgrade(worker); input.set_hook(Some(Arc::new(move || { if let Some(w) = weak.upgrade() { w.notify(crate::virtio::console::RX_QUEUE); } })));}Your checklist:
- Write
learner/crates/vmm/src/virtio/console.rs, implementingVirtioDevicewith the queue table above. - Add
--console stdio|file:Finlearner/crates/macvmm/src/cli.rs, next to--serial, refusing two stdio sinks with exit code 2: only one can receive stdin. - The slot wiring is given: copy the
Consolearm,connect_console_inputand the smallconsole_devicehelper from the reference'scrates/vmm/src/machine/virt.rs. - From inside
learner/, test withcargo test -q -p vmm --test virtio_console. - Stuck?
scripts/learner hint 17climbs from a nudge to the reference file.
The refusal from step 2, on the reference:
cargo run -q -p macvmm -- run --mem 64M --kernel target/guests/aarch64-unknown-none/release/hello --console stdio --serial stdiomacvmm: invalid configuration: only one of --serial/--console may be stdiousage: macvmm run [options]options: --mem SIZE guest RAM, e.g. 64M, 2G (default 512M; 64M..255G, a multiple of 2M) --cpus N number of vCPUs, 1..64 and at most what this Mac allows (default 1); vCPU 0 boots, the others wait for PSCI CPU_ON --kernel FILE an ELF test guest or an arm64 Linux Image (detected from its bytes; an EFI zboot vmlinuz is refused: run scripts/fetch.sh linux) --initrd FILE an initramfs for an Image kernel, placed above the kernel --cmdline STRING the kernel command line for an Image (at most 2047 bytes; default console=ttyAMA0 earlycon=pl011,<the PL011 address>) --machine BOARD virt (default) or vmapple (experimental: AVPBooter's first device accesses, needs a build with --features experimental-vmapple; it does not boot macOS; at most two per user, an advisory lock in $HOME/.cache/macvmm/vmapple-slots) --bios FILE a firmware ROM image, at most 64 MiB (virt: U-Boot in flash bank 0, entered at 0x0 instead of --kernel; vmapple: default the system AVPBooter, read in place and never copied) --dry-run print the boot plan, memory map and device-tree summary, then exit 0 without creating a VM (needs no entitlement) --raw FILE@0xADDR load FILE's bytes at guest-physical ADDR (repeatable); the first one is the entry point when there is no --kernel --timeout SECS stop the guest after SECS seconds (exit code 5) --unhandled-mmio POLICY fatal (default: exit code 3) or log (read as zero, ignore writes) --trace exits:FILE[:CATS][,max=SIZE] write one JSON line per VM exit to FILE (created 0600; never a symlink). CATS: comma-separated mmio,hvc,sysreg,psci,cancel,all (default all). SIZE caps the file (default 1G) --testdev map the 512-register test device at 0x0b000000 --disk FILE[,ro] add a virtio-blk disk backed by the raw image FILE (repeatable; the first is /dev/vda). ,ro opens it read-only. The image is locked (flock) while macvmm runs; a locked image is refused --rng add a virtio-rng device fed by the host CSPRNG (getentropy) --net unixgram:LOCAL,peer=REMOTE[,mac=XX:XX:XX:XX:XX:XX] add a virtio-net NIC whose wire is a Unix datagram socket bound at LOCAL; frames go to, and are accepted only from, the socket at REMOTE (another macvmm's LOCAL). Both must be in a directory you own that is not group- or world-writable. A stale socket of yours at LOCAL is replaced; anything else there is refused. Repeatable (at most 4). Default MAC 02:6d:76 plus 3 random bytes. unixgram:LOCAL,learn instead locks the peer to the first sender (logged). No host network access and no entitlement --on-reset ACTION reboot (default: rebuild the VM in-process) or exit (exit code 4) when the guest calls PSCI SYSTEM_RESET --debug-hvc, --no-debug-hvc force the macvmm debug hypercalls on or off (default: on for ELF and --raw test guests, off for kernels and firmware) --dtb-out FILE write the generated device tree to FILE (created 0600; never a symlink), with its rng-seed and kaslr-seed zeroed --serial SINK[,strict|,raw][,max=SIZE] where the PL011 console goes: stdio (default; also gets stdin, with Ctrl-A x quit, Ctrl-A t trace ring, Ctrl-A s stats), file:FILE (created 0600, never a symlink, capped at SIZE, default 1G) or none. Guest output is filtered for terminal safety; strict shows every control visibly, raw disables the filter (not recommended) --console SINK[,strict|,raw][,max=SIZE] add a virtio-console (Linux /dev/hvc0) whose output goes to stdio or file:FILE, filtered like --serial. At most one of --serial and --console may be stdio, and that one gets stdin: --console stdio needs --serial file:FILE or --serial none --stats print the console I/O counters, the exit counts, the vCPU exec and WFI time and the host CPU time when the VM stops --log LEVEL error|warn|info|debug|trace (default warn; also MACVMM_LOG) --no-sandbox run unconfined. By default, after opening every file, macvmm confines itself: no file opened by path, no network, no new process (macOS sandbox, threat model SBX-2), and exits 1 if the sandbox cannot be applied. Needed for --net ...,learn --sandbox[=best-effort] --sandbox is the default and changes nothing; best-effort warns and runs unconfined if the sandbox cannot be applied. Not together with --no-sandboxOnce your transmit side passes, compare it with the reference's:
/// transmitq: copy each chain's readable bytes into a fresh buffer and hand them to the/// sink, which filters terminal escapes out of them and queues them for its writer thread, so/// the device never blocks on host output.fn process_tx(&mut self, budget: u16) -> Result<QueueProgress, VirtioError> { let Some(a) = self.active.as_mut() else { return Err(VirtioError::NotActivated); }; let budget = budget.min(a.tx.size()); // one ring's worth at most let mem = &*a.mem; let mut used = false; let mut progress = QueueProgress::Drained; // One 10 ms full-queue budget for the whole batch (one device-mutex hold). let mut wait = FullWait::new(); for n in 0..=budget { if n == budget { progress = QueueProgress::MoreWork; break; } let Some(chain) = a.tx.pop(mem)? else { break; }; // Every descriptor checked; each direction's total capped at 64 KiB. let req = chain.into_validated(CONSOLE_MAX_TOTAL)?; let bytes = read_readable(mem, &req)?; // fresh, zeroed, never reused // The sink's own AnsiFilter runs before any host byte is written; a file sink has a // byte cap; the device never calls write(2), and waits at most 10 ms for // queue space in the whole batch (`wait` is shared by every chain). self.sink.write_guest_within(&bytes, &mut wait); // Used length 0: nothing was written into the chain (writable descriptors are ignored). a.tx.add_used(mem, req.head, 0)?; self.tx_bytes = self.tx_bytes.saturating_add(req.readable_len); used = true; } if used && a.tx.should_interrupt(mem)? { a.irq.signal_used(); } Ok(progress)}write_guest_within gives up when the shared FullWait budget runs out. The test initramfs's console-tx case runs yes macvmm | head -c 65536 into /dev/hvc0 in raw mode:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 60 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet macvmm.test=console-tx"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virtmacvmm-console: tx done[ 1.263785] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=567 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0 console_input_dropped=0 console_input_queued=0 console_written=65536 console_sink_dropped=0 console_capped=0 console_lost=0 console_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 27876: hvc 16, sysreg 2, data abort 27858macvmm: stats: vcpu0 time: exec 0.196 s, wfi 1.001 smacvmm: stats: host cpu 0.382 s over 1.276 s wall (30%)macvmm: stats: rlimit core=0 nofile=1048576console_written=65536 and nothing dropped. The file must be byte-exact against the same bytes made on the host:
shasum -a 256 hvc0.out; yes macvmm | head -c 65536 | shasum -a 256695c42e9ee9cc0a9d666671236dd6b34dac797d238db842219d3d5a2ff48fcab hvc0.out695c42e9ee9cc0a9d666671236dd6b34dac797d238db842219d3d5a2ff48fcab -Exits per kilobyte: PL011 against hvc0
Now the comparison this Part exists for. Use your own chapter 03 cost per exit; ours was 1.43 microseconds. Boot the shell four times:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 30 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"and type one line: it makes 4,096 bytes without newlines, opens the device as file descriptor 3 in raw mode, and writes them with one dd:
modprobe virtio_mmio; sleep 1; yes macvmm | tr -d '\n' | head -c 4096 >/tmp/4k; exec 3<>/dev/ttyAMA0; stty raw -echo <&3; dd if=/tmp/4k bs=4096 count=1 2>/dev/null >&3; poweroff -fOnly two words change: ttyAMA0 (the PL011) or hvc0, and count=1 or count=0, a baseline without the write. Raw mode (tty-termios) stops Linux's tty layer, its terminal code, from adding carriage returns, so exactly 4,096 bytes go out. Read total in each exits: line:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 30 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; sleep 1; yes macvmm | tr -d '\n' | head -c 4096 >/tmp/4k; exec 3<>/dev/ttyAMA0; stty raw -echo <&3; dd if=/tmp/4k bs=4096 count=0 2>/dev/null >&3; poweroff -f[ 2.808485] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=734 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=3 console_input_dropped=0 console_input_queued=0 console_written=0 console_sink_dropped=0 console_capped=0 console_lost=0 console_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 2868: hvc 16, sysreg 2, data abort 2850macvmm: stats: vcpu0 time: exec 0.089 s, wfi 2.715 smacvmm: stats: host cpu 0.104 s over 2.818 s wall (4%)macvmm: stats: rlimit core=0 nofile=1048576cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 30 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; sleep 1; yes macvmm | tr -d '\n' | head -c 4096 >/tmp/4k; exec 3<>/dev/ttyAMA0; stty raw -echo <&3; dd if=/tmp/4k bs=4096 count=1 2>/dev/null >&3; poweroff -fmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacvmmmacv[ 2.819071] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=4830 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=3 console_input_dropped=0 console_input_queued=0 console_written=0 console_sink_dropped=0 console_capped=0 console_lost=0 console_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 11062: hvc 16, sysreg 2, data abort 11044macvmm: stats: vcpu0 time: exec 0.096 s, wfi 2.703 smacvmm: stats: host cpu 0.136 s over 2.829 s wall (5%)macvmm: stats: rlimit core=0 nofile=1048576cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 30 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; sleep 1; yes macvmm | tr -d '\n' | head -c 4096 >/tmp/4k; exec 3<>/dev/hvc0; stty raw -echo <&3; dd if=/tmp/4k bs=4096 count=0 2>/dev/null >&3; poweroff -f[ 2.800671] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=731 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=3 console_input_dropped=0 console_input_queued=0 console_written=0 console_sink_dropped=0 console_capped=0 console_lost=0 console_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 2849: hvc 16, sysreg 2, data abort 2831macvmm: stats: vcpu0 time: exec 0.095 s, wfi 2.701 smacvmm: stats: host cpu 0.113 s over 2.812 s wall (5%)macvmm: stats: rlimit core=0 nofile=1048576cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 30 --stats --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet"[ 0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][ 0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[ 0.000000] random: crng init done[ 0.000000] Machine model: macvmm-virt[ 0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[ 0.000000] printk: legacy bootconsole [pl11] enabledmacvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; sleep 1; yes macvmm | tr -d '\n' | head -c 4096 >/tmp/4k; exec 3<>/dev/hvc0; stty raw -echo <&3; dd if=/tmp/4k bs=4096 count=1 2>/dev/null >&3; poweroff -f[ 2.801751] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=731 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=3 console_input_dropped=0 console_input_queued=0 console_written=4096 console_sink_dropped=0 console_capped=0 console_lost=0 console_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 2853: hvc 16, sysreg 2, data abort 2835macvmm: stats: vcpu0 time: exec 0.095 s, wfi 2.702 smacvmm: stats: host cpu 0.113 s over 2.812 s wall (5%)macvmm: stats: rlimit core=0 nofile=1048576The baselines differ a little, since opening each device costs its own register accesses, so subtract each device's own:
| 4,096 bytes to | Baseline exits | With the write | Extra exits | At 1.43 microseconds each |
|---|---|---|---|---|
PL011 (ttyAMA0) | 2,868 | 11,062 | 8,194 | about 11.7 ms |
virtio-console (hvc0) | 2,849 | 2,853 | 4 | about 6 microseconds |
The PL011 cost two exits per byte. We repeated its two runs with --trace and counted:
for c in 0 1; do echo "count=$c: flag register reads $(grep "\"ipa\":\"0x9000018\"" pl011-$c.jsonl | grep -c "\"wnr\":false"), data register writes $(grep "\"ipa\":\"0x9000000\"" pl011-$c.jsonl | grep -c "\"wnr\":true")"; donecount=0: flag register reads 1391, data register writes 738count=1: flag register reads 5487, data register writes 4834Exactly 4,096 more reads of its flag register (is there room?) and 4,096 more writes of its data register. The console cost four:
grep '"ipa":"0xa0000[56]' hvc0.jsonl | tail -4{"t_ns":2819412708,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a0034","ipa":"0xa000050","wnr":true,"size":4,"reg":1,"value":"0x1","action":"mmio","isv":true}{"t_ns":2819523583,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a0034","ipa":"0xa000050","wnr":true,"size":4,"reg":1,"value":"0x1","action":"mmio","isv":true}{"t_ns":2819581666,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a0884","ipa":"0xa000060","wnr":false,"size":4,"reg":19,"value":"0x1","action":"mmio","isv":true}{"t_ns":2819586500,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0xffff80007a2a08a4","ipa":"0xa000064","wnr":true,"size":4,"reg":19,"value":"0x1","action":"mmio","isv":true}Two doorbells, because Linux's tty layer hands the driver at most 2,048 bytes per call, then one interrupt read and acknowledged. We observed no interrupt read in the 110 microseconds between the doorbells; the level-triggered line stays up until acknowledged, so one interrupt collected both used buffers.
The ratio is about 2,000: one QueueNotify bought 2,048 bytes, moved by memory copies that cost no exit. The console's code does more work per call (a chain walk, validation, a copy), yet wins because it needs far fewer exits.
Try it
The console-tx run above cost 27,876 exits for 64 KiB, far more than four per 4 KiB. Repeat it with --trace exits:tx.jsonl:mmio and count the transmit doorbells (QueueNotify written with 1). Before you look: how many bytes per buffer?
grep '"ipa":"0xa000050"' tx.jsonl | grep -c '"value":"0x1"'93639,363 doorbells: seven bytes each. yes put one line at a time into the pipe, head passed each read on as its own write, and each write became one buffer. Chapter 14 sent the same 64 KiB through the PL011 for 178,073 extra exits; hvc0 took about 25,000 extra (27,876, less about 2,850 of boot), still 7 times fewer, and 2,000 times fewer with big buffers.
Production note
Our doorbell costs a full exit and a trip through the vCPU thread. The Kernel-based Virtual Machine (KVM), Linux's built-in hypervisor, has ioeventfd, which signals the device thread straight from the host kernel, and VIRTIO_F_EVENT_IDX (chapter 16) skips unneeded notifications. The chain of edges is the same.
A worker under attack
hostile-vq is a bare-metal test guest in guests/, built by scripts/build-guests.sh (chapter 03), that plays a malicious driver. For each attack it sets up a ring, plants one malformed chain, rings, checks for DEVICE_NEEDS_RESET and writes Status = 0; a last, well-formed request must still be served. From the repository root:
cargo run -q -p macvmm -- run --mem 64M --rng --kernel target/guests/aarch64-unknown-none/release/hostile-vq --timeout 30cargo run -q -p macvmm -- run --mem 64M --rng --kernel target/guests/aarch64-unknown-none/release/hostile-vq --timeout 30hostile-vq: RAM ends at 0x44000000hostile-vq: rng slot 0: 12 attacks ended in needs-reset, recoveredhostile-vq: 31 empty slots attacked, 3968 alignment faults, 0 unexpected valueshostile-vq: survivedmacvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: ChainTooLong { budget: 16 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: ChainTooLong { budget: 16 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: NextOutOfRange { next: 200, table_len: 16 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: ZeroLength { index: 0 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: BufferOutOfRam { addr: 150994944, len: 32 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: IndirectNotNegotiatedmacvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: BufferOutOfRam { addr: 1140850672, len: 32 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: BufferOutOfRam { addr: 1074298880, len: 4294967295 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: TooLarge { total: 65537, max: 65536 }macvmm: warn: [virtio-rng-0] guest: virtio: queue 0 failed, device needs reset: virtqueue: HeadOutOfRange { head: 999, size: 16 }macvmm: warn: [vcpu0] guest: virtio-mmio: queue 0 refused at DRIVER_OK: virtqueue: RingOutOfRam { ring: Used, addr: 1140850684, len: 134 }macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte write at 0x0 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0x0 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte write at 0x0 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x4 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte write at 0x4 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x4 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0x4 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x8 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte write at 0x8 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x8 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0x8 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x8 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte write at 0x8 is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0xc is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte write at 0xc is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0xc is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0xc is not an aligned 32-bit access (WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 4 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 4 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 8 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 8 bytes at 0x0 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x1 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x1 outside the 0-byte config space (RAZ/WI)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x9 outside the 0-byte config space (RAZ/WI) (989 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x14 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x1f outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x29 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x34 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x3c is not an aligned 32-bit access (RAZ) (989 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0x3c is not an aligned 32-bit access (WI) (989 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x3f outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x49 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x54 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x5f outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x69 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x74 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x7c is not an aligned 32-bit access (RAZ) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0x7c is not an aligned 32-bit access (WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x7f outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x89 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x94 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x9f outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0xa9 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0xb4 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0xbc is not an aligned 32-bit access (RAZ) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0xbc is not an aligned 32-bit access (WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0xbf outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0xc9 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0xd4 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0xdf outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0xe9 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0xf4 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0xfc is not an aligned 32-bit access (RAZ) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte write at 0xfc is not an aligned 32-bit access (WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0xff outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x9 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x14 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x1f outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 1 bytes at 0x29 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: virtio-mmio: config access of 2 bytes at 0x34 outside the 0-byte config space (RAZ/WI) (999 similar messages suppressed)Each attack ended in DEVICE_NEEDS_RESET with a named reason, such as a loop caught by the hop budget, a zero-length buffer, a buffer past the end of RAM, or an indirect table the driver never negotiated (IndirectNotNegotiated). The device recovered each time and the VMM exited 0.
Your turn
Before the checkpoint, check from inside learner/, with G=../target/guests/aarch64-unknown-none/release as in chapter 09:
cargo run -q -p macvmm -- run --mem 64M --rng --kernel $G/virtio-probe --timeout 10prints the probe'srng 32 bytes nonzeroline.- The commands below print
read 1048576 bytes ok, then two equal hashes. - Your journal has the Predict entry, written before the
ddrun, and question 1, from your own four--statsruns.
cargo run -q -p macvmm -- run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 60 --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet macvmm.test=rng"cargo run -q -p macvmm -- run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --console file:hvc0.out --on-reset exit --timeout 60 --cmdline "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1 quiet macvmm.test=console-tx"shasum -a 256 hvc0.out; yes macvmm | head -c 65536 | shasum -a 256To run only the contract tests: cargo test -q -p vmm --test virtio_rng --test virtio_worker --test worker_budget --test virtio_console.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 17You should see, as the last line:
CHECKPOINT 17 PASSIt runs the contract tests, the four runs you have seen (the probe, rng, console-tx with its hash, the two stdio sinks refused) and the journal check:
scripts/checkpoint.sh 17[PASS] contract tests virtio_rng (14 tests), virtio_worker (9 tests), worker_budget (1 tests), virtio_console (20 tests)[PASS] runs on your Mac probe-rng: 4/4 serial markers, exit 0 in 0.05s[PASS] runs on your Mac linux-rng: 4/4 serial markers, exit 0 in 0.63s[PASS] runs on your Mac console-tx: 5/5 serial markers, exit 0 in 1.45s[PASS] runs on your Mac both-stdio: 1/1 serial markers, exit 2 in 0.01s[INFO] journal not checked (not a learner tree)CHECKPOINT 17 PASSWhat now works:
- each virtio device has a worker thread that coalesces doorbells, works in bounded batches and stops cleanly;
- virtio-rng serves Linux's
/dev/hwrngfrom the Mac's CSPRNG and reports exactly what it wrote; - virtio-console carries
hvc0both ways at four exits per 4 KiB instead of 8,194.
The next chapter starts from this state (the reference at the end of chapter 17).
What's next
Random bytes and console text are forgiving. Chapter 18 builds virtio-blk, a disk with guest-chosen sector numbers, a file backend that can be slow, and a FLUSH that must survive a power cut. Today's worker keeps a slow disk from freezing the guest's CPU.
Open question
The hostile-vq run shows what our device does with a zero-length writable buffer. The specification says the device places "one or more" random bytes into the buffer, and that a driver must not trust bytes beyond the used length. The guest posts a zero-length writable buffer to virtio-rng: what should the device do, and what should it report?
Spec hunt
- Virtio 1.2 (OASIS,
virtio-v1.2-cs01), section 5.4.6, "Device Operation" of the Entropy Device, and its requirements: may the device return fewer bytes than the buffer holds, and is there any bound on how few? - Virtio 1.2, section 2.7.8, "The Virtqueue Used Ring", and its requirements on
len: what must a device write before it updatesused.idx, and what may a driver assume about bytes beyondlen? - Linux
drivers/char/hw_random/virtio-rng.c: how large is the buffer the driver posts, how does it use thelenthe device returns, and does the buffer size match the doorbells you counted for one mebibyte?