indicogniBuild a VMM

Contents

Chapter 17 · Part VII

virtio-rng (worked) and virtio-console (faded)

Needs a Mac ~4.5 h
18 of 26

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.

  1. 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 loads avail.idx = 0x0002. How many new requests are there, and in which ring slots are their heads?

    Show answer

    Four: 0x0002 - 0xFFFE in wrapping u16 arithmetic 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.

  2. From chapter 14: Booting Linux to a shell

    A Linux boot log ends with timer_probe: no matching timers found, then Kernel panic - not syncing: Unable to initialise architected timer., and macvmm exits 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 /timer node (or one whose compatible Linux 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.

  3. From chapter 10: The Device Tree: the VMM's promise to the guest

    A node's parent says #address-cells = <2> and #size-cells = <1>. The node's reg describes two ranges. How many bytes long is the reg property?

    Show answer

    Each range is 2 + 1 = 3 cells, and a cell is 4 bytes, so one range is 12 bytes and two ranges are 24. The counts come from the parent, not from the node itself.

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); --kernel for ELF guests (chapter 13); the test initramfs (chapter 14); the virtio-mmio transport and the VirtioDevice trait (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's hw_random and hvc layers (linked); KVM's ioeventfd (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 VirtioDevice trait 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:

crates/vmm/src/virtio/worker.rslines 252-273
/// 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:

crates/vmm/src/virtio/mmio.rslines 628-654
/// 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:

crates/vmm/src/virtio/worker.rslines 390-412
/// 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:

crates/vmm/src/virtio/worker.rslines 357-385
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. MoreWork puts the queue's bit back as pending, so the queue goes round again, through the stop check, and stop can still win.
  • An error is the guest's fault. The device goes to DEVICE_NEEDS_RESET while 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.
  • NotActivated is ignored, because a driver that wrote Status = 0 while 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:

crates/vmm/src/virtio/worker.rslines 277-300
/// 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.idx at least as new as the bell's. Replace it with a polled Relaxed flag 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.idx makes 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?

TerminalReal output
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"exit: 5--- stdout ---[    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.0--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: in crates/vmm/src/virtio/worker.rs, Worker::notify sets the pending bit under the mutex but no longer calls self.shared.wake.notify_one().
course/captures/17-break-no-bell.txt

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

crates/vmm/src/backend/entropy.rslines 45-51
/// 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:

crates/vmm/src/virtio/rng.rslines 94-126
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:

crates/vmm/src/virtio/rng.rslines 130-170
/// 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:

TerminalReal output
cargo test -q -p vmm --test virtio_rngexit: 101--- stdout ---running 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.04s--- stderr ---macvmm: 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`
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: in crates/vmm/src/virtio/rng.rs, process_queue passes u32::try_from(req.readable_len + req.writable_len).unwrap() to add_used instead of written.
course/captures/17-break-used-len-tests.txt

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:

TerminalReal output
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=rngexit: 0--- stdout ---[    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 down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: in crates/vmm/src/virtio/rng.rs, process_queue passes u32::try_from(req.readable_len + req.writable_len).unwrap() to add_used instead of written.
course/captures/17-break-used-len-linux.txt

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

crates/vmm/src/machine/virt.rslines 248-299
/// 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:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --rng --kernel target/guests/aarch64-unknown-none/release/virtio-probe --timeout 10exit: 0--- stdout ---virtio-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 ok--- stderr ---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)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)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: the bare-metal virtio-probe guest with a virtio-rng in slot 0.
course/captures/17-probe-rng.txt

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:

TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: Alpine's kernel and the course test initramfs, test case rng (Linux's own virtio-rng driver reads 1 MiB from /dev/hwrng).
course/captures/17-linux-rng.txt

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

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

Shell
modprobe virtio_mmio; modprobe virtio-rng; sleep 1; dd if=/dev/hwrng bs=1M count=1 | wc -c; poweroff -f
TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, booted to the test initramfs's shell. A script typed this one line at the guest's shell 2 seconds after start: modprobe virtio_mmio; modprobe virtio-rng; sleep 1; dd if=/dev/hwrng bs=1M count=1 | wc -c; poweroff -f
course/captures/17-hwrng-dd.txt

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

TerminalReal output
grep -c '"ipa":"0xa000050"' rng.jsonlexit: 0--- stdout ---16387
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Counts the QueueNotify writes (guest-physical 0x0a000050: slot 0 at 0x0a000000, register offset 0x050) in the trace of the dd run.
course/captures/17-hwrng-notifies.txt

16,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:

TerminalReal output
grep -c '"ipa":"0xa000050"' rng-0.jsonlexit: 0--- stdout ---2
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • A baseline repeat of the dd run with count=0 (the same line typed at the shell, so the driver loads and the device registers, but dd reads nothing), traced with --trace exits:rng-0.jsonl:mmio; --stats reported 2,498 exits in total.
  • Counts its QueueNotify writes (guest-physical 0x0a000050).
course/captures/17-hwrng-notifies-base.txt

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

TerminalReal output
grep '"ipa":"0xa0000[56]' rng.jsonl | sed -n '199,201p'exit: 0--- stdout ---{"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}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Three consecutive trace records for slot 0 from the middle of the dd run: one request's doorbell (0x050), InterruptStatus read (0x060) and InterruptACK write (0x064).
course/captures/17-hwrng-trace.txt

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:

ItemValueWhat it means for you
device ID3device_id()
queue 0, receiveqhost to guest, device-writable buffersthe guest posts empty buffers in advance; you fill them when the host has input
queue 1, transmitqguest to host, device-readable buffersyou read them and hand the bytes to a sink
featuresnone of its ownoffer only VERSION_1, exactly one port
config space12 bytes, all zero, read-onlyignore 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:

  1. 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 calls write, never the worker.
  2. Transmit never blocks. If the sink's queue is full, wait at most 10 ms per batch (the FullWait below), then drop and count the bytes.
  3. 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.
  4. 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.
  5. Receive, nothing writable in a chain is a driver error: DEVICE_NEEDS_RESET.
  6. Budget and reset. At most budget chains per call, clamped to the queue size, then MoreWork. Reset drops the queues but keeps queued input.
  7. Who rings for input? The guest rings QueueNotify 0 when 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:

crates/vmm/src/machine/virt.rslines 341-353
/// 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:

  1. Write learner/crates/vmm/src/virtio/console.rs, implementing VirtioDevice with the queue table above.
  2. Add --console stdio|file:F in learner/crates/macvmm/src/cli.rs, next to --serial, refusing two stdio sinks with exit code 2: only one can receive stdin.
  3. The slot wiring is given: copy the Console arm, connect_console_input and the small console_device helper from the reference's crates/vmm/src/machine/virt.rs.
  4. From inside learner/, test with cargo test -q -p vmm --test virtio_console.
  5. Stuck? scripts/learner hint 17 climbs from a nudge to the reference file.

The refusal from step 2, on the reference:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --kernel target/guests/aarch64-unknown-none/release/hello --console stdio --serial stdioexit: 2--- stderr ---macvmm: 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-sandbox
captured: real output, Apple M5 Pro, macOS 27.2.1, commit 64871bd, 2026-11-20
  • The reference, unmodified: two sinks both asking for the terminal.
course/captures/17-both-stdio.txt

Once your transmit side passes, compare it with the reference's:

crates/vmm/src/virtio/console.rslines 207-244
/// 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:

TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: test case console-tx writes yes macvmm | head -c 65536 to /dev/hvc0 in raw mode.
course/captures/17-linux-console-tx.txt

console_written=65536 and nothing dropped. The file must be byte-exact against the same bytes made on the host:

TerminalReal output
shasum -a 256 hvc0.out; yes macvmm | head -c 65536 | shasum -a 256exit: 0--- stdout ---695c42e9ee9cc0a9d666671236dd6b34dac797d238db842219d3d5a2ff48fcab  hvc0.out695c42e9ee9cc0a9d666671236dd6b34dac797d238db842219d3d5a2ff48fcab  -
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The file the console-tx run wrote, against the same 65,536 bytes made on the host.
course/captures/17-console-sha.txt

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:

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

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

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

TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, booted to the test initramfs's shell. A script typed this one line at the guest's shell 2 seconds after start: 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
  • count=0: the baseline, the same commands with no data written.
course/captures/17-pl011-4k-base.txt
TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, booted to the test initramfs's shell. A script typed this one line at the guest's shell 2 seconds after start: 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 -f
  • count=1: one 4096-byte write to /dev/ttyAMA0.
course/captures/17-pl011-4k.txt
TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, booted to the test initramfs's shell. A script typed this one line at the guest's shell 2 seconds after start: 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
  • count=0: the baseline, the same commands with no data written.
course/captures/17-hvc0-4k-base.txt
TerminalReal output
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"exit: 0--- stdout ---[    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 down--- stderr ---macvmm: 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=1048576
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, booted to the test initramfs's shell. A script typed this one line at the guest's shell 2 seconds after start: 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
  • count=1: one 4096-byte write to /dev/hvc0.
course/captures/17-hvc0-4k.txt

The baselines differ a little, since opening each device costs its own register accesses, so subtract each device's own:

4,096 bytes toBaseline exitsWith the writeExtra exitsAt 1.43 microseconds each
PL011 (ttyAMA0)2,86811,0628,194about 11.7 ms
virtio-console (hvc0)2,8492,8534about 6 microseconds

The PL011 cost two exits per byte. We repeated its two runs with --trace and counted:

TerminalReal output
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")"; doneexit: 0--- stdout ---count=0: flag register reads 1391, data register writes 738count=1: flag register reads 5487, data register writes 4834
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Repeats of the two /dev/ttyAMA0 runs (count=0 and count=1) with --trace exits:pl011-0.jsonl:mmio and --trace exits:pl011-1.jsonl:mmio added; they again cost 2,868 and 11,062 exits.
  • Counts the PL011's flag-register reads (FR, offset 0x018, address 0x09000018) and data-register writes (DR, offset 0x000, address 0x09000000) in each trace.
course/captures/17-pl011-4k-trace.txt

Exactly 4,096 more reads of its flag register (is there room?) and 4,096 more writes of its data register. The console cost four:

TerminalReal output
grep '"ipa":"0xa0000[56]' hvc0.jsonl | tail -4exit: 0--- stdout ---{"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}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The trace of a repeat of the 4 KiB /dev/hvc0 run (count=1) with --trace exits:hvc0.jsonl:mmio added; the console is in slot 0. Its last four doorbell and interrupt records: the 4 KiB write.
course/captures/17-hvc0-4k-trace.txt

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?

TerminalReal output
grep '"ipa":"0xa000050"' tx.jsonl | grep -c '"value":"0x1"'exit: 0--- stdout ---9363
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The trace of a repeat of the console-tx run with --trace exits:tx.jsonl:mmio added. Counts the doorbells for queue 1, the console's transmit queue (QueueNotify written with the value 1).
course/captures/17-console-tx-notifies.txt

9,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:

Shell
cargo run -q -p macvmm -- run --mem 64M --rng --kernel target/guests/aarch64-unknown-none/release/hostile-vq --timeout 30
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --rng --kernel target/guests/aarch64-unknown-none/release/hostile-vq --timeout 30exit: 0--- stdout ---hostile-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: survived--- stderr ---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: 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)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: the hostile-vq test guest attacks the virtio-rng in slot 0 with malformed rings and chains, resetting the device after each attack.
course/captures/17-hostile-vq-rng.txt

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:

  1. cargo run -q -p macvmm -- run --mem 64M --rng --kernel $G/virtio-probe --timeout 10 prints the probe's rng 32 bytes nonzero line.
  2. The commands below print read 1048576 bytes ok, then two equal hashes.
  3. Your journal has the Predict entry, written before the dd run, and question 1, from your own four --stats runs.
Shell
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 256

To 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 Mac

Run this from the repository root:

scripts/checkpoint.sh 17

You should see, as the last line:

CHECKPOINT 17 PASS

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

TerminalReal output
scripts/checkpoint.sh 17exit: 0--- stdout ---[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 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The chapter's checkpoint, run against the reference (scripts/checkpoint.sh 17 --ref): what a finished chapter 17 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/17-checkpoint.txt

What 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/hwrng from the Mac's CSPRNG and reports exactly what it wrote;
  • virtio-console carries hvc0 both 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 updates used.idx, and what may a driver assume about bytes beyond len?
  • Linux drivers/char/hw_random/virtio-rng.c: how large is the buffer the driver posts, how does it use the len the device returns, and does the buffer size match the doorbells you counted for one mebibyte?
Progress is stored only in this browser.