File Coverage

buf_generic.h
Criterion Covered Total %
statement 1136 2130 53.3
branch 355 1032 34.4
condition n/a
subroutine n/a
pod n/a
total 1491 3162 47.1


line stmt bran cond sub pod time code
1             /*
2             * buf_generic.h — Macro-template for shared-memory typed buffers.
3             *
4             * Before including, define:
5             * BUF_PREFIX — function prefix (e.g., buf_i64)
6             * BUF_ELEM_TYPE — C element type (e.g., int64_t)
7             * BUF_VARIANT_ID — unique integer for header validation
8             * BUF_ELEM_SIZE — sizeof(BUF_ELEM_TYPE) or fixed string length
9             *
10             * Optional:
11             * BUF_HAS_COUNTERS — generate incr/decr/cas (integer types only)
12             * BUF_IS_FLOAT — element is float/double (affects SV conversion)
13             * BUF_IS_FIXEDSTR — element is fixed-length char array
14             */
15              
16             /* ================================================================
17             * Part 1: Shared definitions (included once)
18             * ================================================================ */
19              
20             #ifndef BUF_DEFS_H
21             #define BUF_DEFS_H
22              
23             #include
24             #include
25             #include
26             #include
27             #include
28             #include
29             #include
30             #include
31             #include
32             #include
33             #include
34             #include
35             #include
36             #include
37             #include
38             #include
39              
40             /* ---- Constants ---- */
41              
42             #define BUF_MAGIC 0x42554631U /* "BUF1" */
43             #define BUF_VERSION 2 /* v2: reader-slot table for dead-reader rwlock recovery */
44             #define BUF_ERR_BUFLEN 256
45             #define BUF_READER_SLOTS 1024 /* per-process reader-counter mirror */
46              
47             /* ---- Per-process reader-slot table (in shared memory) ----
48             * Mirrors each process's contribution to the global rwlock counters so a
49             * dead reader's contribution can be reclaimed on writer-lock timeout. */
50             typedef struct {
51             uint32_t pid; /* owning PID, 0 = free */
52             uint32_t subcount; /* this process's rwlock reader contribution */
53             uint32_t waiters_parked; /* this process's contribution to rwlock_waiters */
54             uint32_t writers_parked; /* this process's contribution to rwlock_writers_waiting */
55             } BufReaderSlot;
56              
57             /* ---- Shared memory header (128 bytes, 2 cache lines, in mmap) ---- */
58              
59             #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
60             #define BUF_STATIC_ASSERT(cond, msg) _Static_assert(cond, msg)
61             #else
62             #define BUF_STATIC_ASSERT(cond, msg)
63             #endif
64              
65             typedef struct {
66             /* ---- Cache line 0 (0-63): immutable after create ---- */
67             uint32_t magic; /* 0 */
68             uint32_t version; /* 4 */
69             uint32_t variant_id; /* 8 */
70             uint32_t elem_size; /* 12 */
71             uint64_t capacity; /* 16: number of elements */
72             uint64_t total_size; /* 24: total mmap size */
73             uint64_t data_off; /* 32: offset to data array */
74             uint64_t reader_slots_off;/* 40: offset to BufReaderSlot[BUF_READER_SLOTS] */
75             uint8_t _reserved0[16]; /* 48-63 */
76              
77             /* ---- Cache line 1 (64-127): seqlock + rwlock + mutable state ---- */
78             uint32_t seq; /* 64: seqlock counter, odd = writer active */
79             uint32_t rwlock; /* 68: 0=unlocked, readers=1..0x7FFFFFFF, writer=0x80000000|pid */
80             uint32_t rwlock_waiters; /* 72: wake-target counter (readers+writers) */
81             uint32_t stat_recoveries; /* 76 */
82             uint32_t rwlock_writers_waiting; /* 80: reader yield signal (writers only) */
83             uint32_t _pad2; /* 84 */
84             uint64_t _reserved1[5]; /* 88-127 */
85             } BufHeader;
86              
87             BUF_STATIC_ASSERT(sizeof(BufHeader) == 128, "BufHeader must be exactly 128 bytes (2 cache lines)");
88              
89             /* ---- Process-local handle ---- */
90              
91             typedef struct {
92             BufHeader *hdr;
93             void *data; /* pointer to element array in mmap */
94             BufReaderSlot *reader_slots; /* in mmap, BUF_READER_SLOTS entries */
95             size_t mmap_size;
96             char *path; /* backing file path (strdup'd, NULL for anon) */
97             int fd; /* kept open for memfd, -1 otherwise */
98             int efd; /* eventfd for notifications, -1 if none */
99             uint32_t my_slot_idx; /* UINT32_MAX = unclaimed; per-process slot index */
100             uint32_t cached_pid; /* getpid() at claim time */
101             uint32_t cached_fork_gen; /* fork-generation at claim time */
102             uint8_t wr_locked; /* process-local: 1 if lock_wr is held */
103             uint8_t efd_owned; /* 1 if we created the eventfd (close on destroy) */
104             } BufHandle;
105              
106             /* ---- Futex-based read-write lock ---- */
107              
108             #define BUF_RWLOCK_SPIN_LIMIT 32
109             #define BUF_LOCK_TIMEOUT_SEC 2
110              
111 293           static inline void buf_spin_pause(void) {
112             #if defined(__x86_64__) || defined(__i386__)
113 293           __asm__ volatile("pause" ::: "memory");
114             #elif defined(__aarch64__)
115             __asm__ volatile("yield" ::: "memory");
116             #else
117             __asm__ volatile("" ::: "memory");
118             #endif
119 293           }
120              
121             #define BUF_RWLOCK_WRITER_BIT 0x80000000U
122             #define BUF_RWLOCK_PID_MASK 0x7FFFFFFFU
123             #define BUF_RWLOCK_WR(pid) (BUF_RWLOCK_WRITER_BIT | ((uint32_t)(pid) & BUF_RWLOCK_PID_MASK))
124              
125 17           static inline int buf_pid_alive(uint32_t pid) {
126 17 50         if (pid == 0) return 1;
127 17 100         return !(kill((pid_t)pid, 0) == -1 && errno == ESRCH);
    50          
128             }
129              
130             /* ---- Per-process slot lifecycle (dead-reader recovery) ----
131             * Each process claims one BufReaderSlot lazily on first lock op so that
132             * its contribution to the shared rwlock counter can be reclaimed by other
133             * processes if it dies (SIGKILL'd worker no longer pins the counter). */
134             static uint32_t buf_fork_gen = 0;
135             static pthread_once_t buf_atfork_once = PTHREAD_ONCE_INIT;
136 2           static void buf_on_fork_child(void) {
137 2           __atomic_add_fetch(&buf_fork_gen, 1, __ATOMIC_RELAXED);
138 2           }
139 11           static void buf_atfork_init(void) {
140 11           pthread_atfork(NULL, NULL, buf_on_fork_child);
141 11           }
142              
143 557           static inline void buf_claim_reader_slot(BufHandle *h) {
144 557 50         if (!h->reader_slots) return;
145 557           pthread_once(&buf_atfork_once, buf_atfork_init);
146 557           uint32_t cur_gen = __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED);
147 557 50         if (h->cached_fork_gen != cur_gen) {
148 0           h->cached_fork_gen = cur_gen;
149 0           h->my_slot_idx = UINT32_MAX;
150             }
151 557 100         if (h->my_slot_idx != UINT32_MAX) return;
152 28           uint32_t now_pid = (uint32_t)getpid();
153 28           h->cached_pid = now_pid;
154 28           uint32_t start = now_pid % BUF_READER_SLOTS;
155 29 50         for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) {
156 29           uint32_t s = (start + i) % BUF_READER_SLOTS;
157 29           uint32_t expected = 0;
158 29 100         if (__atomic_compare_exchange_n(&h->reader_slots[s].pid,
159             &expected, now_pid, 0,
160             __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
161 28           __atomic_store_n(&h->reader_slots[s].subcount, 0, __ATOMIC_RELAXED);
162 28           __atomic_store_n(&h->reader_slots[s].waiters_parked, 0, __ATOMIC_RELAXED);
163 28           __atomic_store_n(&h->reader_slots[s].writers_parked, 0, __ATOMIC_RELAXED);
164 28           h->my_slot_idx = s;
165 28           return;
166             }
167             }
168             /* Slot table full — silently skip tracking; recovery falls back to
169             * the slow per-op timeout drain. */
170             }
171              
172             /* Atomically subtract `sub` from a counter, capped at 0 (never underflows). */
173 2           static inline void buf_atomic_sub_cap(uint32_t *p, uint32_t sub) {
174 2 50         if (!sub) return;
175 2           uint32_t cur = __atomic_load_n(p, __ATOMIC_RELAXED);
176 0           for (;;) {
177 2 50         uint32_t want = (cur > sub) ? cur - sub : 0;
178 2 50         if (__atomic_compare_exchange_n(p, &cur, want,
179             1, __ATOMIC_RELAXED, __ATOMIC_RELAXED))
180 2           return;
181             }
182             }
183              
184             /* Try to claim a dead slot (CAS pid → 0) and drain its parked-waiter
185             * contributions to the global counters. Returns 1 if drained, 0 if lost
186             * the CAS race or had no contributions. ACQ_REL syncs us with the dead
187             * process's RELAXED stores to mirror fields on weakly-ordered archs. */
188 5           static inline int buf_drain_dead_slot(BufHandle *h, uint32_t i, uint32_t pid) {
189 5           BufHeader *hdr = h->hdr;
190 5           uint32_t expected = pid;
191 5 50         if (!__atomic_compare_exchange_n(&h->reader_slots[i].pid, &expected, 0,
192             0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED))
193 0           return 0;
194 5           uint32_t wp = __atomic_load_n(&h->reader_slots[i].waiters_parked, __ATOMIC_RELAXED);
195 5           uint32_t writp = __atomic_load_n(&h->reader_slots[i].writers_parked, __ATOMIC_RELAXED);
196 5           int drained = 0;
197 5 100         if (wp) { buf_atomic_sub_cap(&hdr->rwlock_waiters, wp); drained = 1; }
198 5 100         if (writp) { buf_atomic_sub_cap(&hdr->rwlock_writers_waiting, writp); drained = 1; }
199             /* Don't zero slot fields — buf_claim_reader_slot zeros them on the
200             * next claim; zeroing here can race a new claimant's increments. */
201 5           return drained;
202             }
203              
204 2           static inline void buf_recover_dead_readers(BufHandle *h) {
205 2 50         if (!h->reader_slots) return;
206 2           BufHeader *hdr = h->hdr;
207 2           int any_live_reader = 0;
208 2           int found_dead_reader = 0;
209 2           int any_recovery = 0;
210              
211             /* Pass 1: scan; classify; immediate-wipe dead slots with sc==0 (no
212             * rwlock contribution to lose). Defer wiping dead-with-sc>0 slots
213             * until force-reset can fire — otherwise we'd lose the only record
214             * of the orphan rwlock contribution while a live reader is present. */
215 2050 100         for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) {
216 2048           uint32_t pid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
217 2048 100         if (pid == 0) continue;
218 7           uint32_t sc = __atomic_load_n(&h->reader_slots[i].subcount, __ATOMIC_RELAXED);
219 7 100         if (buf_pid_alive(pid)) {
220 2 100         if (sc > 0) any_live_reader = 1;
221 2           continue;
222             }
223 5 100         if (sc > 0) { found_dead_reader = 1; continue; }
224 1 50         if (buf_drain_dead_slot(h, i, pid)) any_recovery = 1;
225             }
226              
227             /* Pass 2: only if force-reset will fire. Issue the rwlock CAS first
228             * to keep the race window with new readers narrow, then wipe the
229             * deferred dead slots. */
230 2 100         if (found_dead_reader && !any_live_reader) {
    50          
231             /* ACQUIRE: a late reader's subcount++ (before its rwlock CAS) is then visible below. */
232 1           uint32_t cur = __atomic_load_n(&hdr->rwlock, __ATOMIC_ACQUIRE);
233 1           int drain_ok = 1; /* keep dead slots if the reset doesn't fire */
234 1 50         if (cur > 0 && cur < BUF_RWLOCK_WRITER_BIT) {
    50          
235             /* Re-scan for a live reader (fail-safe: only suppresses a reset). */
236 1           int live_now = 0; /* no slotless readers here: scanning slots is complete */
237 1025 50         for (uint32_t i = 0; !live_now && i < BUF_READER_SLOTS; i++) {
    100          
238 1024           uint32_t p = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
239 1024 100         if (p && buf_pid_alive(p) &&
    100          
240 1 50         __atomic_load_n(&h->reader_slots[i].subcount, __ATOMIC_RELAXED) > 0)
241 0           live_now = 1;
242             }
243 1 50         if (live_now) {
244 0           drain_ok = 0;
245 1 50         } else if (__atomic_compare_exchange_n(&hdr->rwlock, &cur, 0,
246             0, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
247 1           any_recovery = 1;
248 1 50         if (__atomic_load_n(&hdr->rwlock_waiters, __ATOMIC_RELAXED) > 0)
249 0           syscall(SYS_futex, &hdr->rwlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
250             } else {
251 0           drain_ok = 0; /* rwlock changed under us -- shares may still be live */
252             }
253             }
254 1 50         if (drain_ok) {
255 1025 100         for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) {
256 1024           uint32_t p = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
257 1024 100         if (p == 0 || buf_pid_alive(p)) continue;
    100          
258 4 50         if (buf_drain_dead_slot(h, i, p)) any_recovery = 1;
259             }
260             }
261             }
262 2 50         if (any_recovery)
263 2           __atomic_add_fetch(&hdr->stat_recoveries, 1, __ATOMIC_RELAXED);
264             }
265              
266             /* Park/unpark helpers — keep global rwlock_waiters/writers_waiting and
267             * per-slot mirror counters in sync so recovery can drain them. */
268 1           static inline void buf_park_reader(BufHandle *h) {
269 1           __atomic_add_fetch(&h->hdr->rwlock_waiters, 1, __ATOMIC_RELAXED);
270 1 50         if (h->my_slot_idx != UINT32_MAX)
271 1           __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].waiters_parked, 1, __ATOMIC_RELAXED);
272 1           }
273 1           static inline void buf_unpark_reader(BufHandle *h) {
274 1           __atomic_sub_fetch(&h->hdr->rwlock_waiters, 1, __ATOMIC_RELAXED);
275 1 50         if (h->my_slot_idx != UINT32_MAX)
276 1           __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].waiters_parked, 1, __ATOMIC_RELAXED);
277 1           }
278 1           static inline void buf_park_writer(BufHandle *h) {
279 1           __atomic_add_fetch(&h->hdr->rwlock_waiters, 1, __ATOMIC_RELAXED);
280 1           __atomic_add_fetch(&h->hdr->rwlock_writers_waiting, 1, __ATOMIC_RELAXED);
281 1 50         if (h->my_slot_idx != UINT32_MAX) {
282 1           __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].waiters_parked, 1, __ATOMIC_RELAXED);
283 1           __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].writers_parked, 1, __ATOMIC_RELAXED);
284             }
285 1           }
286 1           static inline void buf_unpark_writer(BufHandle *h) {
287 1           __atomic_sub_fetch(&h->hdr->rwlock_waiters, 1, __ATOMIC_RELAXED);
288 1           __atomic_sub_fetch(&h->hdr->rwlock_writers_waiting, 1, __ATOMIC_RELAXED);
289 1 50         if (h->my_slot_idx != UINT32_MAX) {
290 1           __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].waiters_parked, 1, __ATOMIC_RELAXED);
291 1           __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].writers_parked, 1, __ATOMIC_RELAXED);
292             }
293 1           }
294              
295 0           static inline void buf_recover_stale_lock(BufHeader *hdr, uint32_t observed_rwlock) {
296 0           uint32_t mypid = BUF_RWLOCK_WR((uint32_t)getpid());
297 0 0         if (!__atomic_compare_exchange_n(&hdr->rwlock, &observed_rwlock,
298             mypid, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
299 0           return;
300 0           uint32_t seq = __atomic_load_n(&hdr->seq, __ATOMIC_ACQUIRE);
301 0 0         if (seq & 1)
302 0           __atomic_store_n(&hdr->seq, seq + 1, __ATOMIC_RELEASE);
303 0           __atomic_add_fetch(&hdr->stat_recoveries, 1, __ATOMIC_RELAXED);
304 0           __atomic_store_n(&hdr->rwlock, 0, __ATOMIC_RELEASE);
305 0 0         if (__atomic_load_n(&hdr->rwlock_waiters, __ATOMIC_RELAXED) > 0)
306 0           syscall(SYS_futex, &hdr->rwlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
307             }
308              
309             static const struct timespec buf_lock_timeout = { BUF_LOCK_TIMEOUT_SEC, 0 };
310              
311             /* Recovery dispatcher: if a writer is dead, force-reset the lock word;
312             * otherwise scan reader slots for dead readers and drain their stuck
313             * contributions to the rwlock and waiter counters. Reload the lock
314             * value here (rather than trusting a stale snapshot from the futex
315             * caller) so that (a) a writer that died after our futex_wait started
316             * is detected on the same timeout, and (b) phantom waiter/writers_waiting
317             * contributions left by a dead parked writer are drained even when the
318             * lock word itself is now 0. */
319 2           static inline void buf_recover_after_timeout(BufHandle *h) {
320 2           BufHeader *hdr = h->hdr;
321 2           uint32_t val = __atomic_load_n(&hdr->rwlock, __ATOMIC_RELAXED);
322 2 50         if (val >= BUF_RWLOCK_WRITER_BIT) {
323 0           uint32_t pid = val & BUF_RWLOCK_PID_MASK;
324 0 0         if (!buf_pid_alive(pid))
325 0           buf_recover_stale_lock(hdr, val);
326             } else {
327 2           buf_recover_dead_readers(h);
328             }
329 2           }
330              
331 2           static inline void buf_rwlock_rdlock(BufHandle *h) {
332 2           BufHeader *hdr = h->hdr;
333 2           buf_claim_reader_slot(h);
334 2           uint32_t *lock = &hdr->rwlock;
335 2           uint32_t *writers_waiting = &hdr->rwlock_writers_waiting;
336             /* Bump per-process subcount BEFORE attempting the rwlock CAS so a
337             * concurrent recovery scan sees us as a live in-flight reader. */
338 2 50         if (h->my_slot_idx != UINT32_MAX)
339 2           __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].subcount, 1, __ATOMIC_RELAXED);
340 35           for (int spin = 0; ; spin++) {
341 35           uint32_t cur = __atomic_load_n(lock, __ATOMIC_RELAXED);
342 35 50         if (cur > 0 && cur < BUF_RWLOCK_WRITER_BIT) {
    0          
343 0 0         if (__atomic_compare_exchange_n(lock, &cur, cur + 1,
344             1, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED))
345 2           return;
346 35 50         } else if (cur == 0 && !__atomic_load_n(writers_waiting, __ATOMIC_RELAXED)) {
    100          
347 2 50         if (__atomic_compare_exchange_n(lock, &cur, 1,
348             1, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED))
349 2           return;
350             }
351 33 100         if (__builtin_expect(spin < BUF_RWLOCK_SPIN_LIMIT, 1)) {
352 32           buf_spin_pause();
353 33           continue;
354             }
355 1           buf_park_reader(h);
356 1           cur = __atomic_load_n(lock, __ATOMIC_RELAXED);
357 1 50         if (cur >= BUF_RWLOCK_WRITER_BIT || cur == 0) {
    50          
358 1           long rc = syscall(SYS_futex, lock, FUTEX_WAIT, cur,
359             &buf_lock_timeout, NULL, 0);
360 1 50         if (rc == -1 && errno == ETIMEDOUT) {
    50          
361 1           buf_unpark_reader(h);
362 1           buf_recover_after_timeout(h);
363 1           spin = 0;
364 1           continue;
365             }
366             }
367 0           buf_unpark_reader(h);
368 0           spin = 0;
369             }
370             }
371              
372 2           static inline void buf_rwlock_rdunlock(BufHandle *h) {
373             /* Decrement rwlock BEFORE subcount: a concurrent recovery scan that
374             * sees subcount > 0 with our (live) PID will (correctly) treat us as
375             * an in-flight reader and skip force-reset. */
376 2           uint32_t prev = __atomic_sub_fetch(&h->hdr->rwlock, 1, __ATOMIC_RELEASE);
377 2 50         if (h->my_slot_idx != UINT32_MAX)
378 2           __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].subcount, 1, __ATOMIC_RELAXED);
379 2 50         if (prev == 0 && __atomic_load_n(&h->hdr->rwlock_waiters, __ATOMIC_RELAXED) > 0)
    50          
