Chain virtqueue descriptors with VRING_DESC_F_NEXT
Link three split-virtqueue descriptors into one virtio-blk read request with VRING_DESC_F_NEXT, marking only the data and status buffers device-writable.
A virtio request is rarely one buffer. A block read has a header the device reads, a data buffer it fills and a status byte it sets, so the driver links three descriptors into a chain. Each struct vring_desc holds an address, a length, flags and the index of the next descriptor.
#define VRING_DESC_F_NEXT 1 // buffer continues in desc[next]
#define VRING_DESC_F_WRITE 2 // device writes this buffer
struct vring_desc { uint64_t addr; uint32_t len; uint16_t flags; uint16_t next; };
void build_read(struct vring_desc *d, uint64_t hdr, uint64_t buf, uint64_t st) {
d[0] = (struct vring_desc){ hdr, 16, VRING_DESC_F_NEXT, 1 };
d[1] = (struct vring_desc){ buf, 512, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE, 2 };
d[2] = (struct vring_desc){ st, 1, VRING_DESC_F_WRITE, 0 };
}Printing the flags and next fields of the chain gives:
desc0 flags=0x1 next=1
desc1 flags=0x3 next=2
desc2 flags=0x2 next=0The last descriptor has no NEXT flag, so its next field is ignored, and that absence is what ends the chain. VRING_DESC_F_WRITE is set from the device's point of view: the header is readable by the device, while the data and status are buffers it writes into. Put all device-readable descriptors before the writable ones, because the specification requires that order.
The driver then places the index of the chain head, 0 here, into the available ring and updates the available index. The split-ring layout is defined in the VIRTIO 1.2 specification. In the kernel you rarely build descriptors by hand: virtqueue_add_sgs does it.