
Recall first from The Linux virtio subsystem and device matching
- The PCI and MMIO transports register virtio devices with a common Linux bus
- The virtio bus compares a device's device and vendor IDs with a driver's ID table
- The core's virtio_dev_probe invokes the matched device driver's probe callback after core setup succeeds
Read the device configuration
3 min readThe last lesson matched a driver to a device. This lesson answers how the driver reads config space, finds its virtqueues, and uses the add/kick/get_buf API.
Suppose the M11-S06A device defines a configuration field that limits the size of a request. The guest driver needs that value before it accepts a request from userspace. Linux's Writing Virtio Drivers documents the interface the driver uses to reach the device. On virtio-mmio, the transport accesses the device-specific configuration region through MMIO. The function driver supplies the layout and interprets the field according to the device protocol.
Use virtio_cread(vdev, struct device_config, member, &value) for a scalar member in the device's configuration layout. Here struct device_config and member stand for the actual structure type and field in your device protocol. The macro derives the byte offset and access size from the member and checks the types. For a modern virtio device, multibyte scalar fields use little-endian encoding. For example, for a __virtio32 member, the destination is a u32 carrying the CPU-endian value. The helper performs the conversion. Use virtio_cwrite with the same layout and a pointer to the CPU-endian value when the device contract permits the driver to write that member. Check the negotiated feature before accessing a field that depends on it. Validate device-supplied sizes before using them for allocations or buffer lengths.
The config member of struct virtio_device points to the transport's struct virtio_config_ops. Its get and set operations transfer bytes at an offset in device-specific configuration space. These operations and the typed macros have no per-access error return. The same table also contains operations with different purposes. get_features obtains the offered feature bits so the core can negotiate them. set_status updates the device status used in initialization. reset resets the device. find_vqs creates the requested queues, and del_vqs deletes them. A driver normally uses the corresponding core helpers for lifecycle operations. For example, virtio_device_ready sets DRIVER_OK when the driver needs to use the queues before its probe returns. The core also sets DRIVER_OK after a successful probe if the driver has left that step to it.
a transport-provided counter the driver can compare before and after reading device configuration lets the reader detect a change during a snapshot. Consider two fields that must agree, such as a size and an associated limit. If the device updates them between reads, the driver could combine an old value with a new one. When config->generation is available, read it, read the related fields, and read it again. Discard that sample and repeat the entire group if the two generation values differ. Linux 6.8 also applies this pattern in its configuration helpers when a scalar access uses the multi-read path. Separate calls to virtio_cread do not by themselves make several fields a single snapshot. If the transport lacks a meaningful generation counter, a consistency guarantee needs to come from the device protocol, for example by defining the fields as fixed while the driver is active.
Create and use a virtqueue
4 min readDuring probe, decide which queues the driver needs from the device protocol and negotiated features. In Linux 6.8, virtio_find_vqs takes the device, queue count, output array of struct virtqueue *, arrays of callbacks and names, and an optional interrupt affinity descriptor. For a basic driver, pass NULL for the affinity descriptor. Supply the arrays in the queue order defined by the device and check the return value before using the output pointers. A successfully created struct virtqueue is the driver's kernel handle for a queue. It records information such as the owning vdev, the queue index, and the completion callback. The ring implementation maintains additional state behind this handle.
virtio_find_vqs calls the transport's find_vqs operation. For the M11-S06A MMIO path, that operation uses its setup_vq routine for each requested queue. The routine selects the queue, checks the device's queue capacity and availability, creates the ring through the kernel's vring code, and programs the queue size and addresses. With modern virtio-mmio, it supplies separate addresses for the descriptor, available and used areas, then makes the queue ready. The transport also arranges interrupt handling for callbacks. If creation fails, propagate the error. If a later probe step fails after successful creation, unwind the resources the driver has already acquired.
Use scatterlists to describe the kernel buffers in a request. virtqueue_add_outbuf adds device-readable buffers, such as request bytes sent by the guest. virtqueue_add_inbuf adds device-writable buffers, such as space for a reply. virtqueue_add_sgs accepts both directions in one request. Its array holds pointers to scatterlists, with the device-readable lists before the device-writable lists. The counts passed to virtqueue_add_sgs count lists in each direction. Each list can contain multiple segments. Pass a non-null token identifying the request as the data argument. Keep the token and the submitted buffer storage valid until the driver reclaims the request.
Check the add result before calling virtqueue_kick. For example, -ENOSPC means there is insufficient room for the request. A driver can reclaim completed buffers and retry according to its submission policy. An add that succeeds has already published the request to the device. The kick asks the ring code whether the transport needs to notify the device. A true kick result can mean the notification was unnecessary or that it succeeded. A false result indicates failure, and the published buffer still needs safe reclamation. Once the device is ready, it can observe work already published in the ring.
On completion, call virtqueue_get_buf(vq, &len) until it returns NULL. Each non-null result is the original token and len is the used length reported by the device. For a reply, validate that length against the writable space submitted and any minimum required by the protocol before reading the reply. Callbacks signal that completions may be available. A single callback may cover several requests, and a drain may find none. Serialize ordinary operations on the same queue when submission and draining can run concurrently. A spinlock acquired with interrupt state saved is one option when the callback can interrupt the submitting context. Allocate request storage before taking the lock and use an atomic allocation flag for the add call while holding it. Keep sleeps and userspace waits outside that lock.
For the custom device lab, keep a state object per virtio_device and associate it with vdev->priv before the callback can use it. Use the device ID and vendor match from M11-S06A. Read the fields the existing device defines and create its request queue with a callback. Initialize the request and callback state before making the device ready, then expose a simple userspace interface. A sysfs device attribute can expose a scalar configuration value, and a writable attribute can accept a text trigger for a bounded test transaction. The write handler parses the input, submits one kernel-owned request, and waits with a timeout in process context. The callback drains the queue, records the result and signals a completion. A successful write returns the input byte count. A failed request returns a negative error. Keep one transaction in flight for this interface and reject a new one while an earlier timed-out request still owns buffers.
Keep the request storage alive after a timeout until the callback reclaims it or teardown safely reclaims it. During remove, stop new submissions, remove the userspace attributes and let active handlers finish their bounded waits. Reset the device, synchronize completion handling, reclaim any remaining tokens with virtqueue_detach_unused_buf, then delete the queues and release driver state.
Map the API to the split ring
3 min readIn the split-ring implementation, struct vring is a kernel view containing the ring size and pointers to three shared areas. The descriptor table contains struct vring_desc entries with a device-visible buffer address, length, flags and a next index for chaining. For the usual direct chain, each descriptor describes one buffer segment, and the driver advertises the head descriptor in struct vring_avail. The device uses struct vring_used to report completed heads and used lengths. The available and used areas each include an index. Each producer advances its own index as it publishes entries, and each consumer tracks what it has already processed.
In Linux 6.8 the public virtqueue functions select split or packed implementations in the ring code. For a split queue, the add functions reach virtqueue_add_split. It maps the buffer segments as needed, fills descriptors, saves the driver's token in private state associated with the head, writes the head to an available ring slot and publishes the updated available index. Memory ordering ensures the device can see the descriptors and available entry when it sees the new index. virtqueue_kick uses virtqueue_kick_prepare_split to decide whether to invoke the transport notification through virtqueue_notify. virtqueue_get_buf reaches virtqueue_get_buf_ctx_split, which checks the used index, reads the completed head and length, and returns the corresponding token after releasing descriptor resources. The device reports a descriptor ID. The driver token stays in the guest's private state.
Going deeperIndirect descriptors and notification suppression
When VIRTIO_RING_F_INDIRECT_DESC has been negotiated, the kernel can allocate a separate table for the segments of a request. It fills that table and sets VRING_DESC_F_INDIRECT on the main ring descriptor pointing to it. A multi-segment request can then consume a single descriptor in the main table. Allocation can fail, in which case the split implementation can fall back to a direct chain if sufficient descriptors are available. The driver uses the same add API either way.
Without event indices, split rings have suppression flags. The device can request fewer kicks through VRING_USED_F_NO_NOTIFY, and the driver can request fewer callbacks through VRING_AVAIL_F_NO_INTERRUPT. With VIRTIO_RING_F_EVENT_IDX negotiated, the device writes avail_event to request a kick when the driver's available index reaches the indicated event. The driver writes used_event to request an interrupt when the device advances the used index across the indicated event. The kernel compares the old and new producer indices against the requested event using wraparound-safe arithmetic. One comparison can cover a batch of published entries.
virtqueue_disable_cb requests callback suppression. An interrupt can already be in flight, so suppression gives no mutual exclusion. A typical driver disables callbacks, drains completions, and calls virtqueue_enable_cb. If enable returns false, more work is visible and the driver repeats the drain. This recheck covers the race in which the device completes a buffer between the drain and callback re-enable. The driver can also use virtqueue_enable_cb_prepare to re-enable callbacks and obtain a snapshot of the consumer position, then pass that value to virtqueue_poll. The poll checks for used work relative to the snapshot with the required ordering. A true result means the driver should process the observed work before waiting for another interrupt.
The next lesson, virtio-blk and virtio-net drivers, follows how two Linux drivers arrange their requests and completions around these same queue operations.
Key takeaways
- virtio_cread and virtio_cwrite use the device layout and delegate configuration access to transport operations.
- A configuration generation check detects changes during a read that needs a consistent snapshot.
- The transport creates the virtqueue and programs its ring addresses for the device.
- A successful buffer submission transfers ownership until completion or safe reclamation after reset.
Reflect
- Explain to a colleague, in two sentences: trace a typed configuration read through the Linux virtio transport.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationWriting Virtio Drivers
- Kernel documentationVirtio on Linux
- Kernel documentationsysfs: the filesystem for exporting kernel objects
Official documentation first. Links checked when the lesson was published.