</>EmbeddedInterview

Implement a virtual IRQ injection queue.

MediumCoding: Systems, Bitmaps & Virtualization

Short answer: A virtual device can enqueue an interrupt for a vCPU. The hypervisor dequeues pending events and presents them to its virtual interrupt controller.

#include <stdbool.h>
#define N 32
struct irq_queue {
    unsigned irq[N], head, tail, count;
};

bool inject(struct irq_queue *q, unsigned irq)
{
    if (q->count == N) return false;
    q->irq[q->head] = irq;
    q->head = (q->head + 1) % N;
    q->count++;
    return true;
}

bool next_irq(struct irq_queue *q, unsigned *irq)
{
    if (!q->count) return false;
    *irq = q->irq[q->tail];
    q->tail = (q->tail + 1) % N;
    q->count--;
    return true;
}

Initialize the queue to zero. Both operations are O(1). This is a FIFO event model, not a complete vGIC: real injection handles interrupt IDs, priority, masking, level/edge state, EOI and waking the target vCPU. Serialize queue access with a lock when shared across threads; do not silently lose an IRQ on overflow.