indicogniBuild a VMM

Contents

Chapter 18 · Part VII

virtio-blk: a root filesystem that persists

Needs a Mac Runs in browser ~5.5 h Lab: virtio-blk request · Lab: Durability ladder
19 of 26

Course progress: chapter 18 is 19 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 17: virtio-rng (worked) and virtio-console (faded)

    A guest posts one chain to virtio-rng: a 64-byte readable descriptor, then a 32-byte writable one. How many bytes does the device write, where, and what len goes in the used ring?

    Show answer

    32 bytes, all into the writable descriptor; the readable one is never written, not even with its own bytes. The used len is 32: the number of bytes the device actually wrote, never the chain's total of 96.

  2. From chapter 15: Rings and a doorbell: the virtio-mmio transport

    On our board, a driver reads the 32-bit word at 0x0a00_0608 and gets 0. Which register of which slot is that, what must the driver conclude, and should the device tree have a node at 0x0a000600?

    Show answer

    Slots start at 0x0a00_0000 and are 0x200 apart, so 0x0a00_0600 is slot 3 and offset 0x008 is DeviceID. 0 means "no device here": the specification says the driver MUST ignore it. There is no node, because only populated slots are listed; the empty slot still answers on the bus so that a guest which scans the fixed addresses gets a defined answer rather than an unhandled-MMIO fault.

  3. From chapter 11: Getting the CPU back: the timer and a bare interrupt

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

    Show answer

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

Concepts you'll need

Chapters before this one: chapter 17, virtio-rng (worked) and virtio-console (faded).

  • Core, taught here: the virtio-blk request (header, data, status) and its types; the feature bits RO, FLUSH and SEG_MAX; bounds checks on every request; IOERR or UNSUPP versus a device reset; bounce buffers; durability as part of the device contract (write-back with FLUSH, write-through without); locking the image against a second virtual machine monitor (VMM).
  • Core, from earlier: checked arithmetic and guest-memory copies (chapter 04); --on-reset and the reset call of PSCI, the Power State Coordination Interface (chapter 08); the test initramfs and its macvmm.test= cases (chapter 14); the virtio-mmio transport and DEVICE_NEEDS_RESET (chapter 15); descriptor chains, copy-then-validate and the used length (chapter 16); the worker thread and the VirtioDevice trait (chapter 17).
  • Primers (read first): block-storage (sectors and raw images, ext4, root=, the page cache, fsync versus F_FULLFSYNC, pread and pwrite, advisory locks, APFS (Apple File System) clones).
  • Primers (review): linux-boot-sequence (how the kernel finds its root filesystem, and kernel modules).
  • Pointers: man fsync and F_FULLFSYNC on macOS (shown in the body); APFS clones with cp -c; kernel modules and squashfs (an Aside); Homebrew's e2fsprogs.
  • Forward definitions: a second vCPU (virtual CPU) rewriting a request while the worker reads it (chapter 20); confining the VMM with the macOS sandbox (chapter 25). Each is defined at first use.

Here is one line a Linux guest can type: dd if=/dev/zero of=/dev/vda bs=4k count=1 conv=fsync. It writes 4 KiB to its disk and then asks for proof that those bytes would survive a power cut. That proof is a request our virtual machine monitor (VMM) must answer, and we can answer it three ways: by asking macOS for fcntl(F_FULLFSYNC), by asking for plain fsync, or by doing nothing and saying "done". All three pass every test in this chapter. One of them is telling the truth.

Predict Run that line 100 times in a row, each write followed by its flush. Predict the time of the 100 for each version (F_FULLFSYNC, fsync, nothing), as rough ratios. Then: with the do-nothing version, you kill -9 the VMM right after the guest's dd returns. Are the guest's bytes in the image file afterwards?

Write your guesses and one sentence of reasoning under ## Predict in your journal. The section "What FLUSH promises" runs all three, and the second break kills the VMM.

This chapter finishes row 8 of chapter 00's problem ledger, bulk I/O (input and output) at reasonable cost, for storage: chapters 15 to 17 built the rings, the doorbell and the worker, and here a disk goes behind them. By the end, Linux boots from an ext4 root filesystem on your virtual disk, reboots inside the same process, and finds its file still there.

Objectives: by the end you can

  • Implement virtio-blk (device ID 2) from section 5.2 of the virtio 1.2 specification: IN, OUT, FLUSH and GET_ID, offering RO, FLUSH and SEG_MAX.
  • Bounds-check every request with checked arithmetic against the capacity, answer IOERR before touching the file, and move data through capped, zeroed bounce buffers.
  • Back the device with a raw image through pread and pwrite, lock it against a second VMM, and give FLUSH real durability with File::sync_all (F_FULLFSYNC on macOS); measure what that costs.
  • Diagnose an unchecked sector * 512 from a failing hostile test, and explain why a FLUSH that does nothing fails no test.
  • Boot Linux from an ext4 root on /dev/vda and show the data persists across an in-process reboot, with a clean e2fsck afterwards.

Before you start. From the repository root, run scripts/learner start 18; it copies this chapter's journal to learner/journal/18.md. Read the block-storage primer first. You need Homebrew's e2fsprogs (the primer installs it), the kernel and test initramfs from chapter 14, and, for the last section, scripts/fetch.sh rootfs.

Where to run things. The disk tools (cargo xtask mkdisk and mkrootfs) run at the repository root; everything else runs inside learner/, so that cargo run builds your VMM, with the kernel in ../.cache/macvmm/ and the disk images beside you. Our captures come from a workspace laid out the same way, holding the reference's code. At the repository root, make a 64 MiB test disk of known pseudo-random bytes:

TerminalReal output
cargo xtask mkdisk --size 64M --seed 1 --out learner/disk.imgexit: 0--- stdout ---mkdisk: wrote learner/disk.img (67108864 bytes, seed 1)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-mkdisk.txt

Then cd learner and note its hash:

TerminalReal output
shasum -a 256 disk.imgexit: 0--- stdout ---4ae50b0ecaa3f91bdcfe84f5a2e20706045ea6f3387c6c45238200cf50ea7859  disk.img
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-host-sha.txt

What a disk request must say

To use a disk, a driver must say which sectors, which direction, and where in memory the bytes go, and it must learn whether it worked. Chapter 16 gave us the shape: a descriptor chain, readable buffers first, writable buffers after.

So a virtio-blk request is a chain of three parts: a small header the device reads (what to do, and where on the disk), the data, and last one byte the device writes to say how it went. With the answer inside the request, the used ring tells the driver the request is finished and the byte tells it the outcome; no register to read afterwards.

That is the virtio-blk device, device ID 2, with one queue named requestq. Section 5.2.6 of the virtio 1.2 specification calls the layout struct virtio_blk_req:

OUT (write) readable by the device                        |  writable+---------------------------+---------------+  |  +--------+| le32 type | le32 reserved |               |  |  | status || le64 sector               | data: N bytes |  |  | 1 byte |+---------------------------+---------------+  |  +--------+IN and GET_ID (read) readable                      |  writable by the device+---------------------------+  |  +---------------+--------+| le32 type | le32 reserved |  |  |               | status || le64 sector               |  |  | data: N bytes | 1 byte |+---------------------------+  |  +---------------+--------+

One request, as one chain, in each direction; FLUSH carries no data. le32 and le64 are little-endian 32- and 64-bit integers, the byte order of every virtio field.

The sector counts 512-byte units, whatever the disk's real block size (the primer's first table). The type says what to do, and the status says how it went:

TypeValueDataMeaning
IN0writableread N bytes from byte sector × 512
OUT1readablewrite N bytes at byte sector × 512
FLUSH4nonemake every completed write durable
GET_ID8writablea 20-byte serial number
(anything else)status UNSUPP (2)

