Study guides · Advanced

Build virtio block requests: validate direction, length, and sector

Read descriptor direction from the device’s perspective and construct header, data, and status buffers for a split virtqueue.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: read one request through its three buffers
  2. Read direction and descriptor WRITE use different viewpoints
  3. Sector addresses are measured in 512-byte units
  4. Build NEXT and WRITE as independent flags
  5. Prepare request contents before publishing the head
  6. Status belongs to an individual request
  7. Exercise: repair direction, then vary the transfer range
  8. Ask Logeia about this articleCheck your understanding

Goal: read one request through its three buffers

Understanding virtqueue publication does not establish that a disk request itself is valid. This lesson constructs a request header, data buffer, and status buffer, using the virtio 1.2 block interface as its reference. The objective is to connect transfer direction and completion meaning to the descriptor chain. It assumes the first-wave queue lifecycle and a prepared device. Transport initialization and the full feature-negotiation process are outside this exercise, rather than silently treated as implemented.

The demonstration uses a model-owned RAM disk of sixteen sectors, each containing 512 bytes. Each request transfers one or two sectors, with at most four requests and sixteen descriptors in a split queue. It accesses neither host files nor a real disk. Resetting initializes the RAM disk again; pausing observation preserves in-progress work. These explicit boundaries make it possible to validate reads and writes without presenting a completed RAM operation as durable storage on the user's computer.

Read direction and descriptor WRITE use different viewpoints

A READ transfers disk contents into the guest's data buffer. A WRITE transfers guest-buffer contents into the disk. By contrast, VIRTQ_DESC_F_WRITE describes permission for the device to write a particular buffer. The same word appears at two interfaces with different viewpoints. The READ data descriptor is device-writable, while the WRITE data descriptor is device-readable. This apparent reversal is a common defect worth testing explicitly rather than inferring direction from the request name alone.

For either operation, the header is read by the device and the status byte is written by it. Guest readability is not the same question as device access direction. Before choosing flags, state who reads and who writes every buffer. This short description makes the mapping auditable. The model must reject a READ whose data buffer is not device-writable; merely producing the expected text on screen would hide a malformed chain instead of demonstrating a valid transfer.

BufferREADWRITE
Request headerDevice-readableDevice-readable
DataDevice-writableDevice-readable
StatusDevice-writableDevice-writable

Sector addresses are measured in 512-byte units

The sector field expresses the starting position in units of 512 bytes, so sector three begins at byte 1536. A separately advertised logical block size is not a reason to reinterpret that address unit. The model fixes sectors at 512 bytes and accepts data lengths of either 512 or 1024 bytes. It tracks a sixteen-byte header and a one-byte status separately, rather than adding their lengths to the data transfer and calling the result a sector count.

On a sixteen-sector RAM disk, a one-sector request at sector fifteen fits, while a two-sector request starting there crosses the end. A valid starting address does not imply a valid complete range. Check nonnegative integer addresses, length units, and the end bound independently. Invalid model input stops at validation rather than modifying part of the disk and reporting success. Range and direction checks are separate: passing one does not authorize publication when the other fails.

Build NEXT and WRITE as independent flags

In the elementary chain, the header comes first, data second, and status last. The first two descriptors have a next element and set NEXT; the last does not. READ flags are therefore one, three, and two: NEXT is one, WRITE is two, and three combines them. WRITE uses one, one, and two because its data buffer is device-readable. Also keep the chain's head identity separate from a descriptor's position within the chain and from the ring slot that publishes it.

The code computes these permissions without constructing DMA mappings or actual device addresses. An implementation project must additionally specify addr, len, flags, next, and each request's owned buffers. Reject cycles and links outside the descriptor table. Three displayed rows do not by themselves establish a valid chain: the references between them matter. Following those references before publication is the difference between checking an illustrative layout and checking that the device can traverse a bounded, well-formed request.

javascript
const NEXT = 1, WRITE = 2;
function chain(op) {
  if (!['READ','WRITE'].includes(op)) throw Error('operation');
  return [
    {part:'header', len:16, flags:NEXT, next:1},
    {part:'data', len:512, flags:NEXT | (op === 'READ' ? WRITE : 0), next:2},
    {part:'status', len:1, flags:WRITE}
  ];
}
console.log(chain('READ').map(d=>d.flags).join(','));
console.log(chain('WRITE').map(d=>d.flags).join(','));

Prepare request contents before publishing the head

Before handing work to the device, prepare operation type, sector, data, status storage, and the chain. The header uses IN for the selected read request and OUT for write; reserved storage is not repurposed as payload. Even a structurally valid request can be unsafe if its head becomes available before prepared contents are visible. The model therefore separates preparation, the required visibility relation, and publication instead of pretending that a final valid-looking structure proves the ordering was correct.

The barrier explanation identifies what must be visible before publication. A TypeScript assignment is not evidence of sufficient ordering under every real CPU memory model. After publication, keep the buffers stable until completion has been confirmed. That lifetime applies to WRITE input as well as READ output and status storage. Sending a notification does not return ownership to the driver. Thinking about permissions without also tracking buffer lifetime leaves an important class of otherwise well-formed but unsafe requests unchecked.

Status belongs to an individual request

Initialize status so that an untouched byte can be distinguished from a device-written result. A teaching sentinel of 255 means unfinished, not success. On completion, associate success, I/O error, or unsupported-operation status with the request's head ID. A notification for the queue is insufficient to mark every request successful. When only some requests finish, keep the other statuses and buffers in their pending state rather than filling in results that were never returned.

For a successful READ, verify that data came from the intended sector and reached the intended buffer. A success status alone cannot excuse writing into another request's storage. For WRITE, check that only the selected disk range changed, preserving other sectors and the other VM's memory. The RAM disk is reinitialized on a new run, so completion is not described as persistence. Request validity, processing outcome, and durable storage remain separate questions even though a real storage stack eventually needs answers to all three.

Exercise: repair direction, then vary the transfer range

Load the repair input whose READ data descriptor lacks WRITE. Correct its device-to-guest permission without breaking header or status direction, then read a sector with known contents. Repeat with two sectors and a different start position. Explain the original defect using both viewpoints: the request names a disk operation, while the descriptor flag grants device access to a buffer. Matching one expected string is weaker than demonstrating the same valid relationship for several requests.

At the boundary, confirm that one sector from sector fifteen succeeds and two sectors from there are rejected. Record that rejected requests leave data unchanged. Then predict the change for a WRITE request. Its data buffer becomes device-readable, but its status remains device-writable. The next lesson follows these valid chains through completion to determine which buffer may be reused and when. Building a correct request is a necessary starting condition, not the end of ownership and ordering checks.

Try the interactive model

Virtio block requests and completion

Loading demo checkpoint…

Reading and practice are recorded separately in this browser, for each language.

Choose a learning path