380 0           syscall(SYS_futex, &h->hdr->rwlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
381 2           }
382              
383 555           static inline void buf_rwlock_wrlock(BufHandle *h) {
384 555           BufHeader *hdr = h->hdr;
385 555           buf_claim_reader_slot(h);
386 555           uint32_t *lock = &hdr->rwlock;
387 555           uint32_t mypid = BUF_RWLOCK_WR((uint32_t)getpid());
388 817           for (int spin = 0; ; spin++) {
389 817           uint32_t expected = 0;
390 817 100         if (__atomic_compare_exchange_n(lock, &expected, mypid,
391             1, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
392 555           return;
393 262 100         if (__builtin_expect(spin < BUF_RWLOCK_SPIN_LIMIT, 1)) {
394 261           buf_spin_pause();
395 262           continue;
396             }
397 1           buf_park_writer(h);
398 1           uint32_t cur = __atomic_load_n(lock, __ATOMIC_RELAXED);
399 1 50         if (cur != 0) {
400 1           long rc = syscall(SYS_futex, lock, FUTEX_WAIT, cur,
401             &buf_lock_timeout, NULL, 0);
402 1 50         if (rc == -1 && errno == ETIMEDOUT) {
    50          
403 1           buf_unpark_writer(h);
404 1           buf_recover_after_timeout(h);
405 1           spin = 0;
406 1           continue;
407             }
408             }
409 0           buf_unpark_writer(h);
410 0           spin = 0;
411             }
412             }
413              
414 555           static inline void buf_rwlock_wrunlock(BufHandle *h) {
415 555           __atomic_store_n(&h->hdr->rwlock, 0, __ATOMIC_RELEASE);
416 555 100         if (__atomic_load_n(&h->hdr->rwlock_waiters, __ATOMIC_RELAXED) > 0)
417 1           syscall(SYS_futex, &h->hdr->rwlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
418 555           }
419              
420             /* ---- Seqlock ---- */
421              
422 34           static inline uint32_t buf_seqlock_read_begin(BufHeader *hdr) {
423 34           int spin = 0;
424 0           for (;;) {
425 34           uint32_t s = __atomic_load_n(&hdr->seq, __ATOMIC_ACQUIRE);
426 34 50         if (__builtin_expect((s & 1) == 0, 1)) return s;
427 0 0         if (__builtin_expect(spin < 100000, 1)) {
428 0           buf_spin_pause();
429 0           spin++;
430 0           continue;
431             }
432 0           uint32_t val = __atomic_load_n(&hdr->rwlock, __ATOMIC_RELAXED);
433 0 0         if (val >= BUF_RWLOCK_WRITER_BIT) {
434 0           uint32_t pid = val & BUF_RWLOCK_PID_MASK;
435 0 0         if (!buf_pid_alive(pid)) {
436 0           buf_recover_stale_lock(hdr, val);
437 0           spin = 0;
438 0           continue;
439             }
440             }
441 0           struct timespec ts = {0, 1000000};
442 0           nanosleep(&ts, NULL);
443 0           spin = 0;
444             }
445             }
446              
447 34           static inline int buf_seqlock_read_retry(uint32_t *seq, uint32_t start) {
448             /* Acquire FENCE (LoadLoad): the section's data loads must retire before we
449             * re-read seq; a plain acquire load is the wrong direction (ARM64 torn read). */
450 34           __atomic_thread_fence(__ATOMIC_ACQUIRE);
451 34           return __atomic_load_n(seq, __ATOMIC_RELAXED) != start;
452             }
453              
454 555           static inline void buf_seqlock_write_begin(uint32_t *seq) {
455 555           __atomic_add_fetch(seq, 1, __ATOMIC_RELEASE); /* seq becomes odd */
456             /* StoreStore: publish the odd seq before the section's data writes, else an
457             * ARM64 reader could see an even seq with half-written data (Linux smp_wmb). */
458 555           __atomic_thread_fence(__ATOMIC_RELEASE);
459 555           }
460              
461 555           static inline void buf_seqlock_write_end(uint32_t *seq) {
462 555           __atomic_add_fetch(seq, 1, __ATOMIC_RELEASE);
463 555           }
464              
465             /* ---- mmap create/open ---- */
466              
467             /* Race-safe create-or-attach with restrictive perms + symlink refusal.
468             * The backing file is created 0600 by default (see file_mode); a local peer
469             * cannot pre-create it as a symlink (O_NOFOLLOW) nor open a wider-permissioned
470             * copy. Sets *created=1 iff this call won the O_EXCL race and made the file. */
471 46           static int buf_secure_open(const char *path, mode_t file_mode, int *created, char *errbuf) {
472 46 50         for (int attempt = 0; attempt < 100; attempt++) {
473 46           int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, file_mode);
474 46 100         if (fd >= 0) { (void)fchmod(fd, file_mode); *created = 1; return fd; } /* exact mode: umask narrowed the create */
475 7 50         if (errno != EEXIST) {
476 0           snprintf(errbuf, BUF_ERR_BUFLEN, "create(%s): %s", path, strerror(errno));
477 0           return -1;
478             }
479 7           fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
480 7 50         if (fd >= 0) { *created = 0; return fd; }
481 0 0         if (errno == ENOENT) continue; /* creator unlinked between our two opens; retry */
482 0           snprintf(errbuf, BUF_ERR_BUFLEN, "open(%s): %s", path, strerror(errno));
483 0           return -1;
484             }
485 0           snprintf(errbuf, BUF_ERR_BUFLEN, "open(%s): create/attach kept racing", path);
486 0           return -1;
487             }
488              
489 46           static BufHandle *buf_create_map(const char *path, uint64_t capacity,
490             uint32_t elem_size, uint32_t variant_id,
491             mode_t file_mode, char *errbuf) {
492 46           errbuf[0] = '\0';
493 46           int created = 0;
494 46           int fd = buf_secure_open(path, file_mode, &created, errbuf);
495 46 50         if (fd < 0) {
496 0           return NULL;
497             }
498              
499             /* Lock file for init race prevention */
500 46 50         if (flock(fd, LOCK_EX) < 0) {
501 0           snprintf(errbuf, BUF_ERR_BUFLEN, "flock(%s): %s", path, strerror(errno));
502 0           close(fd);
503 0           return NULL;
504             }
505              
506 46           uint64_t reader_slots_off = sizeof(BufHeader); /* 128 */
507 46           uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
508 46           uint64_t data_off = reader_slots_off + reader_slots_size; /* cache-aligned */
509 46 50         if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) {
    50          
510 0           snprintf(errbuf, BUF_ERR_BUFLEN, "buffer size overflow");
511 0           flock(fd, LOCK_UN);
512 0           close(fd);
513 0           return NULL;
514             }
515 46           uint64_t total_size = data_off + capacity * elem_size;
516              
517             struct stat st;
518 46 50         if (fstat(fd, &st) < 0) {
519 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fstat(%s): %s", path, strerror(errno));
520 0           flock(fd, LOCK_UN);
521 0           close(fd);
522 0           return NULL;
523             }
524              
525 46 100         if (!created && st.st_size > 0 && (uint64_t)st.st_size < sizeof(BufHeader)) {
    50          
    50          
526 0           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: file too small (%lld)", path, (long long)st.st_size);
527 0           flock(fd, LOCK_UN); close(fd); return NULL;
528             }
529 46 100         if (created || st.st_size == 0) {
    50          
530 39 50         if (ftruncate(fd, (off_t)total_size) < 0) {
531 0           snprintf(errbuf, BUF_ERR_BUFLEN, "ftruncate(%s): %s", path, strerror(errno));
532 0           flock(fd, LOCK_UN);
533 0           close(fd);
534 0           return NULL;
535             }
536             }
537              
538             /* Re-stat after possible truncate */
539 46 50         if (fstat(fd, &st) < 0) {
540 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fstat(%s): %s", path, strerror(errno));
541 0           flock(fd, LOCK_UN);
542 0           close(fd);
543 0           return NULL;
544             }
545              
546 46           void *base = mmap(NULL, (size_t)st.st_size, PROT_READ | PROT_WRITE,
547             MAP_SHARED, fd, 0);
548 46 50         if (base == MAP_FAILED) {
549 0           snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(%s): %s", path, strerror(errno));
550 0           flock(fd, LOCK_UN);
551 0           close(fd);
552 0           return NULL;
553             }
554              
555 46           BufHeader *hdr = (BufHeader *)base;
556              
557 46 100         if (created || hdr->magic == 0) {
    50          
558             /* A pre-existing but uninitialized file (magic==0, not created by us) may
559             * be smaller than the region we are about to zero; a hostile peer could
560             * pre-create an undersized file to drive the init memset out of bounds. */
561 39 50         if (!created && (uint64_t)st.st_size < total_size) {
    0          
562 0           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: file too small to initialize", path);
563 0           goto fail;
564             }
565             /* Initialize header */
566 39           memset(hdr, 0, sizeof(BufHeader));
567 39           hdr->magic = BUF_MAGIC;
568 39           hdr->version = BUF_VERSION;
569 39           hdr->variant_id = variant_id;
570 39           hdr->elem_size = elem_size;
571 39           hdr->capacity = capacity;
572 39           hdr->total_size = (uint64_t)st.st_size;
573 39           hdr->data_off = data_off;
574 39           hdr->reader_slots_off = reader_slots_off;
575             /* Zero reader_slots + data area */
576 39           memset((char *)base + reader_slots_off, 0,
577 39           (size_t)(reader_slots_size + capacity * elem_size));
578 39           __atomic_thread_fence(__ATOMIC_RELEASE);
579             } else {
580             /* Validate existing header */
581 7 100         if (hdr->magic != BUF_MAGIC) {
582 1           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: bad magic (0x%08x)", path, hdr->magic);
583 1           goto fail;
584             }
585 6 50         if (hdr->version != BUF_VERSION) {
586 0           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: version mismatch (%u != %u)",
587             path, hdr->version, BUF_VERSION);
588 0           goto fail;
589             }
590 6 100         if (hdr->variant_id != variant_id) {
591 1           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: variant mismatch (%u != %u)",
592             path, hdr->variant_id, variant_id);
593 1           goto fail;
594             }
595 5 50         if (hdr->elem_size != elem_size) {
596 0           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: elem_size mismatch (%u != %u)",
597             path, hdr->elem_size, elem_size);
598 0           goto fail;
599             }
600 5 50         if (hdr->elem_size == 0 ||
601 5 50         hdr->reader_slots_off < sizeof(BufHeader) ||
602 5 50         hdr->reader_slots_off > (uint64_t)st.st_size ||
603 5 50         hdr->reader_slots_off + reader_slots_size > (uint64_t)st.st_size ||
604 5 50         hdr->data_off < hdr->reader_slots_off + reader_slots_size ||
605 5 50         hdr->data_off > (uint64_t)st.st_size ||
606 5 50         hdr->capacity > ((uint64_t)st.st_size - hdr->data_off) / hdr->elem_size) {
607 0           snprintf(errbuf, BUF_ERR_BUFLEN, "%s: corrupt header (data doesn't fit in file)", path);
608 0           goto fail;
609             }
610             }
611              
612 44           flock(fd, LOCK_UN);
613 44           close(fd);
614              
615 44           BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
616 44 50         if (!h) {
617 0           snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
618 0           munmap(base, (size_t)st.st_size);
619 0           return NULL;
620             }
621 44           h->hdr = hdr;
622 44           h->data = (char *)base + hdr->data_off;
623 44           h->reader_slots = (BufReaderSlot *)((char *)base + hdr->reader_slots_off);
624 44           h->my_slot_idx = UINT32_MAX;
625 44           h->mmap_size = (size_t)st.st_size;
626 44           h->path = strdup(path);
627 44           h->fd = -1;
628 44           h->efd = -1;
629 44           return h;
630              
631 2           fail:
632 2           munmap(base, (size_t)st.st_size);
633 2           flock(fd, LOCK_UN);
634 2           close(fd);
635 2           return NULL;
636             }
637              
638             /* ---- Anonymous mmap (no file, fork-only sharing) ---- */
639              
640 40           static BufHandle *buf_create_anon(uint64_t capacity, uint32_t elem_size,
641             uint32_t variant_id, char *errbuf) {
642 40           errbuf[0] = '\0';
643 40           uint64_t reader_slots_off = sizeof(BufHeader);
644 40           uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
645 40           uint64_t data_off = reader_slots_off + reader_slots_size;
646 40 50         if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) {
    50          
647 0           snprintf(errbuf, BUF_ERR_BUFLEN, "buffer size overflow");
648 0           return NULL;
649             }
650 40           uint64_t total_size = data_off + capacity * elem_size;
651              
652 40           void *base = mmap(NULL, (size_t)total_size, PROT_READ | PROT_WRITE,
653             MAP_SHARED | MAP_ANONYMOUS, -1, 0);
654 40 50         if (base == MAP_FAILED) {
655 0           snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(anon): %s", strerror(errno));
656 0           return NULL;
657             }
658              
659 40           BufHeader *hdr = (BufHeader *)base;
660 40           memset(hdr, 0, sizeof(BufHeader));
661 40           hdr->magic = BUF_MAGIC;
662 40           hdr->version = BUF_VERSION;
663 40           hdr->variant_id = variant_id;
664 40           hdr->elem_size = elem_size;
665 40           hdr->capacity = capacity;
666 40           hdr->total_size = total_size;
667 40           hdr->data_off = data_off;
668 40           hdr->reader_slots_off = reader_slots_off;
669             /* MAP_ANONYMOUS already zero-fills reader_slots and data. */
670              
671 40           BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
672 40 50         if (!h) {
673 0           snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
674 0           munmap(base, (size_t)total_size);
675 0           return NULL;
676             }
677 40           h->hdr = hdr;
678 40           h->data = (char *)base + data_off;
679 40           h->reader_slots = (BufReaderSlot *)((char *)base + reader_slots_off);
680 40           h->my_slot_idx = UINT32_MAX;
681 40           h->mmap_size = (size_t)total_size;
682 40           h->path = NULL;
683 40           h->fd = -1;
684 40           h->efd = -1;
685 40           return h;
686             }
687              
688             /* ---- memfd (named anonymous, shareable via fd passing) ---- */
689              
690 9           static BufHandle *buf_create_memfd(const char *name, uint64_t capacity,
691             uint32_t elem_size, uint32_t variant_id,
692             char *errbuf) {
693 9           errbuf[0] = '\0';
694 9           uint64_t reader_slots_off = sizeof(BufHeader);
695 9           uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
696 9           uint64_t data_off = reader_slots_off + reader_slots_size;
697 9 50         if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) {
    50          
698 0           snprintf(errbuf, BUF_ERR_BUFLEN, "buffer size overflow");
699 0           return NULL;
700             }
701 9           uint64_t total_size = data_off + capacity * elem_size;
702              
703 9           int fd = (int)syscall(SYS_memfd_create, name, MFD_CLOEXEC | MFD_ALLOW_SEALING);
704 9 50         if (fd < 0) {
705 0           snprintf(errbuf, BUF_ERR_BUFLEN, "memfd_create: %s", strerror(errno));
706 0           return NULL;
707             }
708 9 50         if (ftruncate(fd, (off_t)total_size) < 0) {
709 0           snprintf(errbuf, BUF_ERR_BUFLEN, "ftruncate(memfd): %s", strerror(errno));
710 0           close(fd);
711 0           return NULL;
712             }
713 9           (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
714              
715 9           void *base = mmap(NULL, (size_t)total_size, PROT_READ | PROT_WRITE,
716             MAP_SHARED, fd, 0);
717 9 50         if (base == MAP_FAILED) {
718 0           snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(memfd): %s", strerror(errno));
719 0           close(fd);
720 0           return NULL;
721             }
722              
723 9           BufHeader *hdr = (BufHeader *)base;
724 9           memset(hdr, 0, sizeof(BufHeader));
725 9           hdr->magic = BUF_MAGIC;
726 9           hdr->version = BUF_VERSION;
727 9           hdr->variant_id = variant_id;
728 9           hdr->elem_size = elem_size;
729 9           hdr->capacity = capacity;
730 9           hdr->total_size = total_size;
731 9           hdr->data_off = data_off;
732 9           hdr->reader_slots_off = reader_slots_off;
733              
734 9           BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
735 9 50         if (!h) {
736 0           snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
737 0           munmap(base, (size_t)total_size);
738 0           close(fd);
739 0           return NULL;
740             }
741 9           h->hdr = hdr;
742 9           h->data = (char *)base + data_off;
743 9           h->reader_slots = (BufReaderSlot *)((char *)base + reader_slots_off);
744 9           h->my_slot_idx = UINT32_MAX;
745 9           h->mmap_size = (size_t)total_size;
746 9           h->path = NULL;
747 9           h->fd = fd;
748 9           h->efd = -1;
749 9           return h;
750             }
751              
752             /* ---- Open from fd (received via SCM_RIGHTS or dup) ---- */
753              
754 5           static BufHandle *buf_open_fd(int fd, uint32_t elem_size, uint32_t variant_id,
755             char *errbuf) {
756 5           errbuf[0] = '\0';
757             struct stat st;
758 5 50         if (fstat(fd, &st) < 0) {
759 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fstat(fd=%d): %s", fd, strerror(errno));
760 0           return NULL;
761             }
762 5 50         if ((uint64_t)st.st_size < sizeof(BufHeader)) {
763 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: file too small for header", fd);
764 0           return NULL;
765             }
766              
767 5           void *base = mmap(NULL, (size_t)st.st_size, PROT_READ | PROT_WRITE,
768             MAP_SHARED, fd, 0);
769 5 50         if (base == MAP_FAILED) {
770 0           snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(fd=%d): %s", fd, strerror(errno));
771 0           return NULL;
772             }
773              
774 5           BufHeader *hdr = (BufHeader *)base;
775 5 50         if (hdr->magic != BUF_MAGIC) {
776 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: bad magic (0x%08x)", fd, hdr->magic);
777 0           goto fail;
778             }
779 5 50         if (hdr->version != BUF_VERSION) {
780 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: version mismatch (%u != %u)",
781             fd, hdr->version, BUF_VERSION);
782 0           goto fail;
783             }
784 5 100         if (hdr->variant_id != variant_id) {
785 1           snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: variant mismatch (%u != %u)",
786             fd, hdr->variant_id, variant_id);
787 1           goto fail;
788             }
789 4 50         if (hdr->elem_size != elem_size) {
790 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: elem_size mismatch (%u != %u)",
791             fd, hdr->elem_size, elem_size);
792 0           goto fail;
793             }
794 4           uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
795 4 50         if (hdr->elem_size == 0 ||
796 4 50         hdr->reader_slots_off < sizeof(BufHeader) ||
797 4 50         hdr->reader_slots_off > (uint64_t)st.st_size ||
798 4 50         hdr->reader_slots_off + reader_slots_size > (uint64_t)st.st_size ||
799 4 50         hdr->data_off < hdr->reader_slots_off + reader_slots_size ||
800 4 50         hdr->data_off > (uint64_t)st.st_size ||
801 4 50         hdr->total_size != (uint64_t)st.st_size ||
802 4 50         hdr->capacity > ((uint64_t)st.st_size - hdr->data_off) / hdr->elem_size) {
803 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: corrupt header", fd);
804 0           goto fail;
805             }
806              
807             {
808 4           int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
809 4 50         if (myfd < 0) {
810 0           snprintf(errbuf, BUF_ERR_BUFLEN, "fcntl(F_DUPFD_CLOEXEC, fd=%d): %s",
811 0           fd, strerror(errno));
812 0           munmap(base, (size_t)st.st_size);
813 0           return NULL;
814             }
815 4           BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
816 4 50         if (!h) {
817 0           snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
818 0           close(myfd);
819 0           munmap(base, (size_t)st.st_size);
820 0           return NULL;
821             }
822 4           h->hdr = hdr;
823 4           h->data = (char *)base + hdr->data_off;
824 4           h->reader_slots = (BufReaderSlot *)((char *)base + hdr->reader_slots_off);
825 4           h->my_slot_idx = UINT32_MAX;
826 4           h->mmap_size = (size_t)st.st_size;
827 4           h->path = NULL;
828 4           h->fd = myfd;
829 4           h->efd = -1;
830 4           return h;
831             }
832              
833 1           fail:
834 1           munmap(base, (size_t)st.st_size);
835 1           return NULL;
836             }
837              
838             /* ---- msync ---- */
839              
840 3           static inline int buf_msync(BufHandle *h) {
841 3 50         if (!h || !h->hdr) return 0;
    50          
842 3           return msync(h->hdr, h->mmap_size, MS_SYNC);
843             }
844              
845             /* ---- Eventfd integration (opt-in notifications) ---- */
846              
847 8           static int buf_create_eventfd(BufHandle *h) {
848 8 100         if (h->efd >= 0) return h->efd;
849 7           int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
850 7 50         if (efd < 0) return -1;
851 7           h->efd = efd;
852 7           h->efd_owned = 1;
853 7           return efd;
854             }
855              
856 2           static void buf_attach_eventfd(BufHandle *h, int efd) {
857 2 50         if (h->efd >= 0 && h->efd_owned) close(h->efd);
    0          
858 2           h->efd = efd;
859 2           h->efd_owned = 0;
860 2           }
861              
862 7           static int buf_notify(BufHandle *h) {
863 7 100         if (h->efd < 0) return 0;
864 6           uint64_t val = 1;
865 6           return write(h->efd, &val, sizeof(val)) == sizeof(val);
866             }
867              
868 9           static int64_t buf_wait_notify(BufHandle *h) {
869 9 100         if (h->efd < 0) return -1;
870 8           uint64_t val = 0;
871 8 100         if (read(h->efd, &val, sizeof(val)) != sizeof(val)) return -1;
872 6           return (int64_t)val;
873             }
874              
875 97           static void buf_close_map(BufHandle *h) {
876 97 50         if (!h) return;
877             /* Release reader slot — only if we still own it AND no fork has happened
878             * since we claimed it. A forked child that inherits the handle but never
879             * acquired the lock itself must NOT clear the parent's slot. */
880 97 50         if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid &&
    100          
    50          
881 28 100         h->cached_fork_gen == __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED) &&
882 27 50         __atomic_load_n(&h->reader_slots[h->my_slot_idx].subcount, __ATOMIC_ACQUIRE) == 0) {
883             /* subcount==0: a still-held lock's slot must survive for recovery */
884 27           uint32_t expected = h->cached_pid;
885             /* CAS pid → 0; do NOT clear subcount/wp/writp — between the CAS and
886             * a follow-up store, a new process could claim the slot, and our
887             * store would clobber its state. buf_claim_reader_slot zeros all
888             * mirror fields on every claim, so leaving stale values is safe. */
889 27           __atomic_compare_exchange_n(&h->reader_slots[h->my_slot_idx].pid,
890             &expected, 0, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
891             }
892 97 100         if (h->efd >= 0 && h->efd_owned) close(h->efd);
    100          
893 97 50         if (h->hdr) munmap(h->hdr, h->mmap_size);
894 97 100         if (h->fd >= 0) close(h->fd);
895 97 100         if (h->path) free(h->path);
896 97           free(h);
897             }
898              
899             #endif /* BUF_DEFS_H */
900              
901              
902             /* ================================================================
903             * Part 2: Per-variant functions (instantiated per include)
904             * ================================================================ */
905              
906             #ifndef BUF_PREFIX
907             #error "BUF_PREFIX must be defined before including buf_generic.h"
908             #endif
909              
910             #define BUF_PASTE2(a, b) a##_##b
911             #define BUF_PASTE(a, b) BUF_PASTE2(a, b)
912             #define BUF_FN(name) BUF_PASTE(BUF_PREFIX, name)
913              
914             /* ---- Create ---- */
915              
916             #ifdef BUF_IS_FIXEDSTR
917 4           static BufHandle *BUF_FN(create)(const char *path, uint64_t capacity,
918             uint32_t str_len, mode_t file_mode, char *errbuf) {
919 4 50         if (str_len == 0) {
920 0           snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0");
921 0           return NULL;
922             }
923 4           return buf_create_map(path, capacity, str_len, BUF_VARIANT_ID, file_mode, errbuf);
924             }
925             #else
926 42           static BufHandle *BUF_FN(create)(const char *path, uint64_t capacity, mode_t file_mode, char *errbuf) {
  5            
  1            
  1            
  27            
  3            
  1            
  1            
  1            
  1            
  1            
927 42           return buf_create_map(path, capacity, BUF_ELEM_SIZE, BUF_VARIANT_ID, file_mode, errbuf);
  5            
  1            
  1            
  27            
  3            
  1            
  1            
  1            
  1            
  1            
928             }
929             #endif
930              
931             /* ---- Create anonymous ---- */
932              
933             #ifdef BUF_IS_FIXEDSTR
934 8           static BufHandle *BUF_FN(create_anon)(uint64_t capacity, uint32_t str_len, char *errbuf) {
935 8 50         if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; }
936 8           return buf_create_anon(capacity, str_len, BUF_VARIANT_ID, errbuf);
937             }
938 2           static BufHandle *BUF_FN(create_memfd)(const char *name, uint64_t capacity, uint32_t str_len, char *errbuf) {
939 2 50         if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; }
940 2           return buf_create_memfd(name, capacity, str_len, BUF_VARIANT_ID, errbuf);
941             }
942 1           static BufHandle *BUF_FN(open_fd)(int fd, uint32_t str_len, char *errbuf) {
943 1 50         if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; }
944 1           return buf_open_fd(fd, str_len, BUF_VARIANT_ID, errbuf);
945             }
946             #else
947 32           static BufHandle *BUF_FN(create_anon)(uint64_t capacity, char *errbuf) {
  5            
  1            
  0            
  23            
  1            
  0            
  0            
  0            
  1            
  1            
948 32           return buf_create_anon(capacity, BUF_ELEM_SIZE, BUF_VARIANT_ID, errbuf);
  5            
  1            
  0            
  23            
  1            
  0            
  0            
  0            
  1            
  1            
949             }
950 7           static BufHandle *BUF_FN(create_memfd)(const char *name, uint64_t capacity, char *errbuf) {
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
951 7           return buf_create_memfd(name, capacity, BUF_ELEM_SIZE, BUF_VARIANT_ID, errbuf);
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
952             }
953 4           static BufHandle *BUF_FN(open_fd)(int fd, char *errbuf) {
  0            
  0            
  0            
  3            
  1            
  0            
  0            
  0            
  0            
  0            
954 4           return buf_open_fd(fd, BUF_ELEM_SIZE, BUF_VARIANT_ID, errbuf);
  0            
  0            
  0            
  3            
  1            
  0            
  0            
  0            
  0            
  0            
955             }
956             #endif
957              
958             /* ---- Raw byte access (for packed binary interop) ---- */
959              
960 9           static int BUF_FN(get_raw)(BufHandle *h, uint64_t byte_off, uint64_t nbytes, void *out) {
  1            
  0            
  1            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
961 9           uint64_t data_size = h->hdr->capacity * (uint64_t)h->hdr->elem_size;
  1            
  0            
  1            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
962 9 50         if (nbytes > data_size || byte_off > data_size - nbytes) return 0;
  1 50          
  0 0          
  1 0          
  0 50          
  7 50          
  0 0          
  0 0          
  0 50          
  0 100          
  0 0          
  0 0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
963 7           char *data = (char *)h->data;
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
964 7 50         if (h->wr_locked) {
  1 0          
  0 50          
  1 0          
  0 100          
  5 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
965 1           memcpy(out, data + byte_off, (size_t)nbytes);
  0            
  0            
  0            
  0            
  1            
  0            
  0            
  0            
  0            
  0            
  0            
966             } else {
967             uint32_t seq_start;
968             do {
969 6           seq_start = buf_seqlock_read_begin(h->hdr);
  1            
  0            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
970 6           memcpy(out, data + byte_off, (size_t)nbytes);
  1            
  0            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
971 6 50         } while (buf_seqlock_read_retry(&h->hdr->seq, seq_start));
  1 0          
  0 50          
  1 0          
  0 50          
  4 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
972             }
973 7           return 1;
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
974             }
975              
976 8           static int BUF_FN(set_raw)(BufHandle *h, uint64_t byte_off, uint64_t nbytes, const void *in) {
  1            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
977 8           uint64_t data_size = h->hdr->capacity * (uint64_t)h->hdr->elem_size;
  1            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
978 8 50         if (nbytes > data_size || byte_off > data_size - nbytes) return 0;
  1 50          
  0 0          
  0 0          
  0 0          
  7 0          
  0 0          
  0 0          
  0 50          
  0 100          
  0 0          
  0 0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
979 4           char *data = (char *)h->data;
  1            
  0            
  0            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
980 4           int nested = h->wr_locked;
  1            
  0            
  0            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
981 4 50         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); }
  1 0          
  0 0          
  0 0          
  0 50          
  3 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
