Implement a simplified virtqueue available and used ring.
Short answer: A split virtqueue has a descriptor table, an available ring published by the driver and a used ring published by the device. Here a single producer posts descriptor IDs and a single consumer returns completed IDs. Calls are serialized for clarity.
#include <stdint.h>
#include <stdbool.h>
#define N 8
struct queue {
uint16_t avail[N], used[N];
uint16_t a_write, a_read, u_write, u_read;
bool busy[N];
};
bool submit(struct queue *q, uint16_t id)
{
if (id >= N || q->busy[id] ||
(uint16_t)(q->a_write-q->a_read) == N) return false;
q->busy[id] = true;
q->avail[q->a_write++ % N] = id;
return true;
}
bool complete(struct queue *q)
{
if (q->a_read == q->a_write ||
(uint16_t)(q->u_write-q->u_read) == N) return false;
uint16_t id = q->avail[q->a_read++ % N];
/* Process the validated descriptor before publishing completion. */
q->used[q->u_write++ % N] = id;
return true;
}
bool reap(struct queue *q, uint16_t *id)
{
if (q->u_read == q->u_write) return false;
*id = q->used[q->u_read++ % N];
q->busy[*id] = false;
return true;
}
Initialize the queue to zero. Each operation is O(1); a descriptor cannot be reused before completion is consumed. The real virtio ABI includes lengths, flags, chain validation, negotiated endianness and notification suppression. Use the transport's required barriers and cache synchronization to publish descriptors and indices; this example is not a concurrent or wire-compatible virtqueue.