</>EmbeddedInterview

Implement a DMA descriptor ring (as used by Ethernet drivers).

Hard"Coding: Embedded Drivers, Buffers & Schedulers"
#include <stdint.h>
#include <stddef.h>

#define RX_DESC   8u
#define BUF_SIZE  1536u
#define OWN_DMA   (1u << 31)                      /* descriptor owned by the DMA engine */
#define LEN_MASK  0x3FFFu

typedef struct { volatile uint32_t status; uint32_t buf_addr; uint32_t ctrl; uint32_t next; } dma_desc_t;

static dma_desc_t rx_ring[RX_DESC] __attribute__((aligned(32)));
static uint8_t    rx_buf[RX_DESC][BUF_SIZE] __attribute__((aligned(32)));
static unsigned   rx_idx;                         /* next descriptor software will look at */

void rx_ring_init(void)
{
    for (unsigned i = 0; i < RX_DESC; i++) {
        rx_ring[i].buf_addr = (uint32_t)(uintptr_t)rx_buf[i];
        rx_ring[i].ctrl     = BUF_SIZE;
        rx_ring[i].next     = (uint32_t)(uintptr_t)&rx_ring[(i + 1) % RX_DESC];   /* chained ring */
        rx_ring[i].status   = OWN_DMA;            /* give every buffer to the hardware */
    }
    rx_idx = 0;
    /* write &rx_ring[0] to the DMA's descriptor base register, start RX */
}

/* called from the RX interrupt or a polling loop */
void rx_poll(void (*deliver)(const uint8_t *frame, size_t len))
{
    while (!(rx_ring[rx_idx].status & OWN_DMA)) {        /* software owns it: a frame arrived */
        uint32_t st = rx_ring[rx_idx].status;
        /* on cached cores: invalidate rx_buf[rx_idx] before reading it */
        deliver(rx_buf[rx_idx], st & LEN_MASK);
        rx_ring[rx_idx].status = OWN_DMA;                 /* hand the buffer back to the hardware */
        rx_idx = (rx_idx + 1) % RX_DESC;
        /* then write the DMA "poll demand" register in case it stopped on a full ring */
    }
}

Points: each descriptor has an ownership bit: hardware fills a buffer and clears OWN; software processes it and sets OWN again. Software must never touch a descriptor the hardware owns. Descriptors and buffers need the alignment the DMA requires, cache maintenance on cached cores (or a non-cacheable region), and memory barriers between writing buffer/length fields and setting OWN. This is the same producer/consumer idea as a ring buffer, with the hardware as one side; Linux NIC drivers, virtio virtqueues and USB controllers all use variants of it.