25. Block, net, vsock
Why this layer exists
Chapter 24’s guest printed three lines on a serial port and ended itself. A guest that has only a console is a demonstration: it keeps nothing, it cannot be reached, and nothing outside it can tell it what to do. A workload needs somewhere to keep state, a way to talk to other machines, and a channel its host can use without a network between them. Those are a block device, a network device and a socket device, and the surprise of this chapter is that they are one protocol. Chapter 22 wrote the ring once, in C, and put one block device on it. Here the same ring carries a disk, an Ethernet interface and a stream socket; what changes is the contract about what the buffers hold and what the host does with them. wick fronts all three with one transport, the virtio-mmio register file of chapter 22 written in Rust, and the figure draws that: one ring, three fronts, and under each front the thing on the host that backs it.
The pieces reappear. Chapter 36 serves this protocol again with no host kernel under it: the ring code is the same, and the backends are not a file, a TAP and a Unix socket but whatever hearth can reach with no operating system to ask. Chapter 45’s ward talks to the guests of wick over this chapter’s vsock, and the syllabus’s note on this chapter says what hearth will do instead, because it has no Unix socket: the same protocol rides virtio-console or a vsock device the hypervisor itself backs. The lab boots wick four times: with the block device alone, the network device alone, the socket device alone, and with all three in one guest, after the six lines chapter 22’s harness prints. The code this chapter explains is 4,218 lines of Rust and 8,043 lines of tests that pin them: 2,662 of unit-test lines in the same files and 5,381 in the eleven device test and helper files of wick/tests/ (wc -l and awk, comments and blank lines included, talos, 2026-10-04; the same files hold chapter 27’s save and restore of the transport and the devices). Run in wick/:
awk 'FNR==1{t=0} /^#\[cfg\(test\)\]/{t=1} {if(t) u++; else c++} END{print "code", c, "unit-test", u}' src/mmio.rs src/devices/*.rs src/devices/vsock/*.rs
cat tests/ch22_contract.rs tests/hostile.rs tests/hostile_indirect.rs tests/ioevent.rs tests/net_tap.rs tests/restart.rs tests/vsock.rs tests/vsock_credit.rs tests/vsock_shutdown.rs tests/ring/mod.rs tests/vsockw/mod.rs | wc -l
The first prints 4218 and 2662, the second 5381 (the other files of wick/tests/, the API and boot tests and their guests, are not counted). The tests are twice the size of the code because most of the code reads input a guest controls, and a parser of untrusted input is not finished when it works.
Mechanism
Sources: the Linux tree at tag v7.2.8 (the guest’s drivers, and the host kernel interfaces wick calls, read at that tag); the crates at the versions wick/Cargo.lock pins (virtio-queue 0.18.0, virtio-vsock 0.12.0, virtio-bindings 0.2.7, vm-memory 0.18.0, kvm-ioctls 0.25.0); Firecracker at tag v1.15.1 (docs/vsock.md and src/vmm/src/devices/virtio/vsock/csm/connection.rs, fetched 2026-10-02); and the virtio 1.2 specification, committee specification 01, from https://docs.oasis-open.org/virtio/virtio/v1.2/cs01/virtio-v1.2-cs01.pdf (fetched 2026-10-02; page numbers are the PDF’s own). Kernel, crate and Firecracker blocks are re-extracted with sed -n and headed with their file and lines; specification sentences are quoted with their section and page.
The transport on x86
On the RISC-V virt machine of chapters 11 and 22 the guest found its virtio-mmio windows in the device tree QEMU handed it. A wick guest has no device tree, and, as chapter 24 settled, no ACPI and no MP table: there is no bus to enumerate and no firmware table to read. The windows go on the kernel command line, which the Linux driver parses:
// linux v7.2.8, drivers/virtio/virtio_mmio.c:39-50
* 3. Kernel module (or command line) parameter. Can be used more than once -
* one device will be created for each one. Syntax:
*
* [virtio_mmio.]device=<size>@<baseaddr>:<irq>[:<id>]
* where:
* <size> := size (can use standard suffixes like K, M or G)
* <baseaddr> := physical base address
* <irq> := interrupt number (as passed to request_irq())
* <id> := (optional) platform device id
* eg.:
* virtio_mmio.device=0x100@0x100b0000:48 \
* virtio_mmio.device=1K@0x1001e000:74
wick appends one virtio_mmio.device=4K@<base>:<irq> entry per device, in a fixed order: drives, in the order they were put, then network interfaces, then the vsock device. Window i is at 0xd0000000 + i * 0x1000 on GSI 5 + i (chapter 23’s: KVM’s global interrupt numbers, of which the PIC delivers 0 to 15, chapter 24), so the first eleven numbers after the serial port’s 4 are all a guest can have: at most eleven devices (MAX_DEVICES, devices/attach.rs). That is a property of this machine, not of virtio: a guest with an IOAPIC could have far more lines. What the guest of the lab’s last boot reports of itself, from a scratch init that prints it (talos, 2026-10-02; the run is kept outside the repository):
cmdline virtio_mmio.device=4K@0xd0000000:5
cmdline virtio_mmio.device=4K@0xd0001000:6
cmdline virtio_mmio.device=4K@0xd0002000:7
5: 1 XT-PIC virtio0
6: 0 XT-PIC virtio1
7: 0 XT-PIC virtio2
virtio0 device 0x0002 vendor 0x4b434957 status 0x0000000f
virtio0 features 00000000010000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
virtio1 device 0x0001 vendor 0x4b434957 status 0x0000000f
virtio1 features 00000100000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
virtio2 device 0x0013 vendor 0x4b434957 status 0x0000000f
virtio2 features 00000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
eth0 mac 06:00:ac:10:00:02 mtu 1500
vda size 16 logical_block_size 512 max_sectors_kb 4096 nr_requests 128
vda stat 1 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0
vda max_hw_sectors_kb 2147483647
The three lines that begin with a number are /proc/interrupts: each device’s line is XT-PIC, the PIC, and only the first has a count (one interrupt: the block device completing the read the kernel makes when it probes a new disk, which the vda stat line records as one read of 8 sectors; the other two devices had no traffic). The device values are the specification’s device types: 2 is block, 1 network and 0x13 (19) socket; the vendor is the four bytes WICK.
Chapter 22 gave the register table and the order a driver walks it in; this transport adds rules a model that is attacked has to keep, each from §4.2.2.2 or §3.1.1 and each a counted refusal rather than an error (MmioCounts, mmio.rs). Registers are 32 bits wide, and any other width reads 0 and is counted. A queue’s size and addresses are frozen while the queue is ready: “When QueueReady is not zero, the driver MUST NOT access QueueNum, QueueDescLow, QueueDescHigh, QueueDriverLow, QueueDriverHigh, QueueDeviceLow, QueueDeviceHigh” (§4.2.2.2, p. 65), and so the transport refuses the writes, and checks every ready queue again when DRIVER_OK arrives, because a check made at QueueReady is a check of what was written then: the queue must still be valid (Queue::is_valid, the addresses and size inside guest memory) and its three rings must still be apart (rings_overlap, mmio.rs:427, called at :467 and :525). An address counts as written by its low half; a low half that is not aligned (16 for the descriptor table, 2 for the available ring, 4 for the used ring) is refused, because the crate’s setter would keep the old address and say nothing, and the queue could then become ready on an address the driver never wrote. A queue with a ring at guest address 0 is refused at QueueReady too: virtio-queue treats an available ring at 0 as a queue that is not ready (queue.rs:589) and serves nothing, so such a queue would read back ready and be inert. The crate does not treat the descriptor table or the used ring at 0 that way, and the transport refuses all three alike, since no ring of a real driver is there. Writing 0 to QueueReady of a live queue is honoured (“To stop using the queue the driver MUST write zero (0x0) to this QueueReady and MUST read the value back to ensure synchronization”, the same page): the transport clears the flag and calls the device’s queue_stop, which a device that fills a queue without a doorbell (a network receive queue, a vsock receive queue) must obey, since the driver may free those rings next. FEATURES_OK stays set only if the driver’s accepted features are a subset of the device’s and include VIRTIO_F_VERSION_1, and when it sticks the device is told what was accepted (ack_features), because a device may have to behave by it (the block device does); after a failed activation the device is NEEDS_RESET and a DRIVER_OK is ignored until a reset; and DriverFeatures writes are refused once FEATURES_OK is set. Config space is the one place the width rule bends. The Linux driver reads a network device’s MAC one byte at a time: drivers/net/virtio_net.c:6854 calls virtio_cread_bytes (include/linux/virtio_config.h:595-599, element size 1), and vm_get (drivers/virtio/virtio_mmio.c:137-177) turns each element into a readb for a version-2 device. So the network device’s read_config answers any width at any offset. The 8-byte capacity of a block device and the 8-byte CID of a vsock device are different: vm_get’s case 8 reads them as two aligned 32-bit loads, and the block device keeps chapter 22’s ruling and answers 32-bit aligned reads only.
The doorbell is where this transport leaves chapter 22’s. There a guest write to QueueNotify was an MMIO exit, KVM_RUN returned to the VMM, and the VMM drained the ring before the next KVM_RUN. That costs a trip through the kernel and back for every request. KVM has a second way to deliver the same write, an ioeventfd, which is new vocabulary here and the mirror of chapter 24’s irqfd:
// linux v7.2.8, Documentation/virt/kvm/api.rst:2093-2104
4.59 KVM_IOEVENTFD
------------------
:Capability: KVM_CAP_IOEVENTFD
:Architectures: all
:Type: vm ioctl
:Parameters: struct kvm_ioeventfd (in)
:Returns: 0 on success, !0 on error
This ioctl attaches or detaches an ioeventfd to a legal pio/mmio address
within the guest. A guest write in the registered address will signal the
provided event instead of triggering an exit.
The VMM creates an eventfd per queue and registers it for the address of QueueNotify in the device’s window, with the queue’s index as the datamatch value, so that a 32-bit write of 0 to that address signals queue 0’s eventfd inside KVM and the guest never leaves guest mode. kvm-ioctls turns the type of the datamatch argument into the access width (register_ioevent, src/ioctls/vm.rs:816-840: len is size_of::<T>(), and a u32 is 4 bytes), so a guest that writes another width or an index no queue has gets an ordinary MMIO exit, lands in write_register, and is counted as bad_notify. wick/tests/ioevent.rs boots a tiny 32-bit guest on the real KVM and shows both halves: a doorbell for queue 0 produces no MMIO exit and one eventfd count, a doorbell with value 7 exits. The VMM thread’s epoll loop (chapter 24) reads the eventfd and calls the device. An ioeventfd and an irqfd are the two halves of an exit-free notify: the guest rings the device through one, the device interrupts the guest through the other, and neither crosses the vCPU thread. If the registration ever fails the transport says so once and falls back to ringing the same eventfd from write_register, one exit per doorbell, the way chapter 22’s lab ran.
The interrupt half is Irq (listed in the Walkthrough): a device sets bit 0 of InterruptStatus in an atomic and writes the irqfd; the driver reads the status register and writes the bit back to InterruptACK (§4.2.3.4.1, chapter 22). The status bit is state; the irqfd write is only an edge, KVM injects one for each write, and several writes before the guest runs can become one interrupt, so the lab’s capture never pins an interrupt count.
The ring as chapter 22 left it
Chapter 22 closed with a promise: wick’s Rust ring would meet the same six checks that labs/ch22/harness.c pins on the C ring. It does, and wick’s version of the six lines is not a copy but a run: cargo run --example ch22-harness plays a driver on virtio-queue’s mock rings and wick’s own segments and prints the six harness: lines, and the lab diffs them against head -6 labs/ch22/capture.txt, so the contract is literally chapter 22’s lines. The six lines say little. What stands behind them is wick/tests/ch22_contract.rs, and its last test, each_refusal_names_its_layer, is the table this section prints: which behaviour belongs to the crate, which to wick, and which to both (the crate does part and wick the rest). The crate does less than chapter 22’s C backend, and the difference is the first thing a reader of the Rust has to know.
- Empty queue pops nothing. The crate:
pop_descriptor_chainisNone. - Readable descriptors before writable ones (§2.7.4.2).
wick:segments. - The element, then the index. The crate:
add_used, with a release store. - Wrap at 65536. The crate:
Wrapping<u16>. - An
avail.idxtoo far ahead. The crate:InvalidAvailRingIndex. - A loop. Both: the crate bounds the walk at the queue size, and
wickrefuses more than 16 descriptors or a chain that ends on anext. - A
nextpast the table.wick: the crate’s short chain ends on anext. - A head past the table. Both:
segmentsrefuses the empty chain, andadd_usedrefuses the return. - A zero-length descriptor, or one outside guest memory.
wick:segments, withcheck_range. - A bounded drain.
wick: the block and net loops runqueue.size()times for a doorbell. The vsock transmit loop stops aftersizechains in a pass, andpumpruns further passes while the wake’s budget lasts, so a doorbell moves at mostwake_packets(512) packets, and stops oncewake_bytes(1 MiB) has been moved, which can be up to one packet (44 + 64 KiB) past it, since the budget is checked before a packet is taken and spent after; then it asks to be woken again. - A refused chain returns with
used.len0.wick, in each device (exercise (b)).
Five differences from chapter 22’s C backend follow, and each is a decision the chapter’s reader will meet in the code. First, the crate reports a malformed chain as a short one; it never says malformed. A loop ends after size descriptors, a next past the table ends the walk where it stands, and an unreadable descriptor does the same, and a short chain can look well formed (a header and nothing else). segments is where wick says no, and it carries the head index in its error so that the caller can still return the buffer. Second, a chain wick refuses is consumed: AvailIter::next advances next_avail before it hands the chain out, so the device returns the refused buffer with used.len 0 and goes on, where chapter 22’s virtq_pop left last_avail where it was and the VMM set DEVICE_NEEDS_RESET.
// virtio-queue 0.18.0, src/queue.rs:740-750
let offset = VIRTQ_AVAIL_RING_HEADER_SIZE + elem_off;
let addr = self.avail_ring.checked_add(offset)?;
let head_index: u16 = self
.mem
.load(addr, Ordering::Acquire)
.map(u16::from_le)
.map_err(|_| error!("Failed to read from memory {:x}", addr.raw_value()))
.ok()?;
*self.next_avail += Wrapping(1);
Third, a head index past the table cannot be returned at all, because the crate refuses it:
// virtio-queue 0.18.0, src/queue.rs:441-453
fn add_used<M: GuestMemory>(
&mut self,
mem: &M,
head_index: u16,
len: u32,
) -> Result<(), Error> {
if head_index >= self.size {
error!(
"attempted to add out of bounds descriptor to used ring: {}",
head_index
);
return Err(Error::InvalidDescriptorIndex);
}
so for that one chain the device counts it (bad_chains and unreturned) and moves on; used.idx does not advance for it. Fourth, indirect descriptors:
// virtio-queue 0.18.0, src/chain.rs:178-181
if desc.refers_to_indirect_table() {
self.switch_to_indirect_table(desc).ok()?;
return self.next();
}
the crate follows a descriptor that points at an indirect table whether or not VIRTIO_F_INDIRECT_DESC was negotiated, and wick serves such a chain (the contract test builds one and shows it served), where chapter 22’s backend refused it. Neither device offers the feature, so a conforming driver never sends one; the point is that the crate, not wick, decides, and a hostile guest can send it anyway. Fifth, the longest chain: chapter 22’s C backend allowed 8 descriptors, its queue size, so its bound and the queue’s were one number. wick’s MAX_SEGS is 16, its own choice, below the queue sizes the block (128) and net (256) devices offer, which is a limit the device documents and the specification allows: “The device MAY have a reasonable limit of descriptors it will allow in a chain” (§2.7.4.1, p. 27). The vsock transmit queue is the exception, as the vsock section says.
Two threads and one ring
Chapter 22 said its barriers were in the code because the code was the contract, and that wick’s device would one day run beside the vCPU thread. This is the day. In chapter 22’s lab the guest could not store anything while the device drained the ring: KVM_RUN had returned, the vCPU was stopped, and one thread did both. In wick the guest runs in guest mode on the vCPU thread while the VMM thread serves the queue, and the guest’s stores to the rings are ordinary stores in the same memory. The sharing is therefore between the guest and the VMM thread. The vCPU thread’s own Rust code does not touch a ring after the driver is live: it runs the transport, whose queue registers are frozen once the queue is ready, and activate hands the device copies of the queues (Queue::try_from(q.state())), so the VMM thread alone pops from the device’s Queue (the vCPU thread touches the object only to stop it, queue_stop, under the device’s mutex).
The barriers that make the sharing correct are in virtio-queue, and a reader can find each by name. The device’s acquire is the load of avail.idx in iter (pop_descriptor_chain calls it once per chain):
// virtio-queue 0.18.0, src/queue.rs:581-595
fn iter<M>(&mut self, mem: M) -> Result<AvailIter<'_, M>, Error>
where
M: Deref,
M::Target: GuestMemory,
{
// We're checking here that a reset did not happen without re-initializing the queue.
// TODO: In the future we might want to also check that the other parameters in the
// queue are valid.
if !self.ready || self.avail_ring == GuestAddress(0) {
return Err(Error::QueueNotReady);
}
self.avail_idx(mem.deref(), Ordering::Acquire)
.map(move |idx| AvailIter::new(mem, idx, self))?
}
and the ring slot is read with an acquire too, in the code quoted above (queue.rs:745), so the descriptors the slot names, written by the driver before its release of avail.idx, are visible. The device’s release is the store that publishes used.idx, after the element it covers:
// virtio-queue 0.18.0, src/queue.rs:463-477
mem.write_obj(VirtqUsedElem::new(head_index.into(), len), addr)
.map_err(Error::GuestMemory)?;
self.next_used += Wrapping(1);
self.num_added += Wrapping(1);
mem.store(
u16::to_le(self.next_used.0),
self.used_ring
.checked_add(2)
.ok_or(Error::AddressOverflow)?,
Ordering::Release,
)
.map_err(Error::GuestMemory)
}
The fourth barrier of chapter 22’s list, the full fence between publishing a used buffer and reading the driver’s notification-suppression flag, is in needs_notification:
// virtio-queue 0.18.0, src/queue.rs:498-502
fn needs_notification<M: GuestMemory>(&mut self, mem: &M) -> Result<bool, Error> {
let used_idx = self.next_used;
// Complete all the writes in add_used() before reading the event.
fence(Ordering::SeqCst);
and wick never calls it. wick sends an interrupt for every doorbell that returned a buffer, and never reads avail.flags or used_event: §2.7.7.2 says that with the flag set “the device SHOULD NOT send a notification”, and a SHOULD NOT is an optimisation the device may decline. The cost is interrupts a driver asked not to get; the gain is that the one reader-after-writer hazard chapter 22 spent a paragraph on is not on wick’s path. The descriptors themselves are read with plain loads, whole, once per walk (DescriptorChain::next copies the 16 bytes into a local), and segments copies the address and length into a Seg before any device code looks at them, which is chapter 22’s rule that every field is read once: a guest that rewrites a descriptor while the device walks it changes nothing the device already holds.
What the vCPU thread does share with the VMM thread is the device. The device sits behind a Mutex, and the VMM thread holds it for the whole of a doorbell. The comment in Vmm::doorbell (listed in the Walkthrough) counts the places the other thread takes it, and says for how long each can wait. Six guest actions take the lock in the transport: a write of 0 to Status (reset), a write that sets DRIVER_OK (activate), a write of 0 to the QueueReady of a live queue (queue_stop), a read of DeviceID, and a read or write of config space. A queue’s doorbell is not among them, because the ioeventfd takes it in the kernel. Each of the six can wait for the doorbell in progress and no longer, and what a doorbell can do is bounded by the device’s own limits, which the Block and vsock sections give. This is the design’s price and the chapter does not hide it: the VMM thread that serves the disk is also the one that answers the API thread’s requests (chapter 24), so a doorbell that moved its whole bound of work would delay an API request, and the bound is what keeps the delay finite.
Block
A block request is chapter 22’s: a 16-byte header (type, reserved, sector), data, and one status byte (§5.2.6, p. 101; the layout is quoted in chapter 22), in the order §2.7.4.2 requires (p. 27), so that the device reads the header and any data to write and writes any data to read and the status. Chapter 22’s model served the one arrangement of three descriptors and set DEVICE_NEEDS_RESET on any other. wick does what §2.7.4.1 asks (p. 27), “The device MUST NOT make assumptions about the particular arrangement of descriptors”: segments gives it the readable bytes and the writable bytes as lists of ranges, the header is the first 16 readable bytes however the driver cut them (a header split across two descriptors is still a header, a_header_split_across_two_descriptors_is_still_a_header), the status is the last writable byte, and whatever lies between is the data. A request is read, write or flush (the one other type a conformant driver may send, VIRTIO_BLK_T_GET_ID, which has no feature bit, is answered UNSUPP; Linux’s block driver issues it only to fill the serial sysfs attribute, and turns only -EIO into an empty string, so reading serial fails with the not-supported error: drivers/block/virtio_blk.c:806-830 and :892-908): the data must be a non-zero multiple of 512 bytes going the way the type says, inside the file, and a write to a read-only drive is refused (§5.2.6.2: “A device MUST set the status byte to VIRTIO_BLK_S_IOERR for a write request if the VIRTIO_BLK_F_RO feature if offered, and MUST NOT write any data”, p. 103). Anything else gets a status byte and nothing is touched, and the check is made on the whole request before any I/O: execute returns the status to answer with, or the number of bytes written.
The answer to a failed request is chapter 22’s ruling, which §2.7.8.2 now bears out in full: used.len is 0. The sentence is “The device MUST write at least len bytes to descriptor, beginning at the first device-writable buffer, prior to updating the used idx” (p. 31), and a failed read wrote none of the data, whatever it wrote to the status byte after it. The note beside it says why a device must not round up: “len is permitted to be an underestimate: that’s preferable to the driver believing that uninitialized memory has been overwritten when it has not.” A write that completes must be stable when the driver declined VIRTIO_BLK_F_FLUSH, the feature the device offers so that a driver can ask for what it needs: “A write becomes stable once it is completed and one or more of the following conditions is true: 1. neither VIRTIO_BLK_F_CONFIG_WCE nor VIRTIO_BLK_F_FLUSH feature were negotiated, but VIRTIO_BLK_F_FLUSH was offered by the device” (§5.2.6.2, p. 103), and the next page says what the device owes for them: “If the device is backed by persistent storage, the device MUST ensure that stable writes are committed to it, before reporting completion of the write (cases 1 and 2) or the flush (case 3)” (p. 104). So the device records what was negotiated (ack_features) and does sync_data after each completed write when FLUSH was not accepted, and only on a flush request when it was; BlockCounts::syncs counts both. Linux accepts FLUSH when it is offered, so the lab’s guest never pays for this. A successful read answers len + 1 (the data and the status byte), a successful write 1. What a guest’s driver does with len is another matter, and the lab’s IMPL=mine shows it: Linux’s block driver never looks.
// linux v7.2.8, drivers/block/virtio_blk.c:350-369
static void virtblk_done(struct virtqueue *vq)
{
struct virtio_blk *vblk = vq->vdev->priv;
bool req_done = false;
int qid = vq->index;
struct virtblk_req *vbr;
unsigned long flags;
unsigned int len;
spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
do {
virtqueue_disable_cb(vq);
while ((vbr = virtqueue_get_buf(vblk->vqs[qid].vq, &len)) != NULL) {
struct request *req = blk_mq_rq_from_pdu(vbr);
if (likely(!blk_should_fake_timeout(req->q)))
blk_mq_complete_request(req);
req_done = true;
}
} while (!virtqueue_enable_cb(vq));
virtqueue_get_buf returns the length in len, and virtblk_done does not use it; the request’s result is the status byte, read from the request’s own header memory, in the driver’s per-request area:
// linux v7.2.8, drivers/block/virtio_blk.c:329-332
static inline u8 virtblk_vbr_status(struct virtblk_req *vbr)
{
return *((u8 *)&vbr->in_hdr + vbr->in_hdr_len - 1);
}
That area is allocated zeroed (block/blk-mq.c, blk_mq_alloc_rqs, with __GFP_ZERO), and VIRTIO_BLK_S_OK is 0. A device that never writes the status byte therefore reads as success to this driver the first time a request uses its slot, and the data it did not write is whatever the page held. The lab’s stub shows exactly that, and exercise (b) shows the converse, that a wrong len on an error is invisible to this driver.
The drive’s file is opened once, at PUT /drives, with the type read from metadata first (a FIFO would block the VMM thread in open), O_NONBLOCK, at least one sector long, and wick keeps the descriptor; attach_devices hands the device a dup. A path that is swapped, renamed, removed or replaced by a FIFO between the PUT and the start cannot matter, and a test unlinks the file after the PUT and boots a guest that reads it (a_drive_file_unlinked_after_the_put_still_serves_the_guest). The capacity the guest sees is the file’s length at the start, in whole sectors. Data moves through a 64 KiB buffer, pread or pwrite and then a copy into guest memory or out of it, so a 4 MiB request does not allocate 4 MiB. MAX_DATA is 4 MiB per request: this guest’s /sys/block/vda/queue/max_sectors_kb reads 4096 and max_hw_sectors_kb 2147483647 (talos, 2026-10-02, the same scratch run as above), so the cap is what the guest’s own queue limit would form, and a hostile guest’s bigger request is refused before any I/O. A flush is sync_data on the file; the device offers VIRTIO_BLK_F_FLUSH (“Devices SHOULD always offer VIRTIO_BLK_F_FLUSH”, §5.2.5.2, p. 101, the line chapter 22’s RAM disk declined) and VIRTIO_BLK_F_RO when the drive is read-only. This guest negotiated bits 9 and 32, as the string it printed shows: /sys/bus/virtio/devices/virtio0/features is one character per feature bit, bit 0 first, and the 1s of the block device are at positions 9 and 32.
One queue of up to 128 entries serves the device, and one doorbell serves at most queue.size() chains: a driver that refills the ring as fast as it is served would otherwise keep the VMM thread in the loop for good. a_buffer_that_refills_the_ring_is_drained_at_most_size_chains_per_doorbell is the test that pins the bound: a writable buffer that aliases the available ring makes the device’s own reads the driver’s refill, with no thread and no timing, and exercise (c) removes the bound and watches it fail.
Net
A network device moves Ethernet frames, and §5.1 puts a header in front of each. The header is 12 bytes, struct virtio_net_hdr_v1, which the Linux uapi header spells out:
// linux v7.2.8, include/uapi/linux/virtio_net.h:152-192
struct virtio_net_hdr_v1 {
#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 /* Use csum_start, csum_offset */
#define VIRTIO_NET_HDR_F_DATA_VALID 2 /* Csum is valid */
#define VIRTIO_NET_HDR_F_RSC_INFO 4 /* rsc info in csum_ fields */
#define VIRTIO_NET_HDR_F_UDP_TUNNEL_CSUM 8 /* UDP tunnel csum offload */
__u8 flags;
#define VIRTIO_NET_HDR_GSO_NONE 0 /* Not a GSO frame */
#define VIRTIO_NET_HDR_GSO_TCPV4 1 /* GSO frame, IPv4 TCP (TSO) */
#define VIRTIO_NET_HDR_GSO_UDP 3 /* GSO frame, IPv4 UDP (UFO) */
#define VIRTIO_NET_HDR_GSO_TCPV6 4 /* GSO frame, IPv6 TCP */
#define VIRTIO_NET_HDR_GSO_UDP_L4 5 /* GSO frame, IPv4& IPv6 UDP (USO) */
#define VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV4 0x20 /* UDPv4 tunnel present */
#define VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV6 0x40 /* UDPv6 tunnel present */
#define VIRTIO_NET_HDR_GSO_UDP_TUNNEL (VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV4 | \
VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV6)
#define VIRTIO_NET_HDR_GSO_ECN 0x80 /* TCP has ECN set */
__u8 gso_type;
__virtio16 hdr_len; /* Ethernet + IP + tcp/udp hdrs */
__virtio16 gso_size; /* Bytes to append to hdr_len per frame */
union {
struct {
__virtio16 csum_start;
__virtio16 csum_offset;
};
/* Checksum calculation */
struct {
/* Position to start checksumming from */
__virtio16 start;
/* Offset after that to place checksum */
__virtio16 offset;
} csum;
/* Receive Segment Coalescing */
struct {
/* Number of coalesced segments */
__le16 segments;
/* Number of duplicated acks */
__le16 dup_acks;
} rsc;
};
__virtio16 num_buffers; /* Number of merged rx buffers */
};
The last field, num_buffers, is at byte 10 of the 12. Queue 0 receives and queue 1 transmits; the device offers no control queue. On the host side the frames go to a TAP, chapter 23’s virtual Ethernet interface, whose wire is a file descriptor. The kernel’s description:
// linux v7.2.8, Documentation/networking/tuntap.rst:21-31
TUN/TAP provides packet reception and transmission for user space programs.
It can be seen as a simple Point-to-Point or Ethernet device, which,
instead of receiving packets from physical media, receives them from
user space program and instead of sending packets via physical media
writes them to the user space program.
In order to use the driver a program has to open /dev/net/tun and issue a
corresponding ioctl() to register a network device with the kernel. A network
device will appear as tunXX or tapXX, depending on the options chosen. When
the program closes the file descriptor, the network device and all
corresponding routes will disappear.
A frame the guest transmits is a write of that many bytes to the descriptor, and the host kernel treats it as having arrived on the interface; a frame the kernel routes out of the interface is a read. wick opens the TAP with IFF_TAP | IFF_NO_PI | IFF_VNET_HDR and sets the header size to 12 (TUNSETVNETHDRSZ), so that the header the TAP puts in front of each frame has the shape of the one the guest does, and the device copies bytes in both directions without building a header of its own. The Walkthrough’s listing issues the three ioctls; their numbers are constants above it in net.rs, and a unit test recomputes them from _IOW.
The lab’s TAP does not exist on the host. run.sh begins by re-executing itself under unshare -Urn, which makes a new user namespace (chapter 15’s: inside it the calling user is root, mapped from the real uid, and holds every capability over the objects the namespace owns) and a new network namespace, chapter 15’s wrapping of one global resource, here the network stack: a private set of interfaces, addresses, routes and sockets that starts with nothing but a loopback. tap0, with the address 172.16.0.1/24, is created in it by an unprivileged ip tuntap add, and wick runs in it. The guest’s eth0, bridged to tap0 by the device, talks to a network stack that the rest of the host cannot see; no process outside the namespace can address 172.16.0.1, and nothing the guest sends can leave. That is what makes the lab need no privilege and leaves nothing on the host to clean up. The reason it works only inside the namespace is the permission check on creating an interface:
// linux v7.2.8, drivers/net/tun.c:2774-2775
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
ns_capable(net->user_ns, CAP_NET_ADMIN) asks for the capability in the user namespace that owns the network namespace in question. In the host’s own network namespace that is the initial user namespace, where an ordinary user has none; in the namespace unshare -Urn made, it is the new user namespace, where the user is root. Exercise (d) takes the unshare away and shows the refusal. wick itself never creates a TAP: open_tap looks the name up with if_nametoindex first, because inside such a namespace a bare TUNSETIFF on a misspelled name would otherwise quietly create a new, unconnected interface, and checks the index again after the ioctl.
The header carries the one subtle rule of this device. A TAP opened with IFF_VNET_HDR acts on the header in front of each frame the writer writes. TUNSETOFFLOAD 0 turns off what the kernel hands the reader: no checksum-pending or segmentation-offload frames come out. It does not limit the writer, whose header tun_get_user reads and acts on: the header decides what packet the kernel builds, a checksum-pending one or a segmented one (drivers/net/tun.c:1738-1747, tun_vnet.h:120-147, include/linux/virtio_net.h:51-205). The specification says what a driver may put in it, with no offload negotiated: “If VIRTIO_NET_F_CSUM is not negotiated, the driver MUST set flags to zero and SHOULD supply a fully checksummed packet to the device” (§5.1.6.2.1, p. 85), and what the device must do about the rest, “The device MUST ignore flag bits that it does not recognize” (§5.1.6.2.2, p. 86). The TAP does not ignore them; so the device does: send_frame clears the guest’s 12 header bytes before the one write and counts a guest that sent anything else (tx_hdr_cleared). On receive the device owes the driver a header it can read: “If VIRTIO_NET_F_MRG_RXBUF has not been negotiated, the device MUST set num_buffers to 1” and “If VIRTIO_NET_F_GUEST_CSUM is not negotiated, the device MUST set flags to zero” (§5.1.6.4.1, p. 87), so deliver zeroes bytes 0 to 9 of what the TAP produced and writes 1 at byte 10.
The device does not enforce the TAP’s MTU: it writes any frame up to 65562 bytes with its header, and the host TAP decides (an independent check sent frames of 8,042 and 60,042 bytes that reached tap0), which the specification allows, since no MTU feature is negotiated and so there is no obligation. The device offers VIRTIO_F_VERSION_1 and VIRTIO_NET_F_MAC and nothing else. This guest negotiated exactly those: the features string of the network device in the run above has 1 at positions 5 (MAC) and 32. What is missing, and what each absence costs, is worth stating once. Without CSUM and GUEST_CSUM every frame in either direction carries a complete checksum, so the guest computes them in software and the host’s kernel computes them before it hands a frame to the reader. Without the TSO, UFO and USO features no frame is larger than the interface’s MTU, 1500 here (eth0 mtu 1500, same run), and each frame is one descriptor chain, one write or read system call and one trip through the ring; §5.1.6.3 gives the sizes (1514 bytes of frame and 1526 with the header, without the guest segmentation features, against 65550 and 65562 with them), and wick accepts frames up to the larger bound in both directions (MAX_FRAME_WITH_HDR, 65562), which a guest of this device never sends. Without MRG_RXBUF one frame is one buffer (“The device MUST use only a single descriptor if VIRTIO_NET_F_MRG_RXBUF was not negotiated”, §5.1.6.3.2, p. 86), so the driver must post buffers as large as the largest frame it can receive. Without CTRL_VQ there is no filtering and no queue to pair, without MQ one pair of queues, and without STATUS the link is always up and the configuration space is the six bytes of the MAC.
The two directions are not symmetric. The guest decides when it transmits: it rings queue 1’s doorbell, the VMM thread calls transmit, and each chain, up to one queue’s worth, is gathered and written to the TAP in a single write. The descriptor is non-blocking, and a frame it will not take (its queue full, or the kernel refusing the header) is dropped and counted, which is what a full wire does, so the VMM thread never waits on the host’s network. The host decides when frames arrive, and nothing rings a doorbell: the TAP’s descriptor is registered with the VMM thread’s epoll loop, and when it is readable the loop calls receive, which reads up to 256 frames per wake and gives each to the next buffer the guest has posted, with one interrupt for the batch. The registration is level-triggered, so an interface with frames waiting wakes the loop again until it is empty (level-triggered: the descriptor reports readiness as long as it is true; its opposite, edge-triggered, reports once when it becomes true, and vsock below uses it). Level-triggering makes one rule necessary: every frame the loop is woken for must be read, or it spins. A frame that arrives when the guest has posted no receive buffer is therefore read and dropped, counted as rx_dropped_no_buffer. The alternative is to stop watching the TAP until the driver posts a buffer; the frames would then wait in the kernel’s queue until it overflowed there, and the cost is a way for the vCPU thread to tell the VMM thread when buffers arrive, which is a second wake-up mechanism, for a benefit no guest can use (frames sent before the driver is ready are lost on a real wire too). The lab’s capture does not count frames for the same reason: frames reach the TAP before the driver is up and are dropped.
A buffer too small for the frame at the head of the queue drops the frame and leaves the buffer posted for a smaller one. If a guest posts buffers too small for every frame, none is ever delivered: head-of-line blocking, which is the guest’s own doing, and which the Linux driver does not do, because without MRG_RXBUF it posts buffers for the largest frame.
vsock
A socket device gives the guest and the host a stream connection that needs no network between them. The addresses are the AF_VSOCK ones: a CID, which chapter 23 defined as the 32-bit address of an endpoint, and a 32-bit port. CID 2 is the host (VMADDR_CID_HOST), CIDs 0 and 1 are reserved, and the guest’s is the guest_cid of PUT /vsock, 3 in the lab; §5.10.4 reserves 0xffffffff too, which the route refuses. The device has three queues, receive (0), transmit (1) and event (2), and a configuration space that is one le64, the guest’s CID.
Every packet is a 44-byte header and up to 64 KiB of payload:
// linux v7.2.8, include/uapi/linux/virtio_vsock.h:56-67
struct virtio_vsock_hdr {
__le64 src_cid;
__le64 dst_cid;
__le32 src_port;
__le32 dst_port;
__le32 len;
__le16 type; /* enum virtio_vsock_type */
__le16 op; /* enum virtio_vsock_op */
__le32 flags;
__le32 buf_alloc;
__le32 fwd_cnt;
} __attribute__((packed));
The header names the flow (src_cid, src_port, dst_cid, dst_port), the length of the payload, a type (1 for a stream; 2, seqpacket, is not offered and gets a reset, §5.10.6.4.2), an op and the credit fields. The virtio-vsock crate parses it, byte order and all, and wick uses the crate for exactly that; why it does not use the crate for the chain walk is below. The operations and the shutdown flags are the kernel’s header, which agrees with the specification’s (§5.10.6, pp. 159-160; the specification writes the two flags as the bit numbers 0 and 1, the kernel as the values 1 and 2):
// linux v7.2.8, include/uapi/linux/virtio_vsock.h:74-96
enum virtio_vsock_op {
VIRTIO_VSOCK_OP_INVALID = 0,
/* Connect operations */
VIRTIO_VSOCK_OP_REQUEST = 1,
VIRTIO_VSOCK_OP_RESPONSE = 2,
VIRTIO_VSOCK_OP_RST = 3,
VIRTIO_VSOCK_OP_SHUTDOWN = 4,
/* To send payload */
VIRTIO_VSOCK_OP_RW = 5,
/* Tell the peer our credit info */
VIRTIO_VSOCK_OP_CREDIT_UPDATE = 6,
/* Request the peer to send the credit info to us */
VIRTIO_VSOCK_OP_CREDIT_REQUEST = 7,
};
/* VIRTIO_VSOCK_OP_SHUTDOWN flags values */
enum virtio_vsock_shutdown {
VIRTIO_VSOCK_SHUTDOWN_RCV = 1,
VIRTIO_VSOCK_SHUTDOWN_SEND = 2,
};
A connection is a (guest port, host port) pair. One that the guest opens begins with a REQUEST it sends on queue 1; if something listens on the host the device answers RESPONSE and the stream is up, and if not it answers RST (“A VIRTIO_VSOCK_OP_RST reply is sent if a listening socket does not exist on the destination”, §5.10.6.5, p. 161). A packet for a connection that does not exist is answered RST too, except an RST, which is never answered (the kernel’s virtio_transport_reset makes the same choice), and an RST echoes the type of the packet that caused it. Data is RW packets, and the flow is governed by credit.
Credit is how a stream socket keeps a fast sender from burying a slow receiver. Each side tells the other, in every packet’s header, buf_alloc, “the total receive buffer space, in bytes, for this socket”, and fwd_cnt, “the free-running bytes received counter”; the sender tracks tx_cnt, its own free-running count of bytes sent (the device’s Conn calls its count rx_cnt, bytes the device has received from the host and sent to the guest: the specification’s tx_cnt from the device’s side), and computes how much the peer can still take: u32 peer_free = peer_buf_alloc - (tx_cnt - peer_fwd_cnt); (§5.10.6.3, pp. 160-161). It sends payload only up to that. A receiver that wants to tell the sender it has room again sends a CREDIT_UPDATE, and a sender that is stalled may send a CREDIT_REQUEST, which is answered with an update. The arithmetic is on counters that wrap, and the device’s version of it, peer_credit (listed in the Walkthrough), is two lines. Wrapping<u32> does the free-running subtraction, and saturating_sub is the departure from the specification’s expression: the specification’s u32 would wrap if the peer shrank its own buf_alloc with bytes in flight, and the kernel computes the same quantity in 64 bits and clamps at zero for that reason (net/vmw_vsock/virtio_transport_common.c:1022-1034, quoted in exercise (e)). The device advertises 256 KiB, BUF_ALLOC, the Linux default for a stream socket (VSOCK_DEFAULT_BUFFER_SIZE, net/vmw_vsock/af_vsock.c:200), and that is also the most one connection can have buffered toward a slow host: a guest that sends past it is reset, which is the kernel’s own rule applied to us (virtio_transport_inc_rx_pkt, net/vmw_vsock/virtio_transport_common.c:569-586; vtc.c abbreviates this file from here on). The device’s fwd_cnt advances by what the host’s socket has taken, not by what the guest sent, so a slow host shrinks the guest’s window and nothing is dropped. The Linux guest never sends a CREDIT_REQUEST (grep CREDIT_REQUEST net/vmw_vsock/* finds only the trace string and the handler) and sends a CREDIT_UPDATE only when the free space of its buffer has fallen under 64 KiB or its queue is nearly empty (vtc.c:786-788), so the device tells the guest about its window itself, when the guest’s picture of it is half gone and 16 KiB have moved since it was last told, and sends one CREDIT_REQUEST per stall when it has data and the guest has no credit.
The host’s end is a Unix socket, and the protocol on it is Firecracker’s, which wick follows, so that a client written against Firecracker’s documentation works against it. There are two directions, and Firecracker’s docs/vsock.md describes each:
// firecracker v1.15.1, docs/vsock.md:52-62
When a microvm having a vsock device attached is started, Firecracker will begin
listening on an AF_UNIX socket (e.g. `/path/to/v.sock`). When the host needs to
initiate a connection, it should connect to that Unix socket, then send a
connect command, in text form, specifying the destination AF_VSOCK port:
"CONNECT PORT\\n". Where PORT is the decimal port number, and "\\n" is EOL
(ASCII 0x0A). Following that, the same connection will be forwarded by
Firecracker to the guest software listening on that port, thus establishing the
requested channel. If the connection has been established, Firecracker will send
an acknowledgement message to the connecting end (host-side), in the form "OK
PORT\\n", where `PORT` is the vsock port number assigned to the host end. If no
one is listening, Firecracker will terminate the host connection.
// firecracker v1.15.1, docs/vsock.md:79-86
When the virtio-vsock device model in Firecracker detects a connection request
coming from the guest (a VIRTIO_VSOCK_OP_REQUEST packet), it tries to forward
the connection to an AF_UNIX socket listening on the host, at
`/path/to/v.sock_PORT` (or whatever path was configured via the `uds_path`
property of the vsock device), where `PORT` is the destination port (in
decimal), as specified in the connection request packet. If no such socket
exists, or no one is listening on it, a connection cannot be established, and a
VIRTIO_VSOCK_OP_RST packet will be sent back to the guest.
(The two excerpts are the first paragraphs under the document’s headings “Host-Initiated Connections” and “Guest-Initiated Connections”; the figure’s two arrows are these two paragraphs.) The lab’s two host helpers play the two roles: vsock-connect is the first paragraph’s client, vsock-listen the second’s server. wick binds uds_path when the machine starts, not when PUT /vsock arrives, so that a socket file exists only while a machine is serving it and a start that fails leaves none; it unlinks the file when the device is dropped, only if the inode is still the one it bound. There is no signal handler: a wick that is killed leaves its socket files, and the next wick on the same path replaces a leftover that no one is listening on and refuses one that someone is. The CONNECT line is parsed exactly: upper-case, one space, one to ten digits, a bare newline, at most 32 bytes; Firecracker’s parser is looser (it splits on whitespace and ignores case) and the document it ships says CONNECT PORT\n. CONNECT 0 is refused, there being no port 0 to listen on, and 0xffffffff is VMADDR_PORT_ANY. A client that connects before the guest’s driver is up is not accepted and not refused: it waits in the listen queue (the backlog, the kernel’s queue of connections that have completed but have not been accepted, 128 deep here) and is served when the driver is live, which is why the lab waits for the guest before it connects to a guest listener. A client that sends a bad or over-long line is refused with its input read first, so it sees the end of the stream and not a reset (a socket closed with unread bytes resets its peer).
Transmit chains are the vsock device’s other difficulty. The guest’s packets arrive on queue 1 as chains, and the Linux driver sends a packet of up to 64 KiB as the header in one descriptor and the payload in the buffer’s page fragments, one descriptor each. A 64 KiB payload is at most 16 page fragments: that is 64 KiB divided by the 4 KiB of an order-0 page, which the allocator falls back to when larger pages are not to be had (virtio_vsock_alloc_skb calls alloc_skb_with_frags, which refuses to go past MAX_SKB_FRAGS fragments):
// linux v7.2.8, net/core/skbuff.c:6788-6790
while (data_len) {
if (nr_frags == MAX_SKB_FRAGS)
goto failure;
A send with MSG_ZEROCOPY pins the caller’s own pages instead, and unaligned user pages can need one more fragment, 17 (__zerocopy_sg_from_iter):
// linux v7.2.8, net/vmw_vsock/virtio_transport_common.c:80-91
static int virtio_transport_fill_skb(struct sk_buff *skb,
struct virtio_vsock_pkt_info *info,
size_t len,
bool zcopy)
{
struct msghdr *msg = info->msg;
if (zcopy)
return __zerocopy_sg_from_iter(msg, NULL, skb,
&msg->msg_iter, len, NULL);
virtio_vsock_skb_put(skb, len);
So a chain of a header and 16 fragments is ordinary and one of a header and 17 is possible, and the driver’s own arrays are MAX_SKB_FRAGS + 1 long,
// linux v7.2.8, net/vmw_vsock/virtio_transport.c:60-70
/* These fields are used only in tx path in function
* 'virtio_transport_send_pkt_work()', so to save
* stack space in it, place both of them here. Each
* pointer from 'out_sgs' points to the corresponding
* element in 'out_bufs' - this is initialized in
* 'virtio_vsock_probe()'. Both fields are protected
* by 'tx_lock'. +1 is needed for packet header.
*/
struct scatterlist *out_sgs[MAX_SKB_FRAGS + 1];
struct scatterlist out_bufs[MAX_SKB_FRAGS + 1];
and CONFIG_MAX_SKB_FRAGS is 17 in the lab’s kernel (its .config; the option’s range is 17 to 45, net/Kconfig:293-296). The crate’s VsockPacket::from_tx_virtq_chain takes the header descriptor and at most one data descriptor after it, so it refuses the guest’s ordinary 64 KiB packets (a test builds a header and two 32 KiB descriptors and shows the crate return DescriptorLengthTooSmall for it and the device deliver all 65536 bytes). The device therefore walks vsock’s transmit chains with segments_up_to, whose bound is the queue’s size, 256, while block and net keep wick’s MAX_SEGS of 16, and gathers them whatever their layout: the 44 header bytes first and then exactly len bytes of payload. A packet the device cannot accept after the guest’s send window has already moved for it would leave a hole in the stream, so a packet that decodes as a stream packet for a live connection and cannot be accepted resets that connection, and the guest sees an error and not a corrupted stream.
The receive side is a pull. A connection owes the guest control packets (a response, a reset, a shutdown, a credit update) as flags on its state, and has host data in a socket; the device builds a packet only when the guest has posted a receive buffer, and reads the host’s socket directly into the buffer’s room, at most as much as the guest’s credit and the buffer allow. A connection with data and no buffer, or no credit, leaves its bytes in the host’s socket, and the host’s writer waits: the backpressure is the kernel’s, not a queue of ours. The guest’s receive buffers are each a little under 4 KiB (VIRTIO_VSOCK_DEFAULT_RX_BUF_SIZE is SKB_WITH_OVERHEAD(1024 * 4), include/linux/virtio_vsock.h:138, chosen so that a buffer and its overhead fit one page), so a 64 KiB host write becomes many packets. Because every stream socket the device holds is registered with the one epoll descriptor the device exposes to the VMM loop, edge-triggered and read only when the guest can take the data, a stream the device chooses not to read does not wake the outer loop.
A connection ends in one of two ways, and the specification’s sentence is short: “Clean disconnect is achieved by one or more VIRTIO_VSOCK_OP_SHUTDOWN packets that indicate no more data will be sent and received, followed by a VIRTIO_VSOCK_OP_RST response from the peer” (§5.10.6.5, p. 162). The flags make it finer than that. The specification: “bit VIRTIO_VSOCK_SHUTDOWN_F_RECEIVE (bit 0) set indicates that the peer will not receive any more data and bit VIRTIO_VSOCK_SHUTDOWN_F_SEND (bit 1) set indicates that the peer will not send any more data. These hints are permanent once sent and successive packets with bits clear do not reset them” (§5.10.6.5, p. 161); in the kernel’s values, SEND is 2 and RCV is 1. The Linux guest closes or resets only when it has seen both (virtio_transport_common.c:1603-1626), refuses a sendmsg only after the peer’s RCV (af_vsock.c:2204-2208) and ends a recvmsg with end-of-file after the peer’s SEND (:2355-2358); on shutdown(SHUT_WR) it sends SEND alone (virtio_transport_shutdown, vtc.c:1217-1231), and on close both (:1428). So the protocol has a half-close, and a host client that writes a request, shuts down its writing half and waits for the reply must get its reply. Firecracker does not provide that. Its connection treats a host end-of-file as a full close:
// firecracker v1.15.1, src/vmm/src/devices/virtio/vsock/csm/connection.rs:224-235
if read_cnt == 0 {
// A 0-length read means the host stream was closed down. In that case,
// we'll ask our peer to shut down the connection. We can neither send nor
// receive any more data.
self.state = ConnState::LocalClosed;
self.expiry = Some(
Instant::now() + Duration::from_millis(defs::CONN_SHUTDOWN_TIMEOUT_MS),
);
pkt.hdr
.set_op(uapi::VSOCK_OP_SHUTDOWN)
.set_flag(uapi::VSOCK_FLAGS_SHUTDOWN_RCV)
.set_flag(uapi::VSOCK_FLAGS_SHUTDOWN_SEND);
The two flags are set together, the connection goes to LocalClosed, and a reply the guest was about to write is lost. wick implements the half-close in both directions. The transitions:
- The host half-closes (the stream’s peer shut its writing half:
EPOLLRDHUPand no hang-up). The device owesSHUTDOWN{SEND}, keeps the stream, stops reading it, and keeps delivering what the guest sends under the credit rule. No deadline. - The host closes (a hang-up before the device’s own
shutdown(SHUT_WR), orEPIPEorECONNRESETon a write). It drops what was parked toward the host and tells the guestRCVat once if a write failed; delivers what the host sent before it closed, under the credit rule and the deadlines below; then owesSHUTDOWNfor the flags the guest has not been told (no flag is sent twice) and waits for the guest’sRSTunder a deadline. - Guest
SHUTDOWN{SEND}. After every byte the guest sent has reached the host socket,shutdown(SHUT_WR)on it; the host’s data keeps flowing. - Guest
SHUTDOWN{RCV}. The device stops reading the host socket and doesshutdown(SHUT_RD)on it, so that a host writer getsEPIPEand not an endless wait. - Both directions done.
RSTto the guest, and the socket is closed. - Guest
RST. Close; no reply.
The first two cases depend on telling a half close from a full one on a Unix socket, and what epoll reports does not say it directly. EPOLLHUP on an AF_UNIX stream means that this end’s sk_shutdown is both directions:
// linux v7.2.8, net/unix/af_unix.c:3373-3376
if (shutdown == SHUTDOWN_MASK)
mask |= EPOLLHUP;
if (shutdown & RCV_SHUTDOWN)
mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
so a peer’s shutdown(SHUT_WR) alone gives EPOLLRDHUP without EPOLLHUP, a peer’s close gives both, and, once the device has done shutdown(SHUT_WR) itself, a later peer SHUT_WR also raises EPOLLHUP, because then this end’s shutdown state is complete. hangup_probe, a test in bridge.rs, prints what the kernel reports for each case (kernel 7.2.5 on talos, 2026-10-02, cargo test --release --lib hangup_probe -- --nocapture):
(IN, RDHUP, HUP, ERR)
peer shutdown(WR) (true, true, false, false)
peer shutdown(RDWR) (true, true, true, false)
peer close(2) (true, true, true, false)
our shutdown(RD), then peer close(2) (true, true, true, false)
our shutdown(WR), then peer close(2) (true, true, true, false)
peer shutdown(RD) only (false, false, false, false)
our shutdown(WR) only (false, false, false, false)
our shutdown(WR), then peer shutdown(WR) (true, true, true, false)
our shutdown(WR), then peer shutdown(RDWR) (true, true, true, false)
our shutdown(RD), then peer shutdown(WR) (true, true, false, false)
peer writes then shutdown(WR) (true, true, false, false)
peer shutdown(RDWR) again (same as above) (true, true, true, false)
(Columns: IN, RDHUP, HUP, ERR.) The rule the device uses follows from the rows: RDHUP without the device’s own SHUT_WR is a half close; HUP before it, or a write error, is a full close; after it, only a write error or both directions finishing ends the connection. One consequence is a decision the chapter records: on a write failure the host’s last bytes are still delivered, because they are in the socket and the guest has not been told it will get no more; Firecracker closes and drops them.
Three more rules close the lifecycle. A REQUEST for the ports of a live connection replaces it, silently and counted: a Linux guest reuses a port pair only after its socket for the old one is gone (its own close, its eight-second close timeout, or the device’s full SHUTDOWN), and if the device’s reset for the old connection was ever lost, refusing the new request would leave the guest’s connect to time out; the guest can only affect its own connections this way, and a test shows that a request naming the ports a host client was handed (host ports begin at 1 << 30, Firecracker’s OK 1073741824) takes nothing over: the client sees its OK and then its stream end. A packet that cannot be accepted resets its connection, as above. And resets echo the offending packet’s type, as the kernel’s reset_no_sock does, so that the guest’s socket, which ignores a packet of another type, sees them.
VIRTIO_VSOCK_EVENT_TRANSPORT_RESET is the event that tells a guest its connections are gone and its CID may have changed (“The driver shuts down established connections and the guest_cid configuration field is fetched again”, §5.10.6.7, p. 162). Nothing in this chapter sends it, and the event queue’s buffers stay with the driver: a boot starts with no connections. A restored snapshot has connections that are gone, and the restore of chapter 27 is what sends it.
The bounds
Every number that limits what a peer can make the device hold is a field of Limits or a named constant, and each is pinned by a test that was shown to fail with the bound removed. The list says what each stops, on either side:
- Connections, 128 (
max_conns). A guest can open 128, and the 129thREQUESTis reset; 128 connections hold at most 128 descriptors of the process’s 1024 and 32 MiB. A host client can connect 128, and later ones are accepted and closed at once, which is what Firecracker does. - Half-open host clients, 16 (
max_half_open), with a listen backlog of 128. A host client can hold the 16 slots with silent connections forline_timeout(5 s); the rest wait in the listen queue and delay every host-initiated connect that long. A guest cannot reach this bound except through the next one. - The
CONNECTline, 32 bytes andline_timeout(5 s). A host client gets nothing from it: a line over 32 bytes, a bad line, or silence for 5 s closes it. - The guest’s answer to a host
CONNECT,response_timeout(5 s). A host connection counts as half-open until the guest answersRESPONSE; only a guest that never answers reaches the timeout, which ends the connection after 5 s with a reset to the guest and the host socket closed (a Linux guest with no listener on the port answers aREQUESTwith anRSTat once,virtio_transport_reset_no_sock). - Bytes toward a slow host, 256 KiB per connection (
BUF_ALLOC). A guest that sends more is reset. A host that reads slowly shrinks the guest’s window; nothing is dropped and nothing grows. - Resets for connections that do not exist, 1024 (
max_pending_rx). A guest that sends packets to nowhere with no receive buffer posted gets 1024 queued, and the device then stops taking transmit chains until the guest takes some. - Payload per packet, 64 KiB both ways (
MAX_PKT_DATA). A guest’slenof 4 GiB resets its connection and costs the 44 bytes of header read, not 4 GiB. - Descriptors per chain, the queue’s size on vsock transmit (
segments_up_to), 16 for block and net. A chain of 17 fragments is served on vsock; a loop ends at the queue size and is refused. - Work per wake,
wake_packets512,wake_bytes1 MiB (on transmit the header and payload of each packet are spent, a refused packet its whole length; on receive the payload alone),wake_events32 epoll events andaccept_per_wake16 accepts. A guest or a host that keeps the ring or the socket full finds a wake stopping at its budget and the device asking to be woken again. - A host that is gone,
shutdown_timeout(5 s without progress once the host has closed, restarted by each packet of its last bytes) andhost_gone_max(60 s, absolute). A guest that grants a byte of credit every four seconds to hold a connection whose host has left is ended by the 60 s cap. - The work list, one entry per live connection. A guest that opens and closes 3,000 connections behind a stuck one does not grow it.
Each is a field of Limits (devices/vsock/mod.rs) except the constants named; the list covers every field of Limits: max_conns, max_half_open, max_pending_rx, line_timeout, response_timeout, shutdown_timeout, host_gone_max, wake_packets, wake_bytes, wake_events and accept_per_wake.
The host-gone cap shows a pattern: a deadline that restarts with progress (the tail of a closed host’s data is finite, and a guest that reads slowly is not a stuck one) needs an absolute bound over it, or progress made slowly enough holds the slot for ever.
Why this is the control plane ward will use, and what hearth will have instead. A vsock connection needs no network configuration in the guest and no address on the host. The device identifies the guest by the queue a packet arrives on and refuses a packet whose source CID is not the guest’s, so a guest can name only itself and the host. And its host end is a path in a file system, which a per-guest jail (chapter 26) can place in a directory only that guest’s wick and its supervisor see. hearth has no Unix socket, as the syllabus says of this chapter: the same protocol will have to ride virtio-console, or a vsock device the hypervisor itself backs, which is chapter 36’s subject.
A driver that is not trusted, in code
Chapter 22 made the rule for the ring; this section is the rule for the devices, and it is short because it is one rule: a condition the guest can bring about is answered, never a panic. The answer is one of four things, chosen by what there is to answer with: a status byte, when the protocol has one (a block request: IOERR or UNSUPP); used.len 0 and the buffer back, when it does not (a transmit chain the device will not walk); a counted drop, when nothing is owed (a network frame no buffer is posted for, a runt); a RST, when there is a connection to tell. Every one of them is counted, never logged: the guest can do any of them as often as it likes, and a log line per hostile packet is a way to fill a disk. unwrap and expect appear in the device code only where a comment names the invariant that makes them infallible.
The tests that pin it are the larger half of the code: tests/hostile.rs has 69 tests, 32 of them against the block device (a chain with a loop, an out-of-range next, a head past the queue, a write-only header, a read-only status byte, a request past the end of the disk, a sector that overflows the byte offset, a buffer outside guest memory, a request over the cap), 22 against the network device and 15 against vsock (a len of 4 GiB, a packet for another CID, a credit the guest lies about, ten thousand requests to nowhere); tests/vsock.rs runs a mock guest against the whole device with 47 tests; and tests/restart.rs checks that failed starts leave no descriptor and no socket file behind. (Counted on talos, 2026-10-02, with grep -c '#\[test\]' and by the file’s mod net and mod vsock_hostile boundaries.) A test is only as strong as its failure, and exercise (c) runs the one that pins the drain bound with the bound removed. The same aliasing form pins the net device’s bound: its transmit queue writes nothing into the ring but the used ring, so the test lays the used ring over the available ring. The vsock tests of the per-wake budgets (packets, bytes, events, accepts) offer a finite number of chains and assert exact counts, with no thread and no timing; the transmit loop of the vsock device stops after size chains in a pass, and pump runs further passes while the wake’s budget lasts, so one doorbell moves at most wake_packets (512) packets, and stops once wake_bytes (1 MiB) has been moved, up to one packet (44 + 64 KiB) past it (the budget is checked before a packet is taken and spent after), and then the device asks to be woken again; one_doorbell_on_a_self_refilling_transmit_ring_serves_exactly_the_wake_budget_and_the_next_wake_continues lays the used ring over the available ring, with a small budget, and shows one doorbell serving exactly that budget, the kick pending, and the next wake continuing.
The claim was also checked against a real guest, by an independent examiner on 2026-10-02 (talos): a variant guest kernel with CONFIG_DEVMEM, the kernel’s own virtio driver unbound through sysfs, and a program that drove a device’s registers and rings by hand through /dev/mem against a live wick, with 2 million doorbells, every malformed chain of the hostile tests and 20,000 racing resets; plus about 29 million register operations against each device in a fuzzer, a two-thread race on the rings for 6 to 10 s for each device, a hostile host peer, 64 MiB each way over vsock verified byte for byte, and the whole suite in release and debug builds with overflow checks. Nothing crashed, hung, spun a core or left the guest. The lab’s own kernel has no CONFIG_DEVMEM, so a guest of the lab cannot do this.
The axes
Chapter 14’s three axes, for the three devices. Shared: guest RAM, which the VMM maps and every device reads and writes through the same GuestMemoryMmap; the host kernel, through the system calls the devices make on its behalf (pread, pwrite, read and write on a TAP, the Unix socket calls); and the host’s network namespace, which the lab makes private and a production wick would take from the jailer (chapter 26). The three devices also share the VMM thread, as the lock paragraph said. Trusted: the host kernel, tun, and the Unix socket layer below the devices; wick’s own parsers, which is the part a hostile guest reaches; and the operator, who names the drive’s path, the TAP and the socket path, none of which the guest chooses. The guest is trusted with nothing but its own data. Copy: each byte crosses the VMM’s memory once more than the hardware’s design needs. A block read is pread into a 64 KiB buffer and then a copy into guest memory; a write is the same two copies reversed. A received frame is read from the TAP into the device’s buffer and then copied into the guest’s; a transmitted one is gathered out of the guest’s descriptors into one buffer and written. A vsock payload does the same through the device’s scratch buffers. Those are two user-space copies per direction, on top of the copy the kernel makes into or out of its own buffers, and removing them takes a different design (a backend inside the host kernel, as vhost is) than this book builds.
Walkthrough
The listings follow one request’s life: how a device gets a window, how the guest’s register accesses reach it, how a chain becomes ranges, how a doorbell becomes work, and then each device’s work. Each is the repository’s file, kept equal to it by make sync. The prose beside a listing says what to look for in it; the rules are the Mechanism section’s.
Giving a device a window
/// Place one virtio device in the next MMIO window: its transport on `mmio`, its `virtio_mmio.device=` entry on
/// the command line, its queue eventfds in `vmm.devices` for the loop to subscribe once the machine is up.
fn add_virtio(vmm: &mut Vmm, vm: &Vm, cmdline: &mut Cmdline, mmio: &mut Bus, dev: impl VirtioDevice + 'static) -> Result<()> {
let slot = vmm.devices.len();
if slot >= MAX_DEVICES {
return Err(Error::Config(format!("at most {MAX_DEVICES} virtio devices fit the interrupt lines wick has")));
}
let dev: Arc<Mutex<dyn VirtioDevice>> = Arc::new(Mutex::new(dev));
let device_type = dev.lock().unwrap_or_else(PoisonError::into_inner).device_type();
let transport = MmioTransport::new(dev.clone(), vm, slot as u32)?;
let evts = transport.queue_events().iter().map(EventFd::try_clone).collect::<std::io::Result<Vec<_>>>()?;
let base = MMIO_BASE + slot as u64 * MMIO_LEN;
cmdline
.add_virtio_mmio_device(MMIO_LEN, GuestAddress(base), IRQ_BASE + slot as u32, None)
.map_err(|e| Error::Config(format!("the command line has no room for the virtio device in slot {slot}: {e}")))?;
let transport = Arc::new(Mutex::new(transport));
mmio.insert(base, MMIO_LEN, transport.clone())?;
let host = dev.lock().unwrap_or_else(PoisonError::into_inner).host_fd().map(|fd| fd.try_clone_to_owned()).transpose()?;
vmm.devices.push(Slot { dev, evts, device_type, host, transport });
Ok(())
}
The order inside add_virtio is the order of what can fail. MmioTransport::new comes first because it registers the irqfd, whose refusal ends the start, and the queue ioeventfds, whose refusal is logged and leaves the doorbell on its fallback. The command-line entry comes next, because it is the one that can run out of room: the line has finite capacity, and chapter 24’s check against setup_header.cmdline_size comes after it. Only then is the transport put on the bus the vCPU will use, and the device recorded in vmm.devices with clones of its queue eventfds and a second reference to the transport, which a snapshot (chapter 27) reads and sets. Nothing is registered on the VMM thread’s loop here: the loop’s registration object exists only while it is running an event, so Vmm::started subscribes the eventfds, and the TAP or the vsock device’s epoll descriptor, after the start has been answered. That is why the capture’s wick: virtio-mmio slot N type T lines come after wick: InstanceStart: the log line is written where the subscription is.
The contract, and the walk
// 2. A block read in 2.7.4.2's order: header (device-readable), data and status (device-writable).
let (vq, mut q) = queue(&mem);
set_desc(&vq, 0, HDR, 16, NEXT, 1);
set_desc(&vq, 1, DATA, 512, NEXT | WRITE, 2);
set_desc(&vq, 2, STAT, 1, WRITE, 0);
driver_offer(&vq, 0);
let Some(chain) = q.pop_descriptor_chain(&mem) else { fail("3-seg chain: pop returned nothing") };
let head = chain.head_index();
let descs: Vec<Descriptor> = chain.collect();
let pat: Vec<&str> = descs.iter().map(|d| if d.is_write_only() { "wo" } else { "ro" }).collect();
let shape = [(HDR, 16), (DATA, 512), (STAT, 1)];
if head != 0 || descs.iter().map(|d| (d.addr().0, d.len())).ne(shape) {
fail("3-seg chain: wrong segments");
}
println!("harness: 3-seg read chain: head {head} segs {} {}", descs.len(), pat.join(","));
This is the second of the six harness lines: a driver’s three-descriptor read, built on the crate’s mock rings and read back the way the C harness reads it (the head, the number of segments, which are write-only).
/// Walk one chain into its device-readable and device-writable parts.
/// Refuses (virtio 1.2 section 2.7.4.2, the order rule, and chapter 22's rulings): a readable
/// descriptor after a writable one; more than `MAX_SEGS` descriptors; a zero-length descriptor; a range
/// that is not wholly inside guest memory; a chain with no descriptors; a chain that ends on a descriptor
/// that names a next (the crate's way of saying a loop, a `next` past the table, or an unreadable
/// descriptor cut the walk short).
pub fn segments(
mem: &GuestMemoryMmap<()>,
chain: DescriptorChain<&GuestMemoryMmap<()>>,
) -> std::result::Result<Segments, (u16, Error)> {
segments_up_to(mem, chain, MAX_SEGS)
}
/// `segments` with the device's own bound on descriptors. The block and net devices use `MAX_SEGS`, 16, `wick`'s own
/// limit (chapter 22's C backend used 8, its queue size); the vsock device's transmit chains are the Linux driver's packets,
/// which can be a header and up to 16 page fragments, or 17 with `MSG_ZEROCOPY` (the queue's own size bounds a walk anyway, so
/// `virtio-queue` is what stops a loop).
pub fn segments_up_to(
mem: &GuestMemoryMmap<()>,
chain: DescriptorChain<&GuestMemoryMmap<()>>,
max_segs: usize,
) -> std::result::Result<Segments, (u16, Error)> {
let head = chain.head_index();
let refuse = |why: String| (head, Error::Device(format!("descriptor chain {head}: {why}")));
let mut segs = Segments { head, readable: Vec::new(), writable: Vec::new() };
let mut seen = 0;
let mut says_next = false;
for desc in chain {
seen += 1;
if seen > max_segs {
return Err(refuse(format!("more than {max_segs} descriptors")));
}
let seg = Seg { addr: desc.addr(), len: desc.len() };
if seg.len == 0 {
return Err(refuse("a zero-length descriptor".into()));
}
if !mem.check_range(seg.addr, seg.len as usize) {
return Err(refuse(format!("{:#x}+{:#x} is not inside guest memory", seg.addr.0, seg.len)));
}
if desc.is_write_only() {
segs.writable.push(seg);
} else if segs.writable.is_empty() {
segs.readable.push(seg);
} else {
return Err(refuse("a device-readable descriptor after a device-writable one (virtio 1.2 section 2.7.4.2)".into()));
}
says_next = desc.has_next();
}
if seen == 0 {
return Err(refuse("no descriptors (the head is outside the table, or unreadable)".into()));
}
if says_next {
return Err(refuse("ends on a descriptor that names a next (a loop, or a next outside the table)".into()));
}
Ok(segs)
}
segments is the function every device calls before it believes a chain. It walks once, so each descriptor is read once, and it checks in the order of cost: the count, then the length, then the range, then the direction. The head index is carried in every error so that the caller can still hand the buffer back, and the says_next flag is what turns the crate’s silent short chain into a refusal. segments_up_to is the same function with a bound the device chooses: block and net call segments, which fixes 16, and the vsock transmit queue passes its queue’s size.
The registers
/// A read of the register at `offset` from the window's base.
fn read_register(&mut self, offset: u64, data: &mut [u8]) {
if offset >= u64::from(VIRTIO_MMIO_CONFIG) {
self.device().read_config(offset - u64::from(VIRTIO_MMIO_CONFIG), data);
return;
}
// Registers are 32 bits wide (section 4.2.2.2); anything else reads as 0 and is counted.
if data.len() != 4 {
data.fill(0);
self.counts.bad_width += 1;
return;
}
let queue = self.queues.get(self.queue_sel as usize);
let value = match offset as u32 {
VIRTIO_MMIO_MAGIC_VALUE => MAGIC,
VIRTIO_MMIO_VERSION => 2,
VIRTIO_MMIO_DEVICE_ID => self.device().device_type(),
VIRTIO_MMIO_VENDOR_ID => VENDOR,
VIRTIO_MMIO_DEVICE_FEATURES => match self.device_features_sel {
0 => self.device_features as u32,
1 => (self.device_features >> 32) as u32,
_ => 0,
},
VIRTIO_MMIO_QUEUE_NUM_MAX => queue.map_or(0, |q| u32::from(q.max_size())),
VIRTIO_MMIO_QUEUE_READY => queue.map_or(0, |q| u32::from(q.ready())),
VIRTIO_MMIO_INTERRUPT_STATUS => self.irq.status(),
VIRTIO_MMIO_STATUS => self.status,
VIRTIO_MMIO_CONFIG_GENERATION => 0,
// Table 4.1: a shared-memory region that does not exist has length -1 and base all ones; there are none.
VIRTIO_MMIO_SHM_LEN_LOW | VIRTIO_MMIO_SHM_LEN_HIGH | VIRTIO_MMIO_SHM_BASE_LOW | VIRTIO_MMIO_SHM_BASE_HIGH => u32::MAX,
_ => 0,
};
data.copy_from_slice(&value.to_le_bytes());
}
/// A write to the register at `offset` from the window's base.
fn write_register(&mut self, offset: u64, data: &[u8]) {
if offset >= u64::from(VIRTIO_MMIO_CONFIG) {
self.device().write_config(offset - u64::from(VIRTIO_MMIO_CONFIG), data);
return;
}
let Ok(word) = <[u8; 4]>::try_from(data) else {
self.counts.bad_width += 1;
return;
};
let v = u32::from_le_bytes(word);
match offset as u32 {
VIRTIO_MMIO_DEVICE_FEATURES_SEL => self.device_features_sel = v,
VIRTIO_MMIO_DRIVER_FEATURES_SEL => self.driver_features_sel = v,
VIRTIO_MMIO_DRIVER_FEATURES if self.status & VIRTIO_CONFIG_S_FEATURES_OK != 0 => self.counts.refused_feature_writes += 1,
VIRTIO_MMIO_DRIVER_FEATURES => match self.driver_features_sel {
0 => self.driver_features = (self.driver_features & !0xffff_ffff) | u64::from(v),
1 => self.driver_features = (self.driver_features & 0xffff_ffff) | (u64::from(v) << 32),
_ => {}
},
VIRTIO_MMIO_QUEUE_SEL => self.queue_sel = v,
reg @ (VIRTIO_MMIO_QUEUE_NUM
| VIRTIO_MMIO_QUEUE_READY
| VIRTIO_MMIO_QUEUE_DESC_LOW
| VIRTIO_MMIO_QUEUE_DESC_HIGH
| VIRTIO_MMIO_QUEUE_AVAIL_LOW
| VIRTIO_MMIO_QUEUE_AVAIL_HIGH
| VIRTIO_MMIO_QUEUE_USED_LOW
| VIRTIO_MMIO_QUEUE_USED_HIGH) => self.write_queue(reg, v),
VIRTIO_MMIO_QUEUE_NOTIFY => match self.queue_evts.get(v as usize) {
// The eventfd the VMM loop reads. With an ioeventfd registered this write never happens:
// KVM writes the eventfd itself and the guest does not exit.
Some(evt) => {
self.counts.notifies += 1;
if evt.write(1).is_err() {
self.counts.bad_notify += 1;
}
}
None => self.counts.bad_notify += 1,
},
VIRTIO_MMIO_INTERRUPT_ACK => self.irq.acknowledge(v),
VIRTIO_MMIO_STATUS => self.write_status(v),
_ => {}
}
}
The read is a match on the offset with one arm per register of the table and a zero for the rest. Config space is handed to the device first, before the width check, which is where the net device’s byte reads get through. The write is a match whose arm order matters, since the first arm that matches wins: the DriverFeatures arm with its FEATURES_OK guard comes before the unguarded one that stores the value. All eight queue registers go to one function, write_queue, where the frozen-registers rule, the alignment rule and the “low half counts” rule are, and the QueueNotify arm is only the fallback for a write the ioeventfd did not take.
impl Irq {
pub fn new(irqfd: EventFd) -> Irq {
Irq { status: Arc::new(AtomicU32::new(0)), irqfd: Arc::new(irqfd) }
}
/// The device used a buffer: set the bit the driver reads, then pulse the line.
pub fn signal_used(&self) -> Result<()> {
self.status.fetch_or(VIRTIO_MMIO_INT_VRING, Ordering::SeqCst);
self.irqfd.write(1)?;
Ok(())
}
/// What `InterruptStatus` reads.
pub fn status(&self) -> u32 {
self.status.load(Ordering::SeqCst)
}
fn acknowledge(&self, bits: u32) {
self.status.fetch_and(!bits, Ordering::SeqCst);
}
}
signal_used sets the status bit before it writes the irqfd. The other order would let the guest take the interrupt and read a status of 0, and a driver that reads 0 treats the interrupt as not its own.
The doorbell
/// A queue's doorbell rang: read the eventfd (always, or the level-triggered loop would spin on it), then let the
/// device serve the queue.
fn doorbell(&mut self, token: u32) {
let Some(evt) = self.doorbells.get(&token) else { return };
let _ = evt.read();
let (slot, queue) = ((token - TOKEN_QUEUE_BASE) / QUEUES_PER_SLOT, (token - TOKEN_QUEUE_BASE) % QUEUES_PER_SLOT);
let Some(slot) = self.devices.get(slot as usize) else {
self.stray_doorbells += 1;
return;
};
// The device's mutex is held for the whole doorbell: at most one queue's worth of requests and their I/O (and
// one `sync_data` for a flush), all of it bounded by the device's own limits (`MAX_DATA` per request, the
// queue size in chains). The vCPU thread takes the same mutex, in the transport, for exactly these guest actions:
// a write of 0 to `Status` (reset), a write that sets `DRIVER_OK` (activate), a write of 0 to the `QueueReady` of
// a live queue (queue_stop), a read of `DeviceID`, and a read or write of config space (read_config, write_config).
// Each can wait for the doorbell in progress and no longer; a queue doorbell never reaches the vCPU (the
// ioeventfd takes it in the kernel).
slot.dev.lock().unwrap_or_else(PoisonError::into_inner).queue_notify(queue as u16);
}
The first lines of doorbell are the ones a level-triggered loop cannot do without: the eventfd is read before the slot is looked up, so that a doorbell for a slot that no longer exists still drains it. The comment is the lock accounting of the Mechanism section, in the place a maintainer will be reading when they add a seventh site.
Block
fn queue_notify(&mut self, queue: u16) {
// A doorbell for a queue that does not exist, or before DRIVER_OK, is the driver's mistake; ignore it.
if queue != 0 {
return;
}
let Some(mut active) = self.active.take() else {
return;
};
let mut used_any = false;
// At most one queue's worth of chains per doorbell. A driver that refills the ring as fast as it is
// served would otherwise keep this thread here for good (chapter 22: "a doorbell drains at most
// `num` chains").
for _ in 0..active.queue.size() {
let Some(chain) = active.queue.pop_descriptor_chain(active.mem.as_ref()) else {
break;
};
self.counts.chains += 1;
let head = chain.head_index();
let len = match segments(active.mem.as_ref(), chain) {
Ok(segs) => self.handle_request(active.mem.as_ref(), &segs),
Err(_) => {
self.counts.bad_chains += 1;
0
}
};
// The crate refuses a head outside the table: the buffer cannot be returned, and nothing else can be done with it.
match active.queue.add_used(active.mem.as_ref(), head, len) {
Ok(()) => used_any = true,
Err(_) => self.counts.unreturned += 1,
}
}
if used_any && active.irq.signal_used().is_err() {
self.counts.unreturned += 1;
}
self.active = Some(active);
}
queue_notify takes self.active out of the Option and puts it back at the end, which is how it holds the queue and self.counts at once under the borrow checker; a doorbell for a queue the device does not have, or before activation, finds nothing and returns. The loop runs queue.size() times at most. A chain segments refuses becomes bad_chains and is returned with length 0, and so does one whose status cannot be written; add_used is the one call that can refuse a chain after that, and the case a guest can reach is a head past the table.
/// Do the request the driver described. `readable` is everything the device may read (the header, then any
/// data to write), `data_in` the device-writable part before the status byte. Returns the bytes written into
/// `data_in`, or the status byte to answer with. Nothing is done until the request has been checked whole.
fn execute(&mut self, mem: &GuestMemoryMmap<()>, readable: &[Seg], data_in: &[Seg]) -> std::result::Result<u32, u8> {
let (header, data_out) = split_at(readable, HEADER_LEN);
if total_len(&header) != HEADER_LEN {
return Err(STATUS_IOERR);
}
let mut raw = Vec::with_capacity(HEADER_LEN as usize);
read_all(mem, &header, &mut raw, HEADER_LEN as usize).map_err(|_| STATUS_IOERR)?;
// INVARIANT: `header` totals 16 bytes (checked above), so `raw` does and the two slices below are 4 and 8 bytes.
let typ = u32::from_le_bytes(raw[0..4].try_into().expect("4 bytes"));
let sector = u64::from_le_bytes(raw[8..16].try_into().expect("8 bytes"));
match typ {
VIRTIO_BLK_T_IN | VIRTIO_BLK_T_OUT => {
let write = typ == VIRTIO_BLK_T_OUT;
// Data goes the way the type says: a write's data is device-readable, a read's device-writable.
let (data, wrong_way) = if write { (&data_out[..], total_len(data_in)) } else { (data_in, total_len(&data_out)) };
let len = total_len(data);
let end = sector.checked_mul(SECTOR).and_then(|offset| offset.checked_add(len));
let in_range = end.is_some_and(|end| end <= self.sectors * SECTOR);
if wrong_way != 0 || len == 0 || !len.is_multiple_of(SECTOR) || len > MAX_DATA || !in_range || (write && self.read_only) {
return Err(STATUS_IOERR);
}
// INVARIANT: `in_range` checked `sector * SECTOR` for overflow.
self.transfer(mem, data, sector * SECTOR, write).map_err(|_| STATUS_IOERR)?;
// Section 5.2.6.2: with FLUSH offered and not negotiated, a completed write must already be stable.
// A failed sync answers IOERR with `used.len` 0 although the bytes reached the file: the guest is told the write is
// not stable, which is true.
if write && !self.flush_negotiated {
self.counts.syncs += 1;
self.file.sync_data().map_err(|_| STATUS_IOERR)?;
}
Ok(if write { 0 } else { len as u32 })
}
VIRTIO_BLK_T_FLUSH => {
self.counts.syncs += 1;
self.file.sync_data().map(|()| 0).map_err(|_| STATUS_IOERR)
}
_ => Err(STATUS_UNSUPP),
}
}
/// Serve one chain and return the `len` for the used ring. The status byte is the last byte of the
/// device-writable part; a chain with none cannot be answered, so it is not served at all.
fn handle_request(&mut self, mem: &GuestMemoryMmap<()>, segs: &Segments) -> u32 {
let writable = total_len(&segs.writable);
let (data_in, status) = split_at(&segs.writable, writable.saturating_sub(1));
if status.is_empty() {
self.counts.bad_chains += 1;
return 0;
}
let (code, used_len) = match self.execute(mem, &segs.readable, &data_in) {
Ok(written) => (STATUS_OK, written + 1),
// 2.7.8.2: `len` counts bytes written from the first writable buffer, and a failed request wrote none.
Err(code) => (code, 0),
};
if write_all(mem, &status, &[code]).is_err() {
self.counts.bad_chains += 1;
return 0;
}
if code == STATUS_OK {
self.counts.ok += 1;
} else {
self.counts.errors += 1;
}
used_len
}
execute validates the whole request and does the I/O last: the header is gathered first, the direction check uses the lists segments split, the range check is in checked arithmetic (checked_mul, checked_add), and transfer is called only when every refusal has passed. handle_request finds the status byte, the last writable byte, before it asks execute anything, because a chain with nowhere to say how it went cannot be answered and is not served at all. The 0 in the failure arm is the used.len ruling. This is the function IMPL=mine replaces.
Net
/// Attach to the TAP `name`, which must already exist (`ip tuntap add dev NAME mode tap`): `wick` never creates one,
/// since creating a network device takes a capability the VMM does not have outside its own network namespace, and
/// inside one a misspelled name would otherwise quietly become a new, unconnected TAP. The descriptor is
/// non-blocking and carries `virtio_net_hdr_v1` in front of every frame: `IFF_VNET_HDR` and a 12-byte header
/// (`TUNSETVNETHDRSZ`). `TUNSETOFFLOAD` 0 turns off what the kernel hands the READER (`tun.c` `set_offload`, line 2862:
/// no checksum or GSO frames on receive). It does not limit the writer: `tun_get_user` (linux v7.2.8,
/// `drivers/net/tun.c:1738-1747`) reads the header through `__tun_vnet_hdr_get` (`drivers/net/tun_vnet.h:120-147`),
/// and the header then decides what skb is built, checksum-pending or GSO: `tun_get_user` calls
/// `tun_vnet_hdr_tnl_to_skb` (`tun.c:1821`; `tun_vnet.h:198`), which calls `virtio_net_hdr_tnl_to_skb`
/// (`include/linux/virtio_net.h:296`), which with no tunnel bit set calls `virtio_net_hdr_to_skb` (`:207-212`, `:311`)
/// and so `__virtio_net_hdr_to_skb` (`:51-205`). So `send_frame` clears the guest's header before it writes.
pub fn open_tap(name: &str) -> Result<File> {
check_tap_name(name)?;
let refuse = |why: String| Error::Config(format!("network interface {name}: {why}"));
let cname = CString::new(name).map_err(|_| refuse("a NUL in the name".into()))?;
// SAFETY: `cname` is a NUL-terminated string that outlives the call.
let index = unsafe { libc::if_nametoindex(cname.as_ptr()) };
if index == 0 {
return Err(refuse("the TAP does not exist (wick attaches to a TAP, it cannot create one)".into()));
}
let tun = std::fs::OpenOptions::new()
.read(true)
.write(true)
.custom_flags(libc::O_NONBLOCK)
.open("/dev/net/tun")
.map_err(|e| refuse(format!("/dev/net/tun: {e}")))?;
let fd = tun.as_raw_fd();
let mut ifreq = [0u8; IFREQ_LEN];
ifreq[..name.len()].copy_from_slice(name.as_bytes());
ifreq[IFNAMSIZ..IFNAMSIZ + 2].copy_from_slice(&(IFF_TAP | IFF_NO_PI | IFF_VNET_HDR).to_ne_bytes());
// SAFETY: `fd` is the open tun descriptor; TUNSETIFF reads and writes one `struct ifreq`, which `ifreq` is the size of.
if unsafe { libc::ioctl(fd, TUNSETIFF, ifreq.as_mut_ptr()) } < 0 {
return Err(refuse(format!("TUNSETIFF: {}", std::io::Error::last_os_error())));
}
let size = HDR_LEN as libc::c_int;
// SAFETY: TUNSETVNETHDRSZ reads one `int` from the pointer.
if unsafe { libc::ioctl(fd, TUNSETVNETHDRSZ, &size as *const libc::c_int) } < 0 {
return Err(refuse(format!("TUNSETVNETHDRSZ: {}", std::io::Error::last_os_error())));
}
// SAFETY: TUNSETOFFLOAD takes its flags by value; 0 turns every offload off.
if unsafe { libc::ioctl(fd, TUNSETOFFLOAD, 0 as libc::c_ulong) } < 0 {
return Err(refuse(format!("TUNSETOFFLOAD: {}", std::io::Error::last_os_error())));
}
// TUNSETIFF creates a TAP if the name vanished since the check; the same name could even be another interface now.
// The index must be the one seen before. If not, `tun` is dropped here and the kernel destroys what it made.
// SAFETY: as above.
if unsafe { libc::if_nametoindex(cname.as_ptr()) } != index {
return Err(refuse("the TAP changed while it was being attached".into()));
}
Ok(tun)
}
Everything the Net section said about the TAP is in this function’s order: the name is checked, the interface looked up (and refused if missing), then the three ioctls, then the interface looked up again. The doc comment is the chain of calls from tun_get_user to the header’s handling, which is the evidence that TUNSETOFFLOAD does not constrain the writer.
/// The guest rang queue 1: send each chain it offered, up to one queue's worth, and give every buffer back.
/// A frame is the chain's device-readable bytes, `virtio_net_hdr_v1` first, written to the TAP in one call. The TAP
/// is non-blocking: a frame it cannot take is dropped and counted, which is what a full wire does, and the
/// thread never waits for it.
fn transmit(&mut self) {
let Some(a) = self.active.as_mut() else { return };
if !a.queues[TXQ].ready() {
return;
}
let mut used_any = false;
for _ in 0..a.queues[TXQ].size() {
let Some(chain) = a.queues[TXQ].pop_descriptor_chain(a.mem.as_ref()) else { break };
let head = chain.head_index();
match segments(a.mem.as_ref(), chain) {
Ok(segs) => send_frame(&self.tap, a.mem.as_ref(), &segs, &mut self.tx_buf, &mut self.counts),
Err(_) => self.counts.tx_refused += 1,
}
match a.queues[TXQ].add_used(a.mem.as_ref(), head, 0) {
Ok(()) => used_any = true,
Err(_) => self.counts.unreturned += 1,
}
}
if used_any && a.irq.signal_used().is_err() {
self.counts.unreturned += 1;
}
}
/// Write one transmit chain to the TAP, or count why not. The chain must be all device-readable, hold at least the
/// header and at most `MAX_FRAME_WITH_HDR` bytes.
fn send_frame(tap: &File, mem: &GuestMemoryMmap<()>, segs: &Segments, buf: &mut Vec<u8>, counts: &mut NetCounts) {
let len = total_len(&segs.readable);
if !segs.writable.is_empty() || len < HDR_LEN as u64 || len > MAX_FRAME_WITH_HDR as u64 {
counts.tx_refused += 1;
return;
}
buf.clear();
if read_all(mem, &segs.readable, buf, MAX_FRAME_WITH_HDR).is_err() {
counts.tx_refused += 1;
return;
}
// The device answers for the header. Nothing was offered, so a driver writes zeros (section 5.1.6.2.1: "If
// VIRTIO_NET_F_CSUM is not negotiated, the driver MUST set flags to zero", and gso_type NONE without the TSO and
// UFO features; section 5.1.6.2.2: the device "MUST ignore flag bits that it does not recognize"). The TAP does not
// ignore them: it turns NEEDS_CSUM into a checksum the host kernel computes and a GSO type into a segmented skb, from
// values the guest chose. So the header goes out as zeros, and a guest that sent anything else is counted.
if buf[..HDR_LEN].iter().any(|&b| b != 0) {
counts.tx_hdr_cleared += 1;
buf[..HDR_LEN].fill(0);
}
let mut tap = tap;
match tap.write(buf) {
Ok(n) if n == buf.len() => {
counts.tx_frames += 1;
counts.tx_bytes += n as u64;
}
_ => counts.tx_dropped += 1,
}
}
transmit is the loop and send_frame is the policy: refuse a chain with a writable descriptor, one shorter than the header, one longer than the bound; gather it into one reused buffer; clear the header; one write. A short or failed write is a dropped frame and a counter, and the thread has already moved on.
/// The TAP is readable: take the frames waiting (at most `RX_BUDGET`) and hand each to the next posted receive
/// buffer. Every frame is read, so the level-triggered loop cannot spin on a TAP nobody serves; one that finds no
/// buffer is dropped and counted. The alternative, to stop watching the TAP until the driver posts a buffer,
/// would leave frames queued in the kernel and need the vCPU thread to tell the loop when buffers arrive.
/// One interrupt for the batch. Returns false when the TAP can never be read again.
fn receive(&mut self) -> bool {
let mut delivered = false;
let mut readable = true;
for _ in 0..RX_BUDGET {
let n = match (&self.tap).read(&mut self.rx_buf) {
Ok(n) if n > 0 => n,
Err(e) if e.kind() == ErrorKind::WouldBlock => break,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
_ => {
self.counts.rx_read_errors += 1;
readable = false;
break;
}
};
if n < HDR_LEN {
self.counts.rx_dropped_runt += 1;
continue;
}
match self.active.as_mut() {
Some(a) => delivered |= deliver(a, &mut self.rx_buf[..n], &mut self.counts),
None => self.counts.rx_dropped_no_buffer += 1,
}
}
if delivered && self.active.as_ref().is_some_and(|a| a.irq.signal_used().is_err()) {
self.counts.unreturned += 1;
}
readable
}
/// Give `frame` (header first) to the next receive buffer. Returns whether a buffer went back to the driver (so the
/// batch needs an interrupt). Without `VIRTIO_NET_F_MRG_RXBUF` the frame must fit one chain, and the device sets
/// `num_buffers` to 1 itself, as section 5.1.6.4.1 says ("If VIRTIO_NET_F_MRG_RXBUF has not been negotiated, the
/// device MUST set num_buffers to 1"), and clears the rest of the header (`include/uapi/linux/virtio_net.h:152` is the struct,
/// `num_buffers` at byte 10).
fn deliver(a: &mut Active, frame: &mut [u8], counts: &mut NetCounts) -> bool {
if !a.queues[RXQ].ready() {
counts.rx_dropped_no_buffer += 1;
return false;
}
let Some(chain) = a.queues[RXQ].pop_descriptor_chain(a.mem.as_ref()) else {
counts.rx_dropped_no_buffer += 1;
return false;
};
let head = chain.head_index();
let used = match segments(a.mem.as_ref(), chain) {
// A receive buffer is all device-writable (sections 2.7.4.2 and 5.1.6); anything else goes back unused.
Ok(segs) if !segs.readable.is_empty() => {
counts.rx_bad_chains += 1;
0
}
Ok(segs) if total_len(&segs.writable) < frame.len() as u64 => {
// Too small for this frame: drop the frame, and leave the buffer posted for a smaller one.
a.queues[RXQ].go_to_previous_position();
counts.rx_dropped_too_big += 1;
return false;
}
Ok(segs) => {
// No VIRTIO_NET_F_GUEST_CSUM or GSO was offered, so the device MUST set flags to zero (section 5.1.6.4.1) and
// the TAP's own flags (DATA_VALID for a checksummed frame) are not the guest's to see.
frame[..NUM_BUFFERS_AT].fill(0);
frame[NUM_BUFFERS_AT..NUM_BUFFERS_AT + 2].copy_from_slice(&1u16.to_le_bytes());
write_all(a.mem.as_ref(), &segs.writable, frame).unwrap_or_else(|_| {
counts.rx_bad_chains += 1;
0
})
}
Err(_) => {
counts.rx_bad_chains += 1;
0
}
};
match a.queues[RXQ].add_used(a.mem.as_ref(), head, used) {
Ok(()) => {
if used > 0 {
counts.rx_frames += 1;
counts.rx_bytes += u64::from(used);
}
true
}
Err(_) => {
counts.unreturned += 1;
false
}
}
}
receive reads before it asks whether anything is posted, which is the rule that keeps the loop from spinning, and it breaks only on WouldBlock, the budget, or a read error that returns false to the loop. deliver is where a frame meets a buffer: no buffer, not ready and refused chains are drops; a buffer too small leaves the chain posted by stepping the queue back (go_to_previous_position); a good one gets its header rewritten, byte 10 set to 1, and is returned with the number of bytes written.
vsock
/// Take what the guest transmitted (at most one queue's worth, and what the wake's budget allows), and give every buffer
/// back. Returns whether any went back (the guest needs an interrupt). Stops, leaving the rest in the queue, when the
/// resets waiting for the guest are at their bound.
fn drain_tx(&mut self, a: &mut Active, budget: &mut Budget) -> bool {
let Active { mem, queues, .. } = a;
let q = &mut queues[TXQ];
if !q.ready() {
return false;
}
let mem = mem.as_ref();
let mut returned = false;
for _ in 0..q.size() {
if budget.exhausted() {
break;
}
if self.pending.len() >= self.limits.max_pending_rx {
self.counts.tx_stalled += 1;
break;
}
let Some(chain) = q.pop_descriptor_chain(mem) else { break };
let head = chain.head_index();
let mut spent = 0;
let peek_chain = chain.clone();
let max_segs = usize::from(q.size());
match segments_up_to(mem, chain, max_segs) {
Err(_) => {
self.counts.tx_refused += 1;
if let Some(hdr) = packet::peek_chain_header(mem, peek_chain) {
self.refused_packet(&hdr);
}
}
Ok(segs) => {
let mut buf = std::mem::take(&mut self.scratch_tx);
match tx_packet(mem, &segs, &mut buf) {
Ok(hdr) => {
self.counts.tx_max_segments = self.counts.tx_max_segments.max(segs.readable.len() as u64);
self.counts.tx_max_payload = self.counts.tx_max_payload.max(u64::from(hdr.len));
// INVARIANT: `tx_packet` checked that the chain held `HDR_LEN + hdr.len` bytes, and `buf` holds them.
spent = HDR_LEN + hdr.len as usize;
self.on_guest_packet(&hdr, &buf[HDR_LEN..spent]);
}
Err(why) => {
self.counts.tx_refused += 1;
if matches!(why, packet::TxRefused::BadLen(_)) {
self.counts.tx_bad_len += 1;
}
spent = buf.len();
if let Some(hdr) = packet::peek_header(mem, &segs.readable) {
self.refused_packet(&hdr);
}
}
}
self.scratch_tx = buf;
}
}
budget.spend(spent);
match q.add_used(mem, head, 0) {
Ok(()) => returned = true,
Err(_) => self.counts.unreturned += 1,
}
}
returned
}
/// One packet from the guest. A type other than stream, or addresses that are not the guest's and CID 2, are answered
/// `RST` (section 5.10.6.4.2: "A VIRTIO_VSOCK_OP_RST reply MUST be sent if a packet is received with an unknown type
/// value"; the same reply makes a connect to another CID fail at once instead of timing out). A packet for a
/// connection that does not exist is answered `RST` too (section 5.10.6.5), except an `RST`, which is never answered
/// (`virtio_transport_reset_no_sock`, `vtc.c:1331`).
fn on_guest_packet(&mut self, hdr: &Header, payload: &[u8]) {
self.counts.tx_packets += 1;
self.counts.tx_bytes += payload.len() as u64;
if hdr.typ != TYPE_STREAM {
self.counts.tx_bad_type += 1;
return self.reset_unknown(hdr);
}
if hdr.dst_cid != HOST_CID || hdr.src_cid != self.guest_cid {
self.counts.tx_bad_cid += 1;
return self.reset_unknown(hdr);
}
let key = ConnKey { guest_port: hdr.src_port, host_port: hdr.dst_port };
if hdr.op == OP_REQUEST {
return self.guest_request(key, hdr);
}
if self.conns.contains_key(&key) {
self.conn_packet(key, hdr, payload);
} else if hdr.op != OP_RST {
self.counts.tx_unknown_conn += 1;
self.reset_unknown(hdr);
}
}
drain_tx is transmit with three more things to guard: the wake’s budget is checked first and the pending-reset bound second, both before the chain is popped (budget.spend comes after the packet is handled), and a chain segments_up_to refuses is not simply dropped, because peek_chain_header may still find a header in its first descriptor to tell which connection to reset. on_guest_packet is the dispatch: type first, then addresses, then REQUEST, then a live connection, and last the reset for one that does not exist, in the order of how much of the packet can be trusted at that point.
/// How many payload bytes may be sent to the guest now: section 5.10.6.3, `peer_free = peer_buf_alloc - (tx_cnt -
/// peer_fwd_cnt)`, in `Wrapping<u32>` so the free-running counters wrap, and never below zero (the guest may shrink
/// `buf_alloc` while bytes are in flight: the kernel does this sum in `s64` and clamps, `vtc.c:1022-1034`).
pub fn peer_credit(&self) -> u32 {
let in_flight = (self.rx_cnt - self.peer_fwd_cnt).0;
self.peer_buf_alloc.saturating_sub(in_flight)
}
rx_cnt is the bytes the device has sent to the guest, the specification’s tx_cnt seen from the device’s side, and peer_fwd_cnt is the last fwd_cnt the guest reported; their free-running difference is what is in flight, and the guest’s buf_alloc less that is the room.
/// Parse `CONNECT <port>\n` out of the bytes peeked from a new host connection. Exactly that: upper-case `CONNECT`, one
/// space, one to ten decimal digits, a bare `\n`. (Firecracker is looser: it splits on whitespace and ignores case.
/// The document it ships says `CONNECT PORT\n`, and a client that wants to talk to the guest can write that.) The
/// port is a `u32`; `0xffffffff` is `VMADDR_PORT_ANY` (`include/uapi/linux/vm_sockets.h:109`), never a port to connect to.
pub fn parse_connect(peeked: &[u8]) -> ConnectLine {
let window = &peeked[..peeked.len().min(MAX_LINE)];
let Some(nl) = window.iter().position(|&b| b == b'\n') else {
return if peeked.len() >= MAX_LINE { ConnectLine::Invalid } else { ConnectLine::Incomplete };
};
let Some(digits) = window[..nl].strip_prefix(b"CONNECT ") else { return ConnectLine::Invalid };
if digits.is_empty() || digits.len() > 10 || !digits.iter().all(u8::is_ascii_digit) {
return ConnectLine::Invalid;
}
let port = digits.iter().fold(0u64, |n, &d| n * 10 + u64::from(d - b'0'));
match u32::try_from(port) {
// Port 0 is no one's: a guest `bind` to 0 asks for an ephemeral port, so there is never a listener to find.
Ok(port) if port != 0 && port != u32::MAX => ConnectLine::Connect { port, len: nl + 1 },
_ => ConnectLine::Invalid,
}
}
parse_connect is a function of bytes and nothing else, so its invalid forms are a table in a unit test (anything_else_is_invalid: other case, extra spaces, a sign, hex, a carriage return, a NUL, and ports of 0, 0xffffffff and past 32 bits). It is handed what recv peeked, not what it consumed: the line is read off the socket only once it parses, and then only up to its newline, so whatever the client sent after it is the connection’s data.
/// The epoll descriptor is readable: handle what it reports (at most `wake_events`; the rest stays reported), then move
/// packets. Always reads what it is given, so the level-triggered loop outside cannot spin on this descriptor.
fn on_host_events(&mut self) -> bool {
let mut events = std::mem::take(&mut self.events);
events.clear();
if self.bridge.wait(&mut events, self.limits.wake_events).is_err() {
self.events = events;
self.counts.epoll_errors += 1;
return false;
}
let mut timer = false;
for &ev in &events {
match ev.id {
TOKEN_LISTENER => self.accept_pending = true,
TOKEN_KICK => self.bridge.drain_kick(),
TOKEN_TIMER => {
self.bridge.drain_timer();
timer = true;
}
id => self.stream_event(id, ev),
}
}
self.events = events;
if timer {
self.expire(Instant::now());
}
self.pump();
self.settle();
true
}
/// An event on a host stream: one still waiting for its `CONNECT` line, or a connection's.
fn stream_event(&mut self, id: u64, ev: Ready) {
if self.lines.contains_key(&id) {
return self.line_event(id, ev);
}
let Some(&key) = self.by_id.get(&id) else { return };
let Some(e) = self.conns.get_mut(&key) else { return };
e.readable |= ev.readable();
e.writable |= ev.writable();
e.rdhup |= ev.rdhup();
if ev.hup() && !e.shut_wr {
e.full = true;
}
let judge = e.rdhup || e.full;
if judge {
self.judge_host(key);
}
if self.conns.get(&key).is_some_and(|e| e.writable && e.conn.buffered() > 0) {
self.flush(key);
}
self.touch(key);
}
on_host_events is the one function the VMM loop calls for the device’s epoll descriptor, and it is built so that it always reads what it is given: at most wake_events events are taken, the kick and the timer are drained, each stream event updates a connection’s flags, and then pump moves packets both ways until nothing more can move or the wake’s budget is gone. stream_event records what an event says (readable, writable, and the two kinds of end, with the rule from the Mechanism section for what EPOLLHUP means: ev.hup() && !e.shut_wr), asks judge_host to decide an end, where a peek at the socket tells an end from more data, and flushes bytes parked toward a host that can take them.
Exercises
Each answer is a run on talos (Intel, 2026-10-02) in a scratch copy of wick/ and of labs/ch25/ with the edit the exercise names, on the lab’s own kernel and initramfs, bounded by timeout; the runs’ output is kept outside the repository, one directory for each. Where an answer is a sentence from the specification or the kernel and not a run, it says so.
(a) Remove VIRTIO_F_VERSION_1 from the features Block offers, and run the block boot. What does the guest’s driver do, and what does wick say?
Answer
The guest’s driver refuses the device before it writes one feature bit, and wick says nothing, because it never sees a refusal. The guest’s virtio_blk lines, added to the init for this run, and its verdict:
virtio_blk virtio0: New virtio-mmio devices (version 2) must provide VIRTIO_F_VERSION_1 feature!
virtio_blk virtio0: probe with driver virtio_blk failed with error -22
blk: FAIL no /dev/vda
The refusal is the driver’s own, in the transport’s feature step:
// linux v7.2.8, drivers/virtio/virtio_mmio.c:119-124
/* Make sure there are no mixed devices */
if (vm_dev->version == 2 &&
!__virtio_test_bit(vdev, VIRTIO_F_VERSION_1)) {
dev_err(&vdev->dev, "New virtio-mmio devices (version 2) must provide VIRTIO_F_VERSION_1 feature!\n");
return -EINVAL;
}
The guest reads Version as 2 because wick reports 2, so a device of this transport that does not offer the bit is unusable to this driver; -22 is -EINVAL, and /dev/vda never appears. The transport’s own rule for the same bit (FEATURES_OK stays set only for a subset that includes VIRTIO_F_VERSION_1, features_ok_sticks_only_for_a_subset_that_has_version_1) is for a driver that gets this far, and the run does not reach it. wick’s end of the run is the same as a good one’s, vcpu 0 exit Shutdown, exit 0, wick rc=0, as chapter 24 said a clean run’s must be; only the capture’s verdict lines and the host’s check, host: FAIL sector 1 not written, tell the runs apart.
The init’s [ -b /dev/vda ] test is there because of this exercise. Without it, with no block device, dd of=/dev/vda makes a regular file of that name on the guest’s devtmpfs, and the later read and compare agree with it: the run printed blk: write verified for a disk that never came up. Only the host-side check, which looks at the file the guest was supposed to write, said otherwise.
(b) Make handle_request answer a failed request with used.len 513 instead of 0, and make a read fail (a stand-in for a medium error: the scratch execute refuses the read that starts at sector 8). Read sector 8 from the guest. What does the driver do? What could a driver that trusted len leak (§2.7.8.2)?
Answer
The guest cannot tell the 513 from the 0. The same run with the reference’s used.len 0 (the control: only the sector-8 refusal is in the scratch copy) prints the same guest lines, apart from the timing dd prints for the first read:
dd sector 0 rc=0
dd: /dev/vda: Input/output error
dd sector 8 rc=1
I/O error, dev vda, sector 8 op 0x0:(READ) flags 0x880700 phys_seg 1 prio class 2
I/O error, dev vda, sector 8 op 0x0:(READ) flags 0x800000 phys_seg 1 prio class 2
The reason is the Block section’s: this driver takes the result from the status byte and never reads len. The other half of the question is not something this guest can answer, and is a cited sentence. The refused request is a page of 4 KiB, none of whose data bytes the device wrote, so 513 claims bytes that were not written, against §2.7.8.2. The specification’s note on the same page says what is at stake for a driver that believes it: “if a driver does not know exactly how much has been written by the device, the driver would have to zero the buffer in advance to ensure no data leakage occurs. For example, a network driver may hand a received buffer directly to an unprivileged userspace application. If the network device has not overwritten the bytes which were in that buffer, this could leak the contents of freed memory from other processes to the application.” For a block driver the buffer is the caller’s data buffer, and one that took the length as proof of data and ignored a failed status would hand the caller whatever the buffer held before.
(c) Remove the bound on a doorbell’s work in Block::queue_notify (the loop over queue.size() becomes loop) and run a_buffer_that_refills_the_ring_is_drained_at_most_size_chains_per_doorbell of tests/hostile.rs. What does the VMM thread do?
Answer
It serves chains until the disk runs out, and the test fails every time. Three runs with the one edit (cargo test --release --test hostile, talos, 2026-10-03):
left: 72
right: 8
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 68 filtered out; finished in 0.00s
left: 72
right: 8
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 68 filtered out; finished in 0.00s
left: 72
right: 8
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 68 filtered out; finished in 0.00s
The test has no thread and no timing. Chain 0 is a header, a 512-byte writable buffer that covers the available ring and the next header, and a status byte, and sector k of the 64-sector disk holds the value of avail.idx that makes the ring look refilled, k + 1 + 8, and the next request’s header. Every read the device serves is therefore the driver’s refill: avail.idx stays eight ahead of the device for as long as there are sectors. Without the bound, one doorbell served 72 chains, the 64 sectors plus the 8 the ring began with, where the bound gives 8, and a disk of any size would have held the thread for as long. The test’s second assertion, that avail.idx ended at 16, is its precondition: it proves the refill happened, so that a pass means the device stopped and not that the ring ran dry. Each chain is one 512-byte pread and a copy, so the work grows with what the guest supplies and not with the queue, and the thread is the one that answers the API’s requests. The bound is what turns that into at most one queue’s worth of chains for each doorbell. The test is also a hostile case of its own: a writable buffer that aliases the ring.
(d) Run the net boot with run.sh’s unshare -Urn line removed, so that the script runs as the ordinary user in the host’s network namespace. What fails, in what order, and why does creating a TAP need a capability the namespace grants only inside itself?
Answer
Several things fail, in the order the script does them, and the guest ends with no network. The script’s own output, then the run’s:
ioctl(TUNSETIFF): Operation not permitted
Cannot find device "tap0"
Cannot find device "tap0"
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /network-interfaces/eth0 400
{"fault_message":"network interface tap0: the TAP does not exist (wick attaches to a TAP, it cannot create one)"}
ctl: PUT /actions 204
ip: can't find device 'eth0'
ip: SIOCGIFFLAGS: No such device
ping: sendto: Network is unreachable
net:
ip tuntap add asks for a TAP and the kernel says no, with the check the Net section quoted in tun_set_iff; ip addr and ip link then find no tap0; wick’s PUT /network-interfaces/eth0 answers 400, because open_tap refuses a name that does not exist (and the machine starts without the interface: the guest’s ip cannot find eth0, and its ping has nowhere to go). The capability is the one the Net section explained: asked for in the user namespace that owns the network namespace, which is the initial one here and the one unshare -Urn makes otherwise. The check for attaching to a TAP that already exists is different, and is a cited sentence, not a run:
// linux v7.2.8, drivers/net/tun.c:513-521
static inline bool tun_not_capable(struct tun_struct *tun)
{
const struct cred *cred = current_cred();
struct net *net = dev_net(tun->dev);
return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
(gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
!ns_capable(net->user_ns, CAP_NET_ADMIN);
}
A TAP created by a privileged setup step with an owner (ip tuntap add dev tap0 mode tap user kyle) can be opened by that user with no capability at all, because tun_not_capable is false when the caller’s uid is the owner’s. That is the arrangement a production host would use, one TAP for each guest made by something privileged; the lab’s namespace is what lets it do without the privileged step.
(e) Make the device advertise buf_alloc 0 (BUF_ALLOC in conn.rs) and run the vsock boot. The guest’s send blocks: where, by the kernel source? Give the guest’s sockets a send timeout to make it stop.
Answer
The connection is made and the guest’s first write waits for credit that never comes. With the lab’s helper unchanged, the run ends only because timeout (15 s here) ends it:
vsock: FAIL write: Broken pipe
host: FAIL read: Resource temporarily unavailable
host: got "" then eof
host: FAIL write: Broken pipe
wick rc=124
waitline: no line containing 'vsock: listening' in out/console.txt within 30 s
The guest’s console shows one line, vsock: FAIL write: Broken pipe; the rest is the hosts’. The first host line is the listener for port 5000: it accepted the guest’s connection, so the connection was up, and gave up on its read after its own 10 s timeout. When it closed, the device told the guest the host would receive no more, the guest’s blocked write woke and ended with EPIPE (the peer_shutdown & RCV_SHUTDOWN test after the wait loop, af_vsock.c:2276-2282), the helper failed and the init went on to its second send. The second and third host lines are the listener for port 5001, which saw that connection and its end with no data (and then, having read the end, wrote its pong to a guest that was already gone, which failed with Broken pipe). The guest’s second send, which made that connection, blocked the same way as the first until timeout ended wick and the guest’s socket with it. waitline gave up after its 30 s, since the guest never printed vsock: listening. The wait is in the guest’s sendmsg:
// linux v7.2.8, net/vmw_vsock/af_vsock.c:2239-2268
while (vsock_stream_has_space(vsk) == 0 &&
sk->sk_err == 0 &&
!(sk->sk_shutdown & SEND_SHUTDOWN) &&
!(vsk->peer_shutdown & RCV_SHUTDOWN)) {
/* Don't wait for non-blocking sockets. */
if (timeout == 0) {
err = -EAGAIN;
remove_wait_queue(sk_sleep(sk), &wait);
goto out_err;
}
err = transport->notify_send_pre_block(vsk, &send_data);
if (err < 0) {
remove_wait_queue(sk_sleep(sk), &wait);
goto out_err;
}
release_sock(sk);
timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
lock_sock(sk);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
remove_wait_queue(sk_sleep(sk), &wait);
goto out_err;
} else if (timeout == 0) {
err = -EAGAIN;
remove_wait_queue(sk_sleep(sk), &wait);
goto out_err;
}
The loop waits while vsock_stream_has_space is 0, and sleeps in wait_woken for the socket’s send timeout, which is unlimited unless set. The space is the transport’s:
// linux v7.2.8, net/vmw_vsock/virtio_transport_common.c:958-965
static u32 virtio_transport_tx_buf_size(struct virtio_vsock_sock *vvs)
{
/* The peer advertises its receive buffer via peer_buf_alloc, but we
* cap it to our local buf_alloc so a remote peer cannot force us to
* queue more data than our own buffer configuration allows.
*/
return min(vvs->peer_buf_alloc, vvs->buf_alloc);
}
// linux v7.2.8, net/vmw_vsock/virtio_transport_common.c:1022-1036
static s64 virtio_transport_has_space(struct virtio_vsock_sock *vvs)
{
s64 bytes;
/* Use s64 arithmetic so if the peer shrinks peer_buf_alloc while
* we have bytes in flight (tx_cnt - peer_fwd_cnt), the subtraction
* does not underflow.
*/
bytes = (s64)virtio_transport_tx_buf_size(vvs) -
(vvs->tx_cnt - vvs->peer_fwd_cnt);
if (bytes < 0)
bytes = 0;
return bytes;
}
The device’s RESPONSE and every later packet carry buf_alloc 0, so peer_buf_alloc is 0, min(0, buf_alloc) is 0, and the free space is 0 minus bytes in flight, clamped to 0, and stays there: the only way out is a packet that raises buf_alloc, and the device sends none. With SO_SNDTIMEO of 3 s on the helper’s sockets (the second run), the same wait ends at the timeout == 0 arm of the loop and the write fails with EAGAIN:
vsock: FAIL write: Resource temporarily unavailable
vsock: FAIL write: Resource temporarily unavailable
vsock: listening
vsock: guest got "hello-from-host"
vsock: FAIL write: Resource temporarily unavailable
host: got ""
host: FAIL write: Broken pipe
host: got "" then eof
host: FAIL write: Broken pipe
host: OK
host: got ""
host: FAIL expected an OK line, got ""
The host lines are the other ends of the same failures: connections that carried no bytes, a listener’s pong written to a guest that had gone (Broken pipe: the helpers ignore SIGPIPE, so a write to a reset peer reaches their error message), and a vsock-connect that read the end of the stream where it expected OK. All three guest sends fail the same way. The host-to-guest direction works: the guest’s listener got hello-from-host, because the host’s data is governed by the guest’s buf_alloc, which is the Linux default, and what the guest could not do is answer.
(f) Remove the host listener for guest port 5000 and run the vsock boot. What errno does the guest’s connect return, and what packet caused it?
Answer
ECONNRESET, “Connection reset by peer”, caused by an RST that the device sent in reply to the guest’s REQUEST. The guest’s lines, and the three wick: lines that two scratch eprintlns added to the device print (guest ports are the guest’s own ephemeral numbers and change from boot to boot):
vsock: FAIL connect: Connection reset by peer
vsock: guest sent "half-from-guest" half-closed got "pong half-from-guest"
vsock: listening
vsock: guest got "hello-from-host"
vsock: guest got "half-from-host" then eof
wick: connect to the host listener of port 5000 failed: No such file or directory (os error 2)
wick: RST queued for guest port 1117494098 from host port 5000 (packet op 1, type 1)
wick: RST queued for guest port 1117494099 from host port 5001 (packet op 6, type 1)
The device took the REQUEST (packet op 1, type 1: stream) from guest port 1117494098, which is the guest’s connect to host port 5000, tried connect_port on out/v.sock_5000, and got ENOENT because no one had bound it. A failed connect is reset_unknown: an RST is queued for the guest’s port, from host port 5000, and sent when the guest next has a receive buffer posted. It is what the last sentence of Firecracker’s paragraph on guest-initiated connections says (“a VIRTIO_VSOCK_OP_RST packet will be sent back to the guest”). The guest’s socket was in its connecting state, and in that state an RST is an error:
// linux v7.2.8, net/vmw_vsock/virtio_transport_common.c:1478-1481
case VIRTIO_VSOCK_OP_RST:
skerr = ECONNRESET;
err = 0;
goto destroy;
(The OP_RST arm of virtio_transport_recv_connecting; at destroy the socket is closed and skerr is stored as its sk_err, which the connect in progress reports.) The second wick: line is not the failure: it is a packet of op 6, a CREDIT_UPDATE, from the guest’s other connection, the one to port 5001, arriving after the device had ended it; a packet for a connection that no longer exists is answered with a reset (and, as the Mechanism section says, a reset is never answered). The same run also shows the other host listener, port 5001, serving its connection: host: got "half-from-guest" then eof, in the lines above.
Lab
make lab CH=25
make lab CH=25 IMPL=mine
tools/remote-lab.sh lab CH=25
make -C wick test clippy
labs/lab.wick.mk is the shared rule set of chapter 24, and labs/ch25/Makefile adds what this lab needs to it: the three helpers of the lab, all native and static (labs/ch25/guest/vsock.c, which goes into the initramfs as /bin/vsock, and the host’s labs/ch25/host/vsock-listen.c and vsock-connect.c), rebuilt when their source or the Makefile changes, and the harness target, which runs cargo run --example ch22-harness into out/harness.txt and diffs it against head -6 ../ch22/capture.txt: the six lines are literally chapter 22’s. run.sh begins by re-executing itself under unshare -Urn, creates tap0 and gives it 172.16.0.1/24, copies the six harness lines into out/run.txt, and boots wick four times, with the guest’s choice of section made from a lab= word on its command line. Each boot starts from a fresh out/disk.img (disk.pattern.sh, chapter 22’s pattern: byte i of sector s is (s * 7 + i) & 0xff, written with printf and octal escapes), starts the host listeners for guest ports 5000 and 5001 before wick so that the sockets exist before the guest can ask for them, makes the same wick ctl calls as chapter 24 with PUT /drives/vda, PUT /network-interfaces/eth0 and PUT /vsock added for the devices the section has, and, for a section with vsock, blocks on labs/waitline.sh out/console.txt 'vsock: listening' 30 before it connects, because a host-initiated connection must find the guest’s listener. waitline.sh is a blocking read of a followed file with an overall deadline, not a sleep loop; chapters 26 and 27 reuse it. Built binaries never travel between the hosts: remote-lab.sh sends no overlay/bin/ and brings back no out/bin/, and the guest helper is staged into the overlay on every run, so each host’s initramfs holds the helper that host built. When wick has exited, cmp compares sector 1 of the disk file with the 512 bytes of 0x5a the guest was to write, and the script prints host: sector 1 written by guest or host: FAIL.
The guest’s side is one script. It reads /proc/cmdline for lab= and runs the sections that word names, between the two sentinels:
mount -t proc proc /proc
mount -t devtmpfs devtmpfs /dev
mount -t sysfs sysfs /sys
dmesg -n 1
# The kernel command line carries lab=blk, lab=net, lab=vsock or lab=all (a word of boot_args).
lab=all
for w in $(cat /proc/cmdline); do
case $w in lab=*) lab=${w#lab=} ;; esac
done
want() { [ "$lab" = "$1" ] || [ "$lab" = all ]; }
echo "=== lab begin"
if want blk && [ ! -b /dev/vda ]; then
# Without the guard, dd would make a regular file called /dev/vda and "verify" a write to it.
echo "blk: FAIL no /dev/vda"
elif want blk; then
set -- $(hexdump -n 16 -e '16/1 "%02x "' /dev/vda)
echo "blk: sector 0: $*"
echo "blk: capacity $(cat /sys/block/vda/size) sectors"
head -c 512 /dev/zero | tr '\0' 'Z' > /tmp/z512
dd if=/tmp/z512 of=/dev/vda bs=512 seek=1 count=1 2>/dev/null
sync
# Drop the block layer's cached copy so the read goes to the device.
blockdev --flushbufs /dev/vda
dd if=/dev/vda bs=512 skip=1 count=1 of=/tmp/back 2>/dev/null
if cmp -s /tmp/z512 /tmp/back; then echo "blk: write verified"; else echo "blk: FAIL write not verified"; fi
fi
if want net; then
ip addr add 172.16.0.2/24 dev eth0
ip link set eth0 up
echo "net: $(ping -c 1 -W 2 172.16.0.1 | grep 'packets transmitted')"
fi
if want vsock; then
/bin/vsock send 5000 hello-from-guest
/bin/vsock send 5001 half-from-guest half
# The helper prints "vsock: listening" itself, once both ports are bound.
/bin/vsock listen 6000 6001:half
fi
echo "=== lab end"
exec >/dev/null 2>&1 </dev/null
reboot -f
The block section reads sector 0’s first 16 bytes with hexdump, the capacity from sysfs, writes sector 1 with dd, flushes the block layer’s cache (blockdev --flushbufs, so that the read-back goes to the device and not to the page cache), and compares. The network section addresses eth0 and pings the TAP’s address once, reducing the output to ping’s statistics line. The vsock section is the figure’s two arrows twice over: vsock send connects out to the host listener, and vsock listen binds guest ports 6000 and 6001 and prints vsock: listening, once both are bound (the helper prints it, and not the init, so that a host that connects the moment it sees the line finds a listener). In each direction there are two connections, a plain one and a half-closed one. The host’s vsock-connect ... half writes its line, does shutdown(SHUT_WR) and still reads the guest’s reply to the end; the guest’s vsock send ... half does the same from its side, and the host listener on port 5001 reads to the end of the stream before it answers, so it has seen the guest’s half-close and the guest’s reply has to come back through it. Those are the lines with half-closed and then eof in the capture.
The capture:
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
=== boot blk-only
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /drives/vda 204
ctl: PUT /actions 204
=== lab begin
blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
blk: capacity 16 sectors
blk: write verified
=== lab end
host: sector 1 written by guest
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0
=== boot net-only
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /network-interfaces/eth0 204
ctl: PUT /actions 204
=== lab begin
net: 1 packets transmitted, 1 packets received, 0% packet loss
=== lab end
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 1
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0
=== boot vsock-only
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /vsock 204
ctl: PUT /actions 204
=== lab begin
vsock: guest sent "hello-from-guest" got "pong hello-from-guest"
vsock: guest sent "half-from-guest" half-closed got "pong half-from-guest"
vsock: listening
vsock: guest got "hello-from-host"
vsock: guest got "half-from-host" then eof
=== lab end
host: got "hello-from-guest"
host: got "half-from-guest" then eof
host: OK
host: got "ack hello-from-host"
host: OK
host: half-closed, got "ack half-from-host"
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 19
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0
=== boot all-three
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /drives/vda 204
ctl: PUT /network-interfaces/eth0 204
ctl: PUT /vsock 204
ctl: PUT /actions 204
=== lab begin
blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
blk: capacity 16 sectors
blk: write verified
net: 1 packets transmitted, 1 packets received, 0% packet loss
vsock: guest sent "hello-from-guest" got "pong hello-from-guest"
vsock: guest sent "half-from-guest" half-closed got "pong half-from-guest"
vsock: listening
vsock: guest got "hello-from-host"
vsock: guest got "half-from-host" then eof
=== lab end
host: got "hello-from-guest"
host: got "half-from-guest" then eof
host: OK
host: got "ack hello-from-host"
host: OK
host: half-closed, got "ack half-from-host"
host: sector 1 written by guest
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: virtio-mmio slot 1 type 1
wick: virtio-mmio slot 2 type 19
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0
It pins what the devices do and refuses what varies. The six harness: lines first. Then, for each of the four boots, the ctl: statuses of the requests (204, and nothing else: a refused request would print its fault_message), the guest’s verdict lines between its sentinels, the host helpers’ lines, and wick’s own account: the KVM version, the memory, the boot protocol, InstanceStart, the line for each device (wick: virtio-mmio slot 0 type 2: block is 2, net 1, vsock 19, in the order the devices were put) and the Shutdown exit. Those device lines come after wick: InstanceStart (the Walkthrough says why). What it does not pin: any interrupt count, exit count or frame count, any address or port number (the guest’s ports are ephemeral, and the host port in OK <port> is dropped by vsock-connect), the kernel’s log, any time. Four runs on talos after a fresh out/ and four on straylight, an AMD machine, are byte-identical to capture.txt, so also to each other (cmp, 2026-10-02; the straylight runs go through tools/remote-lab.sh, which brings each out/run.txt back).
Timings, 2026-10-02, with the kernel, BusyBox and wick already built (the cold cost of those is chapter 24’s): make lab CH=25 on talos took 1.35 s from a removed out/ and overlay/bin/ (the helpers and the initramfs are rebuilt) and 1.06 to 1.07 s on three warm runs, timed with the shell’s time. On straylight, tools/remote-lab.sh lab CH=25 took 4.5 s on two warm runs, and 16.2 s on the first run after the sources changed (it rebuilt wick there); those figures include the rsync of the tree and the start of the Nix shell. Timed inside the Nix shell, make lab CH=25 took 2.05 s from a removed out/ and 1.40 to 1.48 s on three warm runs. Four boots and a cargo check are about a second; the time is the guests’.
IMPL=mine replaces the body of handle_request, with execute going away with it (mine-check allows a difference only between the mine:begin and mine:end lines of block.rs), by a stub that prints MINE: blk request stub once and returns 0 with no status byte written: the chapter’s job is the request, and the stub is the request with nothing done. The diff of capture.txt against that run on talos (the combined boot’s hunks have the same shape, with different stale bytes, and are omitted):
--- capture.txt
+++ out/run.txt
@@ -10,16 +10,17 @@
ctl: PUT /drives/vda 204
ctl: PUT /actions 204
=== lab begin
-blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
+blk: sector 0: 63 6f 6e 73 6f 6c 65 3d 74 74 79 53 30 20 72 65
blk: capacity 16 sectors
-blk: write verified
+blk: FAIL write not verified
=== lab end
-host: sector 1 written by guest
+host: FAIL sector 1 not written
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
+MINE: blk request stub
wick: vcpu 0 exit Shutdown
wick: exit 0
wick rc=0
A reader may expect the guest to report an I/O error. It does not, for the reason the Block section gave: the guest believes the read worked and shows the bytes the page held. Here they are the beginning of the kernel’s command line, console=ttyS0 re; other runs of the same stub on this tree have shown zeros and kernel pointers, so the bytes are a leak of whatever the guest’s memory held and the capture would never pin them. The write is then lost, so the guest’s own read-back fails and the host’s cmp agrees (host: FAIL sector 1 not written). The MINE: line is stderr and run.sh keeps those lines beside the wick: ones, so it is in the diff, in the order wick wrote it. The net and vsock sections of the same run pass: only the block sections differ, in both the single-device boot and the combined one. The same run on straylight differs from talos’s only in the stale bytes. wick rc=0 throughout: as in chapter 24, wick cannot tell a guest that read garbage from one that read the disk, and the verdict is the guest’s lines.
make -C wick test clippy is the crate’s own suite, which includes the contract test, the hostile-driver files and the real-KVM test of the doorbell, and make labs runs every lab of the book: with this chapter every earlier capture is byte-identical.
Further reading
- The virtio 1.2 specification, committee specification 01 (PDF, the page numbers above): §2.7, split virtqueues (§2.7.4 for the framing rules, §2.7.8 for the used ring); §4.2, virtio over MMIO (§4.2.2 for the registers); §5.1, the network device; §5.2, the block device; §5.10, the socket device (§5.10.6.3 for credit, §5.10.6.5 for the stream-socket lifecycle).
docs/vsock.mdat Firecrackerv1.15.1: the two connection directions, as the host sees them; andcsm/connection.rsin the same tree, for the connection state machinewickdeparts from on half-close.- The crates
wickis written against:virtio-queue0.18.0, the split ring and its barriers;virtio-vsock0.12.0, the packet header (and the chain constructorwickdoes not use);virtio-bindings0.2.7, the constants. Documentation/networking/tuntap.rstat the pinned tag, the TUN/TAP driver’s own description; and, in the same tree,include/uapi/linux/virtio_vsock.handnet/vmw_vsock/virtio_transport_common.c, the guest driver’s side of the protocol.Documentation/virt/kvm/api.rstat the same tag: §4.59KVM_IOEVENTFD, which is this chapter’s new ioctl, and §4.75KVM_IRQFD, chapter 24’s.- Chapter 22, whose ring this chapter’s devices serve; chapter 24, whose guest they are in; and chapter 23, which drew the devices this chapter builds and the ones it refused.