Status values: OK (0), IOERR (1), the request was understood and failed, and UNSUPP (2), the type is unknown. In the reference, as constants:

crates/vmm/src/virtio/blk.rslines 146-159
/// Request types (§5.2.6).pub mod req {    pub const IN: u32 = 0;    pub const OUT: u32 = 1;    pub const FLUSH: u32 = 4;    pub const GET_ID: u32 = 8;}/// Status values (§5.2.6).pub mod blk_status {    pub const OK: u8 = 0;    pub const IOERR: u8 = 1;    pub const UNSUPP: u8 = 2;}

One rule from section 2.7.4 shapes the parser: a device must not assume how the parts are split across descriptors. So the reference reads all readable descriptors as one byte stream (header, then write data) and all writable ones as another (read data, then the status as the last byte).

What the device tells the driver

The driver reads the disk's size from the configuration space (chapter 15). Our device fills 24 bytes of it:

OffsetFieldSizeOur value
0capacityle64the disk's size in 512-byte sectors
8size_maxle3265536, but its feature bit is not offered, so drivers ignore it
12seg_maxle32126
16geometry4 byteszero (not offered)
20blk_sizele32512

The feature bits are named VIRTIO_BLK_F_FLUSH and so on in the specification; we drop the prefix. We offer SEG_MAX (at most 126 data buffers per request, QEMU's choice: a 128-entry indirect table minus the header and the status), BLK_SIZE (a preferred block size of 512), FLUSH (a write cache exists, and FLUSH requests are accepted), RO for a disk opened with ,ro, VERSION_1 (chapter 15), which every device offers, and INDIRECT_DESC (chapter 16), which blk is the first of our devices to offer. We do not offer SIZE_MAX: FreeBSD refuses a disk whose size_max is smaller than its own largest transfer, so 64 KiB is only our device's internal chunk size (next section).

Labels such as BLK-3 or VQ-9 in the comments of this chapter's code are the reference's own test and threat-model labels; ignore them.

crates/vmm/src/virtio/blk.rslines 620-630
fn device_features(&self) -> u64 {    let mut f = features::VERSION_1        | features::INDIRECT_DESC        | blk_features::SEG_MAX        | blk_features::BLK_SIZE        | blk_features::FLUSH;    if self.read_only {        f |= blk_features::RO;    }    f}

Of the bits the driver accepts, only FLUSH changes the device's behaviour. Its meaning waits for the second half of this chapter:

crates/vmm/src/virtio/blk.rslines 633-639
/// One accepted bit changes the device: `FLUSH` selects write-back, its absence/// write-through (module docs, §5.2.6). The rest need nothing here: `INDIRECT_DESC` is/// enforced by the queue (the transport tells it), and an OUT on a read-only disk fails/// even if the driver ignored `RO`.fn ack_features(&mut self, accepted: u64) {    self.writeback = accepted & blk_features::FLUSH != 0;}

Every field is hostile

Every field of a request comes from the guest, and a hostile guest chooses them to hurt us. Chapter 16's walk already checked that every descriptor lies inside guest RAM, without loops, readable before writable. The device adds its own checks, in this order:

  1. There must be a status byte. With no writable byte at all, there is nowhere to put any answer, so the chain breaks the protocol itself: DEVICE_NEEDS_RESET, as for a broken ring.
  2. The header is 16 readable bytes, copied once into a local BlkHeader (copy-then-validate). Fewer readable bytes: IOERR. Copied once, because a second vCPU (virtual CPU) of the same guest can rewrite memory in the middle of a request (chapter 20 adds it), and a check on one read and a use of another would see two different headers.
  3. At most 128 descriptors in all (126 data buffers, the header, the status): IOERR beyond. A driver that splits the header across two descriptors gets one data buffer fewer.
  4. A known type, moving data one way only: an unknown type is UNSUPP; an IN with readable data, an OUT with writable data, or a FLUSH with any data is IOERR.
  5. No writes to a read-only disk: an OUT on a ,ro disk is IOERR.
  6. The range must be inside the disk: the length a whole number of sectors and at most about 8 MiB (126 × 64 KiB), offset = sector × 512 and offset + length both without overflow, and the end at most the capacity. Else IOERR, and the file is never touched. The 8 MiB cap bounds how long one request holds the device, not memory. The driver is never told this number (there is no size_max), so an honest driver tuned for larger requests would also get IOERR; Linux, FreeBSD and U-Boot by default stay well below it.

Notice the split: a bad request gets a status and the queue carries on; a bad chain, with no place for a status, resets the device. Chapter 16's open question, [writable header, readable data, readable status], never reaches blk, because the walk refuses it; rule 1 catches its cousin with no writable byte at all.

Rule 1 lives in execute, the only place that writes the status:

crates/vmm/src/virtio/blk.rslines 327-354
/// Execute one validated chain; returns the used `len` (the bytes/// actually written, never the length the guest asked for). `Err` is a protocol/// violation that leaves nowhere to write a status (DEVICE_NEEDS_RESET).fn execute(    &mut self,    mem: &dyn GuestMemoryOrdered,    req: &ValidatedChain,) -> Result<u32, VirtioError> {    // The status is the last writable byte, so the chain needs ≥ 1 writable byte    // (zero-length descriptors were already refused by the walk).    let status_at = last_byte(&req.writable).ok_or(VirtioError::Device(        "blk request without a writable status byte",    ))?;    let data_in = req.writable_len.saturating_sub(1);    let (status, written) = match self.parse_and_run(mem, req, data_in) {        Ok(written) => (blk_status::OK, written),        Err((status, written)) => (status, written),    };    match status {        blk_status::IOERR => self.stats.ioerr = self.stats.ioerr.saturating_add(1),        blk_status::UNSUPP => self.stats.unsupp = self.stats.unsupp.saturating_add(1),        _ => {}    }    // Exactly one byte is written for the status.    mem.write_u8(status_at, status)        .map_err(|e| VirtioError::Queue(e.into()))?;    Ok(written.saturating_add(1))}

Rules 2 and 3, in parse:

crates/vmm/src/virtio/blk.rslines 358-376
/// The header rule and the segment cap: the header, copied once from readable bytes only, and the/// OUT data length behind it. `Err` is IOERR.fn parse(    mem: &dyn GuestMemoryOrdered,    req: &ValidatedChain,) -> Result<(BlkHeader, u64), Answer> {    const IOERR: Answer = (blk_status::IOERR, 0);    if req.readable_len < BLK_HDR_LEN {        return Err(IOERR); // a short header, or one in a writable descriptor    }    let hdr = read_header(mem, &req.readable).map_err(|_| IOERR)?;    // Segments: header + SEG_MAX data + status at most (`seg_max`).    let descs = req.readable.len().saturating_add(req.writable.len());    let max = usize::try_from(SEG_MAX).unwrap_or(usize::MAX);    if descs > max.saturating_add(2) {        return Err(IOERR);    }    Ok((hdr, req.readable_len.saturating_sub(BLK_HDR_LEN)))}

Then the dispatch on the type, whose match guards are rule 4; rule 5 opens the OUT arm:

crates/vmm/src/virtio/blk.rslines 382-405
/// One parsed request. `data_out` readable and `data_in` writable data/// bytes surround the header and the status; each type allows data in one direction only./// `Ok(written)` is OK; `Err` carries the status and the data bytes already written.fn parse_and_run(    &mut self,    mem: &dyn GuestMemoryOrdered,    req: &ValidatedChain,    data_in: u64,) -> Result<u32, Answer> {    const IOERR: Answer = (blk_status::IOERR, 0);    let (hdr, data_out) = Self::parse(mem, req)?;    match hdr.kind {        req::IN if data_out == 0 => {            let offset = self.bounds_check(hdr.sector, data_in).ok_or(IOERR)?;            self.read_into_guest(mem, &req.writable, offset, data_in)        }        req::OUT if data_in == 0 => {            if self.read_only {                return Err(IOERR); // a read-only disk            }            let offset = self.bounds_check(hdr.sector, data_out).ok_or(IOERR)?;            self.write_from_guest(mem, &req.readable, offset, data_out)?;            Ok(0)        }

and the rest, ending with the wrong-direction and unknown-type answers:

crates/vmm/src/virtio/blk.rslines 408-430
        req::FLUSH if data_out == 0 && data_in == 0 => {            self.stats.flushes = self.stats.flushes.saturating_add(1);            // OK only once the data is durable. A read-only disk has nothing to            // flush (and its fd is O_RDONLY).            if !self.read_only {                self.sync().map_err(|_| IOERR)?;            }            Ok(0)        }        req::GET_ID if data_out == 0 => {            // The ID string: min(20, writable data bytes).            let n = usize::try_from(data_in)                .unwrap_or(usize::MAX)                .min(BLK_ID_BYTES);            let id = self.id.get(..n).unwrap_or_default();            copy_to_guest(mem, &req.writable, 0, id).map_err(|_| IOERR)?;            self.stats.ids = self.stats.ids.saturating_add(1);            Ok(u32::try_from(n).unwrap_or(0))        }        req::IN | req::OUT | req::FLUSH | req::GET_ID => Err(IOERR), // wrong data direction        _ => Err((blk_status::UNSUPP, 0)),    }}

And rule 6, the check this chapter's first break removes:

crates/vmm/src/virtio/blk.rslines 441-451
/// The byte offset of `sector`, if `len` bytes from there are a whole number of/// sectors, at most [`BLK_MAX_DATA`], and inside the disk. Every step is checked: a/// wrapped multiplication would turn a huge sector number into a small offset.fn bounds_check(&self, sector: u64, len: u64) -> Option<u64> {    if !len.is_multiple_of(SECTOR_SIZE) || len > BLK_MAX_DATA {        return None;    }    let offset = sector.checked_mul(SECTOR_SIZE)?;    let end = offset.checked_add(len)?;    (end <= self.capacity_bytes).then_some(offset)}

In the blk-request lab, build a chain field by field and watch which rule fires:

Lab

virtio-blk request

Build a disk request descriptor by descriptor, see its header bytes, and watch which of the device's checks fires, what reaches the disk and which status byte comes back.

Runs in browserOpen full page: virtio-blk request
virtio-blk request: 512 bytes at sector 64 of a 64-sector disk A three-descriptor chain: a readable 16-byte header (type IN, sector 64), a writable 512-byte data buffer and a writable 1-byte status. The walk and rules 1 to 5 pass. Rule 6 fires: 64 × 512 + 512 = 33280, which is more than the disk's 32768 bytes. The device writes status IOERR (1) into the status byte, used length 1, and never touches the disk file. One request, three descriptors, a 64-sector (32 KiB) disk 0 readable, 16 B header: IN, sector 64 1 writable, 512 B data (untouched) 2 writable, 1 B status: 01 (IOERR) walk passes 3 descriptors, readable before writable rules 1-5 pass status byte, header, 3 <= 128, IN with writable data, not OUT rule 6 FIRES 64 × 512 + 512 = 33280 > 32768 Status IOERR (1), used length 1. The disk file is never touched. With JavaScript on, the lab lets you change every field and descriptor.

If the lab does not load: 512 bytes at sector 64 of a 64-sector (32 KiB) disk fails rule 6, because 64 × 512 + 512 = 33280 > 32768: status IOERR, used length 1.

Security

Two different addresses arrive in every request. The sector is an offset into the image file, which the guest already owns; the descriptor addresses point into guest RAM, which lives inside our process. A bad sector check corrupts data; a bad descriptor check lets an IN request copy disk bytes over the VMM's own memory. Journal question 2 asks you to work out both.

Bytes through a bounce buffer

Data moves between the file and guest memory through a host buffer, a bounce buffer, and three rules make it safe. It is at most 64 KiB, so a request for 8 MiB costs 64 KiB of memory. It is allocated fresh and zeroed for each piece, so a short read can never hand the guest bytes left over from another request or another disk. And a short read or an I/O error is IOERR, with the used length counting only the bytes really copied (chapter 16's rule). A pread may return fewer bytes than asked: at end of file, for instance if someone shrank the image after we opened it. So the backend's read_full retries until it has them all or learns why not.

crates/vmm/src/virtio/blk.rslines 455-489
/// IN: disk → bounce buffer → guest, chunk by chunk (a fresh, zeroed buffer). Returns the bytes written to/// the guest; a short read or an I/O error is IOERR with the bytes produced so far.fn read_into_guest(    &mut self,    mem: &dyn GuestMemoryOrdered,    writable: &[Descriptor],    offset: u64,    len: u64,) -> Result<u32, Answer> {    let mut done: u64 = 0;    for (addr, seg) in ranges(writable, 0, len) {        let mut seg_done: u64 = 0;        while seg_done < seg {            let n = seg.saturating_sub(seg_done).min(MAX_BOUNCE as u64);            let mut buf = vec![0u8; usize::try_from(n).unwrap_or(0)]; // fresh and zeroed            self.batch_bytes = self.batch_bytes.saturating_add(n);            let (got, res) = read_full(&*self.backend, &mut buf, offset.saturating_add(done));            let got_u = u64::try_from(got).unwrap_or(0);            if got > 0 {                let to = GuestAddress(addr.saturating_add(seg_done));                mem.write(to, buf.get(..got).unwrap_or_default())                    .map_err(|_| (blk_status::IOERR, written(done)))?;            }            done = done.saturating_add(got_u);            seg_done = seg_done.saturating_add(got_u);            if res.is_err() || got_u < n {                return Err((blk_status::IOERR, written(done))); // short: the file shrank since open            }        }    }    self.stats.reads = self.stats.reads.saturating_add(1);    self.stats.bytes_read = self.stats.bytes_read.saturating_add(done);    Ok(written(done))}

The backend underneath is the primer's positional I/O: pread and pwrite take the offset as an argument, so threads share no file position. The device needs five methods from a disk (capacity, read-only, read at, write at, sync), each one standard-library call for a file:

crates/vmm/src/backend/file.rslines 142-163
impl BlockBackend for DiskFile {    fn capacity_sectors(&self) -> u64 {        self.capacity_sectors    }    fn read_only(&self) -> bool {        self.read_only    }    /// `pread(2)` on the image's fd. No cursor, no seek (module docs).    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {        self.file.read_at(buf, offset)    }    /// `pwrite(2)`. On a `,ro` disk the fd is `O_RDONLY`, so the kernel answers `EBADF`    /// whatever the caller checked (host test `disk_ro_is_o_rdonly`).    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {        self.file.write_at(buf, offset)    }    /// `File::sync_all` = `fcntl(F_FULLFSYNC)` on Apple targets: the data    /// reaches stable storage, not only the drive cache.    fn sync(&self) -> io::Result<()> {        self.file.sync_all()    }}

Your turn: build the device

The breaks below edit your device, so build it now. In your workspace, learner/:

  1. crates/vmm/src/virtio/blk.rs: the request parser and the six rules in order, the bounce-buffer data paths, FLUSH through the backend (its meaning comes in the second half; for now call the backend's sync), and the features and configuration space above. GET_ID: disk_serial(index) returns macvmm-disk<index>, padded with zero bytes to 20, and the device writes min(20, data bytes) of it.
  2. crates/vmm/src/backend/file.rs: a BlockBackend trait (capacity, read-only, read at, write at, sync), read_full and write_full, and a DiskFile that checks for a regular file, fixes the capacity and takes the lock (its section comes later; the tests here use in-memory disks).
  3. Copy crates/vmm/tests/virtio_blk_hostile.rs, blk_short_read.rs and blk_budget.rs into learner/crates/vmm/tests/ (chapter 16 already gave you virtio_support/). Their use lines name the items they test (such as req, blk_status, disk_serial, read_full); give yours the same names and paths.

The tests also import these constants. Give yours the same values:

ConstantValueWhy
BLK_QUEUE_SIZE256the requestq's size
SIZE_MAX64 KiBone bounce buffer, the chunk size; its feature bit is not offered
SEG_MAX126data buffers per request, QEMU's choice
BLK_MAX_DATASEG_MAX × SIZE_MAX, about 8 MiBrule 6's cap
BLK_CHAIN_MAX2 × BLK_QUEUE_SIZE × u32::MAX, about 2 TiBthe total cap passed to chapter 16's walk
BLK_BATCH_BYTES2 × BLK_MAX_DATAa batch of requests ends after this many data bytes, or after one sync
BLK_CONFIG_LEN24the configuration space in the table above

One trap hides in BLK_CHAIN_MAX. Pass chapter 16's walk a total cap far above 8 MiB, so that an oversized but well-formed request reaches rule 6 and gets IOERR. If you pass BLK_MAX_DATA, the walk calls the chain too large, which means DEVICE_NEEDS_RESET, and one big request kills the disk.

The batch limits matter for blk_budget: the worker serves requests in batches and releases the device between them, so one batch never holds the device for long, even when every request is slow. Run the three suites from inside learner/; against the reference they print:

TerminalReal output
cargo test -q -p vmm --test virtio_blk_hostile --test blk_short_read --test blk_budgetexit: 0--- stdout ---running 1 test.test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.55srunning 7 tests.......test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00srunning 32 tests................................test result: ok. 32 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.64s--- stderr ---blk_budget: 21 batches, 107 requests posted, 22 syncs, max 2 requests and 74.321ms per batch, observer took the device mutex 3 times (worst wait 1.469160333s), stop took 42.829333ms
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-reference-tests.txt

The blk_budget line on standard error is information. The figure it checks is the time per batch ("max ... per batch", under 250 ms). The observer's worst wait is printed but not checked, because Rust's standard Mutex is not fair: the worker can take the lock again before a waiting thread does.

Stuck? scripts/learner hint 18 climbs from a nudge to the reference file, and scripts/learner lifeline MODULE lends you a reference module (yours is kept as .mine) so you can move on.

Breaking it on purpose

Deliberate breakage 1: an unchecked sector * 512. In your bounds_check, replace checked_mul and checked_add with wrapping_mul and wrapping_add, which is what C's * and + do on 64-bit unsigned numbers. Predict: which hostile tests fail, and how? Then run the device's host tests (no virtual machine needed):

TerminalReal output
cargo test -q -p vmm --test virtio_blk_hostileexit: 101--- stdout ---running 32 tests............. 13/32random_requests_match_the_model --- FAILED... 17/32sector_times_512_overflow_is_ioerr_not_a_wrap --- FAILED........ 26/32sector_past_the_end_is_ioerr_and_never_reaches_the_disk --- FAILED.....failures:---- random_requests_match_the_model stdout ----thread 'random_requests_match_the_model' (124870728) panicked at crates/vmm/tests/virtio_blk_hostile.rs:86:13:attempt to add with overflownote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace---- sector_times_512_overflow_is_ioerr_not_a_wrap stdout ----thread 'sector_times_512_overflow_is_ioerr_not_a_wrap' (124870733) panicked at crates/vmm/tests/virtio_blk_hostile.rs:201:9:assertion `left == right` failed: status byte  left: 0 right: 1---- sector_past_the_end_is_ioerr_and_never_reaches_the_disk stdout ----thread 'sector_past_the_end_is_ioerr_and_never_reaches_the_disk' (124870732) panicked at crates/vmm/tests/virtio_blk_hostile.rs:78:36:range start index 18446744073709551104 out of range for slice of length 32768failures:    random_requests_match_the_model    sector_past_the_end_is_ioerr_and_never_reaches_the_disk    sector_times_512_overflow_is_ioerr_not_a_wraptest result: FAILED. 29 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.58s--- stderr ---error: test failed, to rerun pass `-p vmm --test virtio_blk_hostile`
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: in bounds_check (crates/vmm/src/virtio/blk.rs), checked_mul and checked_add replaced by wrapping_mul and wrapping_add, the arithmetic C would do.
course/captures/18-break-wrap.txt

Read sector_times_512_overflow_is_ioerr_not_a_wrap first. It asks for sector 2^55; 2^55 × 512 = 2^64 wraps to 0, so the check saw "offset 0, end 512" and the device answered OK (left: 0; the test wanted IOERR, 1) with sector 0's contents. A wrapped offset is a valid offset, only the wrong one.

In sector_past_the_end_is_ioerr_and_never_reaches_the_disk, the sector is u64::MAX / 512. Times 512 that is 2^64 − 512, which fits; adding the length wrapped the end to 0, so 0 <= capacity passed and the huge offset reached the test's in-memory disk. That is the checked_add half.

The third, random_requests_match_the_model, sends up to 10,000 random requests and compares each answer with a simple model of the disk. One random OUT used a sector near u64::MAX; both the offset and the end wrapped, our check let it through, and it reached the in-memory disk's write_at, whose own off + buf.len() overflowed (line 86 of the test file). The panic is in the test's code, but the bug is ours: the disk should never have seen that offset.

Now try the version a Rust programmer writes by habit, plain sector * SECTOR_SIZE and offset + len:

TerminalReal output
cargo test -q -p vmm --test virtio_blk_hostileexit: 101--- stdout ---running 32 tests............... 15/32random_requests_match_the_model --- FAILEDsector_times_512_overflow_is_ioerr_not_a_wrap --- FAILED......... 26/32sector_past_the_end_is_ioerr_and_never_reaches_the_disk --- FAILED.....failures:---- random_requests_match_the_model stdout ----thread 'random_requests_match_the_model' (124867699) panicked at crates/vmm/src/virtio/blk.rs:447:22:attempt to multiply with overflownote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace---- sector_times_512_overflow_is_ioerr_not_a_wrap stdout ----thread 'sector_times_512_overflow_is_ioerr_not_a_wrap' (124867704) panicked at crates/vmm/src/virtio/blk.rs:447:22:attempt to multiply with overflow---- sector_past_the_end_is_ioerr_and_never_reaches_the_disk stdout ----thread 'sector_past_the_end_is_ioerr_and_never_reaches_the_disk' (124867703) panicked at crates/vmm/src/virtio/blk.rs:448:19:attempt to add with overflowfailures:    random_requests_match_the_model    sector_past_the_end_is_ioerr_and_never_reaches_the_disk    sector_times_512_overflow_is_ioerr_not_a_wraptest result: FAILED. 29 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.58s--- stderr ---error: test failed, to rerun pass `-p vmm --test virtio_blk_hostile`
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1, second form: in bounds_check, plain sector * SECTOR_SIZE and offset + len (cargo test builds with overflow checks on).
course/captures/18-break-mul.txt

The same three tests fail again, but now every panic is inside our bounds_check: two with attempt to multiply with overflow, and the past-the-end one with attempt to add with overflow, because there the multiply fit and the end overflowed. cargo test builds with overflow checks on, as every debug build does, so the wrap became a panic. This workspace also turns the checks on for release builds (in Cargo.toml), so the shipped VMM would stop the same way instead of wrapping. Better than reading sector 0, but a crash the guest can trigger at will is still a bug. Answer journal question 1 now, while the break is fresh.

What you saw: three hostile tests fail, first with wrong data, then with a crash. The misconception: "the file system call will reject a bad offset". The tool that found it: the hostile host tests, which ask for the sectors nobody would.

Linux reads your disk

Step 4 of your build. Wire the device into your VMM as chapter 17 wired rng. --disk FILE[,ro] (repeatable; the first disk becomes /dev/vda) opens the image with DiskFile, wraps it in a Blk, and gives it a virtio-mmio slot and a device tree node.

Then, from inside learner/, boot the test initramfs with its vda case, which hashes the whole disk from inside the guest:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 60 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=vda"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virtmacvmm-vda: /dev/vda 131072 sectors ro=0macvmm-vda: sha256=4ae50b0ecaa3f91bdcfe84f5a2e20706045ea6f3387c6c45238200cf50ea7859[    0.349581] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-vda-read.txt

Linux read all 131,072 sectors (64 MiB) through your rings and computed the hash shasum printed on the Mac. The vda-write case writes 1 MiB of the text macvmm at byte 8 MiB with conv=fsync, a FLUSH; look at those bytes on the host afterwards:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 60 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=vda-write"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virtmacvmm-vda: /dev/vda 131072 sectors ro=0macvmm-vda: write done[    0.120153] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-vda-write.txt
TerminalReal output
xxd -s 8388608 -l 64 disk.imgexit: 0--- stdout ---00800000: 6d61 6376 6d6d 0a6d 6163 766d 6d0a 6d61  macvmm.macvmm.ma00800010: 6376 6d6d 0a6d 6163 766d 6d0a 6d61 6376  cvmm.macvmm.macv00800020: 6d6d 0a6d 6163 766d 6d0a 6d61 6376 6d6d  mm.macvmm.macvmm00800030: 0a6d 6163 766d 6d0a 6d61 6376 6d6d 0a6d  .macvmm.macvmm.m
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-vda-write-xxd.txt

Now the same image with ,ro. The device offers RO, and Linux marks the disk read-only (ro=1):

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img,ro --on-reset exit --timeout 60 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=vda-ro"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virtmacvmm-vda: /dev/vda 131072 sectors ro=1macvmm-vda-ro: write rejected[    0.099142] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-vda-ro.txt

Before this run, shasum -a 256 disk.img printed 61da37b8…e5ee; after it, the same:

TerminalReal output
shasum -a 256 disk.imgexit: 0--- stdout ---61da37b8b77d7f9d7d8ba1c797f0988c2b02ef36a339e2d321bfa5ce9245e5ee  disk.img
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-sha-after-ro.txt

Booting the shell on your disk

The test cases run a script and power off. For your own commands, boot the shell case instead:

Shell
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"

At the / # prompt, load the drivers and give them a second to find the device: modprobe virtio_mmio; modprobe virtio_blk; sleep 1. The test cases load these modules for you; the shell does not. Leave with poweroff -f (chapter 14). --timeout 100 stops the VMM after 100 seconds in any case, so anything you do beside it, such as the lock test below, must start before then.

The vda-ro case hid dd's own message. At the shell on the same disk opened ,ro, the refusal reads:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img,ro --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_blk; sleep 1/ # cat /sys/block/vda/ro1/ # dd if=/dev/zero of=/dev/vda bs=4k count=1 conv=fsyncdd: error writing '/dev/vda': Operation not permitted1+0 records in0+0 records out0 bytes (0B) copied, 0.000340 seconds, 0B/s/ # poweroff -f[    9.826434] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Typed at the / # prompt, one line at a time: the lines shown after each prompt.
course/captures/18-ro-dd.txt

Operation not permitted is Linux's block layer refusing the write itself, because the disk is marked read-only; an IOERR from our device would have reached dd as an I/O error. So this write never reached rule 5; the open question at the end asks what rule 5 should do when a driver ignores the bit.

Try it

At the shell on your read-write disk, type cat /sys/block/vda/serial; echo (the echo ends the line, since the serial has no newline). Reading that file makes Linux send a GET_ID request. What does it print, and how many bytes of the 20 did your device write? Look for 12 visible characters; the device wrote all 20, the other 8 being zero padding, so the used length was 21 with the status byte.

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_blk; sleep 1/ # cat /sys/block/vda/serial; echomacvmm-disk0/ # cat /sys/block/vda/size /sys/block/vda/ro1310720/ # poweroff -f[    8.708675] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Typed at the / # prompt, one line at a time: the lines shown after each prompt.
course/captures/18-get-id.txt

One image, one VMM

Two VMMs writing one image means two guest caches, each sure it owns every block: corruption. So the backend takes an image lock when it opens the file, with the primer's advisory flock: an exclusive lock for read-write, a shared one for ,ro (several readers may share a disk, but never beside a writer). It also refuses anything that is not a regular file, such as /dev/disk0, your Mac's whole internal drive:

crates/vmm/src/backend/file.rslines 101-126
/// Wrap the fd `file`, opened `O_RDONLY` if `read_only` and `O_RDWR` otherwise: `fstat`/// it (it must be a regular file, not a device), fix the capacity once from the open fd,/// and lock it so two VMs cannot write one disk.pub fn new(file: File, read_only: bool) -> Result<DiskFile, DiskError> {    let meta = file.metadata().map_err(DiskError::Stat)?; // fstat(2) on the fd    if !meta.file_type().is_file() {        return Err(DiskError::NotRegular);    }    let locked = if read_only {        file.try_lock_shared()    } else {        file.try_lock()    };    match locked {        Ok(()) => {}        Err(TryLockError::WouldBlock) => return Err(DiskError::Locked),        Err(TryLockError::Error(e)) => return Err(DiskError::Lock(e)),    }    let size_bytes = meta.len();    Ok(DiskFile {        file,        read_only,        size_bytes,        capacity_sectors: size_bytes / SECTOR_SIZE,    })}

In one terminal, boot the shell on disk.img (the command from "Booting the shell on your disk"), and leave it at its prompt. In a second terminal, also inside learner/, start a second VMM on the same image:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --disk disk.img --timeout 10exit: 2--- stderr ---macvmm: disk image is locked: "disk.img" is in use by another process (macvmm takes an advisory flock on every --disk; BLK-8)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • A first macvmm was already running on disk.img (the shell case, at its prompt) in another terminal, started with the command shown in the lesson.
course/captures/18-locked.txt

Exit code 2, before any virtual machine exists. The lock belongs to the open file, so a crashed VMM never leaves an image locked.

Good place to stop. Your device reads, writes and refuses correctly. The second half is about what "written" means, and needs about 2 hours.

What FLUSH promises

When a guest's OUT completes, where are the bytes? In the Mac's page cache, where pwrite copied them; the macOS kernel writes them to the drive later. That is a write-back cache, and the FLUSH feature bit is how a device admits to one. The specification's deal (section 5.2.6) is that a write is stable once a later FLUSH has completed. A guest filesystem builds its safety on that deal: ext4 writes its journal, sends FLUSH, and only then writes the commit record that says the journal is valid.

So FLUSH must not answer OK until the data would survive a power cut. If the driver did not accept FLUSH, it has no way to ask, so the device must be write-through instead: sync after every write, before answering. The reference's write path ends with exactly that when writeback (true only if the driver accepted FLUSH) is false:

crates/vmm/src/virtio/blk.rslines 493-524
/// OUT: guest → bounce buffer → disk, chunk by chunk. Each guest byte is read once into a/// fresh buffer and written from that copy. In write-through mode (FLUSH not negotiated,/// module docs) the write is synced before it may answer OK (§5.2.6).fn write_from_guest(    &mut self,    mem: &dyn GuestMemoryOrdered,    readable: &[Descriptor],    offset: u64,    len: u64,) -> Result<(), Answer> {    const IOERR: Answer = (blk_status::IOERR, 0);    let mut done: u64 = 0;    for (addr, seg) in ranges(readable, BLK_HDR_LEN, len) {        let mut seg_done: u64 = 0;        while seg_done < seg {            let n = seg.saturating_sub(seg_done).min(MAX_BOUNCE as u64);            let mut buf = vec![0u8; usize::try_from(n).unwrap_or(0)];            mem.read(GuestAddress(addr.saturating_add(seg_done)), &mut buf)                .map_err(|_| IOERR)?;            self.batch_bytes = self.batch_bytes.saturating_add(n);            write_full(&*self.backend, &buf, offset.saturating_add(done)).map_err(|_| IOERR)?;            done = done.saturating_add(n);            seg_done = seg_done.saturating_add(n);        }    }    if !self.writeback {        self.sync().map_err(|_| IOERR)?; // write-through: stable before OK    }    self.stats.writes = self.stats.writes.saturating_add(1);    self.stats.bytes_written = self.stats.bytes_written.saturating_add(done);    Ok(())}

Add that branch to your own write path now.

Now the opening Predict. We ran the flushed writes in three builds: the reference, a copy whose DiskFile::sync calls plain fsync, and a copy whose DiskFile::sync does nothing. In each, at the shell, after loading the drivers, we timed one 64 MiB write with a single flush at the end, then the 100 flushed 4 KiB writes:

Shell
time dd if=/dev/zero of=/dev/vda bs=1M count=64 conv=fsynctime sh -c 'for i in $(seq 1 100); do dd if=/dev/zero of=/dev/vda bs=4k count=1 seek=$i conv=fsync 2>/dev/null; done'

These runs overwrite disk.img with zeros. Time your own build and use our numbers for the others (the terminal's echo wraps the long line).

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_blk; sleep 1; cat /sys/block/vda/size131072/ # time dd if=/dev/zero of=/dev/vda bs=1M count=64 conv=fsync64+0 records in64+0 records out67108864 bytes (64.0MB) copied, 0.096901 seconds, 660.5MB/sreal	0m 0.09suser	0m 0.00ssys	0m 0.01s/ # time sh -c 'for i in $(seq 1 100); do dd if=/dev/zero of=/dev/vda bs=4k count=1 seek=$i conv=fsync 2>/dev/null; done'real	0m 0.47suser	0m 0.02ssys	0m 0.01s/ # poweroff -f[   16.718124] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Typed at the / # prompt, one line at a time: the lines shown after each prompt.
  • The reference: FLUSH runs File::sync_all, which is fcntl(F_FULLFSYNC) on macOS.
course/captures/18-flush-full.txt
TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_blk; sleep 1; cat /sys/block/vda/size131072/ # time dd if=/dev/zero of=/dev/vda bs=1M count=64 conv=fsync64+0 records in64+0 records out67108864 bytes (64.0MB) copied, 0.191912 seconds, 333.5MB/sreal	0m 0.19suser	0m 0.00ssys	0m 0.01s/ # time sh -c 'for i in $(seq 1 100); do dd if=/dev/zero of=/dev/vda bs=4k count=1 seek=$i conv=fsync 2>/dev/null; done'real	0m 0.08suser	0m 0.01ssys	0m 0.01s/ # poweroff -f[   16.573860] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Typed at the / # prompt, one line at a time: the lines shown after each prompt.
  • Edited copy: DiskFile::sync (crates/vmm/src/backend/file.rs) calls plain fsync(2) instead of File::sync_all.
course/captures/18-flush-fsync.txt
TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_blk; sleep 1; cat /sys/block/vda/size131072/ # time dd if=/dev/zero of=/dev/vda bs=1M count=64 conv=fsync64+0 records in64+0 records out67108864 bytes (64.0MB) copied, 0.087569 seconds, 730.9MB/sreal	0m 0.08suser	0m 0.00ssys	0m 0.01s/ # time sh -c 'for i in $(seq 1 100); do dd if=/dev/zero of=/dev/vda bs=4k count=1 seek=$i conv=fsync 2>/dev/null; done'real	0m 0.04suser	0m 0.01ssys	0m 0.00s/ # poweroff -f[   16.678345] reboot: Power down
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Typed at the / # prompt, one line at a time: the lines shown after each prompt.
  • Deliberate breakage 2: DiskFile::sync (crates/vmm/src/backend/file.rs) returns Ok(()) without syncing anything.
course/captures/18-flush-noop.txt

The 100 flushed writes took 0.47 s with F_FULLFSYNC, 0.08 s with fsync and 0.04 s with nothing: about 4.7 ms per honest flush, six times fsync and more than ten times nothing (busybox's time rounds to 10 ms; your drive will differ). The single 64 MiB write cost about the same in all three: the price is per flush, not per byte.

Why is fsync so much cheaper? Read the manual on your Mac:

TerminalReal output
man 2 fsync | col -b | sed -n 18,37pexit: 0--- stdout ---     Note that while fsync() will flush all data from the host to the drive     (i.e. the "permanent storage device"), the drive itself may not     physically write the data to the platters for quite some time and it may     be written in an out-of-order sequence.     Specifically, if the drive loses power or the OS crashes, the application     may find that only some or none of their data was written.  The disk     drive may also re-order the data so that later writes may be present,     while earlier writes are not.     This is not a theoretical edge case.  This scenario is easily reproduced     with real world workloads and drive power failures.     For applications that require tighter guarantees about the integrity of     their data, Mac OS X provides the F_FULLFSYNC fcntl.  The F_FULLFSYNC     fcntl asks the drive to flush all buffered data to permanent storage.     Applications, such as databases, that require a strict ordering of writes     should use F_FULLFSYNC to ensure that their data is written in the order     they expect.  Please see fcntl(2) for more detail.
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-man-fsync.txt

On macOS, fsync sends the data to the drive, which may keep it in its own volatile cache; Linux's fsync also flushes that cache, which macOS keeps for F_FULLFSYNC. A guest's FLUSH means the Linux promise, so it needs F_FULLFSYNC. In Rust that is File::sync_all, and we checked the pinned standard library rather than trust a comment. To check it yourself, run rustup component add rust-src first (it only adds the standard library's source files), then the grep shown:

TerminalReal output
grep -n -B5 -A2 "unsafe fn os_fsync" "$(rustc --print sysroot)/lib/rustlib/src/rust/library/std/src/sys/fs/unix.rs"exit: 0--- stdout ---1264-    pub fn fsync(&self) -> io::Result<()> {1265-        cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;1266-        return Ok(());1267-1268-        #[cfg(target_vendor = "apple")]1269:        unsafe fn os_fsync(fd: c_int) -> c_int {1270-            libc::fcntl(fd, libc::F_FULLFSYNC)1271-        }1272-        #[cfg(not(target_vendor = "apple"))]1273:        unsafe fn os_fsync(fd: c_int) -> c_int {1274-            libc::fsync(fd)1275-        }
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • rustc 1.99.0, the toolchain rust-toolchain.toml pins.
course/captures/18-std-fullfsync.txt

sync_all calls this fsync method, and on Apple targets it is fcntl(fd, F_FULLFSYNC). The reference's DiskFile::sync is one line, self.file.sync_all(), and FLUSH answers OK only after it returned Ok. Answer journal question 3 now.

The primer's durability-ladder lab follows a write through each cache, then kills the process or the power:

Lab

Durability ladder

Follow one guest fsync() through the guest page cache, the VMM, the host page cache, the drive's cache and flash, choose how the VMM answers FLUSH, then kill the process or cut the power and see what the guest's journal finds.

Runs in browserOpen full page: Durability ladder
The durability ladder Five rungs between a guest write() and storage that survives: 1, the guest page cache in guest RAM; 2, a request in flight in the VMM; 3, the host page cache owned by macOS; 4, the SSD's volatile cache; 5, flash. A guest kernel crash wipes rung 1. Killing the VMM process wipes rungs 1 and 2. A macOS crash wipes rungs 1 to 3. A power cut wipes rungs 1 to 4. The virtio OUT request moves data past rung 1, pwrite past rung 2, fsync past rung 3, and only F_FULLFSYNC past rung 4, which is why the VMM must answer the guest's FLUSH with F_FULLFSYNC. rung wiped by 1 guest page cache 2 request in flight in the VMM 3 host page cache (macOS) 4 SSD's volatile cache 5 flash: survives virtio OUT request pwrite() returns fsync() F_FULLFSYNC guest crash, kill -9, macOS crash, power kill -9, macOS crash, power macOS crash, power power nothing guest above, host below

If the lab does not load: a killed process loses nothing that reached the page cache; a power cut loses everything not yet on the drive's permanent storage, including what plain fsync left in the drive's cache.

Deliberate breakage 2: FLUSH that does nothing (one you explain rather than see fail). In crates/vmm/src/backend/file.rs, make DiskFile::sync return Ok(()) without calling anything; leave the device's call to it alone. Predict: which test fails? Run the three host suites:

TerminalReal output
cargo test -q -p vmm --test virtio_blk_hostile --test blk_short_read --test blk_budgetexit: 0--- stdout ---running 1 test.test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.58srunning 7 tests.......test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01srunning 32 tests................................test result: ok. 32 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.60s--- stderr ---blk_budget: 21 batches, 107 requests posted, 22 syncs, max 2 requests and 77.582ms per batch, observer took the device mutex 3 times (worst wait 1.508571s), stop took 74.535417ms
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 2 build: DiskFile::sync (crates/vmm/src/backend/file.rs) returns Ok(()) without syncing anything.
course/captures/18-noop-tests.txt

Every test passes. The test flush_calls_sync_once_and_reports_its_failure counts sync calls on an in-memory disk: it proves the device asks, not that the backend keeps its promise. Now the opening's second question. Keep the break-2 build: this is the do-nothing FLUSH from the Predict. From inside learner/, make a fresh disk, so the 8 MiB mark starts random, and look at it:

Shell
(cd .. && cargo xtask mkdisk --size 64M --seed 1 --out learner/disk.img)
TerminalReal output
xxd -s 0x800000 -l 16 disk.imgexit: 0--- stdout ---00800000: e17d 14c4 9cf0 b268 b925 1eba e325 2876  .}.....h.%...%(v
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-kill9-before.txt

In terminal 1, boot the shell on disk.img, and at the prompt type these two lines (the terminal's echo wraps the long one in the capture below):

Shell
modprobe virtio_mmio; modprobe virtio_blk; sleep 1yes macvmm | head -c 1048576 > /tmp/p; dd if=/tmp/p of=/dev/vda bs=1M seek=8 count=1 conv=fsync

As soon as dd prints its summary, kill the VMM from terminal 2, inside learner/. lsof -a -c macvmm -t disk.img prints the process ID of the macvmm that holds the image, and nothing else that happens to have it open:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk disk.img --on-reset exit --timeout 100 --cmdline "console=ttyAMA0 panic=-1 quiet macvmm.test=shell"exit: none (ended by a signal)--- stdout ---macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_blk; sleep 1/ # yes macvmm | head -c 1048576 > /tmp/p; dd if=/tmp/p of=/dev/vda bs=1M seek=8 count=1 conv=fsync1+0 records in1+0 records out1048576 bytes (1.0MB) copied, 0.001988 seconds, 503.0MB/s/ # 
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Terminal 1. Deliberate breakage 2 build: DiskFile::sync (crates/vmm/src/backend/file.rs) returns Ok(()) without syncing anything.
  • Typed at the / # prompt, one line at a time: the lines shown after each prompt. Terminal 2 then ran kill -9 (18-kill9-kill.txt).
course/captures/18-kill9.txt
TerminalReal output
kill -9 $(lsof -a -c macvmm -t disk.img)exit: 0
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Terminal 2, run once terminal 1 showed the dd summary.
course/captures/18-kill9-kill.txt
TerminalReal output
xxd -s 0x800000 -l 16 disk.imgexit: 0--- stdout ---00800000: 6d61 6376 6d6d 0a6d 6163 766d 6d0a 6d61  macvmm.macvmm.ma
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-kill9-after.txt

The bytes are in the file: pwrite had already handed them to the macOS kernel, which outlives our process. (The persistence run in the next section passes on this build too.)

What would show the bug? With the do-nothing FLUSH, the data may still sit in the Mac's page cache, so a host crash or a power loss loses it. Plain fsync is shown up only by a power cut while the data sits in the drive's own cache. Neither can be tested honestly on a laptop.

What you saw: nothing, except cheaper flushes. The misconception: "the guest's filesystem keeps the disk consistent, so the VMM can cache freely"; the filesystem is consistent only because FLUSH means durable. The tool that finds it: reading the contract (the specification and man fsync), not a test. Put it back.

A root filesystem that persists

Everything so far ran from the initramfs, a filesystem in RAM. Now the disk becomes the guest's root filesystem, the one / lives on (the linux-boot-sequence primer). With an initramfs, its init program picks the root itself. Ours always mounts /dev/vda and switches to it with switch_root; the root=/dev/vda on the command line only records the convention a stock initramfs would read.

At the repository root, build an ext4 image of Alpine's minimal root filesystem in learner/ with the course's builder, which uses mkfs.ext4 from e2fsprogs:

TerminalReal output
cargo xtask mkrootfs --out learner/rootfs.img --size 256Mexit: 0--- stdout ---mkrootfs: OK learner/rootfs.img (268435456 bytes; 83 files, 96 dirs, 335 symlinks, 0 hard links; 181 modes applied in the guest; setid stripped: none; e2fsprogs 1.47.4)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-mkrootfs.txt

File owners need root privileges, which the builder does not have. File modes it holds back on purpose, so that downloaded bytes never become executable programs on the Mac. It records both, and the guest applies them on its first boot (the "modes" and "ownership" lines below).

Back inside learner/, clone the image, so the run never writes the image you built. cp -c makes an APFS (Apple File System) clone, a copy-on-write copy that costs no space until one side changes (man cp). Chapter 22 uses the same trick for FreeBSD's disk.

TerminalReal output
cp -c rootfs.img root.imgexit: 0
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-clone.txt

Alpine's ext4 driver is a module, shipped in a separate image, modloop-virt; the run attaches it as a second, ,ro disk, /dev/vdb, and the test initramfs loads ext4 from it before mounting /dev/vda.

Aside

A kernel module is a piece of the kernel kept in a separate file and loaded at run time, so one kernel can serve many machines. modloop-virt is a squashfs image, a compressed read-only filesystem the kernel mounts directly (squashfs documentation).

The rootfs case does the rest. Boot 1 writes 16 MiB of random bytes and their hash to /persist.bin and /persist.sha on the ext4 root, then reboots with a PSCI reset call; with the default --on-reset reboot, our VMM rebuilds the virtual machine inside the same process, over the same open disk (chapter 08). Boot 2 hashes the file again:

TerminalReal output
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk root.img --disk ../.cache/macvmm/modloop-virt,ro --log info --timeout 120 --cmdline "console=ttyAMA0 panic=-1 quiet root=/dev/vda macvmm.test=rootfs"exit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virtmacvmm-rootfs: insmod jbd2macvmm-rootfs: insmod mbcachemacvmm-rootfs: insmod crc16macvmm-rootfs: insmod ext4macvmm-rootfs: mounted ext4 /dev/vdamacvmm-rootfs: applied 181 modesmacvmm-rootfs: boot 1macvmm-rootfs: ownership fixedmacvmm-rootfs: wrote /persist.bin sha256=628f16360487442a2919951f0958f476a62e17b89badf337fe670922a45104camacvmm-rootfs: rebooting[    0.657453] reboot: Restarting systemmacvmm-initramfs: ready 6.18.60-0-virtmacvmm-rootfs: insmod jbd2macvmm-rootfs: insmod mbcachemacvmm-rootfs: insmod crc16macvmm-rootfs: insmod ext4macvmm-rootfs: mounted ext4 /dev/vdamacvmm-rootfs: boot 2macvmm-rootfs: persist ok sha256=628f16360487442a2919951f0958f476a62e17b89badf337fe670922a45104ca[    0.453170] reboot: Power down--- stderr ---macvmm: info: [main] guest reset: rebooting (boot 1)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-rootfs.txt

Two boots, one hash. The guest reset line comes from our VMM's own standard error, which no guest byte reaches, so the guest cannot fake the reboot. Last, check the filesystem from the Mac, read-only:

TerminalReal output
"$(brew --prefix e2fsprogs)/sbin/e2fsck" -fn root.imgexit: 0--- stdout ---Pass 1: Checking inodes, blocks, and sizesPass 2: Checking directory structurePass 3: Checking directory connectivityPass 4: Checking reference countsPass 5: Checking group summary informationroot: 530/65536 files (0.9% non-contiguous), 51291/262144 blocks--- stderr ---e2fsck 1.47.4 (6-Mar-2025)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20course/captures/18-e2fsck.txt

Security

Every byte of root.img was now chosen by the guest, and e2fsck is a host program parsing it. So -n opens it read-only, only the clone is checked, and nothing on the Mac mounts it. Chapter 25 confines our VMM itself with the macOS sandbox, a kernel-enforced list of what a process may touch.

We also ran this section on the break-2 build, the do-nothing FLUSH: it passes, and e2fsck is clean.

TerminalReal output
cp -c rootfs.img root.img && cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --disk root.img --disk ../.cache/macvmm/modloop-virt,ro --log info --timeout 120 --cmdline "console=ttyAMA0 panic=-1 quiet root=/dev/vda macvmm.test=rootfs" && "$(brew --prefix e2fsprogs)/sbin/e2fsck" -fn root.imgexit: 0--- stdout ---macvmm-initramfs: ready 6.18.60-0-virtmacvmm-rootfs: insmod jbd2macvmm-rootfs: insmod mbcachemacvmm-rootfs: insmod crc16macvmm-rootfs: insmod ext4macvmm-rootfs: mounted ext4 /dev/vdamacvmm-rootfs: applied 181 modesmacvmm-rootfs: boot 1macvmm-rootfs: ownership fixedmacvmm-rootfs: wrote /persist.bin sha256=c84a791a9b9dc00a0682de0d62c1fc9bfc2bce771897e167bbe23c5daa85399amacvmm-rootfs: rebooting[    0.403864] reboot: Restarting systemmacvmm-initramfs: ready 6.18.60-0-virtmacvmm-rootfs: insmod jbd2macvmm-rootfs: insmod mbcachemacvmm-rootfs: insmod crc16macvmm-rootfs: insmod ext4macvmm-rootfs: mounted ext4 /dev/vdamacvmm-rootfs: boot 2macvmm-rootfs: persist ok sha256=c84a791a9b9dc00a0682de0d62c1fc9bfc2bce771897e167bbe23c5daa85399a[    0.329637] reboot: Power downPass 1: Checking inodes, blocks, and sizesPass 2: Checking directory structurePass 3: Checking directory connectivityPass 4: Checking reference countsPass 5: Checking group summary informationroot: 530/65536 files (0.9% non-contiguous), 51291/262144 blocks--- stderr ---macvmm: info: [main] guest reset: rebooting (boot 1)e2fsck 1.47.4 (6-Mar-2025)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 2 build: DiskFile::sync (crates/vmm/src/backend/file.rs) returns Ok(()) without syncing anything.
course/captures/18-noop-rootfs.txt

Your build is complete once its write path has the write-through branch from "What FLUSH promises" and your VMM passes this run. Your journal has the Predict entry and questions 1 to 3 by now; question 4 is the open question at the end.

Explain it back: a hostile chain

This closes Part VII's storage chapters, so here is a request you have not seen. In about 200 words, in your own notes (nothing checks them), say which checks fire, in what order, and what the device does. The disk was opened ,ro. After chapter 16's walk, the device sees:

DescriptorFlagsLengthContents
0readable8type = 1, reserved = 0
1readable520sector = 0x0080_0000_0000_0000, then 512 bytes of data
2writable1the status byte

Score yourself, one point each: every check named, in order, and where it stops; evidence from the chain (the values that decide each check); and a next step someone could test, such as a host test.

Our answer, to read after yours. The walk accepts the chain. Rule 1: descriptor 2 is a status byte. Rule 2: 528 readable bytes, so the header is copied once from two descriptors, as section 2.7.4 allows: OUT at sector 2^55. Rules 3 and 4 pass. Rule 5 fires: IOERR, used length 1, file untouched. The sector is a decoy: on a read-write disk rule 6 refuses it (2^55 × 512 overflows), and C's arithmetic would have overwritten sector 0.

Checkpoint

Back at the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 18

You should see, as the last line:

CHECKPOINT 18 PASS

It runs the three host suites you copied in "Your turn: build the device", three runs on your Mac, and the journal check. disk-vda boots the vda, vda-write and vda-ro cases on a fresh random disk, with the host checking every hash; in disk-lock, a second VMM beside one holding the image must exit with code 2, read-write and ,ro; disk-rootfs boots a clone of your learner/rootfs.img twice, then runs e2fsck -fn. Against an unmodified copy of the reference:

TerminalReal output
scripts/checkpoint.sh 18exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   virtio_blk_hostile (32 tests), blk_short_read (7 tests), blk_budget (1 tests)[PASS] runs on your Mac disk-vda: 11/11 serial markers, exit 0 in 3.87s[PASS] runs on your Mac disk-lock: 6/6 serial markers, exit 0 in 0.14s[PASS] runs on your Mac disk-rootfs: 11/11 serial markers, exit 0 in 0.91s[INFO] journal          not checked (not a learner tree)CHECKPOINT 18 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The chapter's checkpoint, run against an unmodified copy of the reference laid out as a learner/ workspace (scripts/checkpoint.sh 18 --impl <tree>): what a finished chapter 18 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/18-checkpoint.txt

What now works: every request is checked before the file or guest memory is touched; writes are durable when the guest asks, at the honest price; two VMMs cannot share one image; and Linux boots from an ext4 root on your disk and finds its data after a reboot. This is the course's first milestone, "It persists": an unmodified Linux on a VMM you wrote, with a disk that remembers.

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

What's next

A disk answers when asked. A network card does not get to choose: packets arrive whenever the other side sends them, and the guest may have posted no buffer to put them in. Chapter 19 builds virtio-net, with two queues and a backend that needs no networking entitlement at all.

Open question

The ,ro run never reached our device's read-only check, because Linux saw the RO bit and refused the write itself (Operation not permitted). A driver that ignores the bit will send the OUT anyway. Should the device refuse it with IOERR, or accept it with OK and drop the bytes? Defend your answer from the guest's point of view: what does it believe afterwards? This is journal question 4.

Spec hunt

  • virtio 1.2, section 5.2.6, "Device Operation": where does the specification define when a write is "stable", and what does that mean for a driver that did not accept VIRTIO_BLK_F_FLUSH although the device offered it?
  • virtio 1.2, section 2.7.4, "Message Framing": why may a device not assume that the 16-byte header sits alone in the first descriptor, and which of our parser's choices does that force?
  • man fcntl on your Mac, the entry for F_FULLFSYNC: what does it promise beyond fsync, on which file systems is it implemented, and which drives does the manual say have ignored it?
Progress is stored only in this browser.