982 4           memcpy(data + byte_off, in, (size_t)nbytes);
  1            
  0            
  0            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
983 4 50         if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); }
  1 0          
  0 0          
  0 0          
  0 50          
  3 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
984 4           return 1;
  1            
  0            
  0            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
985             }
986              
987             /* ---- Clear (zero entire buffer) ---- */
988              
989 7           static void BUF_FN(clear)(BufHandle *h) {
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
990 7           BufHeader *hdr = h->hdr;
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
991 7           int nested = h->wr_locked;
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
992 7 50         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
  1 0          
  0 50          
  1 0          
  0 100          
  5 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
993 7           memset(h->data, 0, (size_t)(hdr->capacity * hdr->elem_size));
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
994 7 50         if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
  1 0          
  0 50          
  1 0          
  0 100          
  5 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
995 7           }
  1            
  0            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
996              
997             /* ---- Single-element atomic get (lock-free for numeric types) ---- */
998              
999             #ifdef BUF_IS_FIXEDSTR
1000              
1001 22           static int BUF_FN(get)(BufHandle *h, uint64_t idx, char *out, uint32_t *out_len) {
1002 22           BufHeader *hdr = h->hdr;
1003 22           uint32_t esz = hdr->elem_size;
1004 22 50         if (idx >= hdr->capacity) return 0;
1005 22           char *data = (char *)h->data;
1006 22 100         if (h->wr_locked) {
1007 1           memcpy(out, data + idx * esz, esz);
1008             } else {
1009             uint32_t seq_start;
1010             do {
1011 21           seq_start = buf_seqlock_read_begin(hdr);
1012 21           memcpy(out, data + idx * esz, esz);
1013 21 50         } while (buf_seqlock_read_retry(&hdr->seq, seq_start));
1014             }
1015 22           uint32_t len = esz;
1016 260 100         while (len > 0 && out[len - 1] == '\0') len--;
    100          
1017 22           *out_len = len;
1018 22           return 1;
1019             }
1020              
1021 521           static int BUF_FN(set)(BufHandle *h, uint64_t idx, const char *val, uint32_t len) {
1022 521           BufHeader *hdr = h->hdr;
1023 521           uint32_t esz = hdr->elem_size;
1024 521 50         if (idx >= hdr->capacity) return 0;
1025 521           char *data = (char *)h->data;
1026 521           int nested = h->wr_locked;
1027 521 100         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
1028 521           memset(data + idx * esz, 0, esz);
1029 521           uint32_t copy_len = len < esz ? len : esz;
1030 521           memcpy(data + idx * esz, val, copy_len);
1031 521 100         if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
1032 521           return 1;
1033             }
1034              
1035             #elif defined(BUF_IS_FLOAT)
1036              
1037             /* Float/double: GCC __atomic builtins don't support FP types.
1038             * Use same-sized integer atomic load/store + memcpy for lock-free access. */
1039              
1040             #if BUF_ELEM_SIZE == 4
1041             typedef uint32_t BUF_PASTE(BUF_PREFIX, _uint_t);
1042             #elif BUF_ELEM_SIZE == 8
1043             typedef uint64_t BUF_PASTE(BUF_PREFIX, _uint_t);
1044             #else
1045             #error "BUF_IS_FLOAT requires BUF_ELEM_SIZE of 4 or 8"
1046             #endif
1047              
1048 14           static int BUF_FN(get)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE *out) {
  9            
  5            
1049 14           BufHeader *hdr = h->hdr;
  9            
  5            
1050 14 50         if (idx >= hdr->capacity) return 0;
  9 50          
  5            
1051             typedef BUF_PASTE(BUF_PREFIX, _uint_t) uint_t;
1052 14           uint_t *idata = (uint_t *)h->data;
  9            
  5            
1053 14           uint_t tmp = __atomic_load_n(&idata[idx], __ATOMIC_RELAXED);
  9            
  5            
1054 14           memcpy(out, &tmp, sizeof(BUF_ELEM_TYPE));
  9            
  5            
1055 14           return 1;
  9            
  5            
1056             }
1057              
1058 1016           static int BUF_FN(set)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE val) {
  1012            
  4            
1059 1016           BufHeader *hdr = h->hdr;
  1012            
  4            
1060 1016 50         if (idx >= hdr->capacity) return 0;
  1012 50          
  4            
1061             typedef BUF_PASTE(BUF_PREFIX, _uint_t) uint_t;
1062 1016           uint_t *idata = (uint_t *)h->data;
  1012            
  4            
1063             uint_t tmp;
1064 1016           memcpy(&tmp, &val, sizeof(BUF_ELEM_TYPE));
  1012            
  4            
1065 1016           __atomic_store_n(&idata[idx], tmp, __ATOMIC_RELAXED);
  1012            
  4            
1066 1016           return 1;
  1012            
  4            
1067             }
1068              
1069             #else /* integer types */
1070              
1071 1130           static int BUF_FN(get)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE *out) {
  2            
  1107            
  10            
  2            
  2            
  2            
  2            
  3            
1072 1130           BufHeader *hdr = h->hdr;
  2            
  1107            
  10            
  2            
  2            
  2            
  2            
  3            
1073 1130 50         if (idx >= hdr->capacity) return 0;
  2 100          
  1107 50          
  10 50          
  2 50          
  2 50          
  2 50          
  2 50          
  3            
1074 1127           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  2            
  1104            
  10            
  2            
  2            
  2            
  2            
  3            
1075 1127           *out = __atomic_load_n(&data[idx], __ATOMIC_RELAXED);
  2            
  1104            
  10            
  2            
  2            
  2            
  2            
  3            
1076 1127           return 1;
  2            
  1104            
  10            
  2            
  2            
  2            
  2            
  3            
1077             }
1078              
1079 90           static int BUF_FN(set)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE val) {
  1            
  70            
  9            
  1            
  1            
  1            
  3            
  4            
1080 90           BufHeader *hdr = h->hdr;
  1            
  70            
  9            
  1            
  1            
  1            
  3            
  4            
1081 90 50         if (idx >= hdr->capacity) return 0;
  1 100          
  70 50          
  9 50          
  1 50          
  1 50          
  1 50          
  3 50          
  4            
1082 87           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  67            
  9            
  1            
  1            
  1            
  3            
  4            
1083 87           __atomic_store_n(&data[idx], val, __ATOMIC_RELAXED);
  1            
  67            
  9            
  1            
  1            
  1            
  3            
  4            
1084 87           return 1;
  1            
  67            
  9            
  1            
  1            
  1            
  3            
  4            
1085             }
1086              
1087             #endif /* BUF_IS_FIXEDSTR */
1088              
1089             /* ---- Bulk operations (seqlock-guarded) ---- */
1090              
1091             #ifdef BUF_IS_FIXEDSTR
1092              
1093 2           static int BUF_FN(get_slice)(BufHandle *h, uint64_t from, uint64_t count,
1094             void *out) {
1095 2           BufHeader *hdr = h->hdr;
1096 2           uint32_t esz = hdr->elem_size;
1097 2 50         if (count > hdr->capacity || from > hdr->capacity - count) return 0;
    50          
1098 2           char *data = (char *)h->data;
1099 2 100         if (h->wr_locked) {
1100 1           memcpy(out, data + from * esz, count * esz);
1101             } else {
1102             uint32_t seq_start;
1103             do {
1104 1           seq_start = buf_seqlock_read_begin(hdr);
1105 1           memcpy(out, data + from * esz, count * esz);
1106 1 50         } while (buf_seqlock_read_retry(&hdr->seq, seq_start));
1107             }
1108 2           return 1;
1109             }
1110              
1111 1           static int BUF_FN(set_slice)(BufHandle *h, uint64_t from, uint64_t count,
1112             const void *in) {
1113 1           BufHeader *hdr = h->hdr;
1114 1           uint32_t esz = hdr->elem_size;
1115 1 50         if (count > hdr->capacity || from > hdr->capacity - count) return 0;
    50          
1116 1           char *data = (char *)h->data;
1117 1           int nested = h->wr_locked;
1118 1 50         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
1119 1           memcpy(data + from * esz, in, count * esz);
1120 1 50         if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
1121 1           return 1;
1122             }
1123              
1124             #else /* numeric */
1125              
1126 9           static int BUF_FN(get_slice)(BufHandle *h, uint64_t from, uint64_t count,
  1            
  1            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1127             BUF_ELEM_TYPE *out) {
1128 9           BufHeader *hdr = h->hdr;
  1            
  1            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1129 9 50         if (count > hdr->capacity || from > hdr->capacity - count) return 0;
  1 50          
  1 50          
  0 50          
  7 0          
  0 0          
  0 100          
  0 100          
  0 0          
  0 0          
  0 0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
1130 7           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
1131 7 50         if (h->wr_locked) {
  1 50          
  1 0          
  0 100          
  5 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1132 1           memcpy(out, &data[from], count * sizeof(BUF_ELEM_TYPE));
  0            
  0            
  0            
  1            
  0            
  0            
  0            
  0            
  0            
  0            
1133             } else {
1134             uint32_t seq_start;
1135             do {
1136 6           seq_start = buf_seqlock_read_begin(hdr);
  1            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1137 6           memcpy(out, &data[from], count * sizeof(BUF_ELEM_TYPE));
  1            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1138 6 50         } while (buf_seqlock_read_retry(&hdr->seq, seq_start));
  1 50          
  1 0          
  0 50          
  4 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1139             }
1140 7           return 1;
  1            
  1            
  0            
  5            
  0            
  0            
  0            
  0            
  0            
  0            
1141             }
1142              
1143 6           static int BUF_FN(set_slice)(BufHandle *h, uint64_t from, uint64_t count,
  1            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1144             const BUF_ELEM_TYPE *in) {
1145 6           BufHeader *hdr = h->hdr;
  1            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1146 6 50         if (count > hdr->capacity || from > hdr->capacity - count) return 0;
  1 50          
  1 50          
  0 50          
  4 0          
  0 0          
  0 50          
  0 100          
  0 0          
  0 0          
  0 0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
1147 5           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  1            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
1148 5           int nested = h->wr_locked;
  1            
  1            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
1149 5 50         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
  1 50          
  1 0          
  0 100          
  3 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1150 5           memcpy(&data[from], in, count * sizeof(BUF_ELEM_TYPE));
  1            
  1            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
1151 5 50         if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
  1 50          
  1 0          
  0 100          
  3 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1152 5           return 1;
  1            
  1            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
1153             }
1154              
1155             #endif /* BUF_IS_FIXEDSTR */
1156              
1157             /* ---- Fill ---- */
1158              
1159             #ifdef BUF_IS_FIXEDSTR
1160              
1161 2           static void BUF_FN(fill)(BufHandle *h, const char *val, uint32_t len) {
1162 2           BufHeader *hdr = h->hdr;
1163 2           uint32_t esz = hdr->elem_size;
1164 2           char *data = (char *)h->data;
1165 2           int nested = h->wr_locked;
1166 2 50         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
1167 2           uint32_t copy_len = len < esz ? len : esz;
1168 2           memset(data, 0, (size_t)hdr->capacity * esz);
1169 27 100         for (uint64_t i = 0; i < hdr->capacity; i++)
1170 25           memcpy(data + i * esz, val, copy_len);
1171 2 50         if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
1172 2           }
1173              
1174             #else
1175              
1176 11           static void BUF_FN(fill)(BufHandle *h, BUF_ELEM_TYPE val) {
  1            
  1            
  0            
  9            
  0            
  0            
  0            
  0            
  0            
  0            
1177 11           BufHeader *hdr = h->hdr;
  1            
  1            
  0            
  9            
  0            
  0            
  0            
  0            
  0            
  0            
1178 11           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  1            
  0            
  9            
  0            
  0            
  0            
  0            
  0            
  0            
1179 11           int nested = h->wr_locked;
  1            
  1            
  0            
  9            
  0            
  0            
  0            
  0            
  0            
  0            
1180 11 50         if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
  1 50          
  1 0          
  0 100          
  9 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1181 437 100         for (uint64_t i = 0; i < hdr->capacity; i++)
  51 100          
  11 0          
  0 100          
  375 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1182 426           data[i] = val;
  50            
  10            
  0            
  366            
  0            
  0            
  0            
  0            
  0            
  0            
1183 11 50         if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
  1 50          
  1 0          
  0 100          
  9 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1184 11           }
  1            
  1            
  0            
  9            
  0            
  0            
  0            
  0            
  0            
  0            
