Chapter 16 · Part VII
Split virtqueues: shared memory with an adversary
Course progress: chapter 16 is 17 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 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 04: Guest memory: the only safe access is a copy
A guest asks the VMM to read 8 bytes at address
0xFFFF_FFFF_FFFF_FFFC. Guest RAM is0x4000_0000..0x4400_0000. Computeaddr + lenin 64-bit wrapping arithmetic, and say whether the checkaddr >= 0x4000_0000 && addr + len <= 0x4400_0000accepts the access.Show answer
The true sum is
0x1_0000_0000_0000_0004, which needs 65 bits; wrapped to 64 bits it is0x4. Both halves of the check pass (0xFFFF_FFFF_FFFF_FFFCis above the base,0x4is below the end), so a wrapping check accepts an access that starts 4 bytes below the top of the address space.checked_addreturnsNoneinstead, and the access is refused.From chapter 04: Guest memory: the only safe access is a copy
hv_vm_mapis asked to map 4 KiB of host memory at guest address0x4000_0000, which is 16 KiB-aligned. What does it answer on a Mac with the default configuration?Show answer
HV_BAD_ARGUMENT. The address is fine, but the size must be a whole number of 16 KiB host pages, because HVF's stage-2 table, the one that maps guest memory to ours, uses the Mac's 16 KiB page size by default.From chapter 04: Guest memory: the only safe access is a copy
A guest RAM made of two adjacent regions,
0x4000_0000(64 KiB) and0x4001_0000(64 KiB). Is an 8-byte read at0x4000_FFFCvalid, and why?Show answer
No. The range crosses from the first region into the second. The two regions are separate host allocations that only look contiguous to the guest, so one copy from a single host pointer would run off the end of the first allocation. An access must lie inside one region.
From chapter 04: Guest memory: the only safe access is a copy
Why does the
GuestMemorycontract have noget_slicethat returns a&[u8]into guest RAM?Show answer
A
&[u8]promises the compiler that nobody changes those bytes while the reference lives, and the compiler uses that promise (it may load a byte once and reuse the value, or load it twice and assume both loads agree). The guest, another vCPU or a device thread can change guest RAM at any moment, so the promise would be false. The contract hands out copies instead, and the VMM checks its own copy.From chapter 04: Guest memory: the only safe access is a copy
check_range(GuestAddress(0x4000_0000), 0)on a valid RAM region: true or false, and why does the contract choose that answer?Show answer
False. A zero-length range is never a valid access, so
readandwriterefuse an empty buffer too, andcheck_rangeis true exactly when the matchingreadwould succeed.From chapter 04: Guest memory: the only safe access is a copy
Name two things a volatile load guarantees and two things it does not.
Show answer
It guarantees that the compiler performs the load, at its size, every time the program says so, in program order relative to other volatile accesses, and never assumes the value is unchanged. It does not make an access of several elements atomic, and it gives no ordering or visibility guarantee towards other threads or the guest (that needs atomics and barriers, chapter 16). Volatile does not mean thread-safe.
From chapter 04: Guest memory: the only safe access is a copy
write_u32(GuestAddress(0x4000_0010), 0xdead_beef)succeeds. Which byte doesread_u8(GuestAddress(0x4000_0010))return, and why?Show answer
0xef. The helpers are little-endian, like the guest: the least significant byte of the value goes to the lowest address, so the bytes in memory areef be ad de.From chapter 04: Guest memory: the only safe access is a copy
A region table is given the region
base = 0xFFFF_FFFF_FFFF_C000, size = 0x8000. Both are 16 KiB multiples. Which construction rule rejects it, and what would go wrong without that rule?Show answer
The overflow rule:
base + sizepassesu64::MAX. Without it, the region's end would wrap to0x4000, and a test of the formaddr < endwould place the region's end in low memory, so the table would answer nonsense for addresses near zero.From chapter 04: Guest memory: the only safe access is a copy
Your VMM's bounds check uses
addr + lenwith Rust's default release settings, where overflow is not checked. A guest calls the memory-hash debug call withaddr = 0xFFFF_FFFF_FFFF_FFF0, len = 0x20. What happens, and what changes if overflow checks are on?Show answer
Without overflow checks the sum wraps to
0x10, the range test passes, and the VMM forms a host pointer far outside the RAM allocation: a guest-chosen read of host memory, unless a second check catches it. With overflow checks on, the addition panics, and the guest has crashed the VMM. Both are wrong: onlychecked_add, which turns the overflow into an ordinary error, keeps the VMM running and safe.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
The eight bytes at offset
0x10of an Image header are00 00 2a 02 00 00 00 00, andtext_offsetis 0. Where does the kernel's memory start and end in our plan?Show answer
The field is
image_size, little-endian:0x022a0000. The kernel starts at the 2 MiB-aligned base0x4020_0000plustext_offset0, so it owns0x4020_0000..0x424a_0000(start plusimage_size, end exclusive).From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
That kernel ends at
0x424a_0000. Where does our plan put a 9 MB initramfs, and which part of that choice comes from the boot protocol and which from us?Show answer
At
0x4260_0000, the end rounded up to the next 2 MiB boundary. The protocol only requires that it lie outside the kernel'simage_sizespan and, with the kernel, inside one 1 GiB-aligned window of at most 32 GiB; the 2 MiB rounding is our choice, to keep the numbers readable.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
A
--kernelfile begins with the bytes4d 5aand haszimgat offset 4. What is it, what does our VMM do with it, and what do you run instead?Show answer
An EFI zboot wrapper: a compressed kernel packaged as a UEFI program (the
MZis the PE/COFF signature). The VMM refuses it with "EFI zboot image" and exit code 2 before creating a VM;cargo xtask unzboot(run byscripts/fetch.sh linux) unwraps it on the host into the raw Image.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
An Image's
flagsfield is6. Does our loader accept it?Show answer
No. Bit 0 is 0 (little-endian, fine), but bits 1 and 2 read
0b11= 3, "64 KiB pages", which Apple Silicon does not implement. The loader refuses it with a named error rather than let the kernel die in early boot with no output.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
A header claims
image_size = 0xFFFF_FFFF_FFFF_FFFF. Why doesload + image_size <= ram_endnot catch it, and what does?Show answer
With wrapping arithmetic the sum overflows to a small number (here
0x401F_FFFF), which passes the comparison; in a Rust debug build+panics instead.load.checked_add(image_size)returnsNoneon overflow, and the range check (RamRange::contains) treats that as "outside RAM", so the plan fails with exit code 2.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
An ELF program header of type
PT_LOADsaysp_filesz = 0x100andp_memsz = 0x80. What does the loader do?Show answer
Refuse the file. A segment cannot hold more file bytes than memory:
p_filesz <= p_memszmust hold, and the difference is the zero-filled tail (the BSS). Copyingp_fileszbytes into ap_memszslot would write past the segment.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
List the register values our vCPU starts a Linux kernel with, and the one system-register setting that goes with them.
Show answer
PC = the kernel's first byte (
0x4020_0000),x0= the device tree's address (0x4000_0000),x1,x2andx3= 0,CPSR=0x3c5(EL1h with D, A, I and F masked). The MMU is off:SCTLR_EL1.M(and the cache-enable bits C and I) cleared.From chapter 13: Loading kernels: arm64 Image, initramfs and ELF
macvmm run --dry-run ...printed a full boot plan and exited 0 from a binary that lacks the hypervisor entitlement. What does that prove, and why is it worth designing for?Show answer
That planning makes no Hypervisor.framework call: without the entitlement,
hv_vm_createwould have failed withHV_DENIED. Keeping placement a pure computation means every overlap and bound can be printed, unit-tested and property-tested on any machine, and is checked before a VM exists.
Concepts you'll need
Chapters before this one: chapter 15, Rings and a doorbell: the virtio-mmio transport.
- Core, taught here: the split virtqueue: descriptor table, available ring and used ring, with their sizes and alignment; free-running
u16indices and wrapping subtraction; descriptor chains, indirect descriptors and the readable-before-writable rule; the hop budget; TOCTOU (time of check to time of use) and copy-then-validate;GuestMemoryOrdered, with its two ordered accesses and one full fence;DEVICE_NEEDS_RESETon any queue error; the exactused.len. - Core, from earlier: copy-only guest memory,
read_obj,checked_addandcheck_range(chapter 04); the virtio-mmio transport, its queue registers,QueueNotify,DRIVER_OK,DEVICE_NEEDS_RESET, theVirtioDevicetrait and the inline doorbell path with its budget of N requests per call (chapter 15); the guest as an adversary and bounding work (chapters 03 and 04); property-based testing (chapter 13). - Primers (read first):
memory-ordering(store buffers, acquire and release as a pair, why a store followed by a load needs a full fence, the lost-wakeup race, and the table of pairs between macvmm and the Linux driver). - Primers (review):
host-concurrency(threads, atomics andOrdering). - Pointers: packed rings and
VIRTIO_F_EVENT_IDX(an Aside); rust-vmm'svirtio-queuecrate (a Production note); the virtio 1.2 specification, Linux'svirtio_ring.cand a Xen double-fetch advisory (linked sentences). - Forward definitions: the device worker thread (chapter 17); the virtio-blk request layout (chapter 18); a second guest vCPU writing while we read (chapter 20). Each is defined at first use.
Here are sixteen bytes a guest wrote into its own RAM: a descriptor, the record a virtio driver uses to describe one buffer. Its address is 0x4000_8000, inside RAM. Its length is 8, small and non-zero. Its flags say "another descriptor follows", and its next field says which one: 0. It is descriptor 0. Every field passes every check you could write for a single field. Now your virtual machine monitor (VMM) walks the chain to find the request's buffers.
Predict Walk this descriptor with your chain walker, with its loop guard (the hop budget, below) commented out. Panic, error, or hang?
Write your answer and one sentence of reasoning under ## Predict in your journal. The section on the hop budget shows our run on the reference, and Your turn has you repeat it on your own walker.
This chapter continues row 8 of the problem ledger, bulk I/O at reasonable cost. Chapter 15 built the doorbell and the registers that tell us where the rings are; here we build the rings, and make them safe against a guest that writes them while we read. Sitting A (about 3.5 hours) is the layout and the chain walk; sitting B (about 3 hours) is ordering and the time-of-check bug, with two of the chapter's three deliberate breaks.
Objectives: by the end you can
- (Sitting A) Lay out a split virtqueue (descriptor table, available ring, used ring) with the alignments and sizes of the virtio 1.2 split-ring table, compute each size with
checked_mulandchecked_add, and refuse a ring that is unaligned or not inside one RAM region. - (Sitting A) Explain why there are two rings plus a table (completions can be out of order; each location has one writer) and why the
u16indices are free-running; compute pending entries across the wrap at 65535. - (Sitting A) Implement a descriptor-chain walker that copies each descriptor exactly once with
read_obj, validates only the copy, enforces a hop budget of N,next < N,addr + lenin RAM, readable before writable, indirect-table rules and a total per device, and puts the device intoDEVICE_NEEDS_RESETon any error, never panicking. - (Sitting A) Bound the work in both directions: at most N hops per chain, and at most N chains per call into the device.
- (Sitting B) Use exactly two ordered accesses, an acquire load of
avail.idxand a release store ofused.idx, plus aSeqCstfence before readingavail.flags, and name what each one pairs with in the Linux driver. - (Sitting B) Diagnose a double fetch with a test that rewrites a descriptor after its first read, and predict which tests catch it and which cannot.
Before you start. Run scripts/learner start 16 from the repository root; it copies this chapter's journal to learner/journal/16.md. You are in the spec stage: the lesson shows the reference, and you write the code from the rules, checking it against the tests. Everything here is pure Rust over guest memory, so every test runs on the host. Read the memory-ordering primer before sitting B.
The reference's comments tag each rule with an identifier from macvmm's threat model in docs/security/ (VQ- for virtqueue rules, MEM- for guest-memory rules) or from its design notes in docs/; you can read the code without them. Section signs in the comments point into the virtio 1.2 specification.
Three tables in guest RAM
Chapter 15 left us with three guest addresses (QueueDesc, QueueDriver, QueueDevice), a queue size N, and a doorbell. What must live at those addresses? Work it out from what the two sides need to say.
The driver has to describe buffers: where each one is, how long, and whether the device reads it or writes it. A disk read, for example, needs a small header the device reads ("read sector 2048") and a buffer the device fills. So there is a table of buffer descriptions, the descriptor table: N descriptors of 16 bytes each.
The driver also has to say "these requests are ready, in this order". That list is the available ring, and only the driver writes it. The device has to say "this request is done, and I wrote this many bytes". That is the used ring, and only the device writes it.
Why not one list? Because a disk may finish request 5 before request 2, so completions come back in their own order. And because a location with one writer needs no lock: the driver never writes the used ring and we never write the available ring. Together the three parts are a split virtqueue.
guest RAM (both sides read all three) +-----------------------+ +--------------------------+ +-----------------------------+ | descriptor table | | available ring | | used ring | | N x {addr, len, | | flags, idx, | | flags, idx, | | flags, next} | | ring[N] = head indices | | ring[N] = {id, len} | +-----------------------+ +--------------------------+ +-----------------------------+ written by the driver written by the driver written by the device (us)Each part has exactly one writer. A head is the index of a request's first descriptor. The trust boundary runs through every byte: the guest can change all of it at any time.
The virtio 1.2 specification (section 2.7, "Split Virtqueues") fixes each part's alignment and size:
| Part | Alignment | Size in bytes, queue size N |
|---|---|---|
| descriptor table | 16 | 16 × N |
| available ring | 2 | 6 + 2 × N |
| used ring | 4 | 6 + 8 × N |
The 6 bytes are a 16-bit flags, a 16-bit idx, and a trailing 16-bit field used only by a feature we do not offer. Chapter 15's transport calls validate at DRIVER_OK; here is its full story. Every size is computed with checked arithmetic, and every ring must lie inside one RAM region, so a ring can never overlap device registers or run off the end of RAM:
/// Check the ring placement at DRIVER_OK (§2.7 alignment table): size, alignment,/// and each ring entirely inside one RAM region, all lengths with `checked_*`.pub fn validate(&self, mem: &dyn GuestMemory) -> Result<(), QueueError> { if !self.size_ok(self.size) { return Err(QueueError::BadSize { size: self.size, max: self.max_size, }); } let n = u64::from(self.size); let rings = [ (Ring::Desc, self.desc_table, 16, DESC_SIZE.checked_mul(n)), ( Ring::Avail, self.avail_ring, 2, n.checked_mul(2).and_then(|b| b.checked_add(6)), ), ( Ring::Used, self.used_ring, 4, n.checked_mul(8).and_then(|b| b.checked_add(6)), ), ]; for (ring, addr, align, len) in rings { if !addr.0.is_multiple_of(align) { return Err(QueueError::Unaligned { ring, addr: addr.0 }); } let len = len.ok_or(QueueError::RingOutOfRam { ring, addr: addr.0, len: u64::MAX, })?; // `check_range` computes the end with `checked_add` and demands one region. if !mem.check_range(addr, len) { return Err(QueueError::RingOutOfRam { ring, addr: addr.0, len, }); } } Ok(())}Aside
Virtio 1.1 added a second layout, the packed virtqueue, which merges the three parts into one ring of descriptors to touch fewer cache lines. And the optional VIRTIO_F_EVENT_IDX feature replaces the "no interrupt, please" flag with an index, using the 16-bit fields at the end of each ring. Both are faster and both add parsing a hostile guest can aim at, so macvmm offers neither. The specification describes them in sections 2.8 and 2.7.7 (virtio 1.2).
Indices that never wrap at N
The driver puts the index of each request's first descriptor, its head, into ring[avail.idx % N] and then adds 1 to avail.idx. The device keeps its own counter, next_avail, of how many it has taken. The surprise is that neither counter is reduced modulo N: both count up forever and wrap only at 65536, because they are u16. Each is a free-running index.
Why not keep idx in 0..N? Then a full ring and an empty ring look the same: both sides at the same slot. With free-running counters the difference says it directly, 0 for empty, N for full, with no wasted slot and no extra flag.
Wrapping subtraction gives the right count across the wrap for any N. With N = 8, say next_avail is 0xFFFE and the driver adds 4: avail.idx is now 0x0002, and 0x0002 - 0xFFFE in u16 is 4. The slot, idx % N, also stays in step across the wrap, but only because N divides 65536: the slots are 0xFFFE % 8 = 6, then 7, 0 and 1. With N = 6, slot 65535 % 6 = 3 would be followed by 0 % 6 = 0, skipping two slots. That is why chapter 15 accepted only a power of two as the queue size, as section 2.7 of the specification requires.
Our side keeps its positions in Wrapping<u16>, Rust's integer type whose + and - wrap by design. The block ends with at, the helper behind every ring address: base + head + elem × i (the ring's address, the offset of its array, the entry size, the slot), computed with checked arithmetic and failing with Overflow:
/// One queue: the registers the driver programmed, and our ring positions (module docs).#[derive(Clone, Debug, PartialEq, Eq)]pub struct Queue { max_size: u16, size: u16, ready: bool, desc_table: GuestAddress, avail_ring: GuestAddress, used_ring: GuestAddress, next_avail: Wrapping<u16>, next_used: Wrapping<u16>, indirect: bool, broken: bool,}/// `(offset of ring[i])` helpers: `base + head + elem·i` with `checked_*`.fn at(base: GuestAddress, head: u64, elem: u64, i: u16) -> Result<GuestAddress, QueueError> { elem.checked_mul(u64::from(i)) .and_then(|off| off.checked_add(head)) .and_then(|off| base.checked_add(off)) .ok_or(QueueError::Overflow { addr: base.0, len: u32::from(i), })}Taking the next request is pop. It loads avail.idx once (sitting B explains why that load is special), refuses a jump of more than N, which no honest driver can produce with N slots, copies the head index out of the ring once, and checks it against N:
/// Take the next available chain, if any (§2.7.13.x device side). On `Err`/// the queue is marked broken until the driver resets the device.pub fn pop<'m>( &mut self, mem: &'m dyn GuestMemoryOrdered,) -> Result<Option<DescriptorChain<'m>>, QueueError> { let r = self.pop_inner(mem); // A ring the guest broke latches; asking an unready queue is not the ring's fault. if let Err(e) = &r && !matches!(e, QueueError::NotReady | QueueError::Broken) { self.broken = true; } r}fn pop_inner<'m>( &mut self, mem: &'m dyn GuestMemoryOrdered,) -> Result<Option<DescriptorChain<'m>>, QueueError> { self.check_usable()?; // Acquire: pairs with the driver's write barrier before it bumped avail.idx, so the // entry and descriptor copies below see what it wrote first (module docs). let avail_idx = mem.read_u16_acquire(at(self.avail_ring, 2, 0, 0)?)?; let pending = Wrapping(avail_idx) - self.next_avail; if pending.0 > self.size { // The index jumped by more than the queue holds. return Err(QueueError::AvailIdxJump { avail_idx, next_avail: self.next_avail.0, size: self.size, }); } if pending.0 == 0 { return Ok(None); } // `size` is a power of two (checked), so `& (size - 1)` is `% size` (§2.7.6). let slot = self.next_avail.0 & self.size.wrapping_sub(1); let head = mem.read_obj::<u16>(at(self.avail_ring, 4, 2, slot)?)?; // copied once if head >= self.size { return Err(QueueError::HeadOutOfRange { head, size: self.size, }); } self.next_avail += Wrapping(1); Ok(Some(DescriptorChain::new( mem, self.desc_table, self.size, head, self.indirect, )))}The tests build rings with small helpers from crates/vmm/tests/virtio_support/mod.rs. Ring plays the driver, writing a table and rings into a VecMemory; d(addr, len, flags, next) makes a descriptor; BUF is a buffer address inside RAM. pop_validated is pop followed by into_validated (below) with a byte cap, and K64 is 64 KiB. set_positions starts our counters somewhere other than 0. The wrap test is a positive case, the kind that is easy to forget: with N = 4, both counters start at 65533 and four requests cross the boundary.
#[test]fn avail_and_used_idx_wrap_at_65535() { let mem = mem(); let mut ring = Ring::new(mem.clone(), 4); for i in 0..4 { ring.set_desc(i, d(BUF + 64 * u64::from(i), 16, WRITE, 0)); } ring.set_avail_idx(65533); let mut q = ring.queue(); q.set_positions(65533, 65533); for i in 0..4u16 { ring.push(i); } assert_eq!(ring.avail_idx, 1, "avail.idx wrapped"); let mut heads = Vec::new(); while let Some(v) = pop_validated(&mut q, &mem, K64).unwrap() { heads.push(v.head); q.add_used(&*mem, v.head, 16).unwrap(); } assert_eq!(heads, vec![0, 1, 2, 3]); assert_eq!(q.next_avail(), 1); assert_eq!(ring.used_idx(), 1, "used.idx wrapped: 65533 + 4"); // The used elements sit at slots 65533..65537 mod 4 = 1, 2, 3, 0. assert_eq!(ring.used_elem(1).0, 0); assert_eq!(ring.used_elem(0).0, 3);}Descriptors and chains
Each descriptor is 16 little-endian bytes, copied out in one piece. The flags are named from the device's side: WRITE means the device writes this buffer, otherwise the device only reads it.
/// `VIRTQ_DESC_F_NEXT` (§2.7.5).pub const F_NEXT: u16 = 1;/// `VIRTQ_DESC_F_WRITE`: device-writable (§2.7.5).pub const F_WRITE: u16 = 2;/// `VIRTQ_DESC_F_INDIRECT` (§2.7.5.3).pub const F_INDIRECT: u16 = 4;/// The size of one descriptor in a table (§2.7.5).pub const DESC_SIZE: u64 = 16;/// One descriptor, as copied out of guest memory (the copy is what we validate).#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct Descriptor { pub addr: u64, pub len: u32, pub flags: u16, pub next: u16,}One request is a descriptor chain: the head named in the available ring, then each next while NEXT is set. Every buffer the device reads comes before every buffer it writes, so a device can read the whole request before it writes any reply. A virtio-blk read, which chapter 18 builds, is a 16-byte header (readable), the data buffer (writable) and a one-byte status (writable).
The walker is an iterator that yields Result<Descriptor, QueueError>. Its state is the table being walked, the next index, and a budget:
/// An iterator over one chain's buffer descriptors (indirect tables flattened in place).pub struct DescriptorChain<'m> { mem: &'m dyn GuestMemoryOrdered, head: u16, queue_size: u16, /// The table being walked: the queue's descriptor table, or an indirect table. table: GuestAddress, table_len: u16, next: Option<u16>, /// Hops left in the current table: the budget that ends loops and over-long chains. budget: u16, in_indirect: bool, indirect_allowed: bool, failed: bool,}Reading a descriptor checks the index against the table, computes the address with checked arithmetic, and copies the 16 bytes once with read_obj from chapter 04. From then on, every check and every use reads the local copy:
/// Read descriptor `index` of the current table: once, into a local, so the guest/// cannot change it between our check and our use.fn read_desc(&self, index: u16) -> Result<Descriptor, QueueError> { if index >= self.table_len { return Err(QueueError::NextOutOfRange { next: index, table_len: self.table_len, }); } let addr = DESC_SIZE .checked_mul(u64::from(index)) .and_then(|off| self.table.checked_add(off)) .ok_or(QueueError::Overflow { addr: self.table.0, len: u32::from(index), })?; Ok(self.mem.read_obj::<Descriptor>(addr)?)}One step of the walk is where the rules live. In order: spend one hop of the budget; copy the descriptor; if it points to an indirect table (a second descriptor table for one request, two sections down), switch to it; refuse a zero length; refuse addr + len that overflows; refuse a buffer not entirely inside one RAM region (never MMIO, the memory-mapped I/O addresses where devices live, never straddling the end of RAM); and check next before following it:
/// One step of the walk: the next *buffer* descriptor, or `None` at the end of the chain.fn step(&mut self) -> Result<Option<Descriptor>, QueueError> { loop { let Some(index) = self.next else { return Ok(None); }; // The hop budget catches loops and over-long chains without a visited set. self.budget = self.budget.checked_sub(1).ok_or(QueueError::ChainTooLong { budget: if self.in_indirect { self.table_len } else { self.queue_size }, })?; let d = self.read_desc(index)?; if d.flags & F_INDIRECT != 0 { self.enter_indirect(&d)?; continue; } // On the copy: non-empty, no overflow, entirely in one RAM region. if d.len == 0 { return Err(QueueError::ZeroLength { index }); } let overflow = QueueError::Overflow { addr: d.addr, len: d.len, }; GuestAddress(d.addr) .checked_add(u64::from(d.len)) .ok_or(overflow)?; if !self.mem.check_range(GuestAddress(d.addr), u64::from(d.len)) { return Err(QueueError::BufferOutOfRam { addr: d.addr, len: d.len, }); } self.next = if d.flags & F_NEXT != 0 { if d.next >= self.table_len { return Err(QueueError::NextOutOfRange { next: d.next, table_len: self.table_len, }); } Some(d.next) } else { None }; return Ok(Some(d)); }}The Iterator impl adds one rule: after the first error it yields nothing more, so a broken chain is never half used.
impl Iterator for DescriptorChain<'_> { type Item = Result<Descriptor, QueueError>; fn next(&mut self) -> Option<Self::Item> { if self.failed { return None; } match self.step() { Ok(Some(d)) => Some(Ok(d)), Ok(None) => { self.next = None; None } Err(e) => { self.failed = true; Some(Err(e)) } } }}Finally, into_validated walks the whole chain as one request, splits it by direction, refuses a readable descriptor after a writable one, and caps each direction's total at a limit the device chooses, summed with checked_add:
/// Walk the whole chain and check it as one request: readable descriptors first,/// and each direction's total at most `max_total` bytes.pub fn into_validated(mut self, max_total: u64) -> Result<ValidatedChain, QueueError> { let mut v = ValidatedChain { head: self.head, ..ValidatedChain::default() }; while let Some(d) = self.next().transpose()? { let len = u64::from(d.len); if d.is_write() { v.writable_len = v .writable_len .checked_add(len) .filter(|t| *t <= max_total) .ok_or(QueueError::TooLarge { total: v.writable_len.saturating_add(len), max: max_total, })?; v.writable.push(d); } else { if !v.writable.is_empty() { return Err(QueueError::ReadableAfterWritable); } v.readable_len = v .readable_len .checked_add(len) .filter(|t| *t <= max_total) .ok_or(QueueError::TooLarge { total: v.readable_len.saturating_add(len), max: max_total, })?; v.readable.push(d); } } Ok(v)}In the visualizer, add a request of two or three descriptors and process it, then switch on hostile mode and try a loop in next, an address outside RAM and an index wrap:
Virtqueue visualizer
Play the driver and the device on one split virtqueue: publish requests, ring the doorbell, walk and serve chains, reclaim them, then misbehave as the driver and watch which check refuses each hostile ring.
Runs in browserOpen full page: Virtqueue visualizerIf the lab does not load, here is a sketch of the lab's state for the opening puzzle's queue, with the device's verdict (a drawing, not program output; the real run is in the next section):
DESC [0: addr=0x40008000 len=8 flags=NEXT next=0] [1..7: unused] N = 8AVAIL idx=1 ring=[0] device next_avail=0 -> 1 pending, head 0walk hop 1: desc 0 (budget 8 -> 7) ... hop 8: desc 0 (budget 1 -> 0) hop 9: budget exhausted -> ChainTooLong { budget: 8 } -> DEVICE_NEEDS_RESETThe hop budget
Back to the opening puzzle. How do you stop a walk that loops? The textbook answer is a visited set: remember every descriptor you have seen. But that costs an allocation and bookkeeping on every hop, against loops of whatever shape the guest picks: a self-loop, a 2-cycle, a 5-cycle hidden after three good descriptors.
There is a cheaper fact. A legal chain uses each descriptor at most once, so it can never have more than N of them. A walk that wants hop N + 1 must have revisited something. So we count: a hop budget of N per chain. No allocation, one counter: the work is bounded by N, which chapter 15 capped at QueueNumMax.
Here is the opening puzzle as a test, in crates/vmm/tests/walk_self_loop.rs. It builds the ring with the helpers above (N = 8, descriptor 0 with NEXT set and next = 0, avail.idx = 1), pops the request, and walks it with the bare iterator, counting descriptors:
#[test]fn walk_a_self_loop() { let mem = mem(); // N = 8. Descriptor 0: 8 bytes at 0x4000_8000, NEXT set, next = 0 (itself). let mut ring = Ring::new(mem.clone(), 8); ring.set_desc(0, d(BUF, 8, NEXT, 0)); ring.push(0); // ring[0] = head 0, avail.idx = 1 let mut q = ring.queue(); let chain = q.pop(&*mem).unwrap().expect("one request is pending"); let mut count: u64 = 0; for item in chain { match item { Ok(_) => count += 1, Err(e) => { say(&format!( "walk_a_self_loop: refused after {count} descriptors: {e}" )); return; } } } panic!("the walk ended normally after {count} descriptors");}Run it against the reference, from the repository root:
cargo test -q -p vmm --test walk_self_loop -- --nocapturecargo test -q -p vmm --test walk_self_loop -- --nocapturerunning 1 test.test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00swalk_a_self_loop: refused after 8 descriptors: virtqueue: ChainTooLong { budget: 8 }Deliberate breakage 1: comment out the hop budget. In step, comment out the statement at the top of the loop that subtracts one from self.budget, then run the same test. Check your Predict entry first. You will do this to your own walker in Your turn; here is our run on the reference, stopped after five seconds as Ctrl-C would:
cargo test -q -p vmm --test walk_self_loop -- --nocapturerunning 1 testNo panic, no error, no output: a hang. The test thread spins at full speed reading the same 16 bytes forever. What you saw: one 16-byte write by the guest pins a host thread, with no memory bug anywhere. The misconception it exposes: "if every field is valid, the chain is valid". Validity is also about the shape of the walk. The tool that finds it: a bound on work, here the budget, and tests that build loops on purpose.
The hostile suite's own self_loop case tells a subtler story. It walks through into_validated with a 64 KiB cap, and without the budget it fails differently:
cargo test -q -p vmm --test virtqueue_hostile self_looprunning 1 testself_loop --- FAILEDfailures:---- self_loop stdout ----thread 'self_loop' (121249646) panicked at crates/vmm/tests/virtqueue_hostile.rs:637:5:assertion `left == right` failed: case self_loop: a descriptor whose next is itself left: Err(TooLarge { total: 65544, max: 65536 }) right: Err(ChainTooLong { budget: 8 })note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures: self_looptest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 61 filtered out; finished in 0.00serror: test failed, to rerun pass `-p vmm --test virtqueue_hostile`TooLarge with a total of 65544 bytes, which is 8,193 hops of 8 bytes. The byte cap stopped the walk by accident: 8,193 hops where the budget would have stopped at hop 9, about 900 times more work. It worked only because zero-length descriptors are refused, so each hop adds at least one byte. The virtio-net device of chapter 19 passes no byte cap (it checks frame sizes itself), so for it the budget is the only guard. Keep defences that do not depend on each other.
Indirect descriptors
A request with 64 buffers would fill most of a small ring. With VIRTIO_F_INDIRECT_DESC negotiated, one descriptor with the INDIRECT flag can point at a separate table of descriptors in guest RAM, and the whole request takes one ring slot. An indirect descriptor is another table the guest controls, so it gets the same treatment and a few rules of its own: only if negotiated, never nested, never combined with NEXT, a length that is a whole number of descriptors and at most N of them, the table inside RAM, and a fresh hop budget of len / 16, the table's own size:
/// Switch the walk to the indirect table `d` describes (§2.7.5.3). The referring/// descriptor's `F_WRITE` is ignored, as §2.7.5.3.2 requires of the device.fn enter_indirect(&mut self, d: &Descriptor) -> Result<(), QueueError> { if !self.indirect_allowed { return Err(QueueError::IndirectNotNegotiated); } if self.in_indirect { return Err(QueueError::NestedIndirect); } if d.flags & F_NEXT != 0 { return Err(QueueError::IndirectWithNext); } let entries = u64::from(d.len) / DESC_SIZE; if d.len == 0 || !u64::from(d.len).is_multiple_of(DESC_SIZE) || entries > u64::from(self.queue_size) { return Err(QueueError::BadIndirectLen { len: d.len }); } let entries = u16::try_from(entries).map_err(|_| QueueError::BadIndirectLen { len: d.len })?; GuestAddress(d.addr) .checked_add(u64::from(d.len)) .ok_or(QueueError::Overflow { addr: d.addr, len: d.len, })?; if !self.mem.check_range(GuestAddress(d.addr), u64::from(d.len)) { return Err(QueueError::BufferOutOfRam { addr: d.addr, len: d.len, }); } self.table = GuestAddress(d.addr); self.table_len = entries; self.next = Some(0); self.budget = entries; // the hop budget restarts at len / 16, the table's entries self.in_indirect = true; Ok(())}When the guest breaks the rules
Every refusal so far is a QueueError. Almost every variant is something the guest did; the last two, Broken and NotReady, are bookkeeping states (the queue already failed, or was never set up):
/// Why a ring or a descriptor chain was refused (`docs/security/threat-model.md`/// lists each rule)./// Every variant is something the *guest* did; the transport answers each with/// DEVICE_NEEDS_RESET.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum QueueError { /// The queue size is 0, above its maximum, or not a power of two (§2.7). BadSize { size: u16, max: u16 }, /// A ring address is not aligned as §2.7 requires (16 / 2 / 4). Unaligned { ring: Ring, addr: u64 }, /// A ring does not fit in one RAM region, or its end overflows. RingOutOfRam { ring: Ring, addr: u64, len: u64 }, /// `avail.idx` moved by more than the queue size since we last looked. AvailIdxJump { avail_idx: u16, next_avail: u16, size: u16, }, /// An avail-ring entry names a descriptor `≥ N`. HeadOutOfRange { head: u16, size: u16 }, /// A descriptor's `next` is outside its table. NextOutOfRange { next: u16, table_len: u16 }, /// `addr + len` overflows. Overflow { addr: u64, len: u32 }, /// A buffer is not entirely inside one RAM region: outside RAM, in MMIO, or straddling /// the end of RAM. BufferOutOfRam { addr: u64, len: u32 }, /// A zero-length descriptor. ZeroLength { index: u16 }, /// More descriptors than the hop budget (`N`, or `len / 16` inside an indirect table): /// a loop or an over-long chain. ChainTooLong { budget: u16 }, /// `F_INDIRECT` without the feature negotiated. IndirectNotNegotiated, /// `F_INDIRECT` inside an indirect table (§2.7.5.3.1). NestedIndirect, /// `F_INDIRECT` together with `F_NEXT` (§2.7.5.3.1). IndirectWithNext, /// An indirect table length that is 0, not a multiple of 16, or more than `N` entries. BadIndirectLen { len: u32 }, /// A device-readable descriptor after a device-writable one (§2.7.4.2). ReadableAfterWritable, /// The chain's readable or writable total exceeds the device's `max_total`. TooLarge { total: u64, max: u64 }, /// A guest-memory access failed on a ring itself (cannot happen after `validate` unless /// memory changed shape; kept total, never a panic). Memory(MemoryError), /// The queue already failed and the driver has not reset the device. Broken, /// The queue is not ready or has no size (a driver bug or a device bug). NotReady,}What do we do with one? Not panic, and not stop the virtual machine: a guest that hands us a bad chain has hurt only its own device. For an error in the ring itself, such as a jump in avail.idx or a head out of range, pop also latches the queue broken. For any error, in the ring or in a chain, the device's process_queue returns it, and chapter 15's inline path hands it to report_error, which sets DEVICE_NEEDS_RESET and raises a configuration interrupt. From then on the transport ignores the doorbell until the driver writes 0 to Status.
Work is bounded in the other direction too. As chapter 15 showed, the inline path gives each process_queue call a budget of at most N chains and makes at most four such calls per doorbell, so one doorbell can never keep us busy for as long as the guest likes. From chapter 17, the device worker thread gives each call the same budget.
Security
The descriptor table, both rings and every buffer are guest memory, and the guest can rewrite any byte of them at any moment, including while we walk them. The walker is the one place where guest descriptors become buffers our device will touch, so every check lives there, on the copy, for every device at once. A device model receives a ValidatedChain and never parses a ring.
The suite in crates/vmm/tests/virtqueue_hostile.rs builds each hostile shape on purpose (loops, out-of-range indices, len = u32::MAX, buffers in MMIO, every indirect abuse, unaligned rings), and each must return a named error, never panic. One more test, queue_pop_model, generates 10,000 random rings from a fixed seed and compares our walker's verdict on each with a second, deliberately plain implementation of the same rules: chapter 13's property-based testing, turned into a comparison of two implementations.
Good place to stop. Sitting B needs the memory-ordering primer and about 3 hours.
Two CPUs, one ring, no lock
The driver runs on a guest virtual CPU (vCPU). Our walker runs on a host thread: today the vCPU thread that took the QueueNotify exit, while that vCPU waits, and from chapter 17 a device worker thread, the host thread that owns a device and processes its queues while the vCPUs keep running. From then on two CPUs share the ring with no lock, on a weakly ordered machine: as the memory-ordering primer showed, another core may see our writes in a different order from the one we made them in.
The primer also showed that one ordered index can protect a whole ring of plain copies. The split ring needs exactly two:
- an acquire load of
avail.idx, so that the head index, descriptors and buffers we copy afterwards are what the driver wrote before it published the index; - a release store of
used.idx, so that the used element and every byte we wrote into the guest's buffers are visible before the driver can see the new index.
Those two accessors, plus the fence you meet below, are the whole of GuestMemoryOrdered. It has been in your copied memory/mod.rs since chapter 04; this is its explanation. It is a separate trait on top of chapter 04's contract, so that contract stays minimal and everything else in the ring stays a plain copy:
/// The two ordered accessors of the split virtqueue (virtio 1.2 §2.7.13: the driver publishes/// `avail.idx` after the ring entries, the device publishes `used.idx` after the used/// elements). Frozen from chapter 16 on.pub trait GuestMemoryOrdered: GuestMemory { /// Acquire-ordered 16-bit LE load (`avail.idx`). `addr` must be 2-aligned: reads that /// follow it see everything the guest wrote before publishing the index. fn read_u16_acquire(&self, addr: GuestAddress) -> Result<u16, MemoryError>; /// Release-ordered 16-bit LE store (`used.idx`). `addr` must be 2-aligned: every write /// before it is visible to the guest once it sees the new index. fn write_u16_release(&self, addr: GuestAddress, val: u16) -> Result<(), MemoryError>; /// A full (`SeqCst`) fence between our `used.idx` release store and our later load of /// `avail.flags`. Release/acquire cannot order a /// store before a later load; only a full barrier can, and without it the device may read a /// stale `NO_INTERRUPT` after the driver re-enabled interrupts and went to sleep (the /// lost-wakeup race; Linux's `virtio_mb()` in `virtqueue_enable_cb` is the other half). /// /// It is a method (with this default) rather than a bare `fence` call in `virtio/queue.rs` /// so that the `VecMemory` access log can record *where* the fence sits relative to the /// accesses around it: the `used_idx_release_order` test asserts the order. Implementations /// other than test doubles keep the default. fn fence_seq_cst(&self) { core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst); }}On real guest RAM, each accessor is one atomic 16-bit access:
impl GuestMemoryOrdered for GuestRam { fn read_u16_acquire(&self, addr: GuestAddress) -> core::result::Result<u16, MemoryError> { check_aligned_u16(addr)?; let p = self.host_ptr(addr, 2)?; // SAFETY: `p` is inside a live block (checked) and 2-aligned (the IPA is // 2-aligned and blocks are page-aligned, so the host address is too). `AtomicU16` has // the size and alignment of `u16`. The guest is not Rust: its accesses, including // mixed-size ones, are outside the Rust memory model, and we only ever use the value we // loaded, which callers validate. The `&AtomicU16` lives for this one load. let v = unsafe { AtomicU16::from_ptr(p.cast::<u16>()) }.load(Ordering::Acquire); Ok(u16::from_le(v)) } fn write_u16_release( &self, addr: GuestAddress, val: u16, ) -> core::result::Result<(), MemoryError> { check_aligned_u16(addr)?; let p = self.host_ptr(addr, 2)?; // SAFETY: as in `read_u16_acquire`; the store publishes the VMM's earlier // writes (the used ring elements) to the guest. unsafe { AtomicU16::from_ptr(p.cast::<u16>()) }.store(val.to_le(), Ordering::Release); Ok(()) }}Under the hood
AtomicU16::from_ptr makes an atomic out of a pointer into guest RAM for the length of one access. Rust's memory model only describes Rust code; the guest is a C kernel on another core. As the primer argued, the pairing is made in Arm terms instead: our LDAPRH (a load-acquire, in Arm's slightly weaker RCpc, release-consistent processor-consistent, form) and STLRH (store-release) against the guest's DMB (data memory barrier) instructions, on coherent memory. Neither orders our store before a later load, which is why the third operation below is a separate fence.
Writing a completion uses the release store. The element {id, len} is one 8-byte copy, then the index:
/// Return chain `head` to the driver with `written` bytes produced (§2.7.8).////// `written` MUST be the number of bytes the device actually wrote into the chain's/// writable buffers, never the requested or the available length: the driver trusts it/// (a too-large `len` makes the guest read stale bytes, or previous requests' data). The/// element `{id, len}` is one 8-byte copy; then `used.idx` is published with a **release**/// store, which orders the element (and every buffer write before it) before the index.pub fn add_used( &mut self, mem: &dyn GuestMemoryOrdered, head: u16, written: u32,) -> Result<(), QueueError> { self.check_usable()?; if head >= self.size { return Err(QueueError::HeadOutOfRange { head, size: self.size, }); } let slot = self.next_used.0 & self.size.wrapping_sub(1); let mut elem = [0u8; 8]; let (id, len) = elem.split_at_mut(4); id.copy_from_slice(&u32::from(head).to_le_bytes()); len.copy_from_slice(&written.to_le_bytes()); mem.write(at(self.used_ring, 4, 8, slot)?, &elem)?; self.next_used += Wrapping(1); // Release: pairs with the driver's read barrier after loading used.idx. mem.write_u16_release(at(self.used_ring, 2, 0, 0)?, self.next_used.0)?; Ok(())}len must be the number of bytes the device actually wrote, never the buffer's size. The driver trusts it: report 200 for a 150-byte answer and the guest takes 50 bytes of whatever was in that memory as data. The specification forbids over-reporting and allows under-reporting (section 2.7.8 and its device requirements); we report the exact count. A device writes its reply with ValidatedChain::write_writable, which fills the writable buffers in order and returns that count, ready for add_used:
/// Copy `data` into the writable buffers in order, and return how many bytes were written:/// the value `add_used` must report (never the requested length). Stops at the end of/// `data` or of the buffers. Buffers were range-checked during the walk; a failing write/// (memory changed shape) is an `Err`, never a panic.pub fn write_writable( &self, mem: &dyn GuestMemoryOrdered, data: &[u8],) -> Result<u32, QueueError> { let mut done: usize = 0; for d in &self.writable { let Some(rest) = data.get(done..) else { break }; if rest.is_empty() { break; } let n = rest.len().min(usize::try_from(d.len).unwrap_or(usize::MAX)); let chunk = rest.get(..n).unwrap_or_default(); mem.write(GuestAddress(d.addr), chunk)?; done = done.saturating_add(n); } u32::try_from(done).map_err(|_| QueueError::TooLarge { total: u64::try_from(done).unwrap_or(u64::MAX), max: u64::from(u32::MAX), })}The third ordered operation is the one the primer built its opening puzzle around. After publishing used.idx, we read avail.flags to see whether the driver wants an interrupt: a store followed by a load to a different address, which release and acquire do not order. The driver does the mirror image, and if both loads see old values we stay silent while the driver sleeps on a finished request: the lost wakeup. A fence(SeqCst) on our side pairs with Linux's virtio_mb() on theirs:
/// After `add_used`: does the driver want a used-buffer interrupt (§2.7.7)? It does unless/// `avail.flags` has `NO_INTERRUPT` (a hint: the driver may still poll).////// **The full fence.** Our `used.idx` store and our/// `avail.flags` load are a store followed by a load to *different* addresses; release and/// acquire do not order those, so the CPU may perform the load first. Meanwhile the driver/// does the mirror image in `virtqueue_enable_cb`: clear NO_INTERRUPT, `virtio_mb()`, re-read/// `used.idx`, sleep if nothing new. Without a fence on our side both can read the other's/// stale value: we see NO_INTERRUPT still set and stay silent, the driver sees the old/// `used.idx` and sleeps: a lost wakeup and a hung guest. The `SeqCst` fence here pairs/// with the driver's `virtio_mb()`, so at least one of us sees the other's write.pub fn should_interrupt(&self, mem: &dyn GuestMemoryOrdered) -> Result<bool, QueueError> { mem.fence_seq_cst(); let flags = mem.read_obj::<u16>(self.avail_ring)?; Ok(flags & AVAIL_F_NO_INTERRUPT == 0)}| macvmm (device) | pairs with, in Linux's virtio_ring.c | protects |
|---|---|---|
acquire load of avail.idx | virtio_wmb() before the driver stores avail.idx | the request the driver wrote |
release store of used.idx | virtio_rmb() after the driver loads used.idx | the used element and the data we wrote |
fence(SeqCst) before loading avail.flags | virtio_mb() between clearing NO_INTERRUPT and re-reading used.idx | no lost wakeup |
How do you test an ordering? Not by racing threads on this Mac and hoping. VecMemory, the test double from chapter 04, logs every access with its address, length, direction, whether it was ordered, and every fence. The test then checks the order structurally:
#[test]fn used_idx_release_order() { let mem = mem(); let mut ring = Ring::new(mem.clone(), 8); ring.set_desc(0, d(BUF, 8, WRITE, 0)); ring.push(0); let mut q = ring.queue(); mem.enable_log(); let v = pop_validated(&mut q, &mem, K64).unwrap().unwrap(); q.add_used(&*mem, v.head, 8).unwrap(); assert!(q.should_interrupt(&*mem).unwrap()); let log = mem.log(); // pop: an acquire load of avail.idx comes first, before the ring entry and descriptor. assert!( log[0].ordered && !log[0].write && log[0].addr == AVAIL + 2, "{log:?}" ); let elem = log .iter() .position(|a| a.write && !a.ordered && a.addr == USED + 4 && a.len == 8) .expect("used element written as one 8-byte copy"); let idx = log .iter() .position(|a| a.write && a.ordered && a.addr == USED + 2 && a.len == 2) .expect("release store of used.idx"); let fence = log.iter().position(|a| a.fence).expect("SeqCst fence"); let flags = log .iter() .position(|a| !a.write && !a.fence && a.addr == AVAIL && a.len == 2) .expect("avail.flags read"); assert!(elem < idx && idx < fence && fence < flags, "{log:?}");}Deliberate breakage 2 (watch, do not run: it needs chapter 17's virtio-rng device): drop the release. In add_used, replace write_u16_release with a plain write_u16. We ran Linux's own virtio-rng driver against a build with this change; it reads 1 MiB of random numbers through the queue, and chapter 17 builds the device.
Predict Will a real Linux guest notice the missing release?
Commit to yes or no in your journal (question 4 asks about this run), then compare with the two runs below.
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --rng --on-reset exit --timeout 60 --cmdline 'console=ttyAMA0 quiet panic=-1 macvmm.test=rng'macvmm-initramfs: ready 6.18.60-0-virtmacvmm-rng: hw_random=virtio_rng.0macvmm-rng: read 1048576 bytes ok[ 0.440517] reboot: Power downCheck your prediction: it worked. Only the access log notices:
cargo test -q -p vmm --test virtqueue_hostile used_idx_release_orderrunning 1 testused_idx_release_order --- FAILEDfailures:---- used_idx_release_order stdout ----thread 'used_idx_release_order' (122923408) panicked at crates/vmm/tests/virtqueue_hostile.rs:827:10:release store of used.idxnote: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures: used_idx_release_ordertest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 61 filtered out; finished in 0.00serror: test failed, to rerun pass `-p vmm --test virtqueue_hostile`What you saw: a guest that ran correctly on a broken queue. The misconception it exposes: "it works, so the ordering is right". We can explain this bug, but we cannot make it happen on demand: the window is narrow, and an x86 PC never reorders two stores in hardware, so there this bug cannot happen at all. The tool that finds it: the rules plus a structural check. The primer's litmus program runs this bug's shape between two threads (its mp test), and on this Mac it also counts zero reordered outcomes for the broken version: the bug is real, but it rarely or never shows up.
Litmus
Step two threads through a machine with visible store buffers, list every outcome arm64, x86-64 and the paper model allow, and tell a lucky zero from a guaranteed one.
Runs in browserOpen full page: LitmusThe guest writes while we read
Here is a bug that passes every test of sitting A. A device validates a descriptor, then, when it needs the length again, reads len from guest memory a second time. On still memory both reads agree. But a guest can have a second vCPU (chapter 20 gives it one) or write while our worker thread walks (chapter 17). It sets len = 16, waits until our check passes, and sets len to a value that runs past the end of RAM. We checked one value and used another.
That is a TOCTOU bug, time of check to time of use: the name chapter 04 parked for this chapter, and whose register-level twin you met in chapter 15 when the queue registers froze at DRIVER_OK. Reading the same guest value twice like this is a double fetch. It is a real attack class: Xen security advisory XSA-155 (2015) fixed double fetches in Xen's paravirtualized back-end drivers, which share rings with their guests much as virtio does.
The defence is the rule you have been following all chapter: copy-then-validate. Copy each descriptor once, check the copy, use only the copy. A later rewrite changes guest memory, never our copy.
To test it, the guest has to change memory at the worst moment, every time. VecMemory has a mutation hook for that: after a chosen number of reads, it overwrites some bytes, as a racing vCPU would.
/// After `after_reads` successful reads, write `bytes` at `addr` (once).#[derive(Clone, Debug)]pub struct Mutation { pub after_reads: usize, pub addr: GuestAddress, pub bytes: Vec<u8>,}The first test in virtqueue_toctou.rs rewrites descriptor 0 right after our first read of it, turning it into a huge buffer inside MMIO whose next points back at itself. The walker must act on its first copy, and the log must show each descriptor read exactly once:
#[test]fn descriptor_rewritten_after_its_first_read() { let mem = mem(); let mut ring = Ring::new(mem.clone(), 8); ring.set_desc(0, d(BUF, 16, NEXT, 1)); ring.set_desc(1, d(BUF + 0x100, 64, WRITE, 0)); ring.push(0); // Right after descriptor 0 is copied: point it at MMIO, make it huge, loop it. let evil = d(MMIO_ADDR, u32::MAX, NEXT | WRITE, 0); mem.mutate_after(Mutation { after_reads: READS_BEFORE_HEAD + 1, addr: GuestAddress(desc_addr(0)), bytes: evil.to_le_bytes().to_vec(), }); mem.enable_log(); let mut q = ring.queue(); let v = pop_validated(&mut q, &mem, K64).unwrap().unwrap(); assert_eq!( v.readable, vec![d(BUF, 16, NEXT, 1)], "the first copy is used" ); assert_eq!(v.writable_len, 64); let log = mem.log(); assert_eq!(reads_of(&log, desc_addr(0), 16), 1, "{log:?}"); assert_eq!(reads_of(&log, desc_addr(1), 16), 1, "{log:?}");}The same file also races for real. A second thread flips len between 16 and 1 MiB (past the end of the test's RAM) for one second, while three walkers take turns, a third of a second each: a hand-written walker with a deliberate double fetch; the real walker with a device on top that re-reads len from guest memory after receiving the validated chain; and the real walker alone. In the reference run shown at the checkpoint, the hand-written walker was caught handing out an out-of-RAM buffer 15,934 times in 291,639 walks.
The re-reading device was caught 4,730 times: a correct walker cannot protect a device that goes back to guest memory, so copy-then-validate binds device code too. The real walker was never caught. Of its walks, 62,925 read len = 16 and accepted it, and 75,572 read the 1 MiB value on their single read and correctly refused it with BufferOutOfRam.
Deliberate breakage 3: re-read len after validation. At the end of step, instead of returning the copy d, return it with len replaced by a fresh read_u32 of the descriptor's len field (table + 16 × index + 8).
Predict How many of the 62 hostile-ring tests fail, and how many of the 9 TOCTOU tests?
Write your two numbers in your journal (question 3 asks about this run) before you look at ours.
cargo test -q -p vmm --test virtqueue_hostile --test virtqueue_toctourunning 62 tests..............................................................test result: ok. 62 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.76srunning 9 tests..... 5/9descriptor_rewritten_after_its_first_read --- FAILEDindirect_table_rewritten_after_the_first_read --- FAILEDnext_rewritten_into_a_loop_after_the_read_changes_nothing --- FAILEDracing_len_flip_catches_a_double_fetch_but_not_the_real_walker --- FAILEDfailures:---- descriptor_rewritten_after_its_first_read stdout ----thread 'descriptor_rewritten_after_its_first_read' (123030304) panicked at crates/vmm/tests/virtqueue_toctou.rs:62:46:called `Result::unwrap()` on an `Err` value: TooLarge { total: 4294967295, max: 65536 }note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace---- indirect_table_rewritten_after_the_first_read stdout ----thread 'indirect_table_rewritten_after_the_first_read' (123030305) panicked at crates/vmm/tests/virtqueue_toctou.rs:183:46:called `Result::unwrap()` on an `Err` value: TooLarge { total: 4294967295, max: 65536 }---- next_rewritten_into_a_loop_after_the_read_changes_nothing stdout ----thread 'next_rewritten_into_a_loop_after_the_read_changes_nothing' (123030306) panicked at crates/vmm/tests/virtqueue_toctou.rs:88:46:called `Result::unwrap()` on an `Err` value: ChainTooLong { budget: 8 }---- racing_len_flip_catches_a_double_fetch_but_not_the_real_walker stdout ----thread 'racing_len_flip_catches_a_double_fetch_but_not_the_real_walker' (123030307) panicked at crates/vmm/tests/virtqueue_toctou.rs:360:17:assertion `left == right` failed: the real walker accepted a descriptor it never validated left: [Descriptor { addr: 1073774592, len: 1048576, flags: 2, next: 0 }] right: [Descriptor { addr: 1073774592, len: 16, flags: 2, next: 0 }]failures: descriptor_rewritten_after_its_first_read indirect_table_rewritten_after_the_first_read next_rewritten_into_a_loop_after_the_read_changes_nothing racing_len_flip_catches_a_double_fetch_but_not_the_real_walkertest result: FAILED. 5 passed; 4 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.67squeue_pop_model: seed 1495053, 10000 rings: {"AvailIdxJump": 1004, "BadIndirectLen": 250, "BufferOutOfRam": 1718, "ChainTooLong": 148, "HeadOutOfRange": 694, "IndirectNotNegotiated": 556, "IndirectWithNext": 292, "NestedIndirect": 2, "NextOutOfRange": 357, "Overflow": 473, "ReadableAfterWritable": 53, "TooLarge": 510, "ZeroLength": 908, "empty": 2153, "ok": 882}error: test failed, to rerun pass `-p vmm --test virtqueue_toctou`Check your prediction. All 62 hostile tests pass: their memory never changes after setup, so the second read agrees with the first. Four TOCTOU tests fail. In two, the walker used the rewritten len = u32::MAX, and only the 64 KiB cap refused it. In the race, the real walker handed out len: 1048576, a buffer running past the end of RAM.
The ChainTooLong failure is subtler. The mutation hook fires after a fixed number of reads, and our extra read counted as one, so the rewrite that turns descriptor 1 into a loop landed before the walker copied descriptor 1 instead of after. The walker then followed the rewritten next until the budget stopped it. In some runs the race fails earlier, on its access-log sample, which found a lone 4-byte read of len: the double fetch itself.
cargo test -q -p vmm --test virtqueue_toctou racing_len_fliprunning 1 testracing_len_flip_catches_a_double_fetch_but_not_the_real_walker --- FAILEDfailures:---- racing_len_flip_catches_a_double_fetch_but_not_the_real_walker stdout ----thread 'racing_len_flip_catches_a_double_fetch_but_not_the_real_walker' (123032292) panicked at crates/vmm/tests/virtqueue_toctou.rs:384:13:assertion `left == right` failed: len is never re-read on its own left: 1 right: 0note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures: racing_len_flip_catches_a_double_fetch_but_not_the_real_walkertest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 8 filtered out; finished in 0.67serror: test failed, to rerun pass `-p vmm --test virtqueue_toctou`What you saw: a bug invisible to every test on still memory. The misconception it exposes: "validating a descriptor once makes it safe" (only if you use the copy you validated). The tool that finds it: the mutation hook and the access log, which make the guest strike at the worst moment and count the reads.
Production note
rust-vmm's virtio-queue crate, used by Cloud Hypervisor among others, walks chains the same way: descriptors copied out once, and a hop counter it calls a TTL (time to live) instead of a visited set.
Your turn
In learner/crates/vmm/src/virtio/, extend your chapter 15 queue.rs (the alignment checks in validate, then pop, add_used, should_interrupt and set_positions) and write chain.rs (Descriptor, the walker, into_validated and ValidatedChain::write_writable). GuestMemoryOrdered, and VecMemory's access log and mutation hook, have been in your copy since chapter 04; read them now against the explanations above.
The tests you copy compile only against the names they import. The shared helpers import these:
use std::sync::{Arc, Mutex};use vmm::memory::prelude::*;use vmm::memory::{Access, VecMemory};use vmm::virtio::chain::{F_INDIRECT, F_NEXT, F_WRITE};use vmm::virtio::{ Descriptor, Queue, QueueError, QueueProgress, ValidatedChain, VirtioDevice, VirtioError, VirtioInterrupt, features,};The TOCTOU suite also drives chapter 15's transport, so it imports VirtioMmio and the test interrupt line:
use vmm::bus::{AccessSize, MmioDevice};use vmm::irq::TestIrq;use vmm::memory::Mutation;use vmm::memory::prelude::*;use vmm::virtio::mmio::reg;use vmm::virtio::{Descriptor, QueueError, VirtioInterrupt, VirtioMmio};Beyond those names, the suites call: on Queue, new, set_size, set_desc_table, set_avail_ring, set_used_ring, set_ready, set_indirect, set_positions(next_avail, next_used), next_avail, validate, pop, add_used(mem, head, written), should_interrupt and is_broken; on the chain pop returns, iteration and into_validated(max_total); on ValidatedChain, the public fields head, readable, writable, readable_len and writable_len, and write_writable(mem, data); on Descriptor, to_le_bytes, and copying one out with read_obj (so it implements chapter 04's FromLeBytes); and every QueueError variant shown above, compared by value. Then:
- Copy
crates/vmm/tests/virtqueue_hostile.rs,virtqueue_toctou.rs,walk_self_loop.rs, thevirtio_support/directory anddata/virtqueue_vectors.jsonintolearner/crates/vmm/tests/, and from insidelearner/runcargo test -q -p vmm --test virtqueue_hostile --test virtqueue_toctou. - From inside
learner/, runcargo test -q -p vmm --test walk_self_loop -- --nocapture. Then comment out your hop budget, run it again (stop it with Ctrl-C), restore the budget, and finish your Predict entry.
Stuck? scripts/learner hint 16 gives four hints, from a nudge to the exact reference file.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 16You should see, as the last line:
CHECKPOINT 16 PASSIt runs the two suites from step 1 against the code in learner/: the hostile ring (every shape listed above, the wrap at 65535, the exact used.len, the ordering check in the access log and the 10,000-ring comparison) and the TOCTOU tests (the mutation hook and the one-second race). Then it checks that your journal answers every question. There is no run on a guest yet: the queue's first guest run is chapter 17's virtio-rng device. Against the reference it looks like this:
scripts/checkpoint.sh 16[PASS] contract tests virtqueue_hostile (62 tests), virtqueue_toctou (9 tests)[INFO] runs on your Mac none for this chapter[INFO] journal not checked (not a learner tree)CHECKPOINT 16 PASSThe checkpoint keeps the suites' own notes to itself. Your step 1 run prints them on stderr; here they are from the same command run on the reference, from the repository root:
cargo test -q -p vmm --test virtqueue_hostile --test virtqueue_toctourunning 62 tests..............................................................test result: ok. 62 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.36srunning 9 tests.........test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.00squeue_pop_model: seed 1495053, 10000 rings: {"AvailIdxJump": 1004, "BadIndirectLen": 250, "BufferOutOfRam": 1718, "ChainTooLong": 148, "HeadOutOfRange": 694, "IndirectNotNegotiated": 556, "IndirectWithNext": 292, "NestedIndirect": 2, "NextOutOfRange": 357, "Overflow": 473, "ReadableAfterWritable": 53, "TooLarge": 510, "ZeroLength": 908, "empty": 2153, "ok": 882}racing_len_flip: double-fetch walker caught 15934/291639; re-reading device on the real walker caught 4730/124254; real walker 62925 ok + 75572 refused of 138497 (8656 log-sampled)Your counts on the racing_len_flip line will differ from run to run; the queue_pop_model line will not, because its seed is fixed.
What now works:
- your VMM finds three rings in guest RAM, checks their alignment and placement, and serves requests across the index wrap;
- it walks descriptor chains, direct and indirect, refusing every hostile shape with a named error and putting the device into
DEVICE_NEEDS_RESET, never panicking or hanging; - it reads each descriptor once and never trusts guest memory after a check;
- it publishes completions with a release store, an exact
used.lenand a full fence before deciding on an interrupt.
The next chapter starts from this state (the reference at the end of chapter 16).
What's next
Chapter 17 puts a real device behind the queue: virtio-rng, on its own worker thread, woken by the doorbell. Then you will measure what a queue buys: how many exits it takes to move 4 KiB through a virtio console compared with the PL011, which costs at least one exit for every byte.
Open question
A virtio-blk request is normally [readable header, writable data, writable status]. A hostile guest sends [writable header, readable data, readable status]. What does your device do, and what would a naive one do?
Spec hunt
- Virtio 1.2, section 2.7.4, "Message Framing", with its requirement subsections 2.7.4.1 and 2.7.4.2: where does the specification require device-writable descriptors to come after device-readable ones? Is that a rule for the driver or for the device, and what does 2.7.4.1 tell the device not to assume? Why does macvmm enforce the rule anyway?
- Virtio 1.2, section 2.7.8, "The Virtqueue Used Ring": what exactly must
lencount, and what does the specification allow a driver to do with alenit does not trust? - Linux,
drivers/virtio/virtio_ring.c(source), functionsvirtqueue_add_splitandvirtqueue_get_buf_ctx_split: find thevirtio_wmb()andvirtio_rmb()calls. Which of our two ordered accesses pairs with each?