Chapter 18 · Part VII
virtio-blk: a root filesystem that persists
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.
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
lengoes 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
lenis 32: the number of bytes the device actually wrote, never the chain's total of 96.From chapter 17: virtio-rng (worked) and virtio-console (faded)
Ten
QueueNotifywrites arrive while the worker thread is busy with a batch. How many times will it callprocess_queuefor that queue afterwards, and why is that safe?Show answer
Between one and ten times; usually once. Each notify only sets the queue's bit in the pending mask, and ten sets of one bit are one bit (notify coalescing). It is safe because a notify carries no data: it says "look at the ring", and one look sees every buffer published before it.
From chapter 17: virtio-rng (worked) and virtio-console (faded)
Your worker's
notifysets the pending bit under the mutex but forgetsnotify_one(). Linux boots, printshw_random=virtio_rng.0, then nothing until--timeout. Who is waiting for whom?Show answer
The guest's driver waits (in WFI, idle) for the used-buffer interrupt; the worker sleeps on the condition variable waiting for a bell that never rings. The pending bit is set but nobody looks at it: a lost wake-up. Host CPU stays near 0%, because everyone is asleep.
From chapter 17: virtio-rng (worked) and virtio-console (faded)
Linux reads 1 MiB from
/dev/hwrngand the trace shows 16,387QueueNotifywrites. Estimate the size of each buffer the driver posts and the number of exits per request.Show answer
1,048,576 / 16,384 = 64 bytes per buffer (the other two or three are the kernel's own reads, which ring even when
ddreads nothing). Each request costs about three exits: the doorbell write, then theInterruptStatusread and theInterruptACKwrite in the driver's interrupt handler. Exits follow buffers posted, not bytes.From chapter 17: virtio-rng (worked) and virtio-console (faded)
Writing 4,096 bytes to the PL011 cost 8,194 extra exits; writing them to
/dev/hvc0in onewritecost 4. At about 1.43 microseconds per exit, how long does each spend in exits alone?Show answer
PL011: 8,194 x 1.43 us, about 11.7 ms (two exits per byte: a flag-register read and a data-register write). virtio-console: 4 x 1.43 us, about 6 us. The ratio, about 2,000, comes from the number of exits, not from faster device code.
From chapter 17: virtio-rng (worked) and virtio-console (faded)
Why does a virtio-console need two queues when the PL011 needed none?
Show answer
The device cannot allocate guest memory; it can only write into buffers the driver posted. Host input arrives unprompted, so receive needs a standing pool of empty writable buffers posted in advance, while transmit buffers are readable and posted only when the guest has text: two queues. A UART instead moves one byte at a time through a register in either direction.
From chapter 17: virtio-rng (worked) and virtio-console (faded)
The console's receive queue has posted buffers but the host has typed nothing. What must one pass of
process_rxdo, and why?Show answer
Pop nothing and return. Popping a chain with no input to put in it would force the device to return it empty (
len0), which the driver would take as a zero-byte read. Host bytes wait in the bounded input queue; when they arrive, the input hook rings the worker's doorbell for queue 0, exactly as a guest notify would.From chapter 17: virtio-rng (worked) and virtio-console (faded)
The transmit path of the console writes guest bytes into the sink. Name two things that must happen between the guest's buffer and your terminal.
Show answer
The bytes are copied once into a fresh, zeroed buffer (so a guest rewriting its buffer cannot change them after the check), and they pass through the sink's output filter, which strips dangerous escape sequences on every sink, a file included. The worker also never calls
write(2)itself; the sink's writer thread does, so a stalled terminal cannot hold the device lock.From chapter 15: Rings and a doorbell: the virtio-mmio transport
On our board, a driver reads the 32-bit word at
0x0a00_0608and gets 0. Which register of which slot is that, what must the driver conclude, and should the device tree have a node at0x0a000600?Show answer
Slots start at
0x0a00_0000and are0x200apart, so0x0a00_0600is slot 3 and offset0x008isDeviceID. 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.From chapter 15: Rings and a doorbell: the virtio-mmio transport
A driver writes
Status= 0, 1, 3, then0xb, and reads back0x3. What happened, and what should the driver do next?Show answer
FEATURES_OKdid not latch: the device refused the accepted feature set, because it contained a bit the device never offered or lackedVIRTIO_F_VERSION_1. The driver must treat the device as unusable (it may set FAILED) rather than carry on.From chapter 15: Rings and a doorbell: the virtio-mmio transport
A driver writes
DriverFeaturesSel= 0,DriverFeatures= 0,DriverFeaturesSel= 1,DriverFeatures= 1. Which feature bits did it accept?Show answer
Only bit 32: the selector picks which 32-bit half of the 64 feature bits a write covers, so value 1 in the high half (selector 1) is bit 32,
VIRTIO_F_VERSION_1, and the low half is empty.From chapter 15: Rings and a doorbell: the virtio-mmio transport
A guest reads 2 bytes at offset
0x000of a populated slot, then 2 bytes at offset0x100of the same slot, whose device has an 8-byte config space. What does each read return?Show answer
The first is a control register, which accepts only aligned 32-bit accesses: it reads as zero, with a rate-limited warning (RAZ/WI). The second is config space, which accepts 1, 2, 4 or 8 bytes inside the device's config length, so it returns the device's first two config bytes.
From chapter 15: Rings and a doorbell: the virtio-mmio transport
Queue 0 is not ready. The driver writes
QueueDescLow=0x10, thenQueueDescHigh=0xffff_ffff. What is the descriptor table's address, and is anything checked yet?Show answer
0xffff_ffff_0000_0010, assembled ashigh << 32 | low. Nothing about it is checked when the halves are written; the transport only records it. It is checked once, atDRIVER_OK, and this one lies far outside RAM, so the device would setDEVICE_NEEDS_RESET.From chapter 15: Rings and a doorbell: the virtio-mmio transport
Linux's 12,093-byte boot log cost 32,795 MMIO exits at the PL011, and one exit costs at least 1.4 µs. Estimate the exits and the time for one 4 KiB block sent the same way.
Show answer
32,795 / 12,093 is about 2.7 exits per byte (one write of the data register, plus reads of the flag register). 4096 × 2.7 is about 11,000 exits, and 11,000 × 1.4 µs is at least 15 ms for one block, before any real work (an MMIO exit costs more than the bare round trip chapter 03 measured).
From chapter 15: Rings and a doorbell: the virtio-mmio transport
After
DRIVER_OK, the driver selects a queue that was never made ready and writesQueueNum= 8 andQueueReady= 1. What does our transport do, and why?Show answer
It ignores both writes with a warning:
DRIVER_OKfreezes every queue register. The rings were validated atDRIVER_OK; a queue configured afterwards would have addresses nobody checked.From chapter 15: Rings and a doorbell: the virtio-mmio transport
The driver sets
DRIVER_OKwhile queue 0's used ring straddles the end of RAM. What does it read fromStatusandInterruptStatus, and what is the interrupt line doing?Show answer
Statusreads0x4f(0xfplusDEVICE_NEEDS_RESET, 64),InterruptStatusreads 2 (configuration change), and the line is high. The device was never activated; it does nothing more until the driver writes 0 toStatus.From chapter 15: Rings and a doorbell: the virtio-mmio transport
InterruptStatusis 3, and the driver writes 1 toInterruptACK. Is the line high or low afterwards?Show answer
Still high: bit 0 is cleared, bit 1 remains, and the line is level-triggered, high exactly while
InterruptStatusis not zero. It drops only when the driver also acknowledges bit 1.From chapter 11: Getting the CPU back: the timer and a bare interrupt
A guest reads
CNTV_CTL_EL0and gets0b101. Is its timer raising its interrupt output right now? What about0b111?Show answer
0b101isENABLE(bit 0) andISTATUS(bit 2) withIMASK(bit 1) clear: enabled, not masked, count reached, so yes, the output is up.0b111hasIMASKset as well: the condition still holds, but the interrupt is masked at the timer, so the output is down.From chapter 11: Getting the CPU back: the timer and a bare interrupt
The counter runs at 24 MHz. A guest wants an alarm 250 ms from now and reads
CNTVCT_EL0 = 1,000,000. What does it write toCNTV_CVAL_EL0?Show answer
250 ms is a quarter of 24,000,000 ticks, 6,000,000 ticks, so it writes 7,000,000. The compare value is an absolute count, not a delay.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A VMM sets the vtimer offset to the host's tick count when the VM boots. Ten minutes later the guest is paused for an hour and then resumed without changing anything. What does the guest's counter show on resume, and what offset would make it continue where it stopped?
Show answer
It jumps forward by an hour of ticks, because
CNTVCT = mach_absolute_time() - offsetand the host kept counting. To resume where it stopped, recompute the offset as the host count now minus the count the guest last saw (restore_offset(now, saved)); then the counter continues fromsaved.From chapter 11: Getting the CPU back: the timer and a bare interrupt
With no interrupt controller, your VMM got a
VTIMER_ACTIVATEDexit. Before the next entry the guest'sCNTV_CTL_EL0still readsENABLE = 1, IMASK = 0, ISTATUS = 1. Do you unmask the vtimer? What do you do instead?Show answer
No: the level line is still high, so an unmasked vtimer would exit again at once, before the guest could handle anything (a real Mac shows millions of VTIMER exits). Keep it masked and set the vCPU's IRQ pending for this run with
hv_vcpu_set_pending_interrupt; unmask only onceCNTV_CTL_EL0shows the timer quiet.From chapter 11: Getting the CPU back: the timer and a bare interrupt
A guest's timer fires while the guest has
PSTATE.Iset and is busy in a loop for another 200 ms. When does its IRQ handler run, and is the interrupt lost meanwhile?Show answer
When the guest clears the mask, about 200 ms later. It is not lost: the timer's output is a level, still high, and the VMM keeps the IRQ pending before every entry, so the interrupt waits as state until the CPU listens.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A WFI exit arrives with the PC at
0x40081188. Where must the PC point when you resume the guest, and is it a bug if you resume at once without sleeping?Show answer
At
0x4008118c: a trappedWFIleaves the PC at the instruction, so the VMM adds 4. Resuming at once is not a bug, becauseWFIis allowed to end early; it only costs a busy host core while the guest is idle.From chapter 11: Getting the CPU back: the timer and a bare interrupt
Your
--statsline readsvtimer 1, wfx 9435272after a 10-second timeout, and the guest printed one interval. What did your VMM most likely forget?Show answer
To unmask the vtimer once the guest silenced it. The framework masks the vtimer at the first VTIMER exit; if it stays masked, no further VTIMER exit comes, the WFI handler finds the deadline already past and wakes at once, and guest and VMM loop on WFI exits.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A tick handled with no interrupt controller costs three exits. Your exit costs 1.43 µs. What host CPU do the exits alone cost at 10 Hz and at 250 Hz, and why was the measured 250 Hz cost (23% of a core) so much higher?
Show answer
30 exits per second is about 43 µs per second (0.004%); 750 per second would be about 1 ms per second (0.1%). The measured cost was the guest's own time: after each tick it re-took the stale pending IRQ for over a millisecond until the kick let the VMM drop the line, because the VMM cannot see the guest finish with the interrupt. That lost time also slowed the guest to about 150 ticks per second.
From chapter 11: Getting the CPU back: the timer and a bare interrupt
A key press is signalled as a short pulse while the CPU has IRQs masked. With no latch, what happens to it? Which PL011 register is the latch?
Show answer
It is lost: an edge is an event, and nobody was listening. The PL011's
RISlatches it (it remembers that a byte arrived until the guest clears it), andMIS,RIScombined with the maskIMSC, turns that memory into a level output.
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,FLUSHandSEG_MAX; bounds checks on every request;IOERRorUNSUPPversus 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-resetand the reset call of PSCI, the Power State Coordination Interface (chapter 08); the test initramfs and itsmacvmm.test=cases (chapter 14); the virtio-mmio transport andDEVICE_NEEDS_RESET(chapter 15); descriptor chains, copy-then-validate and the used length (chapter 16); the worker thread and theVirtioDevicetrait (chapter 17). - Primers (read first):
block-storage(sectors and raw images, ext4,root=, the page cache,fsyncversusF_FULLFSYNC,preadandpwrite, advisory locks, APFS (Apple File System) clones). - Primers (review):
linux-boot-sequence(how the kernel finds its root filesystem, and kernel modules). - Pointers:
man fsyncandF_FULLFSYNCon macOS (shown in the body); APFS clones withcp -c; kernel modules and squashfs (an Aside); Homebrew'se2fsprogs. - 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,FLUSHandSEG_MAX. - Bounds-check every request with checked arithmetic against the capacity, answer
IOERRbefore touching the file, and move data through capped, zeroed bounce buffers. - Back the device with a raw image through
preadandpwrite, lock it against a second VMM, and give FLUSH real durability withFile::sync_all(F_FULLFSYNCon macOS); measure what that costs. - Diagnose an unchecked
sector * 512from a failing hostile test, and explain why a FLUSH that does nothing fails no test. - Boot Linux from an ext4 root on
/dev/vdaand show the data persists across an in-process reboot, with a cleane2fsckafterwards.
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:
cargo xtask mkdisk --size 64M --seed 1 --out learner/disk.imgmkdisk: wrote learner/disk.img (67108864 bytes, seed 1)Then cd learner and note its hash:
shasum -a 256 disk.img4ae50b0ecaa3f91bdcfe84f5a2e20706045ea6f3387c6c45238200cf50ea7859 disk.imgWhat 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:
| Type | Value | Data | Meaning |
|---|---|---|---|
| IN | 0 | writable | read N bytes from byte sector × 512 |
| OUT | 1 | readable | write N bytes at byte sector × 512 |
| FLUSH | 4 | none | make every completed write durable |
| GET_ID | 8 | writable | a 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:
/// 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:
| Offset | Field | Size | Our value |
|---|---|---|---|
| 0 | capacity | le64 | the disk's size in 512-byte sectors |
| 8 | size_max | le32 | 65536, but its feature bit is not offered, so drivers ignore it |
| 12 | seg_max | le32 | 126 |
| 16 | geometry | 4 bytes | zero (not offered) |
| 20 | blk_size | le32 | 512 |
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.
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:
/// 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:
- 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. - 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. - At most 128 descriptors in all (126 data buffers, the header, the status):
IOERRbeyond. A driver that splits the header across two descriptors gets one data buffer fewer. - 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 isIOERR. - No writes to a read-only disk: an OUT on a
,rodisk isIOERR. - 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 × 512andoffset + lengthboth without overflow, and the end at most the capacity. ElseIOERR, 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 nosize_max), so an honest driver tuned for larger requests would also getIOERR; 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:
/// 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:
/// 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:
/// 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:
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:
/// 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:
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 requestIf 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.
/// 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:
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/:
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'ssync), and the features and configuration space above. GET_ID:disk_serial(index)returnsmacvmm-disk<index>, padded with zero bytes to 20, and the device writes min(20, data bytes) of it.crates/vmm/src/backend/file.rs: aBlockBackendtrait (capacity, read-only, read at, write at, sync),read_fullandwrite_full, and aDiskFilethat checks for a regular file, fixes the capacity and takes the lock (its section comes later; the tests here use in-memory disks).- Copy
crates/vmm/tests/virtio_blk_hostile.rs,blk_short_read.rsandblk_budget.rsintolearner/crates/vmm/tests/(chapter 16 already gave youvirtio_support/). Theiruselines name the items they test (such asreq,blk_status,disk_serial,read_full); give yours the same names and paths.
The tests also import these constants. Give yours the same values:
| Constant | Value | Why |
|---|---|---|
BLK_QUEUE_SIZE | 256 | the requestq's size |
SIZE_MAX | 64 KiB | one bounce buffer, the chunk size; its feature bit is not offered |
SEG_MAX | 126 | data buffers per request, QEMU's choice |
BLK_MAX_DATA | SEG_MAX × SIZE_MAX, about 8 MiB | rule 6's cap |
BLK_CHAIN_MAX | 2 × BLK_QUEUE_SIZE × u32::MAX, about 2 TiB | the total cap passed to chapter 16's walk |
BLK_BATCH_BYTES | 2 × BLK_MAX_DATA | a batch of requests ends after this many data bytes, or after one sync |
BLK_CONFIG_LEN | 24 | the 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:
cargo test -q -p vmm --test virtio_blk_hostile --test blk_short_read --test blk_budgetrunning 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.64sblk_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.829333msThe 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):
cargo test -q -p vmm --test virtio_blk_hostilerunning 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.58serror: test failed, to rerun pass `-p vmm --test virtio_blk_hostile`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:
cargo test -q -p vmm --test virtio_blk_hostilerunning 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.58serror: test failed, to rerun pass `-p vmm --test virtio_blk_hostile`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:
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"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-vda: /dev/vda 131072 sectors ro=0macvmm-vda: sha256=4ae50b0ecaa3f91bdcfe84f5a2e20706045ea6f3387c6c45238200cf50ea7859[ 0.349581] reboot: Power downLinux 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:
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"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-vda: /dev/vda 131072 sectors ro=0macvmm-vda: write done[ 0.120153] reboot: Power downxxd -s 8388608 -l 64 disk.img00800000: 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.mNow the same image with ,ro. The device offers RO, and Linux marks the disk read-only (ro=1):
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"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-vda: /dev/vda 131072 sectors ro=1macvmm-vda-ro: write rejected[ 0.099142] reboot: Power downBefore this run, shasum -a 256 disk.img printed 61da37b8…e5ee; after it, the same:
shasum -a 256 disk.img61da37b8b77d7f9d7d8ba1c797f0988c2b02ef36a339e2d321bfa5ce9245e5ee disk.imgBooting the shell on your disk
The test cases run a script and power off. For your own commands, boot the shell case instead:
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:
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"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 downOperation 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.
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"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 downOne 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:
/// 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:
cargo run -q -p macvmm -- run --mem 512M --kernel ../.cache/macvmm/Image-virt --disk disk.img --timeout 10macvmm: disk image is locked: "disk.img" is in use by another process (macvmm takes an advisory flock on every --disk; BLK-8)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:
/// 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:
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).
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"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 downcargo 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"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 downcargo 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"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 downThe 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:
man 2 fsync | col -b | sed -n 18,37p 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.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:
grep -n -B5 -A2 "unsafe fn os_fsync" "$(rustc --print sysroot)/lib/rustlib/src/rust/library/std/src/sys/fs/unix.rs"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- }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:
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 ladderIf 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:
cargo test -q -p vmm --test virtio_blk_hostile --test blk_short_read --test blk_budgetrunning 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.60sblk_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.535417msEvery 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:
(cd .. && cargo xtask mkdisk --size 64M --seed 1 --out learner/disk.img)xxd -s 0x800000 -l 16 disk.img00800000: e17d 14c4 9cf0 b268 b925 1eba e325 2876 .}.....h.%...%(vIn 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):
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=fsyncAs 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:
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"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/ # kill -9 $(lsof -a -c macvmm -t disk.img)xxd -s 0x800000 -l 16 disk.img00800000: 6d61 6376 6d6d 0a6d 6163 766d 6d0a 6d61 macvmm.macvmm.maThe 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:
cargo xtask mkrootfs --out learner/rootfs.img --size 256Mmkrootfs: 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)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.
cp -c rootfs.img root.imgAlpine'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:
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"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 downmacvmm: info: [main] guest reset: rebooting (boot 1)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:
"$(brew --prefix e2fsprogs)/sbin/e2fsck" -fn root.imgPass 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 blockse2fsck 1.47.4 (6-Mar-2025)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.
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.imgmacvmm-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 blocksmacvmm: info: [main] guest reset: rebooting (boot 1)e2fsck 1.47.4 (6-Mar-2025)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:
| Descriptor | Flags | Length | Contents |
|---|---|---|---|
| 0 | readable | 8 | type = 1, reserved = 0 |
| 1 | readable | 520 | sector = 0x0080_0000_0000_0000, then 512 bytes of data |
| 2 | writable | 1 | the 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 MacRun this from the repository root:
scripts/checkpoint.sh 18You should see, as the last line:
CHECKPOINT 18 PASSIt 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:
scripts/checkpoint.sh 18checkpoint: 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 PASSWhat 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_FLUSHalthough 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 fcntlon your Mac, the entry forF_FULLFSYNC: what does it promise beyondfsync, on which file systems is it implemented, and which drives does the manual say have ignored it?