22. Virtio as a protocol
Why this layer exists
Chapter 21 ended on a number: a 1024-character string through the 16550 cost 2048 exits, two for every byte, because the device’s interface is one register access per byte and every access is a trip from the guest through the kernel to the VMM and back. A device that moves a disk sector cannot be built that way. It needs an interface in which the bytes cost no exits at all: the guest leaves the data in its own memory, which the VMM already has mapped (chapter 20), and tells the device where, and the device reads or writes it in place. What is left to agree on is the shape of that memory, who may write which part of it and in what order, and how the device knows there is something to look at. That agreement is the virtqueue, and virtio is the standard that fixes it.
Chapter 11 wrote the driver’s half, with ember as the guest and QEMU as the device. This chapter writes the other half, once. virtq.c is the device side of a split virtqueue in seventy lines of freestanding C: it takes a ring that a driver filled and returns chains of buffers, and takes finished chains and hands them back. A host-side harness drives it through six checks, several with more than one case, and the harness is the contract. Its six output lines open the capture, and much of what it checks prints nothing: the counters’ wrap at 65536, every malformed ring but one, a ring offered exactly full, a push that ignores a scribbled used.idx. wick’s Rust ring meets the same checks in chapter 25 and hearth’s serves the same protocol to its guests in chapter 36. Then the same file goes into chapter 21’s VMM behind a virtio-mmio block device over a RAM disk, and a bare guest driver in C, running as the guest under KVM, reads one sector through it. The lab stops there on purpose: one queue, one request type, one thread, and no interrupts. The Mechanism section says where each of those limits is set and what lifting it costs.
Mechanism
The ring, from the side that does not write the table
A virtqueue is the ring chapter 11 defined: a table of buffer descriptors in guest memory that a driver fills and a device drains, with an index on each side saying how far each has got. That chapter built it from the driver’s chair. The specification’s second sentence about the split layout is the rule the whole design turns on (virtio 1.2 §2.7, fetched 2026-10-01):
The split virtqueue format separates the virtqueue into several parts, where each part is write-able by either the driver or the device, but not both.
There are three parts, and the specification’s table gives each its alignment and size for a queue of N entries:
| Part | Alignment | Size | Written by |
|---|---|---|---|
| Descriptor table | 16 | 16 * N |
the driver |
| Available ring | 2 | 6 + 2 * N |
the driver |
| Used ring | 4 | 6 + 8 * N |
the device |
The device’s whole job follows from the third column. It reads the descriptor table and the available ring and writes the used ring and the buffers the descriptors name, and it never writes a descriptor. The specification says the last part twice over (§2.7.5.1): “A device MUST NOT write to a device-readable buffer, and a device SHOULD NOT read a device-writable buffer (it MAY do so for debugging or diagnostic purposes). A device MUST NOT write to any descriptor table entry.” This is why virtq_pop takes the table through a pointer it only loads from, and why struct virtq has no function that stores into desc.
A descriptor is 16 bytes (§2.7.5): a guest-physical address, a length, flags and a next index. VIRTQ_DESC_F_NEXT (1) says the buffer continues in the descriptor next names; VIRTQ_DESC_F_WRITE (2) says the device may write it, and without that flag the device may only read. A chain of descriptors is one request. The available ring (§2.7.6) is a 16-bit flags, a 16-bit idx and a ring of 16-bit descriptor indices, each the head of a chain: “idx field indicates where the driver would put the next descriptor entry in the ring (modulo the queue size). This starts at 0, and increases.” The used ring (§2.7.8) has the same two header fields and a ring of {id, len} pairs, id the head of a finished chain and len the number of bytes the device wrote. Version 2 of the transport takes three separate ring addresses where the legacy interface had one contiguous, page-aligned region (§2.7.2). virtq.h declares the three structures with the natural C layout, which is the specification’s layout (descriptor 16 bytes; flags and idx at offsets 0 and 2, the ring at offset 4 in both rings, 8-byte used elements), and does not pack them: the atomics below need an addressable, naturally aligned idx, and packing would take that away for nothing.
Two cursors
The driver owns avail.idx and the device owns used.idx; both only ever increase, wrap naturally at 65536 (§2.7.13.3: “idx always increments, and wraps naturally at 65536”), and name a slot by the index modulo the queue size. Because the queue size is a power of two, 65536 is a multiple of it and the slot arithmetic stays consistent across the wrap: slot 7 is followed by slot 0 whether the counter is at 7 or at 65535. The device keeps two private numbers: last_avail, the count of chains it has taken, and next_used, its own copy of used.idx. The copy exists because the used ring is guest memory too and a driver can write used.idx; reading it back to decide where the next element goes would let the driver choose the slot. Nothing in guest memory says which chains the device has seen; avail.idx - last_avail does, and it cannot exceed the queue size in a driver that follows the rules, because it may not offer more than the descriptor table holds (§2.7.13: “the 16-bit idx value can always distinguish between a full and empty buffer”). A difference greater than the queue size is a driver that broke the rule, and virtq_pop refuses it. So virtq_pop has one empty test, avail.idx == last_avail, and one commit point, last_avail++; and virtq_push has one commit point, the store to used.idx. Two cursors, one private (last_avail) and one published (used.idx, shadowed by the private next_used), are the entire state the backend keeps.
Barriers: who writes what, and when it is visible
The driver offers a buffer in this order (§2.7.13): it fills the descriptors, writes the chain’s head into the next ring slot, performs “a suitable memory barrier to ensure the device sees the updated descriptor table and available ring before the next step”, and only then increases avail.idx; requirement §2.7.13.3.1 states the same ordering as an obligation: “The driver MUST perform a suitable memory barrier before the idx update, to ensure the device sees the most up-to-date copy.” That is a release: everything written before idx is visible to anyone who sees the new idx. The device’s half is the matching acquire, a load of avail.idx after which the ring slot and the descriptors may be read. The specification names the driver’s barrier and not this one; it is the reader’s half of the pair, and virtq_pop makes it with __ATOMIC_ACQUIRE on the load of avail.idx.
The device’s own obligation is the mirror image, and the specification does state it (§2.7.8.2): “The device MUST set len prior to updating the used idx. The device MUST write at least len bytes to descriptor, beginning at the first device-writable buffer, prior to updating the used idx.” So virtq_push writes the element, and __ATOMIC_RELEASE on the store to used.idx orders the element and every byte the device wrote into the buffers before the index that publishes them. The driver’s acquire on used.idx completes that pair. The figure marks those four: a release by each writer before its index, an acquire by each reader after it. They are not the complete set. After the device stores used.idx it decides whether to notify the driver by loading avail.flags (§2.7.7.2), a store followed by a load, which release and acquire do not order; on a second thread the load can be satisfied before the store is visible and a notification can be lost. The specification puts the matching MUST on the driver side (§2.7.13.4.1: “The driver MUST perform a suitable memory barrier before reading flags or avail_event, to avoid missing a notification”), and the device needs the same full fence for the same reason, so blk_service issues __ATOMIC_SEQ_CST between the push and the flags read.
The strength of those barriers is the specification’s to set, and it sets it in the feature bits (§6, VIRTIO_F_ORDER_PLATFORM, bit 36): “If this feature bit is not negotiated, then the device and driver are assumed to be implemented in software, that is they can be assumed to run on identical CPUs in an SMP configuration. Thus a weaker form of memory barriers is sufficient to yield better performance.” Here both sides are software, the bit is not offered, and the barriers are the ones threads use on one machine, which is what the __atomic acquire and release orderings give; a device behind real hardware (a PCI card) would need the stronger kind and would negotiate the bit.
Nothing in this lab exercises them, and the chapter says so rather than pretending. The harness is one thread. The VMM is one thread too: KVM_RUN returns to the VMM with the vCPU stopped, the doorbell handler runs the ring before the next KVM_RUN, and the guest cannot store anything while it does; nothing the guest does can race with the drain. The barriers are in the code because the code is the contract: wick’s device will run on its own thread beside the vCPU thread (chapter 25), and the ring it serves has to be correct there. Exercise (b) is a two-thread test that shows what the order of the stores does once there is a second reader.
A driver that is not trusted
The ring is the driver’s memory, and the driver is the guest; a guest that is hostile, or merely buggy, can put anything in it. virtq_pop therefore treats every field as an input and makes four decisions about each chain before returning it.
Every field is read once. The descriptor table is guest memory that the guest may change while the device runs, so a copy is only a copy if the compiler really makes it; reading flags from the table to test it and again to follow it would check one value and use another. virtq_pop loads each field of each descriptor, and the ring entry, with a relaxed atomic load and works from those values. Copying the descriptor into a local struct looks like one read and is not guaranteed to be one, because a compiler may load the fields lazily at their uses; the explicit loads cannot be turned back into two reads.
The indices are bounds-checked. An avail.idx more than num ahead of last_avail is not a ring the protocol allows (the device could only serve stale slots), a head or a next of num or more is not a descriptor, and each is refused. The chain length is bounded by VIRTQ_MAX_SEGS (8): the descriptor table’s size is “the maximum possible descriptor chain length” (§2.7.5) and §2.7.5.2 forbids loops (“this implies that loops in the descriptor chain are forbidden!”), so a chain longer than the table is a loop, and the bound is what stops a loop that a hostile driver built anyway. The specification allows a device to set its own limit (§2.7.4.1: “The device MAY have a reasonable limit of descriptors it will allow in a chain”); here the limit is the queue size this device offers, and a device with a larger queue would raise it to the queue size.
The order is enforced. §2.7.4.2: “The driver MUST place any device-writable descriptor elements after any device-readable descriptor elements.” A chain with a readable buffer after a writable one is malformed, and virtq_pop returns -1 on it. The rule is what lets a device treat the chain as “the bytes I read, then the places I write” with no bookkeeping, and it is the one a block device leans on: header first, status last.
The device’s own writes cannot feed the loop. The three areas are disjoint, and QueueReady = 1 refuses a ring in which they overlap. That matters for two reasons: a used ring over the descriptor table would make the device write the table, which §2.7.5.1 forbids, and a used ring over the available ring would have each push store the device’s index into avail.idx, erasing the chains the driver offered (an exact alias with three chains offered served one and dropped the other two). As a second defence the drain serves at most num chains per doorbell: a driver more than num ahead is refused, so num chains are everything that can be offered at that moment. The bound earns its place against history: an earlier virtq_push read used.idx back from guest memory, and with the used ring aliased onto the available ring every push then bumped avail.idx and the drain ran a million chains on one doorbell. That is exactly why the device keeps its own next_used.
Every address is translated. A descriptor’s addr is a guest-physical address, which means nothing to the VMM until gpa2hva turns it into a host pointer; virtq_pop passes the length too, and a NULL back means some byte of the buffer is outside what the guest owns, which is also malformed. The translation is the caller’s because it is the one thing the backend cannot know: in this lab it is an offset into the one memory slot, and in hearth it will be the guest’s G-stage (chapter 19) rather than anything a host process maps.
On any of these virtq_pop returns -1 and leaves last_avail where it was: the request stays at the head of the ring, un-consumed, for the caller to deal with. What the caller does is the device’s policy, not the protocol’s. The VMM sets the device status bit DEVICE_NEEDS_RESET (64) and the configuration-change bit of InterruptStatus, as §2.1.2 asks of a device in an error state it cannot recover from, and stops serving the queue: QueueNotify is refused while the bit is set (like every refusal, it ends the VM with the failure verdict, so a driver must reset the device before ringing again), and a Status write keeps it (§2.1.1: the driver must not clear a status bit); only a reset, a write of 0, clears it.
used.len, and what a driver may trust
The len the device returns is the “total of bytes written into the buffer” (§2.7.8), counted over the device-writable part of the chain. For a block read that is 512 data bytes and one status byte, 513; for a request the device answers with an error status it is 0, because the first device-writable buffer is the data segment and nothing was written to it. The specification lets a device under-report: it “MAY write more than len bytes” (§2.7.8.2), and in exchange it tells the driver what it may assume (§2.7.8.3): “The driver MUST NOT make assumptions about data in device-writable buffers beyond the first len bytes, and SHOULD ignore this data.” A driver that follows that rule and sees a short len has to treat the tail as not written. For this request layout that is a real tension: the status byte sits after the 512 data bytes, so with len 0 (an error answer) a driver that trusts len never looks at the status, and with len 513 it can. A len-trusting driver can see an error status only if the device also writes the data. Chapter 11’s driver does not trust len at all; exercise (c) reads its source and what that choice costs.
The MMIO transport as a state machine
Chapter 21 gave the register table; what it did not need was the order, and the order is what a device model has to enforce. The driver walks a fixed sequence (§3.1.1, which §4.2.3.1 sends the MMIO driver to): reset; set ACKNOWLEDGE (1); set DRIVER (2); read the device’s feature bits and write back the subset it accepts; set FEATURES_OK (8); “re-read device status to ensure the FEATURES_OK bit is still set: otherwise, the device does not support our subset of features and the device is unusable”; set up the queues; set DRIVER_OK (4), “at this point the device is ‘live’”. The Status register carries the bits; writing zero resets the device (§4.2.2: “Writing zero (0x0) to this register triggers a device reset”), and a reset clears InterruptStatus and every QueueReady (§4.2.2.1).
Three places in that sequence need the model to do something.
Features. A device offers all it understands and the driver answers with a subset (§2.2). This one understands exactly one feature, VIRTIO_F_VERSION_1, bit 32 (§6: “This indicates compliance with this specification, giving a simple way to detect legacy devices or drivers”), which “A device MUST offer” (§6.2) and a driver MUST accept (§6.1). Feature words are read 32 bits at a time through a select register, so bit 32 is bit 0 of word 1: DeviceFeatures reads 1 when DeviceFeaturesSel is 1 and 0 otherwise. The model checks the answer when the driver sets FEATURES_OK: it stays set only if the driver accepted word 1 equal to 1 and word 0 equal to 0, and the model clears it otherwise, which is the signal the driver’s read-back at step 6 is looking for. The driver’s Status read is therefore a real check and not a formality; the guest prints it, 0xb, which is ACKNOWLEDGE | DRIVER | FEATURES_OK.
The block device has features of its own (§5.2.3: FLUSH, BLK_SIZE, SEG_MAX and others), and the model offers none of them. §5.2.5.2 says “Devices SHOULD always offer VIRTIO_BLK_F_FLUSH”; a RAM disk has nothing to flush, and the departure is a documented one, not a silent one.
The moment the device learns the ring. The driver programs queue 0 in seven steps (§4.2.3.2): select it with QueueSel; read QueueReady and expect zero; read QueueNumMax; zero the memory; write the size to QueueNum; write the three guest-physical addresses to the QueueDesc, QueueDriver and QueueDevice low/high pairs; “Write 0x1 to QueueReady”. Until the last of those, the device is only collecting numbers. The model stores each write in its vdev, and QueueReady = 1 is where it builds the struct virtq: it checks that the size is a power of two no larger than QueueNumMax and that each of the three addresses has the specification’s alignment (16, 2 and 4), translates each through gpa2hva with the size the table gives (16 * N, 6 + 2 * N, 6 + 8 * N) so that a ring that leaves the memory slot is refused, and records the pointers. §4.2.2.1 draws the line from the other side: “The device MUST NOT access virtual queue contents when QueueReady is zero (0x0)”. A device that read the addresses as they were written would be dereferencing numbers the driver was still in the middle of choosing.
The doorbell. QueueNotify is written with the queue index (§4.2.3.3, when VIRTIO_F_NOTIFICATION_DATA has not been negotiated). It is the one exit per request, and §2.1.2 gives the model its precondition: “The device MUST NOT consume buffers or send any used buffer notifications to the driver before DRIVER_OK.” A write to it before DRIVER_OK, or before the queue is ready, or with an index other than 0, is a driver bug, and the model refuses it the way it refuses every register access it cannot answer.
Width. §4.2.2.2: “The driver MUST only use 32 bit wide and aligned reads and writes to access the control registers described in table 4.1. For the device-specific configuration space, the driver MUST use 8 bit wide accesses for 8 bit wide fields, 16 bit wide and aligned accesses for 16 bit wide fields and 32 bit wide and aligned accesses for 32 and 64 bit wide fields.” The model therefore accepts len == 4 and nothing else, in the control registers and at Config + 0 and Config + 4, the two halves of the 64-bit capacity field. A single 64-bit load of capacity is a driver bug and the model says so (exercise (e) shows it). The same clause makes the direction column of Table 4.1 binding on the driver, “MUST NOT write to the read-only registers (direction R) and MUST NOT read from the write-only registers (direction W)”, so the model’s switch has a separate list for reads and for writes and falls to -1 on everything else. VendorID is the one register the specification leaves meaningless (“Virtio Subsystem Vendor ID”); the model returns 0x554d4551, the ASCII bytes QEMU in little-endian order, and nothing in the lab reads it. A general driver also reads a field wider than 32 bits inside a loop on ConfigGeneration (§2.5.1: drivers “MUST NOT assume reads from fields greater than 32 bits wide are atomic”), so that a change between the two halves is caught; this model’s generation is constant, and the lab’s driver omits the loop because its extra reads would change the pinned exit count.
The block request
A block request (§5.2.6) is a header, the data, and a status byte:
struct virtio_blk_req {
le32 type;
le32 reserved;
le64 sector;
u8 data[];
u8 status;
};
On the ring the header is the first descriptor (16 bytes, device-readable), the data the second (512 bytes, device-writable for a read) and the status byte the third (one byte, device-writable), in the order §2.7.4.2 requires. type 0 is VIRTIO_BLK_T_IN, a read; the other types, a write among them, are not served (only a request shaped as a read, with another type, is answered, with UNSUPP; the next paragraph says what happens to the rest), and the status byte the device writes is “either VIRTIO_BLK_S_OK for success, VIRTIO_BLK_S_IOERR for device or driver error or VIRTIO_BLK_S_UNSUPP for a request unsupported by device”: 0, 1 and 2. The sector number is in units of 512 bytes, and the device’s size is in the same units: “The capacity of the device (expressed in 512-byte sectors) is always present” (§5.2.4), a le64 at offset 0 of the device-specific configuration, which sits at 0x100 of the MMIO window. The RAM disk has 16 sectors, and sector s, byte i holds (s * 7 + i) & 0xff: sector 0 starts 00 01 02 ..., sector 1 starts 07 08 09 ..., and a read of the wrong sector, or a copy to the wrong place, shows in the first bytes. The driver “MUST NOT submit a request which would cause a read or write beyond capacity” (§5.2.6.1); the device does not take that on trust, and answers a sector past the end with IOERR.
The device model serves one arrangement of descriptors, exactly these three, and sets DEVICE_NEEDS_RESET on any other. That is narrower than the specification asks of a full device: §2.7.4.1 says “The device MUST NOT make assumptions about the particular arrangement of descriptors”, so a complete block backend gathers the readable descriptors into the header and the writable ones into data and status, however the driver cut them. The model checks the arrangement because it is cheap and the lab’s driver is the only one.
Why polling is honest here
When the device uses a buffer it is obliged to say so (§2.7.7.2): with the available ring’s flags at 0, “the device MUST send a notification” (this driver never sets the flag, and the device honours it if it did). On the MMIO transport that notification is bit 0 of InterruptStatus, “the interrupt was asserted because the device has used a buffer in at least one of the active virtual queues”, and a line to the interrupt controller. The model sets the bit; nothing asserts a line, because no lab in this part injects an interrupt into a guest (the mechanism is hvip on the hardware and KVM_INTERRUPT or KVM_IRQ_LINE through KVM, as chapter 21 noted, and hearth injects its own in chapter 38). The guest polls used.idx instead and still performs the register half of the protocol: it reads InterruptStatus, sees 1, and writes the value back to InterruptACK (§4.2.3.4.1: “After the interrupt is handled, the driver MUST acknowledge it by writing a bit mask corresponding to the handled events to the InterruptACK register”). Polling is honest because the data path is the ring and the doorbell. An interrupt tells the driver when to look at used.idx; it changes when the driver finds the completion and nothing about how the device produced it.
The three axes
Chapter 14’s axes apply to the backend as they did to the UART. Shared: the three tables and the buffers they name, all in guest memory the VMM maps through the slot, and the register window; the device’s cursors and the RAM disk are the VMM’s own. TCB: virtq_pop and virtq_push are the code that reads untrusted memory, fifty-five lines between them, comments included; in wick they run in a process the jailer confines (chapter 26) and in hearth they are part of the hypervisor image, where a bug in a bounds check is a bug in the TCB. Copy: one memcpy of 512 bytes from the RAM disk into the guest’s buffer per request, and one exit; the descriptors and the buffers cost no exit and no second copy.
Walkthrough
The contract is virtq.h: the three structures of the Mechanism section and the two prototypes. virtq_pop is the device’s half of §2.7.13.
/* The ring is the driver's memory, and the driver may be hostile: every
* field is read once, with a relaxed atomic load, so the value checked is
* the value used. */
#define LOAD(x) __atomic_load_n(&(x), __ATOMIC_RELAXED)
int virtq_pop(struct virtq *q, struct virtq_chain *c)
{
/* Acquire: everything the driver wrote before it bumped idx (the ring
* entry, the descriptors) is visible after this load (2.7.13.3.1 is
* the driver's half of this pair). */
uint16_t avail_idx = __atomic_load_n(&q->avail->idx, __ATOMIC_ACQUIRE);
if (avail_idx == q->last_avail)
return 0; /* 2.7.6: nothing new */
if ((uint16_t)(avail_idx - q->last_avail) > q->num)
return -1; /* 2.7.13: more than the table holds */
uint16_t head = LOAD(q->avail->ring[q->last_avail % q->num]);
uint16_t i = head;
unsigned n = 0;
int seen_writable = 0;
c->head = head;
for (;;) {
if (i >= q->num || n >= VIRTQ_MAX_SEGS)
return -1; /* bad index, or too long / a loop */
struct virtq_desc *dp = &q->desc[i]; /* the table is the driver's: read, never write (2.7.5.1) */
uint64_t addr = LOAD(dp->addr);
uint32_t len = LOAD(dp->len);
uint16_t flags = LOAD(dp->flags);
uint16_t next = LOAD(dp->next);
if (flags & VIRTQ_DESC_F_INDIRECT)
return -1; /* 2.7.5.3: not negotiated */
int w = (flags & VIRTQ_DESC_F_WRITE) != 0;
if (seen_writable && !w)
return -1; /* 2.7.4.2 */
seen_writable |= w;
void *hva = q->gpa2hva(addr, len, q->ctx);
if (!hva)
return -1;
c->seg[n].hva = hva;
c->seg[n].len = len;
c->seg[n].writable = w;
n++;
if (!(flags & VIRTQ_DESC_F_NEXT))
break;
i = next;
}
c->nsegs = n;
q->last_avail++;
return 1;
}
The LOAD macro at the top of the listing is the single-read rule from the Mechanism section: a relaxed atomic load of one field. Everything the function returns is a copy of values it loaded once, and last_avail is incremented only on the path that returns 1.
void virtq_push(struct virtq *q, uint16_t head, uint32_t written)
{
uint16_t idx = q->next_used; /* private: the driver can write used.idx, so it is never read back */
q->used->ring[idx % q->num].id = head;
q->used->ring[idx % q->num].len = written;
q->next_used = (uint16_t)(idx + 1);
/* 2.7.8.2: len, and the bytes it counts, are written before idx.
* Release: the element and the data are visible before the index. */
__atomic_store_n(&q->used->idx, q->next_used, __ATOMIC_RELEASE);
}
virtq_push is the device’s obligation from §2.7.8.2: element first, index after, with the release between them.
The harness is the driver and the memory. It keeps guest-physical memory as a 4096-byte array and a gpa2hva that adds an address to its base, plays the driver’s half of §2.7.13 in driver_offer (ring entry, release, index), and checks six things. The second is the one a block device lives on: the chain of three in §2.7.4.2’s order.
/* 2. A block read in 2.7.4.2's order: header (device-readable),
* data and status (device-writable). */
queue_reset();
set_desc(0, HDR_OFF, 16, VIRTQ_DESC_F_NEXT, 1);
set_desc(1, DATA_OFF, 512, VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE, 2);
set_desc(2, STAT_OFF, 1, VIRTQ_DESC_F_WRITE, 0);
driver_offer(0);
if (pop(&c) != 1) fail("3-seg chain: pop did not return 1");
char pat[3 * VIRTQ_MAX_SEGS + 1] = "";
for (unsigned i = 0; i < c.nsegs; i++)
strcat(pat, i ? (c.seg[i].writable ? ",wo" : ",ro") : (c.seg[i].writable ? "wo" : "ro"));
if (c.head != 0 || c.nsegs != 3 || strcmp(pat, "ro,wo,wo") != 0 ||
c.seg[0].hva != mem + HDR_OFF || c.seg[0].len != 16 ||
c.seg[1].hva != mem + DATA_OFF || c.seg[1].len != 512 ||
c.seg[2].hva != mem + STAT_OFF || c.seg[2].len != 1)
fail("3-seg chain: wrong segments");
printf("harness: 3-seg read chain: head %u segs %u %s\n", c.head, c.nsegs, pat);
The other five are an empty queue (pop returns 0), the used ring after a push, twenty chains through an eight-entry ring with reused descriptors, a run that begins at 65530 and carries the counters across 65536 without printing anything, and the malformed rings and chains: writable before readable, which the output names, and also an avail.idx more than a table ahead, a head past the table, a next past the table, a loop, a descriptor with the INDIRECT flag (not negotiated), and a buffer outside the memory, each refused with last_avail unmoved. Two more silent checks guard the other direction: a ring offered exactly full (num chains, all of them served, then 0) is legal and must not be refused, and a push ignores a used.idx the driver has scribbled on. The harness has caught the bugs it was written for: removing the order check in virtq_pop stops it at wo,ro: not refused; removing the segment bound makes the loop case run off the end of the segment array and abort; not advancing last_avail or not reducing the used slot modulo the queue size stops it in step 4; accepting an unmappable address stops it at unmappable: not refused. Each of those is a one-line edit to a scratch copy of virtq.c.
The VMM adds two things to chapter 21’s, the register file and the request loop. mmio_virtio is the model the Mechanism section described: width first, then a read switch and two write switches (the second is for queue 0 only). Every return -1 is a refusal, and the exit loop turns a refusal into the same “no device here” line that chapter 21 printed.
/* The register file. The driver MUST use 32-bit aligned accesses to the
* control registers and to 64-bit config fields (4.2.2.2), MUST NOT read
* the write-only registers or write the read-only ones, and MUST NOT touch
* anything not in Table 4.1: this model refuses all of it. */
static int mmio_virtio(struct kvm_run *run, struct vdev *dev, unsigned char *mem)
{
unsigned long off = run->mmio.phys_addr - VIRTIO_BASE;
uint32_t v;
if (run->mmio.len != 4) return -1;
if (!run->mmio.is_write) {
switch (off) {
case R_MAGIC: v = 0x74726976; break; /* "virt" */
case R_VERSION: v = 2; break;
case R_DEVICE_ID: v = 2; break; /* 5.2.1: block */
case R_VENDOR_ID: v = 0x554d4551; break; /* "QEMU", little-endian: any value is allowed */
case R_DEV_FEATURES: v = dev->dev_feat_sel == 1; /* bit 32, VERSION_1, and no other */
break;
case R_QUEUE_NUM_MAX: v = dev->queue_sel == 0 ? QUEUE_MAX : 0; break;
case R_QUEUE_READY: v = dev->queue_sel == 0 ? dev->queue_ready : 0; break;
case R_INT_STATUS: v = dev->int_status; break;
case R_STATUS: v = dev->status; break;
case R_CONFIG_GEN: v = 0; break; /* the config never changes */
case R_CONFIG: v = DISK_SECTORS; break; /* 5.2.4: capacity, low half */
case R_CONFIG + 4: v = 0; break; /* high half */
default: return -1;
}
memcpy(run->mmio.data, &v, 4);
return 0;
}
memcpy(&v, run->mmio.data, 4);
switch (off) {
case R_DEV_FEAT_SEL: dev->dev_feat_sel = v; return 0;
case R_DRV_FEAT_SEL: dev->drv_feat_sel = v; return 0;
case R_DRV_FEATURES:
if (dev->drv_feat_sel > 1) return -1;
dev->drv_feat[dev->drv_feat_sel] = v;
return 0;
case R_QUEUE_SEL: dev->queue_sel = v; return 0;
case R_STATUS:
if (v == 0) { dev_reset(dev); return 0; } /* 4.2.2: writing 0 resets */
if ((v & S_FEATURES_OK) && !features_ok(dev)) v &= ~S_FEATURES_OK;
dev->status = v | (dev->status & S_NEEDS_RESET); /* NEEDS_RESET survives driver writes; only the 0 reset clears it */
return 0;
case R_INT_ACK: dev->int_status &= ~v; return 0;
case R_QUEUE_NOTIFY:
/* The value is the queue index (4.2.3.3, NOTIFICATION_DATA not
* negotiated). The device MUST NOT consume buffers before
* DRIVER_OK (2.1.2) nor touch the queue before QueueReady
* (4.2.2.1): a driver that rings the bell early is refused. */
if (v != 0 || !(dev->status & S_DRIVER_OK) || !dev->queue_ready ||
(dev->status & S_NEEDS_RESET)) return -1;
blk_service(dev);
return 0;
}
/* Everything below is about queue 0 only. */
if (dev->queue_sel != 0) return -1;
switch (off) {
case R_QUEUE_NUM: dev->queue_num = v; return 0;
case R_QUEUE_DESC_LO: dev->desc = (dev->desc & ~0xffffffffULL) | v; return 0;
case R_QUEUE_DESC_HI: dev->desc = (dev->desc & 0xffffffffULL) | (uint64_t)v << 32; return 0;
case R_QUEUE_DRV_LO: dev->avail = (dev->avail & ~0xffffffffULL) | v; return 0;
case R_QUEUE_DRV_HI: dev->avail = (dev->avail & 0xffffffffULL) | (uint64_t)v << 32; return 0;
case R_QUEUE_DEV_LO: dev->used = (dev->used & ~0xffffffffULL) | v; return 0;
case R_QUEUE_DEV_HI: dev->used = (dev->used & 0xffffffffULL) | (uint64_t)v << 32; return 0;
case R_QUEUE_READY:
if (v == 0) { dev->queue_ready = 0; return 0; }
if (v != 1 || queue_setup(dev, mem) < 0) return -1;
dev->queue_ready = 1;
return 0;
}
return -1;
}
blk_service runs on the doorbell: it pops chains until the ring is empty, checks the shape, reads the header out of guest memory, serves the read from the RAM disk, writes the status byte, and pushes.
/* QueueNotify: drain the available ring. Each chain is one block request,
* 5.2.6: a 16-byte header the device reads, 512 bytes it writes, a status
* byte it writes. Anything else is a driver the device cannot serve: it
* sets DEVICE_NEEDS_RESET and a configuration-change notification
* (2.1.2) and stops. At most num chains are served per doorbell: that is
* everything the driver can have offered (virtq_pop refuses a driver more
* than num ahead), and it bounds the loop even if the rings overlap. */
static void blk_service(struct vdev *dev)
{
static int told;
struct virtq_chain c;
int r = 0;
for (unsigned n = 0; n < dev->q.num && (r = virtq_pop(&dev->q, &c)) == 1; n++) {
if (c.nsegs != 3 ||
c.seg[0].writable || c.seg[0].len != 16 ||
!c.seg[1].writable || c.seg[1].len != 512 ||
!c.seg[2].writable || c.seg[2].len != 1) {
r = -1;
break;
}
uint32_t type;
uint64_t sector;
memcpy(&type, c.seg[0].hva, 4); /* little-endian host */
memcpy(§or, (unsigned char *)c.seg[0].hva + 8, 8);
uint8_t status = BLK_S_OK;
uint32_t written = 512 + 1; /* the data and the status byte */
if (type != BLK_T_IN) {
status = BLK_S_UNSUPP;
written = 0; /* the data segment is untouched (2.7.8.2) */
} else if (sector >= DISK_SECTORS) {
status = BLK_S_IOERR;
written = 0;
} else {
memcpy(c.seg[1].hva, disk[sector], 512);
}
*(uint8_t *)c.seg[2].hva = status;
virtq_push(&dev->q, c.head, written);
dev->served++;
/* The used.idx store above and this load of avail.flags are a store
* then a load: release and acquire do not order them, a full fence does. */
__atomic_thread_fence(__ATOMIC_SEQ_CST);
/* 2.7.7.2: with avail.flags 0, the device notifies. */
if (!(__atomic_load_n(&dev->q.avail->flags, __ATOMIC_RELAXED) & 1))
dev->int_status |= 1;
}
if (r < 0) {
if (virtq_mine_stub && !told) {
printf("MINE: virtq_pop stub\n");
fflush(stdout);
told = 1;
}
dev->status |= S_NEEDS_RESET;
dev->int_status |= 2;
}
}
The bytes the driver sees, in the order it sees them, are the memcpy into seg[1], the status store into seg[2], and the push that publishes both. A request of the right shape for a read, but for a sector outside the RAM disk, is answered with IOERR, and one with a type other than 0 with UNSUPP, each with a len of 0. A request of any other shape (a conformant write, whose data segment is device-readable, a flush, a get-ID) is not answered at all: it puts the device in DEVICE_NEEDS_RESET.
The guest is a freestanding C program for rv64ima_zicsr linked at 0x80000000, the base of the VMM’s 2 MiB slot, by guest/link.ld, with its stack at the top of that slot. guest/start.S sets the stack pointer, zeroes .bss (the file holds only .text, .rodata and .data, as objcopy -O binary -j extracts them), calls main, and then makes chapter 19’s shutdown call, the SBI SRST ecall that KVM turns into the VM’s shutdown. Its address arithmetic is auipc and addi pairs with relaxation off (.option norelax in the assembly and -mno-relax for the C), as in chapter 21, for the same reason: the image is linked and loaded at one address and must not depend on a linker’s folding of it. The three rings are static arrays aligned to 4096 in .bss. The guest runs with its VS-stage translation Bare, so its addresses are guest-physical addresses, and the address the compiler gives an array is the one the driver writes into the queue registers; the driver prints nothing about any of them. The driver then follows the specification in order:
static int blk_read_sector0(void)
{
if (rd(R_MAGIC) != 0x74726976u) { fail("MagicValue"); return 1; } /* 4.2.3.1.1 */
show("MagicValue", 0x74726976u);
if (rd(R_VERSION) != 2) { fail("Version"); return 1; }
show("Version", 2);
if (rd(R_DEVICE_ID) != 2) { fail("DeviceID"); return 1; } /* 5.2.1: block */
show("DeviceID", 2);
/* 3.1.1: reset, ACKNOWLEDGE, DRIVER, features, FEATURES_OK, read back. */
wr(R_STATUS, 0);
wr(R_STATUS, S_ACKNOWLEDGE);
wr(R_STATUS, S_ACKNOWLEDGE | S_DRIVER);
wr(R_DEV_FEAT_SEL, 1); /* word 1 holds bit 32 */
uint32_t f = rd(R_DEV_FEATURES);
show("DeviceFeatures[1]", f);
if (!(f & 1)) { fail("VERSION_1 not offered"); return 1; } /* section 6 */
wr(R_DRV_FEAT_SEL, 1);
wr(R_DRV_FEATURES, 1); /* VERSION_1, nothing else */
wr(R_DRV_FEAT_SEL, 0);
wr(R_DRV_FEATURES, 0);
wr(R_STATUS, S_ACKNOWLEDGE | S_DRIVER | S_FEATURES_OK);
uint32_t st = rd(R_STATUS);
show("Status", st);
if (!(st & S_FEATURES_OK)) { fail("FEATURES_OK refused"); return 1; }
/* 4.2.3.2: queue 0. */
wr(R_QUEUE_SEL, 0);
if (rd(R_QUEUE_READY) != 0) { fail("queue already ready"); return 1; }
uint32_t max = rd(R_QUEUE_NUM_MAX);
show("QueueNumMax", max);
if (max < QNUM) { fail("queue too small"); return 1; }
wr(R_QUEUE_NUM, QNUM);
uint64_t d = (uint64_t)(uintptr_t)desc, a = (uint64_t)(uintptr_t)&avail, u = (uint64_t)(uintptr_t)&used;
wr(R_QUEUE_DESC_LO, (uint32_t)d); wr(R_QUEUE_DESC_HI, (uint32_t)(d >> 32));
wr(R_QUEUE_DRV_LO, (uint32_t)a); wr(R_QUEUE_DRV_HI, (uint32_t)(a >> 32));
wr(R_QUEUE_DEV_LO, (uint32_t)u); wr(R_QUEUE_DEV_HI, (uint32_t)(u >> 32));
wr(R_QUEUE_READY, 1);
wr(R_STATUS, S_ACKNOWLEDGE | S_DRIVER | S_FEATURES_OK | S_DRIVER_OK);
/* 5.2.4: capacity is a le64 at config offset 0; 4.2.2.2 says 64-bit
* fields are read as two aligned 32-bit halves. */
uint64_t cap = rd(R_CONFIG) | (uint64_t)rd(R_CONFIG + 4) << 32;
show("capacity", cap);
/* 5.2.6: header (device-readable), 512 bytes and a status byte
* (device-writable), chained in that order (2.7.4.2). */
req.type = 0; /* VIRTIO_BLK_T_IN */
req.reserved = 0;
req.sector = 0;
req_status = 0xff; /* a value the device cannot leave behind */
desc[0] = (struct virtq_desc){ (uint64_t)(uintptr_t)&req, 16, VIRTQ_DESC_F_NEXT, 1 };
desc[1] = (struct virtq_desc){ (uint64_t)(uintptr_t)data, 512, VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE, 2 };
desc[2] = (struct virtq_desc){ (uint64_t)(uintptr_t)&req_status, 1, VIRTQ_DESC_F_WRITE, 0 };
/* 2.7.13: head into the ring, barrier, idx, barrier, notify. */
avail.ring[avail.idx % QNUM] = 0;
wmb();
__atomic_store_n(&avail.idx, (uint16_t)(avail.idx + 1), __ATOMIC_RELEASE);
__asm__ volatile("fence" ::: "memory"); /* idx before the doorbell */
wr(R_QUEUE_NOTIFY, 0); /* 4.2.3.3: the queue index */
while (__atomic_load_n(&used.idx, __ATOMIC_ACQUIRE) != 1) /* polled: no interrupt */
;
show("status", req_status);
show("used len", used.ring[0].len);
puts_("guest: sector 0:");
for (int i = 0; i < 16; i++) {
uart_putc(' ');
put_nibbles(data[i], 2);
}
uart_putc('\n');
uint32_t is = rd(R_INT_STATUS); /* 4.2.2: bit 0, used buffer */
show("InterruptStatus", is);
wr(R_INT_ACK, is);
return 0;
}
The first three checks of the driver are §4.2.3.1.1’s, on MagicValue, Version and DeviceID; the next block is §3.1.1 steps 1 to 6; the queue block is §4.2.3.2; the request is §5.2.6 and §2.7.13, with the head into the ring, a release, the index, and a full fence before the doorbell so that the index is visible before the exit begins. The loop polls used.idx with an acquire load. Every number the guest prints is a value it computed from the device’s answers: the three identification registers, the features word, the status, QueueNumMax, capacity, the request’s status byte, used.ring[0].len, the first 16 bytes of the sector and InterruptStatus.
The lab starts red in both halves. With mine/virtq.c, whose virtq_pop sets virtq_mine_stub and returns -1, the harness stops at its first check and the guest’s read never completes; the Lab section shows the diff.
Exercises
Each was run on talos (QEMU 11.1.1, the lab’s kernel and initramfs) in a scratch copy of labs/ch22/, one edit at a time, except (b), whose program is committed as labs/ch22/stress.c.
(a) Give the harness a queue of 16 (NUM 16, AVAIL_OFF 0x100, USED_OFF 0x180) and replace step 2’s chain by nine chained 16-byte descriptors. What does virtq_pop do, and where does the number 8 come from?
Answer
Observed:
harness: empty queue pops 0
harness: FAIL: 3-seg chain: pop did not return 1
virtq_pop returns -1 at the ninth descriptor: n has reached VIRTQ_MAX_SEGS before the chain ends, and the bound is what stands between a driver that builds a loop and a backend that follows it. With VIRTQ_MAX_SEGS raised to 16 the same chain pops (the harness then stops one line later, at 3-seg chain: wrong segments, because it expected three). The 8 is the queue size, the bound the Mechanism section sets. A bound lower than the queue size is a policy the device must document, and a bound above it is no bound at all.
(b) In the guest driver, store avail.idx before avail.ring[0], with no barrier between them (and put the chain at descriptors 4, 5, 6 so the head is not the zero the array starts as). Does the lab still pass? Then run make stress and say why the answer to the first question does not protect wick.
Answer
Observed: the lab passes, with diff against capture.txt reporting nothing. This is the single-threaded doorbell of the Mechanism section’s barrier paragraph: both stores have completed, in whichever order, before blk_service reads the ring.
make stress runs the reference virtq_pop and virtq_push against a second thread that plays the driver. With the entry stored first and avail.idx after (§2.7.13’s order) the device popped 20,000,000 chains with 0 wrong heads; with avail.idx first, idx-first order: 20000000 chains, 639 popped with the wrong head on one run on talos and 13809 on the next. The count is a race, and it varies by orders of magnitude; the point is that it is not zero. A device thread that sees the new idx reads the ring slot, and the slot still holds the previous lap’s head. The failure here is the order of the stores in the program, which can fail on any machine (a release store orders the operations before it, not the plain store after it). A missing barrier with the right order is a different bug, and talos (x86-64, whose stores stay in program order) would not show it; it is not exercised here, and a weaker memory model such as RISC-V’s can show it. wick’s device thread runs beside the vCPU thread, so the ring it serves depends on both the order and the barrier.
(c) Make the device report used.len as 512 instead of 513 for a successful read. What changes, and what does chapter 11’s driver do with len, by its source?
Answer
Observed: one line of the capture changes, guest: used len 0x200 for 0x201; the status, the sector bytes and everything else are as before, because the device still wrote the status byte, only without counting it. 512 is a legal under-report (§2.7.8.2), and by §2.7.8.3 the status byte at offset 512 is then past what a driver may trust: a driver that trusts len must treat the request as having no status.
ember’s blk_wait never reads len: it compares the used ring’s id with its head and reads *req_status, which blk_op set to 0xff before submitting. Read from the source (the lab does not run ember), against this device with len 512 it would behave exactly as before, and it would be correct only because of the sentinel: a status byte the device did not write reads 0xff, which is not S_OK, so a missing write is a failure rather than a pass. A driver that left stale zeros there would read S_OK from a status the device never wrote.
(d) Make the guest read sector 16, one past the RAM disk’s end. What does the device answer? Then delete the sector check from blk_service and read it again.
Answer
Observed, with the check: guest: status 0x1 (IOERR), guest: used len 0x0 (nothing in the data segment was written, and the status byte sits after it), and the 16 bytes of the data buffer are all 00, the buffer as the guest left it. The device refused to read and said so in the protocol’s own terms.
Observed, without it: guest: status 0x0, guest: used len 0x201 and the bytes 00 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00. That is a successful read of 512 bytes from disk[16], which is not in the array: it is whatever the VMM process holds after it, handed to the guest as a disk sector. The bytes depend on the VMM’s layout, and that dependence is what the exercise is for. The sector check is a memory-safety boundary between the guest and the VMM’s own memory, and the specification’s “driver MUST NOT” does not move it.
(e) The capture says vmm: mmio exits 613. Derive it from the driver, then say what a second read would cost; then change the driver to read capacity with one 64-bit load and observe what the device does.
Answer
The count is two terms. The UART: the guest prints 11 lines, and grep '^guest:' capture.txt | wc -c prints 291 bytes, each one an LSR read and a THR write as in chapter 21, which is 582 exits. The device, from blk_read_sector0:
| Phase | Reads | Writes |
|---|---|---|
MagicValue, Version, DeviceID | 3 | 0 |
reset, ACKNOWLEDGE, DRIVER | 0 | 3 |
features: writes of DeviceFeaturesSel, DriverFeaturesSel (twice), DriverFeatures (twice) and Status (FEATURES_OK); reads of DeviceFeatures and Status | 2 | 6 |
queue: QueueSel, QueueReady and QueueNumMax reads, QueueNum, the six address words, QueueReady, DRIVER_OK | 2 | 10 |
capacity, two halves | 2 | 0 |
the doorbell, QueueNotify | 0 | 1 |
InterruptStatus and InterruptACK | 1 | 1 |
That is 10 reads and 21 writes, 31 in all; 582 and 31 make 613, the observed count (the number was pinned by the run before this table was written, and the table is the explanation). The request itself, the whole sector, costs one of them: the doorbell. The other 612 are the console and the setup.
A second read, run as this driver is written (a silent second request, with the same interrupt handling), observed 616: the doorbell, InterruptStatus and InterruptACK, three exits, and none for the descriptors, the ring entry or the 512 bytes. A driver that polls the used ring and never touches the interrupt registers observed 614, one exit, the doorbell: the point of the ring. A second read never touches the queue-setup registers again; that is the saving.
With capacity read as *(volatile uint64_t *)(VIRTIO_BASE + R_CONFIG), observed:
vmm: KVM_RUN exit 6 (KVM_EXIT_MMIO) read gpa 0x10001100 len 8: no device here
vmm: mmio exits 302
vmm: requests served 0
vmm: FAIL
vmm rc=1
The address is Config + 0, the direction is right, and the width is the load’s: 8. §4.2.2.2 asks for 32-bit accesses to 64-bit fields, and the model accepts nothing else.
(f) Write virtq.h as the Rust types and signatures wick’s ring will have. Types only.
Answer
This is a design, and nothing checks it but the C: the harness’s six lines are the test it must pass in chapter 25. The mapping, field by field:
pub const MAX_SEGS: usize = 8;
pub enum Seg { Read(GuestSlice), Write(GuestSlice) } // virtq_seg: hva, len, writable
pub struct Chain { pub head: u16, pub segs: ArrayVec<Seg, MAX_SEGS> }
pub trait GuestMemory { // gpa2hva and its ctx
fn translate(&self, gpa: u64, len: u32) -> Option<GuestSlice>;
}
pub enum Malformed { BadIndex, TooLong, WritableBeforeReadable, Unmappable, Indirect, AheadOfTable }
pub struct Virtq<M: GuestMemory> { // struct virtq
num: u16, desc: u64, avail: u64, used: u64, // guest-physical, not pointers
last_avail: Wrapping<u16>,
next_used: Wrapping<u16>, // the private copy of used.idx
mem: M,
}
impl<M: GuestMemory> Virtq<M> {
pub fn pop(&mut self) -> Result<Option<Chain>, Malformed>; // 1, 0, -1
pub fn push(&mut self, head: u16, written: u32);
}
The return code 1, 0 and -1 becomes Ok(Some), Ok(None) and Err, with the reason the C had to leave out as a variant for each of the six refusals in virtq.h. The function pointer and its context become a trait. The ring addresses stay guest-physical numbers in the struct, which is a change from the C: every access goes through translate, and a Rust ring that held raw pointers would have the same hostile-driver surface with more ways to keep it. GuestSlice is a type that cannot be a plain &[u8], because the guest can change the bytes under any reference that outlives the next instruction: it is a pointer and a length whose accessors are volatile reads and writes, which is the role the single-load rule plays in the C. last_avail and next_used are Wrapping<u16> so that the free-running counter’s wrap is the type’s, not the programmer’s. The atomics in pop and push stay as they are, an acquire load of avail.idx and a release store of used.idx, on the guest memory the GuestMemory hands back. Where the C’s block backend validated “exactly three segments”, this signature validates nothing about arrangement and leaves it to the device above it, which is where §2.7.4.1’s gather belongs.
Lab
make lab CH=22
make lab CH=22 IMPL=mine
make -C labs/ch22 stress
labs/ch22/Makefile is chapter 21’s with these additions. A harness step compiles harness.c and the chosen virtq.c with the host’s cc -O2 -Wall -Wextra -std=c11 and runs it, and the run does not stop on its failure, so that an IMPL=mine diff shows both halves. A guest step builds guest/start.S and guest/blk.c with -march=rv64ima_zicsr -mabi=lp64 -nostdlib -ffreestanding -mcmodel=medany -mno-relax -O2, links them with guest/link.ld and extracts .text, .rodata and .data into overlay/guest.bin. The VMM is compiled with the chosen virtq.c, and overlay/init runs /vmm /guest.bin. The kernel, BusyBox and kernel headers come from chapter 20’s build script and its hp/ch20 cache, as in chapter 21, so a host that has run chapter 20 builds nothing new. The captured run is the harness’s six lines followed by the sentinel section of the boot.
IMPL=mine swaps in mine/virtq.c, where virtq_pop is the part to write: it sets virtq_mine_stub and returns -1. The backend cannot print, so the harness and the VMM do, once each, when they see -1 with the flag set; the reference never prints that line. The harness stops at its first check. In the VM the VMM’s virtq_pop returns -1, the VMM prints the line and marks the device DEVICE_NEEDS_RESET, and the guest, which polls used.idx, never leaves its loop. The run ends when timeout ends QEMU, after TIMEOUT seconds (180), and the diff is:
-harness: empty queue pops 0
-harness: 3-seg read chain: head 0 segs 3 ro,wo,wo
-harness: push used idx 1 id 0 len 513
-harness: wrap: 20 chains, last_avail 20, used idx 20
-harness: malformed wo,ro refused
-harness: PASS
+MINE: virtq_pop stub
+harness: FAIL: empty queue: pop did not return 0
=== lab begin
...
guest: capacity 0x10
-guest: status 0x0
-guest: used len 0x201
...
+MINE: virtq_pop stub
+qemu-system-riscv64: terminating on signal 15 from pid 4107609 (timeout)
(the head and tail of the diff of capture.txt against the run on straylight; the lines between are the guest’s remaining output and the VMM’s summary, absent in the mine run, and the process id in the last line is that run’s). Writing virtq_pop is the lab.
With the reference the capture is:
harness: empty queue pops 0
harness: 3-seg read chain: head 0 segs 3 ro,wo,wo
harness: push used idx 1 id 0 len 513
harness: wrap: 20 chains, last_avail 20, used idx 20
harness: malformed wo,ro refused
harness: PASS
=== lab begin
/dev/kvm
vmm: KVM_GET_API_VERSION 12
vmm: memory slot 0: 0x200000 bytes at gpa 0x80000000
vmm: guest loaded at gpa 0x80000000
vmm: pc=0x80000000 mode=S
guest: MagicValue 0x74726976
guest: Version 0x2
guest: DeviceID 0x2
guest: DeviceFeatures[1] 0x1
guest: Status 0xb
guest: QueueNumMax 0x8
guest: capacity 0x10
guest: status 0x0
guest: used len 0x201
guest: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
guest: InterruptStatus 0x1
vmm: KVM_RUN exit 24 (KVM_EXIT_SYSTEM_EVENT) type 1 (SHUTDOWN) ndata 1
vmm: mmio exits 613
vmm: requests served 1
vmm: PASS
vmm rc=0
=== lab end
The 613 was observed before it was explained, and exercise (e) is the explanation. The harness is the contract and its six lines open the capture; the boot lines are the proof that the contract is enough to read a sector in a guest that did not share a line of code with the backend. Sector 0’s bytes are the formula (s * 7 + i) & 0xff at s = 0, and the capture does not print a ring address, a pointer or the guest image’s size, none of which is a property of the protocol. A make lab CH=22 took 20.2 seconds of wall time on talos and 10.9 seconds on straylight (14.9 for the run after a source edit), both with chapter 20’s kernel cached; the IMPL=mine run on straylight took 189.8 seconds, the 180 of the timeout and the build. The run on talos and two runs on straylight are byte-identical to capture.txt.
Further reading
- Virtual I/O Device (VIRTIO) Version 1.2 (OASIS Committee Specification 01, July 2022): §2.7 (split virtqueues; §2.7.4.2, §2.7.5.1, §2.7.8.2, §2.7.13.3.1 for the rules this chapter’s code enforces), §3.1.1 (device initialization), §4.2.2 and §4.2.3 (the MMIO register table and its driver requirements), §5.2 (the block device; §5.2.6 for the request), §6 (reserved feature bits).
ember/virtio.cin this repository and chapter 11: the driver’s half of the same protocol, in the same register names.rust-vmm/vm-virtioand itsvirtio-queuecrate: the Rust implementation of the split-queue device side thatwickmay read and need not depend on; itsDescriptorChainandQueueare the shapes exercise (f) designs toward.