11. A block device
Why this layer exists
Everything the kernel stores lives in DRAM and dies with the power. A file system needs a device that keeps bytes, and a device that keeps bytes is the first one the kernel cannot politely poll forever: a disk takes time, the request has to be handed off and the answer collected later, and the collecting is an interrupt. That is the mechanical reason. The reason this book cares is the other one: until now ember owned the machine. From this chapter it is a guest — it asks a device it did not write, does not control and cannot see inside for service, through a contract it has to honor exactly, and the thing on the other side of that contract is QEMU. In chapter 22 the contract is taught in full and the backend is written once; in chapter 36 hearth serves it to guests. Standing on the driver side first is how the reader learns what the other side owes.
The contract is virtio: a device model designed so that a guest and a host that never share code can share a ring of buffers. This chapter uses the subset one synchronous request needs and says where it stops.
Mechanism
Finding a device with no bus to ask
A virtqueue is a ring of buffer descriptors in guest memory that a driver fills and a device drains (or the reverse), with an index on each side saying how far it has got; it is the one data structure virtio is built on, and the split layout this chapter uses is the original of the two the spec defines. Before there is a queue there has to be a device, and on this board there is no bus that enumerates devices. There are eight windows of MMIO at 0x10001000, 0x10002000, … 0x10008000, each a possible virtio transport, and the only way to know what is behind one is to look.
Looking is safe because of a magic value. The first register in every virtio-mmio window reads 0x74726976 — the bytes v, i, r, t in little-endian order — and a window that does not read that is not virtio. The second, Version, must read 2 for the modern transport; the third, DeviceID, names the device type, 2 for block, and 0 for a placeholder the spec says to skip without complaint. The driver maps the eight pages (Part I mapped none of the virtio windows), walks them, and stops at the first block device:
static void blk_probe(void)
{
unsigned long pa;
int i;
/* The windows are MMIO the kernel has not mapped until now. */
for (pa = VIRTIO_BASE; pa < VIRTIO_BASE + VIRTIO_COUNT * VIRTIO_STEP;
pa += VIRTIO_STEP)
map_page(pa, pa, PTE_R | PTE_W);
__asm__ volatile("sfence.vma" ::: "memory");
/* 4.2.3.1.1: MagicValue and Version first; DeviceID 0 is a
* placeholder to be ignored without an error. */
for (i = 0; i < VIRTIO_COUNT; i++) {
base = VIRTIO_BASE + (unsigned long)i * VIRTIO_STEP;
if (rd(R_MAGIC) != MAGIC_VIRT)
continue;
if (rd(R_DEVICE_ID) != DEVICE_ID_BLOCK)
continue;
if (rd(R_VERSION) != 2) {
uart_puts("S: blk: legacy transport\r\n");
halt(1); /* the lab passes force-legacy=false; see board facts */
}
blk_irq = (unsigned)(i + 1); /* DTB: interrupts = <n+1> */
uart_puts("S: blk: virtio-mmio at ");
uart_puthex(base);
uart_puts(" irq=");
uart_puthex(blk_irq);
uart_puts(" version=");
uart_puthex(rd(R_VERSION));
uart_puts(" device=");
uart_puthex(rd(R_DEVICE_ID));
uart_puts("\r\n");
return;
}
uart_puts("S: blk: no blk device\r\n");
halt(1);
}
Two facts about this board fall out of the walk, and both are the kind that must be observed rather than remembered. The device is at the eighth window, 0x10008000, not the first: QEMU attaches -device instances to its transports from the top, and the board’s device tree lists the eight virtio_mmio@ nodes in descending order for exactly that reason. And its interrupt line is PLIC source 8, because the device tree says interrupts = <0x08> for that node and <0x01> for the lowest — the eight windows are sources 1 through 8, in address order, which is what the driver’s blk_irq = i + 1 encodes. Chapter 2’s dumpdtb exercise is where a reader confirms both.
The version check has teeth. This QEMU’s virtio-mmio transport is legacy by default: Version reads 1, the modern feature bit is not offered, and the queue is programmed through registers the modern spec does not have. The lab passes -global virtio-mmio.force-legacy=false, and a driver that sees Version 1 anyway prints legacy transport and stops rather than speaking a dialect this chapter did not freeze.
Negotiation is a version handshake
A virtio device offers every feature it understands; the driver answers with the subset it accepts; nothing outside that subset exists for the rest of the conversation. The handshake is carried in the Status register as a sequence of bits the driver sets and never clears: ACKNOWLEDGE (1, “I see a virtio device”), DRIVER (2, “I know how to drive this kind”), then the features, then FEATURES_OK (8), then DRIVER_OK (4). Writing 0 resets the device; FAILED (128) is how the driver gives up.
static void blk_negotiate(void)
{
unsigned int feat_hi;
/* 3.1.1: reset, ACKNOWLEDGE, DRIVER, then features. */
wr(R_STATUS, 0);
wr(R_STATUS, S_ACKNOWLEDGE);
wr(R_STATUS, S_ACKNOWLEDGE | S_DRIVER);
/* Read the word that holds bit 32. A modern device MUST offer
* VIRTIO_F_VERSION_1 (6.2); a driver MUST accept it (6.1). Nothing
* else is written back: a bit the driver never negotiated is a
* promise it never made. */
wr(R_DEV_FEAT_SEL, F_VERSION_1_WORD);
feat_hi = rd(R_DEV_FEATURES);
if (!(feat_hi & F_VERSION_1_BIT)) {
wr(R_STATUS, S_FAILED);
uart_puts("S: blk: VERSION_1 not offered\r\n");
halt(1);
}
wr(R_DRV_FEAT_SEL, F_VERSION_1_WORD);
wr(R_DRV_FEATURES, F_VERSION_1_BIT);
wr(R_DRV_FEAT_SEL, 0);
wr(R_DRV_FEATURES, 0);
/* FEATURES_OK, then read it back: a device that rejects the subset
* clears the bit (2.2.2), and the driver must notice. */
wr(R_STATUS, S_ACKNOWLEDGE | S_DRIVER | S_FEATURES_OK);
if (!(rd(R_STATUS) & S_FEATURES_OK)) {
wr(R_STATUS, S_FAILED);
uart_puts("S: blk: FEATURES_OK refused\r\n");
halt(1);
}
uart_puts("S: blk: VERSION_1 offered and accepted; "
"every other feature declined\r\n");
}
Features are 64 bits, read 32 at a time through a select register. Bits 0–23 belong to the device type, 24–40 to the transport and queue machinery, and one of them is the whole point of the modern interface: VIRTIO_F_VERSION_1, bit 32, which a modern device MUST offer and a driver MUST accept. This driver accepts it and nothing else. That is not laziness; it is the rule the spec states as “MUST NOT accept a feature which the device did not offer” read from the other end — a bit the driver never wrote back is a promise it never made, and every feature it declined is a field in the configuration space or a request type it is not entitled to assume. Observed on this QEMU, the device offers 0x30006e54 in the low word and 0x101 in the high: SEG_MAX, GEOMETRY, BLK_SIZE, FLUSH, TOPOLOGY, CONFIG_WCE, DISCARD, WRITE_ZEROES, and the transport’s INDIRECT_DESC and EVENT_IDX; VERSION_1 and RING_RESET above 32. Ten of those would each have changed what the device expects or what the driver may read. All are declined, and exercise (e) names which one would have added geometry.
FEATURES_OK is written and then read back. A device that cannot live with the subset clears the bit, and a driver that does not look would proceed on a negotiation that failed. Exercise (a) skips the step and finds QEMU forgiving; the spec allows a device not to be.
The ring: three tables and who writes which
static void blk_queue(void)
{
unsigned long ring = kalloc_page(); /* zeroed: used.flags = 0 (2.7.10.1) */
unsigned long bufs = kalloc_page();
if (!ring || !bufs)
halt(1);
desc = (volatile struct virtq_desc *)ring; /* +0x000 */
avail = (volatile struct virtq_avail *)(ring + 0x080); /* 16-byte descs end at 0x80 */
used = (volatile struct virtq_used *)(ring + 0x100);
req = (volatile struct blk_req *)bufs;
req_status = (volatile unsigned char *)(bufs + 0x10);
data = (volatile unsigned char *)kalloc_page();
if (!data)
halt(1);
/* 4.2.3.2, in the spec's order. The addresses are physical: the
* device walks no page table, and these pages are identity-mapped
* kernel memory, so the kernel's pointer and the device's address
* are the same number. That coincidence is the whole of Part IV's
* shared-memory problem, seen from the easy side. */
wr(R_QUEUE_SEL, 0);
if (rd(R_QUEUE_READY) != 0)
halt(1);
if (rd(R_QUEUE_NUM_MAX) < QNUM) {
uart_puts("S: blk: queue too small\r\n");
halt(1);
}
wr(R_QUEUE_NUM, QNUM);
wr(R_QUEUE_DESC_LO, (unsigned int)ring);
wr(R_QUEUE_DESC_HI, (unsigned int)(ring >> 32));
wr(R_QUEUE_DRV_LO, (unsigned int)(ring + 0x080));
wr(R_QUEUE_DRV_HI, (unsigned int)((ring + 0x080) >> 32));
wr(R_QUEUE_DEV_LO, (unsigned int)(ring + 0x100));
wr(R_QUEUE_DEV_HI, (unsigned int)((ring + 0x100) >> 32));
wr(R_QUEUE_READY, 1);
}
The split virtqueue is three arrays. The descriptor table — sixteen bytes per entry: a 64-bit address, a 32-bit length, flags, and a next index — describes buffers, and only the driver writes it. The available ring — a flags word, a free-running 16-bit idx, and a ring of descriptor-chain heads — is how the driver offers chains to the device, and only the driver writes it. The used ring — flags, idx, and a ring of {id, len} pairs — is how the device returns them, and only the device writes it. The ownership is the protocol: each side writes what it owns, reads what the other owns, and the two indices say how far each has got. The queue size is a power of two the driver chooses under the device’s QueueNumMax; this driver picks 8 and puts all three arrays in one page — descriptors at offset 0 (8 × 16 bytes ends at 0x80), the available ring at 0x80, the used ring at 0x100 — then hands the device the three physical addresses and writes 1 to QueueReady, in the order the spec lists. The page came from kalloc_page, so it is zeroed, which is how the used ring’s flags start at 0 as the spec requires.
Every address is physical
The device walks no page table. When it reads descriptor 1 and finds an address, it reads or writes memory at that address on the bus — not through satp, not through anything. Every pointer the driver puts in a descriptor, and every address it writes to the queue registers, is a physical address, and it had better be one the device can reach. On this kernel that is invisible: the ring and the buffers are kalloc pages, identity-mapped U=0, so the kernel’s pointer and the device’s address are the same number, and the driver writes (unsigned long)ring into a register without a translation. Exercise (b) puts a virtual address there instead and shows what “success” looks like when the device writes somewhere else.
This coincidence is the seed of everything Part IV does with shared memory. A guest under hearth will fill a ring with addresses that are physical to the guest and not to the machine; the hypervisor will have to translate them through the G-stage table (chapter 19) before it can touch a byte, or refuse — and the spec has a feature bit for exactly that distinction, VIRTIO_F_ACCESS_PLATFORM (33), “the device’s access to memory is limited and/or translated,” which this device does not offer and this driver would not know what to do with. Chapter 36 is where that bit stops being a footnote.
A request, end to end
A block request is a chain of three descriptors, in the order the spec requires — every device-readable element before every device-writable one. The first is a 16-byte header the device reads: type (VIRTIO_BLK_T_IN = 0 for read, _OUT = 1 for write), a reserved word, and the sector number. The second is the 512-byte data buffer, marked device-writable for a read. The third is a single status byte the device writes: 0 for OK, 1 for an I/O error, 2 for unsupported.
/* One request, one chain of three: the header the device reads, one
* sector it reads or writes, the status byte it writes (2.7.4.2: every
* device-writable element after every device-readable one). */
static void blk_op(unsigned int type, unsigned long lba)
{
if (lba >= capacity) {
uart_puts("S: blk: lba past capacity\r\n");
halt(1); /* 5.2.6.1: never submit beyond capacity */
}
req->type = type;
req->reserved = 0;
req->sector = lba;
*req_status = 0xff; /* a value the device cannot leave behind */
desc[0].addr = (unsigned long)req;
desc[0].len = sizeof(struct blk_req);
desc[0].flags = D_NEXT;
desc[0].next = 1;
desc[1].addr = (unsigned long)data;
desc[1].len = BLK_SECTOR;
desc[1].flags = (unsigned short)(D_NEXT | (type == T_IN ? D_WRITE : 0));
desc[1].next = 2;
desc[2].addr = (unsigned long)req_status;
desc[2].len = 1;
desc[2].flags = D_WRITE;
desc[2].next = 0;
/* 2.7.13: place the head, barrier, bump idx, barrier, notify. */
avail->ring[avail->idx % QNUM] = 0;
fence();
avail->idx++;
fence();
wr(R_QUEUE_NOTIFY, 0); /* 4.2.3.3: the queue index */
blk_wait();
}
void blk_read(unsigned long lba, void *buf)
{
unsigned long i;
blk_op(T_IN, lba);
for (i = 0; i < BLK_SECTOR; i++)
((unsigned char *)buf)[i] = data[i];
}
void blk_write(unsigned long lba, const void *buf)
{
unsigned long i;
for (i = 0; i < BLK_SECTOR; i++)
data[i] = ((const unsigned char *)buf)[i];
blk_op(T_OUT, lba);
}
Then the driver’s side of 2.7.13: put the head index in the available ring, a memory barrier so the device sees the descriptors before the index, bump idx, another barrier, and ring the doorbell — a write of the queue number to QueueNotify, which is an MMIO store and therefore the one moment the driver’s world and the device’s touch. The status byte is preset to 0xff, a value the device cannot leave behind, so a completion that never wrote it is caught.
/* 4.2.3.4.1: read InterruptStatus, handle, acknowledge the same bits.
* Called from the S trap handler when the PLIC delivers our source,
* and from blk_wait after a wfi — idempotent, so either may be first. */
void blk_intr(void)
{
unsigned int st = rd(R_INT_STATUS);
if (!st)
return;
wr(R_INT_ACK, st);
#if HP_CH == 11
if (st & 1)
uart_puts("S: blk: interrupt\r\n");
#endif
}
static void blk_wait(void)
{
/* The device wrote used.idx before raising the line (2.7.8.2). The
* hart sleeps in wfi; wfi resumes on a pending, enabled interrupt
* whether or not sstatus.SIE lets the trap be taken, so the loop
* also polls the acknowledge path. */
while (used->idx == last_used) {
__asm__ volatile("wfi");
blk_intr();
}
fence();
if (used->ring[last_used % QNUM].id != 0) {
uart_puts("S: blk: unexpected used id\r\n");
halt(1);
}
last_used++;
if (*req_status != S_OK) {
uart_puts("S: blk: status ");
uart_puthex(*req_status);
uart_puts("\r\n");
halt(1);
}
}
The device, when it is done, writes the status, writes {id, len} into the used ring, bumps the used idx — in that order, the spec says, so a driver that sees the index can trust the rest — and raises its line. The line is PLIC source 8; chapter 5’s handler claims it and now calls blk_intr, which reads InterruptStatus, acknowledges the same bits into InterruptACK, and (in this chapter’s image) says so. The driver, meanwhile, has been in wfi. Two details of the wait are deliberate. wfi resumes on a pending, enabled interrupt whether or not sstatus.SIE would let the trap be taken — the spec says the global enable does not affect it — so in a later chapter where the kernel runs with interrupts masked, the loop still wakes; and because it might wake without the handler having run, the loop calls blk_intr itself, which is idempotent, so either path may be first. Under QEMU the device completes the request inside the doorbell write, the interrupt is taken on the very next instruction, and the transcript shows S: blk: interrupt before each ok — the same order every run.
One at a time, on purpose
This driver submits one request, waits for it, and only then submits the next; the ring never holds more than one chain, last_used only ever counts by one, and the queue could have been size 1. That is the subset one synchronous path needs and not a model of a real driver, which keeps the ring full and matches completions to requests by id. Chapter 22 builds the protocol in full, on the other side; chapter 12’s file system is the only caller this driver has, and it asks for one sector at a time.
mem_init();
trap_init();
uart_puts("S: kernel up\r\n");
kalloc_init();
blk_init(); /* probe, negotiate, one queue, DRIVER_OK */
blk_lab(); /* read, write, read back; constants in, constants out */
uart_puts("PASS\r\n");
halt(0);
No process runs in this chapter — the kernel is the only client — so the boot stage is the probe, the negotiation, the queue, and a check: read a sector of the pattern mkdisk.c wrote, write a different pattern to another sector, read it back. Constants in, constants out.
Walkthrough
ch11-main (the stage), ch11-probe (the windows, the magic, the version, the eighth slot and its source), ch11-negotiate (the status sequence, bit 32, the read-back), ch11-ring (three tables in one page, physical addresses in the registers, the spec’s order), ch11-submit (a three-descriptor chain, barriers, the doorbell), ch11-complete (the acknowledge path, wfi, the used ring, the status byte).
Exercises
(a) Skip FEATURES_OK — go from DRIVER straight to DRIVER_OK. Predict which devices tolerate it, then run it.
Answer
QEMU tolerates it: the run is unchanged, every sector reads and writes correctly. The spec does not promise that. FEATURES_OK is the device’s one chance to say the subset is unacceptable — “otherwise it MUST fail to set the FEATURES_OK device status bit” — and a device that never sees the bit written has no moment at which to refuse; whether it then serves requests or ignores them is up to the device. A strict device, or a hypervisor written to the spec (chapter 36’s hearth will be), can reasonably treat DRIVER_OK without FEATURES_OK as a broken driver. This driver does the step, and reads the bit back, because “QEMU lets it slide” is not a property of the protocol.
(b) Put a virtual address in the data descriptor — 0x40000000 plus the buffer’s page offset, Part I’s second mapping of a kernel page — and read a sector. Derive what the device does, then run it.
Answer
The device does not know it is a virtual address; there is no such thing on its side of the line. It writes 512 bytes to physical 0x40000000, which on this board is not DRAM and not a device, so the bytes go nowhere; it writes status 0 — from its point of view the transfer happened — and the used ring, and raises the line. The driver sees a completed request with VIRTIO_BLK_S_OK, copies its untouched buffer, and the check fails on the first byte: S: blk: read lba 0x7 MISMATCH at 0x0. Observed. Nothing faulted, because a device DMA is not a load or a store the MMU sees; the only thing that noticed was the driver’s own comparison. That silence is why VIRTIO_F_ACCESS_PLATFORM and an IOMMU exist, and why chapter 36 has to translate every guest-physical address before a real device sees it.
(c) Busy-wait on the used ring with the external interrupt masked — no SEIE, no wfi, just a loop. Does it work? Compute what it costs.
Answer
It works: the loop reads used.idx, the device has already bumped it inside the doorbell write, and every check passes. Observed — with one visible change: the S: blk: interrupt lines move. With the trap never taken, the acknowledge happens only when the next request’s wait loop polls, so each request’s interrupt is acknowledged one request late and the last one never; the device’s line stays asserted at the PLIC with nobody to claim it. The cost is what the hart does while it waits: every cycle, on a real disk for milliseconds per request, on a hart that could have run a process instead — and a device that needs the acknowledge to raise the next interrupt eventually stalls behind an unacknowledged one. The interrupt path costs a trap per request and buys every cycle in between, which is the same arithmetic chapter 5 did for the UART with a keyboard on the other end.
(d) Read two sectors: once as two chains of three, once as one chain of four (header, data, data, status). Do the ring arithmetic.
Answer
Two chains: six descriptors of the eight, two heads in the available ring, idx advanced by two, two used entries, two interrupts (or one, if the device coalesces). One chain: four descriptors, one head, idx by one, one used entry whose len is 1025 (two sectors plus the status byte), one interrupt. Both are legal — the spec says the device “MUST NOT make assumptions about the particular arrangement of descriptors” — and the header’s sector number is the start of a contiguous run either way, so the one-chain form is a two-sector read, not two reads. The driver’s last_used, which counts by one, would have to count completions rather than requests to handle the first form with both chains in flight; that is the bookkeeping this chapter declined and chapter 22 owns.
(e) Which declined feature would have added geometry to the configuration space, and what did the driver correctly refuse to assume?
Answer
VIRTIO_BLK_F_GEOMETRY, bit 4, which the device offers (0x30006e54 has it). Negotiated, it makes the cylinders/heads/sectors struct in virtio_blk_config meaningful; declined, those bytes are present but mean nothing, and reading them is reading noise. The driver reads exactly one configuration field, capacity, because the spec says it “is always present” — every other field is conditional on a bit, and the driver holds none. The same discipline applies to BLK_SIZE (bit 6, also offered): without it the sector is 512 bytes by the protocol’s definition, and the driver assumes nothing finer. Declining a feature is not just declining a capability; it is declining to read the fields that come with it.
(f) Name the chapter 22 moment: what changes when ember is on the other side of this ring?
Answer
Every “the device” in this chapter becomes “we.” The backend reads the descriptor table it did not write, follows next through a chain it must not trust (a loop, an address outside the guest, a length past the buffer), translates each address from guest-physical to something it can touch — in wick a host pointer into the guest’s mapped memory, in hearth a G-stage walk — performs the transfer, writes the status byte and the used entry in that order, and raises an interrupt it now has to inject rather than receive. The magic value, the version, the feature bits and FEATURES_OK are things it must present and enforce rather than check. Same three tables, same indices, same doorbell; the only thing that moved is which side of the dashed line the reader’s code is on.
Lab
make lab CH=11
make lab CH=11 IMPL=mine
labs/ch11/extra.mk adds two things to the QEMU line: -global virtio-mmio.force-legacy=false, without which the device would present the legacy transport and the driver would stop at legacy transport; and -drive file=disk.img,format=raw,if=none,id=hd0 -device virtio-blk-device,drive=hd0. disk.img is generated, never committed: mkdisk.c writes 2048 sectors in which byte i of sector s is (s + i) & 0xff, and a rebuilt image is byte-identical to the last one — determinism of the image is part of the acceptance.
After the boot lines: S: blk: virtio-mmio at 0x10008000 irq=0x8 version=0x2 device=0x2, the probe’s finding; the negotiation line; S: blk: capacity=0x800 sectors, queue 0 size=0x8 — 2048 sectors is the image’s size, the queue size is the driver’s choice; then three pairs of S: blk: interrupt and an ok: the read of sector 7 against the pattern, the write of sector 9, and the read-back of sector 9 against what was written; PASS. The window address and the source number are this board’s, from the device tree; the capacity is the image’s; nothing is a clock.
IMPL=mine copies exactly the objects chapter 11 links and stubs blk_init to print MINE: blk_init stub and halt: the lab boots and fails before any probe line.
Further reading
- Virtual I/O Device (VIRTIO) Version 1.2, Committee Specification 01 (OASIS, July 2022) — every constant in this chapter: §2.1 device status, §2.2 feature bits, §2.7 split virtqueues, §4.2.2 the MMIO register layout, §4.2.3 MMIO initialization, §5.2 the block device, §6 reserved feature bits (
VIRTIO_F_VERSION_1,VIRTIO_F_ACCESS_PLATFORM). The PDF edition has the same text with page numbers. - xv6-riscv (MIT PDOS) —
kernel/virtio_disk.cis the same driver with the ring kept full and completions matched byid, and itsMakefilepasses the sameforce-legacy=false.