The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
atomic_queue.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: eaea6d23e26bbc8d51606a65f7a20564381feb0b $
19 *
20 * @brief Thread-safe queues.
21 * @file io/atomic_queue.c
22 *
23 * This is an implementation of a bounded MPMC ring buffer with per-slot
24 * sequence numbers, as described by Dmitry Vyukov, and independently
25 * discovered/implemented by Alister Winfield.
26 *
27 * @copyright 2026 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
28 * @copyright 2016 Alan DeKok (aland@freeradius.org)
29 * @copyright 2016 Alister Winfield
30 */
31
32RCSID("$Id: eaea6d23e26bbc8d51606a65f7a20564381feb0b $")
33
34#include <stdint.h>
35#include <stdalign.h>
36#include <inttypes.h>
37#include <stdlib.h>
38#include <errno.h>
39#include <unistd.h>
40#include <sys/mman.h>
41
42#include <freeradius-devel/autoconf.h>
43#include <freeradius-devel/io/atomic_queue.h>
44#include <freeradius-devel/util/debug.h>
45#include <freeradius-devel/util/math.h>
46#include <freeradius-devel/util/strerror.h>
47#include <freeradius-devel/util/syserror.h>
48
49/*
50 * Some macros to make our life easier. Not every macro is used.
51 */
52DIAG_OFF(unused-macros)
53#define atomic_int64_t _Atomic(int64_t)
54#define atomic_uint32_t _Atomic(uint32_t)
55#define atomic_uint64_t _Atomic(uint64_t)
56
57#define cas_incr(_store, _var) atomic_compare_exchange_strong_explicit(&_store, &_var, _var + 1, memory_order_release, memory_order_relaxed)
58#define cas_decr(_store, _var) atomic_compare_exchange_strong_explicit(&_store, &_var, _var - 1, memory_order_release, memory_order_relaxed)
59#define load(_var) atomic_load_explicit(&_var, memory_order_relaxed)
60#define acquire(_var) atomic_load_explicit(&_var, memory_order_acquire)
61#define store(_store, _var) atomic_store_explicit(&_store, _var, memory_order_release)
62DIAG_ON(unused-macros)
63
64/*
65 * The distance two addresses need to be apart so that one core
66 * writing does not slow another core reading. On Apple silicon
67 * the hardware line is 128 bytes. On x86 the hardware line is
68 * 64 bytes but the adjacent line prefetcher fetches lines in
69 * 128 byte pairs, so neighbouring 64 byte lines still appear to
70 * contend in benchmarks.
71 */
72#define CACHE_LINE_SIZE 128
73
74/** One slot in the queue
75 *
76 * The sequence number, then the element: `elem_len` of data, padded
77 * out to the slot size. For the pointer API the element is the pointer
78 * itself.
79 *
80 * Must not be packed. Packing drops the struct's alignment to 1
81 * (same as an array of uint8_t), so the compiler has to treat `seq`
82 * as possibly unaligned. The native atomic instructions require an
83 * aligned address, so clang stops emitting them and calls the
84 * libatomic fallback instead, which takes a mutex. That turns every
85 * push and pop on this lock free queue into a locked operation. gcc
86 * emits the native instruction regardless, and relies on the address
87 * being aligned at runtime.
88 */
89typedef struct {
90 atomic_int64_t seq; //!< The position this slot was last
91 ///< written or freed at.
92 uint8_t data[]; //!< The element, 8 byte aligned as
93 ///< slots are a power of two bytes from
94 ///< a line boundary.
96
97static_assert(offsetof(fr_atomic_queue_slot_t, data) == 8, "the element must follow the sequence number");
98
99/*
100 * Slots are striped across cache lines.
101 *
102 * A line is exactly one cache line. A stripe is the set of slots at
103 * the same offset in every line, so it runs the complete length of the
104 * queue memory. Stripes let a line hold several slots without the
105 * slots sharing a cache line with their neighbours in queue order.
106 * Padding each slot out to a full cache line instead would waste the
107 * majority of queue memory for no gain.
108 *
109 * Slot `i` translates to `line[i % num_lines].stripe[i / num_lines]`, i.e.
110 * for stripe 0, slot positions match line positions (slot 0 at line 0),
111 * and once the slot number exceeds the number of lines we wrap, and use
112 * the next stripe.
113 *
114 @verbatim
115 stripe[0] stripe[1] stripe[2] ... stripe[7]
116 +----------+----------+----------+ +----------+
117 line[0] | slot 0 | slot 4 | slot 8 | ... | slot 28 | <- one cache line
118 +----------+----------+----------+ +----------+
119 line[1] | slot 1 | slot 5 | slot 9 | ... | slot 29 |
120 +----------+----------+----------+ +----------+
121 line[2] | slot 2 | slot 6 | slot 10 | ... | slot 30 |
122 +----------+----------+----------+ +----------+
123 line[3] | slot 3 | slot 7 | slot 11 | ... | slot 31 |
124 +----------+----------+----------+ +----------+
125 @endverbatim
126 *
127 * How many stripes a line holds depends on the element size, so it is
128 * decided when the queue is created and kept in the queue.
129 */
130
131/** Structure to hold the atomic queue
132 *
133 * @note DO NOT redorder these fields without understanding how alignas works
134 * and maintaining separation. The head and tail must be in different cache lines
135 * to reduce contention between producers and consumers. Cold data (num, chunk)
136 * can share a cache line, but must be separated from head, tail and the line array.
137 */
139 alignas(CACHE_LINE_SIZE) atomic_int64_t head; //!< Position of the producer.
140 ///< Cache aligned bytes to ensure it's in a
141 ///< different cache line to tail to reduce
142 ///< memory contention.
143
144 alignas(CACHE_LINE_SIZE) atomic_int64_t tail; //!< Position of the consumer.
145 ///< Cache aligned bytes to ensure it's in a
146 ///< different cache line to tail to reduce
147 ///< memory contention.
148 ///< Reads may still need to occur from num
149 ///< whilst the producer is writing to tail.
150
151 alignas(CACHE_LINE_SIZE) size_t num; //!< Elements the queue holds. This is static.
152 ///< Also needs to be cache aligned, otherwise
153 ///< it can end up directly after tail in memory
154 ///< and share a cache line.
155
156
157 size_t elem_len; //!< Size of one element.
158 size_t slot_len; //!< The line divided by the stripes:
159 ///< header, element, padding.
160 size_t stripes; //!< Slots per line. The largest power
161 ///< of two the element allows.
162 size_t line_mask; //!< Low bits of a slot index give its line:
163 ///< `line[slot & line_mask]`. Set at init to
164 ///< num_lines - 1.
165
166 uint8_t line_shift; //!< High bits of a slot index give its stripe
167 ///< within that line:
168 ///< `.stripe[slot >> line_shift]`. Equal to
169 ///< log2(num_lines). Set at init,
170 ///< so a lookup is a mask and a shift, no
171 ///< division and no modulo!
172
173 void *chunk; //!< The start of the talloc chunk to pass to free,
174 ///< or NULL if this queue was allocated raw via
175 ///< #fr_atomic_queue_malloc. We need to play
176 ///< tricks to get aligned memory with talloc.
177
178 alignas(CACHE_LINE_SIZE) uint64_t lines[]; //!< The lines, each exactly one cache line,
179 ///< aligned with cache lines to ensure
180 ///< producers and consumers don't conflict.
181};
182
183/*
184 * Everything should reference lines[0]. This allows the underlying type to change, without needing
185 * updates to multiple places that use it.
186 */
187#define LINES_ZERO (((struct fr_atomic_queue_s *) NULL)->lines[0])
188
189static_assert(alignof(fr_atomic_queue_slot_t) <= alignof(typeof(LINES_ZERO)),
190 "slots must not need more alignment than the lines array has");
191static_assert((CACHE_LINE_SIZE % sizeof(LINES_ZERO)) == 0,
192 "a cache line must be a whole number of elements of lines");
193
194/** How many slots a line holds for an element size
195 *
196 * The largest power of two such that the line divided by it still
197 * holds the slot header and the element. A power of two keeps the
198 * slot size a power of two and the line count a power of two, which
199 * the mask and shift lookup depends on.
200 *
201 * @param[in] elem_len Size of the element.
202 * @return 0 if the element does not fit in a line with its header.
203 */
204static inline CC_HINT(always_inline) size_t atomic_queue_stripes(size_t elem_len)
205{
206 size_t need = offsetof(fr_atomic_queue_slot_t, data) + elem_len;
207 size_t stripes;
208
209 if (need > CACHE_LINE_SIZE) return 0;
210
211 stripes = CACHE_LINE_SIZE / need;
212 while (stripes & (stripes - 1)) stripes &= stripes - 1;
213
214 return stripes;
215}
216
217/** Number of cache lines needed to hold `num` slots
218 *
219 * A queue smaller than one line uses a single, partly filled line.
220 *
221 * @param[in] num Slot count, already rounded up to a power of 2.
222 */
223static inline CC_HINT(always_inline) size_t atomic_queue_num_lines(size_t num, size_t stripes)
224{
225 if (num < stripes) return 1;
226
227 return num / stripes;
228}
229
230/** Bytes needed for a queue of `num` slots, header included
231 *
232 * @param[in] num Slot count, already rounded up to a power of 2.
233 */
234static inline CC_HINT(always_inline) size_t atomic_queue_bytes(size_t num, size_t stripes)
235{
236 return sizeof(fr_atomic_queue_t) + (atomic_queue_num_lines(num, stripes) * CACHE_LINE_SIZE);
237}
238
239/** Map a queue position to its slot
240 *
241 * Positions wrap at `num`. Within one stripe, consecutive positions increment
242 * one line at a time, and move to the next stripe once every line has been
243 * visited.
244 *
245 * @param[in] aq The queue.
246 * @param[in] pos The head or tail position, unmasked.
247 */
248static inline CC_HINT(always_inline) fr_atomic_queue_slot_t *atomic_queue_slot(fr_atomic_queue_t *aq, int64_t pos)
249{
250 size_t idx = (size_t)pos & (aq->num - 1);
251
252 /*
253 * The offset is in bytes, but "lines" is not an array of bytes. We want to get the offset to
254 * the cache line, so we have to account for the size of each element in the "lines" array.
255 */
256 return (fr_atomic_queue_slot_t *)(aq->lines + (((idx & aq->line_mask) * CACHE_LINE_SIZE) +
257 ((idx >> aq->line_shift) * aq->slot_len)) / sizeof(aq->lines[0]));
258}
259
260/** Initialise the sequence numbers and head/tail on a fresh queue buffer
261 *
262 * Shared between the talloc and raw allocators. The buffer must already
263 * be cache-line aligned and sized to hold `num` slots.
264 *
265 * @param[in] aq The queue buffer to initialise.
266 * @param[in] num Slot count, already rounded up to a power of 2.
267 * @param[in] elem_len Size of one element, known to fit.
268 */
269static void atomic_queue_init(fr_atomic_queue_t *aq, size_t num, size_t elem_len)
270{
271 size_t i, num_lines;
272
273 aq->elem_len = elem_len;
274 aq->stripes = atomic_queue_stripes(elem_len);
275 fr_assert(aq->stripes > 0);
276 aq->slot_len = CACHE_LINE_SIZE / aq->stripes;
277 num_lines = atomic_queue_num_lines(num, aq->stripes);
278 memset(aq->lines, 0, num_lines * CACHE_LINE_SIZE);
279
280 aq->num = num;
281 aq->line_mask = num_lines - 1;
282 /*
283 * num_lines is a power of two, so the shift is its log2.
284 * The check here is mostly to quiet clang scan, which
285 * complained about the potential underflow.
286 */
287 if (num_lines > 1) {
288 aq->line_shift = fr_high_bit_pos(num_lines) - 1;
289 } else {
290 aq->line_shift = 0;
291 }
292
293 /*
294 * Initialize the slots. Data is NULL, and the sequence
295 * number is the position of the slot.
296 */
297 for (i = 0; i < num; i++) {
298 fr_atomic_queue_slot_t *slot = atomic_queue_slot(aq, (int64_t)i);
299
300 store(slot->seq, (int64_t)i);
301 }
302
303 store(aq->head, 0);
304 store(aq->tail, 0);
306}
307
308/** Create a fixed-size atomic queue
309 *
310 * Push and pop copy `elem_len` bytes in and out, so a queue of pointers
311 * is a queue of `sizeof(uintptr_t)` elements whose callers pass the
312 * address of the pointer. Nothing is allocated per element, and
313 * nothing has to be freed by the consumer.
314 *
315 * @note the queue must be freed explicitly by the ctx being freed, or by using
316 * the #fr_atomic_queue_free function.
317 *
318 * @param[in] ctx The talloc ctx to allocate the queue in.
319 * @param[in] num The number of entries in the queue.
320 * @param[in] elem_len The size of one element. Elements are 8 byte aligned.
321 * @return
322 * - NULL on error, including an element which does not fit in a cache line.
323 * - fr_atomic_queue_t *, a pointer to the allocated and initialized queue.
324 */
325fr_atomic_queue_t *fr_atomic_queue_talloc(TALLOC_CTX *ctx, size_t num, size_t elem_len)
326{
328 TALLOC_CTX *chunk;
329 size_t stripes;
330
331 if ((num == 0) || (elem_len == 0)) return NULL;
332 stripes = atomic_queue_stripes(elem_len);
333 if (stripes == 0) return NULL;
334
335 /*
336 * Roundup to the next power of 2 so we don't need modulo.
337 */
338 num = (size_t)fr_roundup_pow2_uint64((uint64_t)num);
339
340 /*
341 * Allocate a contiguous blob for the header and queue.
342 * This helps with memory locality.
343 *
344 * Since we're allocating a blob, we should also set the
345 * name of the data, too.
346 */
347 chunk = talloc_aligned_array(ctx, (void **)&aq, CACHE_LINE_SIZE, atomic_queue_bytes(num, stripes));
348 if (!chunk) return NULL;
349 aq->chunk = chunk;
350
351 talloc_set_name_const(chunk, "fr_atomic_queue_t");
352
353 atomic_queue_init(aq, num, elem_len);
354
355 return aq;
356}
357
358/** Create fixed-size atomic queue outside any talloc hierarchy
359 *
360 * Backed by `posix_memalign`. The queue has no owner: `chunk` is NULL
361 * and the caller releases it with #fr_atomic_queue_free or plain `free()`.
362 *
363 * For callers that allocate from threads where talloc is not safe (for
364 * example, library-owned callback threads).
365 *
366 * @param[in] num The number of entries in the queue.
367 * @param[in] elem_len The size of one element.
368 * @return
369 * - NULL on error.
370 * - fr_atomic_queue_t *, a pointer to the allocated and initialized queue.
371 */
372static fr_atomic_queue_t *atomic_queue_malloc_raw(size_t num, size_t elem_len)
373{
375 size_t stripes;
376
377 if ((num == 0) || (elem_len == 0)) return NULL;
378 stripes = atomic_queue_stripes(elem_len);
379 if (stripes == 0) return NULL;
380
381 num = (size_t)fr_roundup_pow2_uint64((uint64_t)num);
382
383 if (posix_memalign((void **)&aq, CACHE_LINE_SIZE, atomic_queue_bytes(num, stripes)) != 0) return NULL;
384
385 aq->chunk = NULL;
386 atomic_queue_init(aq, num, elem_len);
387
388 return aq;
389}
390
391/** Owner handle for a queue outside the talloc hierarchy
392 *
393 * Raw and mapped queues keep their memory outside talloc. This handle
394 * is the only talloc'd part, so freeing the context the handle lives in
395 * releases the queue.
396 */
397typedef struct {
398 fr_atomic_queue_t *aq; //!< The memory to release.
399 size_t len; //!< Length of a mapping.
400 int fd; //!< The shared memory object behind a mapping,
401 ///< or -1 for a raw allocation.
403
405{
406 if (owner->fd < 0) {
407 free(owner->aq);
408 } else {
409 (void) munmap(owner->aq, owner->len);
410 (void) close(owner->fd);
411 }
412
413 return 0;
414}
415
416/** Create fixed-size atomic queue outside the talloc hierarchy, owned by a talloc context
417 *
418 * The queue itself is a raw `posix_memalign` allocation, so it can be
419 * pushed to and popped from by threads where talloc is not safe, and
420 * can later be placed in memory talloc does not manage. A small owner
421 * handle allocated in `ctx` frees the queue when `ctx` is freed, or
422 * when the caller calls #fr_atomic_queue_free.
423 *
424 * @param[in] ctx The talloc ctx which owns the queue.
425 * @param[in] num The number of entries in the queue.
426 * @param[in] elem_len The size of one element.
427 * @return
428 * - NULL on error.
429 * - fr_atomic_queue_t *, a pointer to the allocated and initialized queue.
430 */
431fr_atomic_queue_t *fr_atomic_queue_malloc(TALLOC_CTX *ctx, size_t num, size_t elem_len)
432{
435
436 aq = atomic_queue_malloc_raw(num, elem_len);
437 if (!aq) return NULL;
438
439 owner = talloc(ctx, fr_atomic_queue_owner_t);
440 if (!owner) {
441 free(aq);
442 return NULL;
443 }
444 owner->aq = aq;
445 owner->len = 0;
446 owner->fd = -1;
447 talloc_set_destructor(owner, _atomic_queue_owner_free);
448 aq->chunk = owner;
449
450 return aq;
451}
452
453/** Open an anonymous shared memory object of a given length
454 *
455 * @param[in] len bytes the object must hold.
456 * @return
457 * - The descriptor, close on exec.
458 * - -1 on error, with the error in fr_strerror.
459 */
460static int atomic_queue_shm_open(size_t len)
461{
462 int fd;
463
464 fd = memfd_create("fr_aq", MFD_CLOEXEC);
465 if (fd < 0) {
466 fr_strerror_printf("Failed creating shared memory object: %s", fr_syserror(errno));
467 return -1;
468 }
469
470 if (ftruncate(fd, (off_t) len) < 0) {
471 fr_strerror_printf("Failed sizing shared memory object: %s", fr_syserror(errno));
472 close(fd);
473 return -1;
474 }
475
476 return fd;
477}
478
479/** Create or attach to a fixed-size atomic queue in shared memory, owned by a talloc context
480 *
481 * With *fd negative, a new anonymous shared memory object is created,
482 * the queue initialised in it, and its descriptor written back for the
483 * caller to pass to another process. With a descriptor, that object is
484 * mapped and must already hold a queue of this size; the mapping is not
485 * reinitialised. Either way the handle owns the descriptor and closes
486 * it with the mapping. Pages are aligned well beyond a cache line.
487 *
488 * @param[in] ctx The talloc ctx which owns the queue.
489 * @param[in,out] fd A shared memory object holding a queue to attach to, or -1 to
490 * create one, in which case the new descriptor is written here.
491 * @param[in] num The number of entries in the queue.
492 * @param[in] elem_len The size of one element.
493 * @return
494 * - NULL on error, with the error in fr_strerror.
495 * - fr_atomic_queue_t *, a pointer to the mapped queue.
496 */
497fr_atomic_queue_t *fr_atomic_queue_mmap(TALLOC_CTX *ctx, int *fd, size_t num, size_t elem_len)
498{
501 size_t stripes, len;
502 bool attach = (*fd >= 0);
503
504 if ((num == 0) || (elem_len == 0)) return NULL;
505 stripes = atomic_queue_stripes(elem_len);
506 if (stripes == 0) return NULL;
507
508 num = (size_t)fr_roundup_pow2_uint64((uint64_t)num);
509 len = atomic_queue_bytes(num, stripes);
510
511 if (!attach) {
513 if (*fd < 0) return NULL;
514 }
515
516 aq = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0);
517 if (aq == MAP_FAILED) {
518 fr_strerror_printf("Failed mapping shared memory object: %s", fr_syserror(errno));
519 if (!attach) {
520 close(*fd);
521 *fd = -1;
522 }
523 return NULL;
524 }
525
526 /*
527 * The creator laid the queue out for its own size and element.
528 * We can only share it if ours agree.
529 */
530 if (attach && ((aq->num != num) || (aq->elem_len != elem_len))) {
531 fr_strerror_printf("Shared queue holds %zu elements of %zu bytes, expected %zu of %zu",
532 aq->num, aq->elem_len, num, elem_len);
533 (void) munmap(aq, len);
534 return NULL;
535 }
536
537 owner = talloc(ctx, fr_atomic_queue_owner_t);
538 if (!owner) {
539 (void) munmap(aq, len);
540 if (!attach) {
541 close(*fd);
542 *fd = -1;
543 }
544 return NULL;
545 }
546 owner->aq = aq;
547 owner->len = len;
548 owner->fd = *fd;
549 talloc_set_destructor(owner, _atomic_queue_owner_free);
550
551 if (!attach) atomic_queue_init(aq, num, elem_len);
552
553 /*
554 * Each process has its own handle, and the chunk pointer is only
555 * meaningful in the process which set it. The last writer wins,
556 * which is fine as nothing reads it across processes.
557 */
558 aq->chunk = owner;
559
560 return aq;
561}
562
563
564/** Free an atomic queue if it's not freed by ctx
565 *
566 * The queue memory must be cache line aligned, so it lives in one of
567 * three places: a talloc aligned array (`chunk` is the array), a raw
568 * allocation owned by a talloc handle (`chunk` is the handle, whose
569 * destructor frees the queue), or a raw allocation with no owner
570 * (`chunk` is NULL).
571 */
573{
574 if (!*aq) return;
575
576 if ((*aq)->chunk) {
577 talloc_free((*aq)->chunk);
578 } else {
579 free(*aq);
580 }
581 *aq = NULL;
582}
583
584/** Copy an element into the atomic queue, any number of producers
585 *
586 * For a queue of pointers, data is the address of the pointer.
587 *
588 * @param[in] aq The atomic queue to add data to.
589 * @param[in] data the element, `elem_len` long.
590 * @return
591 * - true on successful push
592 * - false on queue full
593 */
595{
596 int64_t head;
598
599 /*
600 * Here we're essentially racing with other producers
601 * to find the current head of the queue.
602 *
603 * 1. Load the current head (which may be incremented
604 * by another producer before we enter the loop).
605 * 2. Find the head slot, which is head modulo the
606 * queue size (keeps head looping through the queue).
607 * 3. Read the sequence number of the slot.
608 * The sequence numbers are initialised to the index
609 * of the slots in the queue. Each pass of the
610 * producer increments the sequence number by one.
611 * 4.
612 * a. If the sequence number is equal to the head,
613 * then we can use the slot. Increment the head
614 * so other producers know we've used it.
615 * b. If it's greater than head, the producer has
616 * already written to this slot, so we need to re-load
617 * the head and race other producers again.
618 * c. If it's less than the head, the slot has not yet
619 * been consumed, and the queue is full.
620 */
621 head = load(aq->head);
622
623 /*
624 * Try to find the current head.
625 */
626 for (;;) {
627 int64_t seq, diff;
628
629 /*
630 * Alloc function guarantees size is a power
631 * of 2, so we can use this hack to avoid
632 * modulo.
633 */
634 slot = atomic_queue_slot(aq, head);
635 seq = acquire(slot->seq);
636 diff = (seq - head);
637
638 /*
639 * head is larger than the current slot, the
640 * queue is full.
641 * The consumer will set slot seq to slot +
642 * queue size, marking it as free for the
643 * producer to use.
644 */
645 if (diff < 0) {
646#if 0
647 fr_atomic_queue_debug(stderr, aq);
648#endif
649 return false;
650 }
651
652 /*
653 * Someone else has already written to this slot
654 * we lost the race, try again.
655 */
656 if (diff > 0) {
657 head = load(aq->head);
658 continue;
659 }
660
661 /*
662 * See if we can increment the head value
663 * (and check it's still at its old value).
664 *
665 * This means no two producers can have the same
666 * slot in the queue, because they can't exit
667 * the loop until they've incremented the head
668 * successfully.
669 *
670 * When we fail, we don't increment head before
671 * trying again, because we need to detect queue
672 * full conditions.
673 */
674 if (cas_incr(aq->head, head)) {
675 break;
676 }
677 }
678
679 /*
680 * Store the data in the queue, and increment the slot
681 * with the new index, and make the write visible to
682 * other CPUs.
683 */
684 memcpy(slot->data, data, aq->elem_len);
685
686 /*
687 * Technically head can overflow. Practically, with a
688 * 3GHz CPU, doing nothing but incrementing head
689 * uncontended it'd take about 100 years for this to
690 * happen. But hey, maybe someone invents an optical
691 * CPU with a significantly higher clock speed, it's ok
692 * for us to exit every 9 quintillion packets.
693 */
694#ifdef __clang_analyzer__
695 if (unlikely((head + 1) == INT64_MAX)) exit(1);
696#endif
697
698 /*
699 * Mark up the slot as written to. Any other producer
700 * attempting to write will see (diff > 0) and retry.
701 */
702 store(slot->seq, head + 1);
703 return true;
704}
705
706/** Copy an element out of the atomic queue, any number of consumers
707 *
708 * For a queue of pointers, data is the address of a pointer to fill.
709 *
710 * @param[in] aq the atomic queue to retrieve data from.
711 * @param[out] data where to write the element, `elem_len` long.
712 * @return
713 * - true on successful pop
714 * - false on queue empty
715 */
717{
718 int64_t tail, seq;
720
721 tail = load(aq->tail);
722
723 for (;;) {
724 int64_t diff;
725
726 slot = atomic_queue_slot(aq, tail);
727 seq = acquire(slot->seq);
728
729 diff = (seq - (tail + 1));
730
731 /*
732 * Tail is smaller than the current slot,
733 * the queue is empty.
734 *
735 * Tail should now be equal to the head.
736 */
737 if (diff < 0) {
738 return false;
739 }
740
741 /*
742 * Tail is now ahead of us.
743 * Something else has consumed it.
744 * We lost the race with another consumer.
745 */
746 if (diff > 0) {
747 tail = load(aq->tail);
748 continue;
749 }
750
751 /*
752 * Same deal as push.
753 * After this point we own the slot.
754 */
755 if (cas_incr(aq->tail, tail)) {
756 break;
757 }
758 }
759
760 /*
761 * Copy the element to the caller BEFORE updating the
762 * queue slot.
763 */
764 memcpy(data, slot->data, aq->elem_len);
765
766 /*
767 * Set the current slot to past the end of the queue.
768 * This is equal to what head will be on its next pass
769 * through the queue. This marks the slot as free.
770 */
771 store(slot->seq, tail + aq->num);
772
773 return true;
774}
775
776/** Copy an element into the atomic queue, one producer only
777 *
778 * The same slots and sequence numbers as the mpmc functions, so the
779 * consumer may be either flavour. With one producer nobody else
780 * advances head, so there is nothing to race and no compare-and-swap:
781 * the slot is free when its sequence number equals head.
782 *
783 * @param[in] aq The atomic queue to add data to.
784 * @param[in] data the element, `elem_len` long.
785 * @return
786 * - true on successful push
787 * - false on queue full
788 */
790{
791 int64_t head = load(aq->head);
793
794 if (acquire(slot->seq) != head) return false;
795
796 memcpy(slot->data, data, aq->elem_len);
797 store(slot->seq, head + 1);
798 store(aq->head, head + 1);
799
800 return true;
801}
802
803/** Copy an element out of the atomic queue, one consumer only
804 *
805 * With one consumer nobody else advances tail, so no compare-and-swap:
806 * the slot is full when its sequence number is one past tail.
807 *
808 * @param[in] aq the atomic queue to retrieve data from.
809 * @param[out] data where to write the element, `elem_len` long.
810 * @return
811 * - true on successful pop
812 * - false on queue empty
813 */
815{
816 int64_t tail = load(aq->tail);
818
819 if (acquire(slot->seq) != (tail + 1)) return false;
820
821 memcpy(data, slot->data, aq->elem_len);
822 store(slot->seq, tail + aq->num);
823 store(aq->tail, tail + 1);
824
825 return true;
826}
827
829{
830 return aq->num;
831}
832
833/*
834 * Segmented single-producer / single-consumer ring.
835 *
836 * Safety argument: one producer owns `head` and writes `seg->next`
837 * exactly once (release). One consumer owns `tail` and reads
838 * `tail->next` with acquire; by the release/acquire pair plus the
839 * invariant "no push into s after s->next is set" the consumer
840 * cannot advance past a segment that still has an in-flight push
841 * as long as it retries `pop(tail->q)` once more after observing
842 * `tail->next != NULL`.
843 */
844
846
848 fr_atomic_queue_t *q; //!< Per-segment queue, driven with the spsc functions.
849 _Atomic(fr_atomic_ring_segment_t *) next; //!< NULL until the producer seals this segment
850 ///< because it filled up and moved on to a
851 ///< fresh one.
852};
853
855 size_t seg_size; //!< Capacity of each segment.
856 _Atomic(fr_atomic_ring_segment_t *) head; //!< Producer end. Writer is the single producer,
857 ///< reader is also the producer - the consumer
858 ///< never loads this.
859 fr_atomic_ring_segment_t *tail; //!< Consumer end. Touched only by the consumer.
860};
861
862/** Allocate a fresh segment and its embedded queue
863 *
864 * Uses the raw (non-talloc) allocator so this function is safe to call
865 * from the producer thread even when that thread cannot safely use talloc.
866 */
868{
870
871 s = malloc(sizeof(*s));
872 if (!s) return NULL;
873
874 s->q = atomic_queue_malloc_raw(seg_size, sizeof(uintptr_t));
875 if (!s->q) {
876 free(s);
877 return NULL;
878 }
879 atomic_init(&s->next, NULL);
880
881 return s;
882}
883
889
890/** talloc destructor for #fr_atomic_ring_t: walk the chain and free segments */
892{
893 fr_atomic_ring_segment_t *s = ring->tail;
894
895 while (s) {
897
899 s = next;
900 }
901
902 return 0;
903}
904
905/** Allocate an empty SPSC ring
906 *
907 * @param[in] ctx talloc ctx that owns the ring handle (segments live
908 * outside talloc; they are freed by the ring's
909 * destructor).
910 * @param[in] seg_size Per-segment capacity. Rounded up to a power of 2.
911 * @return
912 * - NULL on error.
913 * - A ring containing one initial (empty) segment.
914 */
915fr_atomic_ring_t *fr_atomic_ring_alloc(TALLOC_CTX *ctx, size_t seg_size)
916{
917 fr_atomic_ring_t *ring;
919
920 if (seg_size == 0) return NULL;
921
922 ring = talloc(ctx, fr_atomic_ring_t);
923 if (!ring) return NULL;
924
925 seg = atomic_ring_segment_alloc(seg_size);
926 if (!seg) {
927 talloc_free(ring);
928 return NULL;
929 }
930
931 ring->seg_size = seg_size;
932 ring->tail = seg;
933 atomic_init(&ring->head, seg);
934 talloc_set_destructor(ring, _atomic_ring_free);
935
936 return ring;
937}
938
939/** Free the ring and all remaining segments
940 *
941 * Equivalent to `talloc_free()` on the ring, but nulls the caller's
942 * handle in the style of #fr_atomic_queue_free.
943 */
945{
946 if (!*ring_p) return;
947
948 talloc_free(*ring_p);
949 *ring_p = NULL;
950}
951
952/** Link a new segment after the current head and make it the head
953 *
954 * The consumer only inspects `h->next` and advances past `h` once it
955 * sees a non-NULL value there, so `h->next` is published with release
956 * ordering, which pairs with the acquire in fr_atomic_ring_pop().
957 *
958 * Modelled for Coverity in src/coverity-model/merged_model.c, as the
959 * analyser does not treat an atomic store as publishing the pointer.
960 *
961 * @param[in] ring the segment belongs to.
962 * @param[in] h Current head segment.
963 * @param[in] n New segment to publish.
964 */
971
972/** Push a pointer into the ring; allocate a new segment on overflow
973 *
974 * Single-producer only. Must not be called concurrently with itself.
975 *
976 * @param[in] ring Ring to push into.
977 * @param[in] data Value to push (must be non-NULL).
978 * @return
979 * - true on success.
980 * - false if both the current segment is full and a new segment
981 * could not be allocated.
982 */
984{
987
989
990 if (likely(fr_atomic_queue_spsc_push(h->q, &data))) return true;
991
992 n = atomic_ring_segment_alloc(ring->seg_size);
993 if (unlikely(!n)) return false;
994
996
997 return fr_atomic_queue_spsc_push(n->q, &data);
998}
999
1000/** Pop a pointer from the ring, advancing past drained segments
1001 *
1002 * Single-consumer only. Must not be called concurrently with itself.
1003 *
1004 * @param[in] ring Ring to pop from.
1005 * @param[out] p_data Where to write the popped value on success.
1006 * @return
1007 * - true if a value was popped.
1008 * - false if the ring is currently empty.
1009 */
1010bool fr_atomic_ring_pop(fr_atomic_ring_t *ring, void **p_data)
1011{
1015
1016 for (;;) {
1017 cur = ring->tail;
1018
1019 if (likely(fr_atomic_queue_spsc_pop(cur->q, p_data))) return true;
1020
1021 /*
1022 * Empty from our point of view. If the producer hasn't
1023 * sealed this segment there might be pushes in our
1024 * future - return and let the caller come back.
1025 */
1027 if (!n) return false;
1028
1029 /*
1030 * Sealed. One more pop to drain anything the producer
1031 * committed before sealing but after our first (empty)
1032 * pop observation. Without this re-check, late commits
1033 * in the (empty-observation, seal-observation) window
1034 * would be stranded when we advance past `cur`.
1035 */
1036 if (fr_atomic_queue_spsc_pop(cur->q, p_data)) return true;
1037
1038 old = cur;
1039 ring->tail = n;
1041 /* loop to pop from the new tail */
1042 }
1043}
1044
1045#ifdef WITH_VERIFY_PTR
1046/** Check the talloc chunk is still valid
1047 *
1048 */
1049void fr_atomic_queue_verify(fr_atomic_queue_t *aq)
1050{
1051 (void)talloc_get_type_abort(aq->chunk, fr_atomic_queue_t);
1052}
1053#endif
1054
1055#ifndef NDEBUG
1056
1057#if 0
1058typedef struct {
1059 int status; //!< status of this message
1060 size_t data_size; //!< size of the data we're sending
1061
1062 int signal; //!< the signal to send
1063 uint64_t ack; //!< or the endpoint..
1064 void *ch; //!< the channel
1065} fr_control_message_t;
1066#endif
1067
1068
1069/** Dump an atomic queue.
1070 *
1071 * Absolutely NOT thread-safe.
1072 *
1073 * @param[in] aq The atomic queue to debug.
1074 * @param[in] fp where the debugging information will be printed.
1075 */
1077{
1078 size_t i;
1079 int64_t head, tail;
1080
1081 head = load(aq->head);
1082 tail = load(aq->tail);
1083
1084 fprintf(fp, "AQ %p size %zu, head %" PRId64 ", tail %" PRId64 "\n",
1085 aq, aq->num, head, tail);
1086
1087 for (i = 0; i < aq->num; i++) {
1089
1090 slot = atomic_queue_slot(aq, (int64_t)i);
1091
1092 fprintf(fp, "\t[%zu] = { %p, %" PRId64 " }",
1093 i, (void *) slot->data, load(slot->seq));
1094#if 0
1095 if (slot->data) {
1096 fr_control_message_t *c;
1097
1098 c = slot->data;
1099
1100 fprintf(fp, "\tstatus %d, data_size %zd, signal %d, ack %zd, ch %p",
1101 c->status, c->data_size, c->signal, c->ack, c->ch);
1102 }
1103#endif
1104 fprintf(fp, "\n");
1105 }
1106}
1107#endif
int n
Definition acutest.h:642
static fr_atomic_queue_slot_t * atomic_queue_slot(fr_atomic_queue_t *aq, int64_t pos)
Map a queue position to its slot.
atomic_int64_t head
Position of the producer.
size_t len
Length of a mapping.
uint8_t line_shift
High bits of a slot index give its stripe within that line: .stripe[slot >> line_shift].
#define atomic_int64_t
void fr_atomic_queue_debug(FILE *fp, fr_atomic_queue_t *aq)
Dump an atomic queue.
void * chunk
The start of the talloc chunk to pass to free, or NULL if this queue was allocated raw via fr_atomic_...
size_t elem_len
Size of one element.
uint64_t lines[]
The lines, each exactly one cache line, aligned with cache lines to ensure producers and consumers do...
bool fr_atomic_ring_push(fr_atomic_ring_t *ring, void *data)
Push a pointer into the ring; allocate a new segment on overflow.
int fd
The shared memory object behind a mapping, or -1 for a raw allocation.
atomic_int64_t tail
Position of the consumer.
fr_atomic_queue_t * fr_atomic_queue_malloc(TALLOC_CTX *ctx, size_t num, size_t elem_len)
Create fixed-size atomic queue outside the talloc hierarchy, owned by a talloc context.
#define cas_incr(_store, _var)
void fr_atomic_ring_free(fr_atomic_ring_t **ring_p)
Free the ring and all remaining segments.
#define LINES_ZERO
static size_t atomic_queue_num_lines(size_t num, size_t stripes)
Number of cache lines needed to hold num slots.
static void atomic_ring_segment_free(fr_atomic_ring_segment_t *s)
uint8_t data[]
The element, 8 byte aligned as slots are a power of two bytes from a line boundary.
static int _atomic_ring_free(fr_atomic_ring_t *ring)
talloc destructor for fr_atomic_ring_t: walk the chain and free segments
static int _atomic_queue_owner_free(fr_atomic_queue_owner_t *owner)
fr_atomic_ring_t * fr_atomic_ring_alloc(TALLOC_CTX *ctx, size_t seg_size)
Allocate an empty SPSC ring.
bool fr_atomic_queue_mpmc_pop(fr_atomic_queue_t *aq, void *data)
Copy an element out of the atomic queue, any number of consumers.
static fr_atomic_ring_segment_t * atomic_ring_segment_alloc(size_t seg_size)
Allocate a fresh segment and its embedded queue.
bool fr_atomic_ring_pop(fr_atomic_ring_t *ring, void **p_data)
Pop a pointer from the ring, advancing past drained segments.
size_t line_mask
Low bits of a slot index give its line: line[slot & line_mask].
atomic_int64_t seq
The position this slot was last written or freed at.
size_t fr_atomic_queue_size(fr_atomic_queue_t *aq)
static fr_atomic_queue_t * atomic_queue_malloc_raw(size_t num, size_t elem_len)
Create fixed-size atomic queue outside any talloc hierarchy.
fr_atomic_queue_t * fr_atomic_queue_mmap(TALLOC_CTX *ctx, int *fd, size_t num, size_t elem_len)
Create or attach to a fixed-size atomic queue in shared memory, owned by a talloc context.
size_t slot_len
The line divided by the stripes: header, element, padding.
#define load(_var)
static void atomic_ring_segment_publish(fr_atomic_ring_t *ring, fr_atomic_ring_segment_t *h, fr_atomic_ring_segment_t *n)
Link a new segment after the current head and make it the head.
bool fr_atomic_queue_mpmc_push(fr_atomic_queue_t *aq, void const *data)
Copy an element into the atomic queue, any number of producers.
void fr_atomic_queue_free(fr_atomic_queue_t **aq)
Free an atomic queue if it's not freed by ctx.
bool fr_atomic_queue_spsc_push(fr_atomic_queue_t *aq, void const *data)
Copy an element into the atomic queue, one producer only.
fr_atomic_queue_t * fr_atomic_queue_talloc(TALLOC_CTX *ctx, size_t num, size_t elem_len)
Create a fixed-size atomic queue.
#define store(_store, _var)
static void atomic_queue_init(fr_atomic_queue_t *aq, size_t num, size_t elem_len)
Initialise the sequence numbers and head/tail on a fresh queue buffer.
fr_atomic_queue_t * aq
The memory to release.
fr_atomic_queue_t * q
Per-segment queue, driven with the spsc functions.
#define acquire(_var)
static size_t atomic_queue_stripes(size_t elem_len)
How many slots a line holds for an element size.
bool fr_atomic_queue_spsc_pop(fr_atomic_queue_t *aq, void *data)
Copy an element out of the atomic queue, one consumer only.
static size_t atomic_queue_bytes(size_t num, size_t stripes)
Bytes needed for a queue of num slots, header included.
size_t num
Elements the queue holds.
static int atomic_queue_shm_open(size_t len)
Open an anonymous shared memory object of a given length.
size_t seg_size
Capacity of each segment.
#define CACHE_LINE_SIZE
size_t stripes
Slots per line.
Owner handle for a queue outside the talloc hierarchy.
Structure to hold the atomic queue.
One slot in the queue.
struct fr_atomic_queue_s fr_atomic_queue_t
#define RCSID(id)
Definition build.h:609
#define DIAG_ON(_x)
Definition build.h:582
#define unlikely(_x)
Definition build.h:492
#define DIAG_OFF(_x)
Definition build.h:581
free(array)
talloc_free(hp)
static uint64_t fr_roundup_pow2_uint64(uint64_t v)
Definition math.h:32
static uint8_t fr_high_bit_pos(uint64_t num)
Find the highest order high bit in an unsigned 64 bit integer.
Definition math.h:94
unsigned char uint8_t
unsigned long int size_t
int memfd_create(char const *name, unsigned int flags)
Emulates memfd_create with a named shared memory object.
Definition missing.c:597
#define fr_assert(_expr)
Definition rad_assert.h:37
@ memory_order_seq_cst
Definition stdatomic.h:132
@ memory_order_release
Definition stdatomic.h:130
@ memory_order_relaxed
Definition stdatomic.h:127
@ memory_order_acquire
Definition stdatomic.h:129
#define _Atomic(T)
Definition stdatomic.h:77
#define atomic_load_explicit(object, order)
Definition stdatomic.h:312
#define atomic_thread_fence(order)
Definition stdatomic.h:148
#define atomic_store_explicit(object, desired, order)
Definition stdatomic.h:314
#define atomic_init(obj, value)
Definition stdatomic.h:89
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition syserror.c:243
TALLOC_CTX * talloc_aligned_array(TALLOC_CTX *ctx, void **start, size_t alignment, size_t size)
Return a page aligned talloc memory array.
Definition talloc.c:197
static fr_slen_t head
Definition xlat.h:410
#define fr_strerror_printf(_fmt,...)
Log to thread local error buffer.
Definition strerror.h:64
static fr_slen_t data
Definition value.h:1366
static fr_sbuff_err_t char size_t * len
Definition value.h:1061