1185              
1186             #endif
1187              
1188             /* ---- Atomic operations (integer types only) ---- */
1189              
1190             #ifdef BUF_HAS_COUNTERS
1191              
1192 4519           static BUF_ELEM_TYPE BUF_FN(incr)(BufHandle *h, uint64_t idx) {
  1            
  4510            
  1            
  1            
  1            
  1            
  2            
  2            
1193 4519 50         if (idx >= h->hdr->capacity) return 0;
  1 50          
  4510 50          
  1 50          
  1 50          
  1 50          
  1 50          
  2 50          
  2            
1194 4519           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  4510            
  1            
  1            
  1            
  1            
  2            
  2            
1195 4519           return __atomic_add_fetch(&data[idx], 1, __ATOMIC_RELAXED);
  1            
  4510            
  1            
  1            
  1            
  1            
  2            
  2            
1196             }
1197              
1198 13           static BUF_ELEM_TYPE BUF_FN(decr)(BufHandle *h, uint64_t idx) {
  1            
  4            
  1            
  1            
  1            
  1            
  2            
  2            
1199 13 50         if (idx >= h->hdr->capacity) return 0;
  1 50          
  4 50          
  1 50          
  1 50          
  1 50          
  1 50          
  2 50          
  2            
1200 13           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  4            
  1            
  1            
  1            
  1            
  2            
  2            
1201 13           return __atomic_sub_fetch(&data[idx], 1, __ATOMIC_RELAXED);
  1            
  4            
  1            
  1            
  1            
  1            
  2            
  2            
1202             }
1203              
1204 14           static BUF_ELEM_TYPE BUF_FN(add)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE delta) {
  1            
  7            
  1            
  1            
  1            
  1            
  1            
  1            
1205 14 50         if (idx >= h->hdr->capacity) return 0;
  1 50          
  7 50          
  1 50          
  1 50          
  1 50          
  1 50          
  1 50          
  1            
1206 14           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  7            
  1            
  1            
  1            
  1            
  1            
  1            
1207 14           return __atomic_add_fetch(&data[idx], delta, __ATOMIC_RELAXED);
  1            
  7            
  1            
  1            
  1            
  1            
  1            
  1            
1208             }
1209              
1210 1028           static int BUF_FN(cas)(BufHandle *h, uint64_t idx,
  1            
  1021            
  1            
  1            
  1            
  1            
  1            
  1            
1211             BUF_ELEM_TYPE expected, BUF_ELEM_TYPE desired) {
1212 1028 50         if (idx >= h->hdr->capacity) return 0;
  1 50          
  1021 50          
  1 50          
  1 50          
  1 50          
  1 50          
  1 50          
  1            
1213 1028           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  1            
  1021            
  1            
  1            
  1            
  1            
  1            
  1            
1214 1028           return __atomic_compare_exchange_n(&data[idx], &expected, desired,
  1            
  1021            
  1            
  1            
  1            
  1            
  1            
  1            
1215             0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
1216             }
1217              
1218 6           static BUF_ELEM_TYPE BUF_FN(cmpxchg)(BufHandle *h, uint64_t idx,
  0            
  6            
  0            
  0            
  0            
  0            
  0            
  0            
1219             BUF_ELEM_TYPE expected, BUF_ELEM_TYPE desired) {
1220 6 0         if (idx >= h->hdr->capacity) return expected;
  0 50          
  6 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1221 6           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  0            
  6            
  0            
  0            
  0            
  0            
  0            
  0            
1222 6           __atomic_compare_exchange_n(&data[idx], &expected, desired,
  0            
  6            
  0            
  0            
  0            
  0            
  0            
  0            
1223             0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
1224 6           return expected; /* on failure, expected is updated to the current value */
  0            
  6            
  0            
  0            
  0            
  0            
  0            
  0            
1225             }
1226              
1227 4           static BUF_ELEM_TYPE BUF_FN(atomic_and)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE mask) {
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
1228 4 0         if (idx >= h->hdr->capacity) return 0;
  0 0          
  0 50          
  4 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1229 4           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
1230 4           return __atomic_and_fetch(&data[idx], mask, __ATOMIC_RELAXED);
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
1231             }
1232              
1233 4           static BUF_ELEM_TYPE BUF_FN(atomic_or)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE mask) {
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
1234 4 0         if (idx >= h->hdr->capacity) return 0;
  0 0          
  0 50          
  4 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1235 4           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
1236 4           return __atomic_or_fetch(&data[idx], mask, __ATOMIC_RELAXED);
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
1237             }
1238              
1239 2           static BUF_ELEM_TYPE BUF_FN(atomic_xor)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE mask) {
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
1240 2 0         if (idx >= h->hdr->capacity) return 0;
  0 0          
  0 50          
  2 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1241 2           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
1242 2           return __atomic_xor_fetch(&data[idx], mask, __ATOMIC_RELAXED);
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
1243             }
1244              
1245 1003           static int BUF_FN(add_slice)(BufHandle *h, uint64_t from, uint64_t count,
  0            
  1002            
  1            
  0            
  0            
  0            
  0            
  0            
1246             const BUF_ELEM_TYPE *deltas) {
1247 1003 0         if (count > h->hdr->capacity || from > h->hdr->capacity - count) return 0;
  0 0          
  1002 50          
  1 100          
  0 50          
  0 50          
  0 0          
  0 0          
  0 0          
    0          
    0          
    0          
    0          
    0          
    0          
    0          
1248 1002           BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
  0            
  1001            
  1            
  0            
  0            
  0            
  0            
  0            
1249 4007 0         for (uint64_t i = 0; i < count; i++)
  0 100          
  4004 100          
  3 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1250 3005           __atomic_add_fetch(&data[from + i], deltas[i], __ATOMIC_RELAXED);
  0            
  3003            
  2            
  0            
  0            
  0            
  0            
  0            
1251 1002           return 1;
  0            
  1001            
  1            
  0            
  0            
  0            
  0            
  0            
1252             }
1253              
1254             #endif /* BUF_HAS_COUNTERS */
1255              
1256             /* ---- Diagnostics ---- */
1257              
1258 11           static inline uint64_t BUF_FN(capacity)(BufHandle *h) {
  1            
  1            
  1            
  0            
  8            
  0            
  0            
  0            
  0            
  0            
  0            
1259 11           return h->hdr->capacity;
  1            
  1            
  1            
  0            
  8            
  0            
  0            
  0            
  0            
  0            
  0            
1260             }
1261              
1262 1           static inline uint64_t BUF_FN(mmap_size)(BufHandle *h) {
  0            
  0            
  0            
  0            
  1            
  0            
  0            
  0            
  0            
  0            
  0            
1263 1           return (uint64_t)h->mmap_size;
  0            
  0            
  0            
  0            
  1            
  0            
  0            
  0            
  0            
  0            
  0            
1264             }
1265              
1266 9           static inline uint32_t BUF_FN(elem_size)(BufHandle *h) {
  3            
  1            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1267 9           return h->hdr->elem_size;
  3            
  1            
  1            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1268             }
