124а. Lock-free ring buffer between an interrupt and the main loop (SPSC): indices, barriers, power of two, DMA
Section 124 showed three tools — volatile, atomic operations and
barriers — one at a time. Here they are put together into the most common
construction in firmware: a ring buffer written by an interrupt and read by the main
loop (or the other way round). It works without disabling interrupts and without a
LDREX/STREX loop — but only if the contract "one writes, one
reads" and the order "data first, then the index" are kept. What exactly is
needed for that is seen in the instructions the compiler emits and in an experiment with two
threads that breaks the wrong variant.
Basis: alg.c built with gcc 12.2.0 on the computer (stm-sys:1) and run by
host.c — the capacity of two ring variants, counters passing through 2³²,
overflow with dropping the newest and the oldest, spans for memcpy,
the DMA position from NDTR. There race.sh also drives two threads with 10 000 000
numbers each through the correct ring and through two broken ones. The same alg.c
built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M0,
Cortex-M3, Cortex-M4F and Cortex-M7: how many DMB barriers were put into
each function and where — from the disassembly. Nothing was measured on silicon; UART
reception by DMA into a ring is covered in full in section 16б, here — only what
concerns the buffer itself.
Terms used in the documentation
Original Meaning single-producer single-consumer (SPSC) one producer, one consumer head index, tail index the write index and the read index free-running counter a counter that only grows; the mask gives the slot wasted slot an empty separator slot between "full" and "empty" release store / acquire load a store with release, a load with acquire index publication the moment the data become visible to the other side contiguous span (peek / commit) a contiguous piece: look first, then mark as read overflow policy: drop newest or drop oldest discard the new / overwrite the old on overflow non-lock-free atomic an atomic operation done by a library, not by one instruction In plain words. A ring is an array and two numbers. The interrupt puts a byte into a slot and advances its "written" number. The main loop takes the byte and advances its "read" number. Each changes only its own number and only reads the other one — so there is nothing to fight over. One thing matters: the number is advanced after the byte is already in the slot.
124а.1 The SPSC contract: one writes, one reads
A lock-free ring rests on a contract that is not visible in the code: the queue has exactly one producer and exactly one consumer. Typical pairs:
- UART reception: the producer is the
RXNEinterrupt handler, the consumer is the main loop; - transmission: the producer is the main loop (
printfinto the ring), the consumer is theTXEinterrupt; - reception by DMA: the producer is the DMA controller itself (124а.8).
If two start writing into one ring — two interrupts of different priority, or an interrupt and the main loop — the contract is broken, and everything said below stops working: a critical section or compare-and-swap is needed (section 124.5). For event queues from several interrupts section 125а keeps one ring per source — the same contract repeated several times.
124а.2 Indices: who owns what and why disabling interrupts is not needed
typedef struct {
_Atomic uint32_t head; /* пишет только производитель */
_Atomic uint32_t tail; /* пишет только потребитель */
uint32_t dropped; /* счётчик производителя: не влезло */
item_t buf[RING_SIZE];
} ring_t;
Each index has one owner. The producer reads head as its own and
tail as the other's; the consumer — the other way round. A store of head is one
STR instruction of a 32-bit word, and the consumer sees either the old value or
the new one, but never half. The read-modify-write race from
section 124.3 is impossible here: only the producer computes head + 1,
and nobody else changes head meanwhile.
The other side's index may get stale while it is in use — but only in the
safe direction. A producer that read an old tail thinks there is
less free space than there really is; a consumer with an old
head — that there are fewer ready data. Neither will get into a place where the other
is still working. So interrupts need not be disabled, and the handler does not wait
for the main loop a single cycle.
124а.3 Full or empty: a wasted slot or free-running counters
If the indices are kept in the range 0…N−1, then head == tail means both
"empty" and "full". The classic way out is never to fill the last
slot:
bool wring_put(wring_t *r, item_t x)
{
uint16_t h = atomic_load_explicit(&r->head, memory_order_relaxed);
uint16_t n = (uint16_t)((h + 1u) % RING_SIZE);
if (n == atomic_load_explicit(&r->tail, memory_order_acquire)) /* полно: одна ячейка пустует */
return false;
r->buf[h] = x;
atomic_store_explicit(&r->head, n, memory_order_release);
return true;
}
The second way is free-running counters: head and tail only grow and
are never reset, and the mask & (N − 1) gives the slot. Then
"empty" is head == tail, "full" is head − tail == N, and the number of
elements is just the difference:
uint32_t ring_count(ring_t *r)
{
uint32_t h = atomic_load_explicit(&r->head, memory_order_acquire);
uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
return h - t; /* верно и после переполнения uint32_t */
}
The difference of unsigned numbers is computed modulo 2³², so a counter
passing 0xFFFFFFFF breaks nothing: with head = 0x00000010 and
tail = 0xFFFFFFF0 the run gave head − tail = 32. The experiment started with
head = tail = 0xFFFFFF00 and passed 1000 elements through the ring in batches —
not a single error, and head ended at 744, having gone over the edge.
The price of free-running counters is that the size must be a power of two: 2³² must be divisible by N, otherwise after passing the edge the mask points to the wrong slot. This is checked at build time:
#define RING_SIZE 256u /* только степень двойки */
#define RING_MASK (RING_SIZE - 1u)
_Static_assert((RING_SIZE & (RING_SIZE - 1u)) == 0, "RING_SIZE должен быть степенью двойки");
The gain is capacity: a 256-slot ring with free-running counters accepted 256
elements, with a wasted slot — 255. For a UART byte buffer one slot is no
loss; for a ring of 4 large structures one empty slot is a quarter of the memory.
The second gain is one AND instruction instead of a modulo % N; with
N a power of two the compiler replaces % by a mask in the first variant too, but
with an arbitrary N that would be a division.
124а.4 Order: data first, then the index
bool ring_put(ring_t *r, item_t x)
{
uint32_t h = atomic_load_explicit(&r->head, memory_order_relaxed); /* свой индекс */
uint32_t t = atomic_load_explicit(&r->tail, memory_order_acquire); /* чужой индекс */
if (h - t == RING_SIZE) { /* полно */
r->dropped++;
return false;
}
r->buf[h & RING_MASK] = x; /* сначала данные */
atomic_store_explicit(&r->head, h + 1u, memory_order_release); /* потом индекс */
return true;
}
The store of head is the publication: from this moment the consumer treats the
slot as ready and reads it. If the new value of head becomes visible
earlier than the byte in the slot, the consumer reads the old contents —
a byte from the previous lap. Two parties can swap these two stores: the compiler
(for it buf and head are independent variables) and the processor (a write
buffer, a cache, a second core). memory_order_release forbids both:
all stores before it become visible no later than the publication itself.
The consumer is a mirror:
bool ring_get(ring_t *r, item_t *x)
{
uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
uint32_t h = atomic_load_explicit(&r->head, memory_order_acquire);
if (h == t) /* пусто */
return false;
*x = r->buf[t & RING_MASK];
atomic_store_explicit(&r->tail, t + 1u, memory_order_release); /* ячейка свободна */
return true;
}
acquire on the load of head prevents reading the slot before the index, and
release on the store of tail prevents announcing "the slot is free" before the byte
has been taken from it. Each side reads its own index with relaxed: nobody else
changes it. The release — acquire pair is all the synchronisation; nothing stronger
(memory_order_seq_cst) is needed by the ring.
124а.5 volatile or C11 atomics: what gcc emits on M0, M3, M4F and M7
Before C11 the same was written with volatile:
bool vring_put(vring_t *r, item_t x)
{
uint32_t h = r->head;
if (h - r->tail == RING_SIZE)
return false;
r->buf[h & RING_MASK] = x; /* обычная запись: компилятор вправе переставить */
r->head = h + 1u;
return true;
}
volatile orders only accesses to volatile variables among
themselves; an ordinary store into buf may move past the store of head. gcc 12 did not
move it, but the standard does not promise that, and with -flto or another
compiler version the order may change. atomic_signal_fence forbids
reordering to the compiler and emits no instruction at all — this is enough
for a single-core Cortex-M, where the interrupt and the main loop see memory
the same way. The number of DMB barriers from the disassembly:
| Function | M0 | M3 | M4F | M7 |
|---|---|---|---|---|
ring_put |
2 | 2 | 2 | 2 |
ring_get |
2 | 2 | 2 | 2 |
ring_put_relaxed |
0 | 0 | 0 | 0 |
ring_get_relaxed |
0 | 0 | 0 | 0 |
vring_put |
0 | 0 | 0 | 0 |
vring_put_fenced |
0 | 0 | 0 | 0 |
ring_put_overwrite |
1 | 1 | 1 | 1 |
ring_commit |
1 | 1 | 1 | 1 |
gcc puts DMB after every acquire and before every release in the same way on all four
cores: in ring_put one barrier comes right after the load of
tail, the second one — between the store of the byte and the store of head. For Cortex-M4F
the middle of ring_put looks like this:
strb r1, [r0, #12] @ buf[h & 255] = x
dmb ish @ release
movs r0, #1
str r2, [r3, #0] @ head = h + 1
On M0 and M7 the order is the same: strb, dmb, str. The variants with relaxed and
volatile have no barriers. The price of the barriers in size:
| Function | M4F code bytes | M0 code bytes |
|---|---|---|
ring_put |
46 | 48 |
ring_put_relaxed |
32 | 34 |
ring_get |
38 | 38 |
ring_peek |
38 | 38 |
ring_write |
78 | 92 |
ring_get_latest |
72 | 66 |
Is DMB really needed? On single-core Cortex-M0, M3 and M4 without a cache
the processor does not reorder its stores so that an interrupt handler
on the same core could see it: the interrupt sees memory in the same
order in which the program wrote it. There DMB is insurance, and the
mandatory ban is for the compiler. The barrier becomes necessary when the
consumer is not the same core: a second core (H7 with M4 and M7, section 124.6),
DMA reading RAM directly, or the data cache on M7. The practical rule:
always write release/acquire — two barriers of 4 bytes cost less
than hunting for a bug that appears when the code is moved to H7.
124а.6 An experiment on the computer: two threads and 10 000 000 numbers
On a computer the ring can be broken for real: the producer and the consumer are two threads on different cores. The producer puts the numbers 1, 2, 3 … 10 000 000, the consumer checks that each next one is one greater than the previous; any loss, repetition or reordering is an error. Three variants, three runs each, a machine with 24 logical processors:
| Variant | errors, run 1 | run 2 | run 3 |
|---|---|---|---|
ok |
0 | 0 | 0 |
relaxed |
0 | 0 | 0 |
early |
14340 | 11958 | 9924 |
ok is ring_put and ring_get with release and acquire. relaxed — the order
in the text is right, but all accesses use memory_order_relaxed. early —
the index is published before the data:
atomic_store_explicit(&r->head, h + 1u, memory_order_relaxed); /* ошибка: индекс первым */
r->buf[h & RING_MASK] = x;
The early variant broke in every run — about one number in a
thousand: the consumer managed to see the new head and read the slot before
the number got into it. All errors are old contents of the slot, a number
from the previous lap.
The relaxed variant gave no errors on the computer — and that does not mean it
is correct. x86-64 has a strong memory model: other cores see the stores of one core
in the order in which they were made, and loads are not reordered among
themselves either. So release and acquire on x86 turn into no
instructions at all: the disassembly showed that ring_get and ring_get_relaxed
are built into the same instructions, and no ring function has a
barrier. On x86 relaxed is saved by the order in the program text. ARM has a
weaker model: Cortex-A and multi-core systems reorder stores for
real, and on Cortex-M7 with a cache the order of visibility for DMA and a second
core is not guaranteed either. There relaxed is the same bug as early,
only rarer. The x86 experiment proves that the wrong order breaks;
that the right one is sufficient is proved by the C11 memory model, not by a run.
124а.7 Pieces at once: peek/commit and contiguous spans
Taking one element at a time is slow when the data must be copied with
memcpy, given to DMA for transmission or parsed in place. For that the
consumer looks at a contiguous piece, works with it and only then
marks it as read:
uint32_t ring_peek(ring_t *r, const item_t **p) /* непрерывный кусок для чтения */
{
uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
uint32_t h = atomic_load_explicit(&r->head, memory_order_acquire);
uint32_t n = h - t; /* всего готово */
uint32_t to_end = RING_SIZE - (t & RING_MASK);
*p = &r->buf[t & RING_MASK];
return n < to_end ? n : to_end; /* не дальше конца массива */
}
void ring_commit(ring_t *r, uint32_t n) /* n элементов прочитано */
{
uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
atomic_store_explicit(&r->tail, t + n, memory_order_release);
}
A piece breaks off at the end of the array, so data that went over the
edge are handed out in two goes. The run: 100 elements written from position
200, ring_peek gave pieces of 56 and 44, the third call — 0. Until a piece is
marked with ring_commit, the producer does not write into those slots — with the pointer
from ring_peek a DMA transmission can be started and ring_commit called in
its completion interrupt.
For the producer it is the same — a write of up to two memcpy and one publication for
the whole piece:
uint32_t ring_write(ring_t *r, const item_t *src, uint32_t n) /* до двух memcpy */
{
uint32_t h = atomic_load_explicit(&r->head, memory_order_relaxed);
uint32_t t = atomic_load_explicit(&r->tail, memory_order_acquire);
uint32_t space = RING_SIZE - (h - t);
if (n > space)
n = space;
uint32_t i = h & RING_MASK;
uint32_t first = RING_SIZE - i < n ? RING_SIZE - i : n;
memcpy(&r->buf[i], src, first * sizeof(item_t));
memcpy(&r->buf[0], src + first, (n - first) * sizeof(item_t));
atomic_store_explicit(&r->head, h + n, memory_order_release); /* один раз за весь кусок */
return n;
}
Into a ring where 200 slots of 256 are occupied, 56 of the requested 100 elements fitted; the function returns how many were written, and deciding what to do with the rest is up to the caller.
124а.8 DMA as the producer: head from NDTR
For UART reception by DMA in circular mode (section 16б) the producer is
the DMA controller itself. There is no head index in memory: DMA keeps the counter
of remaining transfers NDTR, which falls from N to 1 and is reloaded.
The write position is computed from it:
uint32_t dma_head(uint32_t ndtr) /* позиция записи DMA в кольце 0…N−1 */
{
return (RING_SIZE - ndtr) & RING_MASK; /* NDTR = N сразу после перезарядки — позиция 0 */
}
uint32_t dma_ready(uint32_t ndtr, uint32_t rd) /* сколько принято с позиции rd */
{
return (dma_head(ndtr) - rd) & RING_MASK;
}
The run: NDTR = 256 gives position 0, NDTR = 1 — 255, NDTR = 166 — 90; from
read position 200 with NDTR = 166 there are 146 bytes ready (through the end of the ring).
There are three differences from a software producer. First — the counters here are not
free-running but modulo N, and dma_ready cannot tell "empty" from "exactly one
lap received": that is told apart by the half and complete flags (HT, TC) from section
16б. Second — DMA does not look at tail and always writes: overflow for
it means overwriting the old (124а.10). Third — NDTR is read once into a
local variable and then used from there: two reads in a row give
two different numbers.
A barrier on the consumer side is really needed here: DMA is a separate
bus master, and the read of NDTR must happen before the reads of the bytes it
allows. Peripheral registers are declared volatile, and the buffer read is
ordinary, so __DMB() is placed between them, or the buffer is read through
acquire.
124а.9 The data cache on Cortex-M7
On F7 and H7 with the data cache enabled visibility is added to ordering. DMA writes into RAM bypassing the cache, while the processor may read an old copy of the same addresses from the cache — a barrier will not fix that, it orders accesses, it does not refresh the cache. The rules are the same as in section 124.6 for transmission, only in the opposite direction:
- before reading a piece written by DMA, the cache lines of that piece
are invalidated with
SCB_InvalidateDCache_by_Addr; - the buffer is aligned to 32 bytes and made a multiple of 32 — a cache line is 32 bytes, and invalidating someone else's line nearby will spoil the neighbouring data;
- the simplest is to put the DMA ring into a region the MPU marks as non-cacheable, or into DTCM of the M7, which DMA cannot reach in all families (on H7 — only MDMA).
For a software ring between an interrupt and the main loop on one M7 core the cache does not get in the way: both read through the same cache. It gets in the way when one of the sides is DMA or a second core.
124а.10 Overflow: drop the newest or overwrite the oldest
When the ring is full there are two solutions, and the choice must be made deliberately.
Drop the newest. The producer does not write and counts the loss —
ring_put above increments dropped. The run: 300 elements into an empty
256-slot ring — 256 accepted, 44 dropped, elements from 0 to 255 read.
The dropped counter is written only by the producer, so it needs no
lock either, and the main loop reads it for diagnostics. This is how
commands, a log, a protocol with acknowledgements behave: the beginning matters more than the end.
Overwrite the oldest. The producer always writes, and the consumer, seeing that it has been lapped, jumps to the oldest surviving element:
bool ring_get_latest(ring_t *r, item_t *x, uint32_t *lost)
{
uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
uint32_t h = atomic_load_explicit(&r->head, memory_order_acquire);
if (h - t > RING_SIZE) { /* производитель обогнал на круг */
*lost += h - t - RING_SIZE;
t = h - RING_SIZE; /* перескочить на самое старое уцелевшее */
}
if (h == t)
return false;
*x = r->buf[t & RING_MASK];
atomic_store_explicit(&r->tail, t + 1u, memory_order_release);
return true;
}
The same 300 elements: 256 read — from 44 to 299, 44 lost. This is how
sensor samples and sound behave: fresh data matter. But only the consumer may move
tail — a producer that "threw away the old" itself would
break the SPSC contract. And overwriting has a hole: while the
consumer is reading a slot, the producer may overwrite it. For
one-byte elements this means "a fresh byte was read instead of the
old one", for structures — a mix of two. If that matters, after the read
one checks that head has not run ahead by more than a lap, and repeats.
124а.11 Pitfalls
An index wider than an atomic access. A 16- and 32-bit index is read with
one instruction on any Cortex-M (LDRH, LDR). A 64-bit one is not:
atomic_load for _Atomic uint64_t both on M0 and on M3/M4 was built into a
call of __atomic_load_8, and building a program for M0 and M4F failed with
undefined reference — newlib has no such function. Without atomics a
64-bit index is read by two LDRs, and an interrupt between them gives
half of the old and half of the new. 32 bits are enough: when passing the
edge the difference is still correct.
head read twice. The "there are data" check uses one read of
head, and the piece is computed from a second one: in between an interrupt added
data, and the piece went beyond what was checked. Read the other side's index once into a
local variable, as in ring_peek.
Waiting without volatile or atomics. A loop "wait while head == tail"
on ordinary fields was built by gcc into 5 instructions: both fields are read once, and
then registers are compared in a circle. Exactly as with the flag in
section 124.1.
The index published before the data. On the computer — 14340 errors in
10 000 000 numbers. The store of head is the last line of the producer.
relaxed "works" on x86. On a PC there were no errors, on M7 with DMA or on
the two cores of H7 there will be. Testing memory order on x86 is pointless in
one direction: a run without errors proves nothing.
The size is not a power of two. With free-running counters a ring of 100
slots breaks when passing 2³². _Static_assert on the size.
Two producers. A second interrupt also writes into the ring —
and head + 1 of the two handlers loses elements. One ring per
source or a critical section.
DMA on M7 "lost" bytes. The cache shows an old copy of the buffer. Invalidate the cache for the piece before reading, or a non-cacheable region.
124а.12 Summary
- The SPSC contract: one producer writes
head, one consumer writestail; each reads the other's index and does not touch it. Disabling interrupts andLDREX/STREXare not needed. - Free-running
uint32_tcounters and a mask: a 256-slot ring accepted 256 elements against 255 with a wasted slot; the difference is correct across 2³², the size is only a power of two. - Data first, then the index:
releaseon publication,acquireon reading the other's index. gcc putsDMBon M0 as well as on M3, M4F, M7 — two each inring_putandring_get. - On x86, two threads with 10 000 000 numbers: the correct ring and
relaxed— 0 errors, "index first" — from 9924 to 14340; x86 forgivesrelaxed, ARM does not. - Pieces with
ring_peek/ring_commitandring_write— up to twomemcpyand one publication. - DMA as the producer:
head = (N − NDTR) & (N − 1); on M7 — cache invalidation for the piece or a non-cacheable region. - Overflow — deliberately: drop the newest with a counter or overwrite the oldest on the consumer side.
- A 64-bit index on Cortex-M is not atomic:
__atomic_load_8.
Next: section 125 "Declarations and function pointers: handler tables and callbacks" — how to read
void (*const handlers[])(void) and build handler tables.