1269              
1270             /* ---- Raw pointer access (for passing to external C/XS code) ---- */
1271              
1272 2           static inline void *BUF_FN(ptr)(BufHandle *h) {
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1273 2           return h->data;
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1274             }
1275              
1276 4           static inline void *BUF_FN(ptr_at)(BufHandle *h, uint64_t idx) {
  0            
  0            
  0            
  0            
  4            
  0            
  0            
  0            
  0            
  0            
  0            
1277 4 0         if (idx >= h->hdr->capacity) return NULL;
  0 0          
  0 0          
  0 0          
  0 100          
  4 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0 0          
  0            
1278 3           return (char *)h->data + idx * h->hdr->elem_size;
  0            
  0            
  0            
  0            
  3            
  0            
  0            
  0            
  0            
  0            
  0            
1279             }
1280              
1281             /* ---- Explicit locking for batch operations ---- */
1282              
1283 9           static inline void BUF_FN(lock_wr)(BufHandle *h) {
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1284 9           buf_rwlock_wrlock(h);
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1285 9           buf_seqlock_write_begin(&h->hdr->seq);
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1286 9           h->wr_locked = 1;
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1287 9           }
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1288              
1289 9           static inline void BUF_FN(unlock_wr)(BufHandle *h) {
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1290 9           h->wr_locked = 0;
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1291 9           buf_seqlock_write_end(&h->hdr->seq);
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1292 9           buf_rwlock_wrunlock(h);
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1293 9           }
  2            
  0            
  0            
  0            
  7            
  0            
  0            
  0            
  0            
  0            
  0            
1294              
1295 2           static inline void BUF_FN(lock_rd)(BufHandle *h) {
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1296 2           buf_rwlock_rdlock(h);
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1297 2           }
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1298              
1299 2           static inline void BUF_FN(unlock_rd)(BufHandle *h) {
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1300 2           buf_rwlock_rdunlock(h);
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1301 2           }
  0            
  0            
  0            
  0            
  2            
  0            
  0            
  0            
  0            
  0            
  0            
1302              
1303             /* ---- Cleanup ---- */
1304              
1305             #undef BUF_PASTE2
1306             #undef BUF_PASTE
1307             #undef BUF_FN
1308             #undef BUF_PREFIX
1309             #undef BUF_ELEM_TYPE
1310             #undef BUF_ELEM_SIZE
1311             #undef BUF_VARIANT_ID
1312             #ifdef BUF_HAS_COUNTERS
1313             #undef BUF_HAS_COUNTERS
1314             #endif
1315             #ifdef BUF_IS_FLOAT
1316             #undef BUF_IS_FLOAT
1317             #endif
1318             #ifdef BUF_IS_FIXEDSTR
1319             #undef BUF_IS_FIXEDSTR
1320             #endif