File Coverage

ring.h
Criterion Covered Total %
statement 208 234 88.8
branch 99 216 45.8
condition n/a
subroutine n/a
pod n/a
total 307 450 68.2


line stmt bran cond sub pod time code
1             /*
2             * ring.h -- Shared-memory fixed-size ring buffer for Linux
3             *
4             * Lock-free circular buffer: writes overwrite oldest when full.
5             * Readers access by relative position (0=latest) or absolute sequence.
6             * No consumer tracking — data persists until overwritten.
7             *
8             * v2 layout adds per-slot publication sequence (seqlock-per-slot), so
9             * readers never observe a partially-written or cross-epoch torn slot:
10             * read_seq / read_latest return 0 if the slot is mid-write or has been
11             * overwritten to a different epoch. Safe under MPMC writers.
12             *
13             * Unlike Queue (consumed on read) or PubSub (subscription tracking),
14             * RingBuffer is a simple overwriting circular window.
15             */
16              
17             #ifndef RING_H
18             #define RING_H
19              
20             #include
21             #include
22             #include
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              
36             #define RING_MAGIC 0x524E4732U /* "RNG2" — v2 layout: per-slot publication seq */
37             #define RING_VERSION 2
38             #define RING_ERR_BUFLEN 256
39              
40             #define RING_VAR_INT 0
41             #define RING_VAR_F64 1
42              
43             /* Bounded wait for an abandoned WRITING mark (~2s, matches sister-module
44             * SHM_LOCK_TIMEOUT_SEC). Without per-slot PID tracking we can't detect a
45             * dead writer directly; instead, a writer that lands on a slot still odd
46             * after this many monotonic-coarse ticks (seconds) assumes the prior
47             * writer is dead/abandoned and CAS-takes the slot, overwriting any
48             * partial data. Readers detect the epoch change via the seqlock retry. */
49             #define RING_WRITER_RECOVERY_SEC 2
50              
51             /* ================================================================
52             * Header (128 bytes)
53             * ================================================================ */
54              
55             typedef struct {
56             uint32_t magic;
57             uint32_t version;
58             uint32_t elem_size;
59             uint32_t variant_id;
60             uint64_t capacity;
61             uint64_t total_size;
62             uint64_t data_off; /* 32: offset to data array */
63             uint64_t seq_off; /* 40: offset to per-slot publication seq array */
64             uint8_t _pad0[16]; /* 48-63 */
65              
66             uint64_t head; /* 64: monotonic write cursor (next write position) */
67             uint64_t count; /* 72: total writes (for overwrite detection) */
68             uint32_t waiters; /* 80: blocked on new data */
69             uint32_t wake_seq; /* 84: FUTEX_WAIT target (avoids 64-bit count wraparound) */
70             uint64_t stat_writes; /* 88 */
71             uint64_t stat_overwrites; /* 96 */
72             uint8_t _pad2[24]; /* 104-127 */
73             } RingHeader;
74              
75             #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
76             _Static_assert(sizeof(RingHeader) == 128, "RingHeader must be 128 bytes");
77             #endif
78              
79             typedef struct {
80             RingHeader *hdr;
81             uint8_t *data;
82             uint64_t *seq; /* per-slot publication sequence (cap entries) */
83             size_t mmap_size;
84             uint32_t elem_size;
85             char *path;
86             int notify_fd;
87             int backing_fd;
88             } RingHandle;
89              
90             /* ================================================================
91             * Slot access
92             * ================================================================ */
93              
94 165           static inline uint8_t *ring_slot(RingHandle *h, uint64_t seq) {
95 165           return h->data + (seq % h->hdr->capacity) * h->elem_size;
96             }
97              
98             /* ================================================================
99             * Write — overwrites oldest when full, always succeeds
100             *
101             * Per-slot seq encoding (uint64_t, initial 0):
102             * bit 0 = 1 (odd): writer in progress for pos = (seq >> 1) - 1
103             * bit 0 = 0 (even): data for pos = (seq >> 1) - 1 is published and stable
104             * Writers serialize on the slot via CAS (two writers at pos N and pos N+cap
105             * racing on the same slot index). Readers use a seqlock-style double-load
106             * to detect mid-write tearing.
107             * ================================================================ */
108              
109 108           static inline uint64_t ring_write(RingHandle *h, const void *val, uint32_t vlen) {
110 108           RingHeader *hdr = h->hdr;
111             /* Claim a unique position via fetch_add — ring overwrites, no capacity check. */
112 108           uint64_t pos = __atomic_fetch_add(&hdr->head, 1, __ATOMIC_ACQ_REL);
113 108           uint64_t slot_idx = pos % hdr->capacity;
114 108           uint64_t my_writing = ((pos + 1) << 1) | 1; /* odd: writing for pos */
115 108           uint64_t my_done = (pos + 1) << 1; /* even: pos is committed */
116              
117             /* CAS per-slot seq from a committed (even) mark to our writing-mark.
118             * If another writer is in progress (odd), spin until they commit —
119             * otherwise we'd race data writes to the same slot. If a newer writer
120             * has already committed (seq >> 1 > pos+1), skip: their data wins.
121             *
122             * Bounded WRITING-wait for abandoned slots: a writer that CAS'd seq
123             * even→odd but died before publishing would otherwise strand this
124             * slot forever (every capacity-th write thereafter would spin). We
125             * track wall-clock seconds via CLOCK_MONOTONIC_COARSE; if the slot
126             * stays odd past RING_WRITER_RECOVERY_SEC the prior writer is treated
127             * as abandoned and we CAS over its odd mark, overwriting any partial
128             * data. Readers detect the epoch change via seqlock retry. */
129 108           uint64_t cur = __atomic_load_n(&h->seq[slot_idx], __ATOMIC_ACQUIRE);
130 108           int wrote = 0;
131 108           time_t recovery_deadline = 0; /* 0 = not yet armed (lazy syscall) */
132 0           for (;;) {
133 108 50         if (cur & 1) {
134             /* In-progress writer's pos = (cur >> 1) - 1. If that pos is
135             * past ours, their data supersedes ours — skip entirely. */
136 0 0         if ((cur >> 1) > pos + 1) break;
137             /* Another writer owns the slot. Wait briefly; if it stays
138             * odd past the deadline, take over (assume abandoned). */
139 0 0         if (recovery_deadline == 0) {
140             struct timespec ts;
141 0           clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
142 0           recovery_deadline = ts.tv_sec + RING_WRITER_RECOVERY_SEC;
143             } else {
144             struct timespec ts;
145 0           clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
146 0 0         if (ts.tv_sec >= recovery_deadline) {
147             /* CAS over the odd mark. If it succeeds, we own the
148             * slot and proceed to write. If it fails, someone
149             * else (the original writer or another recoverer)
150             * raced us — reload and continue normally. */
151 0 0         if (__atomic_compare_exchange_n(&h->seq[slot_idx], &cur, my_writing,
152             0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
153 0           wrote = 1; break;
154             }
155             /* CAS failed: cur is now refreshed by the CAS. Reset
156             * the deadline so we re-arm against the new state. */
157 0           recovery_deadline = 0;
158 0           continue;
159             }
160             }
161 0           cur = __atomic_load_n(&h->seq[slot_idx], __ATOMIC_ACQUIRE);
162 0           continue;
163             }
164 108           recovery_deadline = 0; /* slot became even; abandon any recovery clock */
165 108           uint64_t cur_committed = cur >> 1;
166 108 50         if (cur_committed > pos + 1) break; /* newer writer already here */
167 108 50         if (__atomic_compare_exchange_n(&h->seq[slot_idx], &cur, my_writing,
168             0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
169 108           wrote = 1; break;
170             }
171             }
172 108 50         if (wrote) {
173 108           uint32_t sz = h->elem_size;
174 108           uint32_t cp = vlen < sz ? vlen : sz;
175 108           memcpy(ring_slot(h, pos), val, cp);
176 108 50         if (cp < sz) memset(ring_slot(h, pos) + cp, 0, sz - cp);
177 108           __atomic_store_n(&h->seq[slot_idx], my_done, __ATOMIC_RELEASE);
178             }
179              
180 108           uint64_t cnt = __atomic_add_fetch(&hdr->count, 1, __ATOMIC_RELEASE);
181 108 100         if (cnt > hdr->capacity)
182 56           __atomic_add_fetch(&hdr->stat_overwrites, 1, __ATOMIC_RELAXED);
183 108           __atomic_add_fetch(&hdr->stat_writes, 1, __ATOMIC_RELAXED);
184 108           __atomic_add_fetch(&hdr->wake_seq, 1, __ATOMIC_RELEASE);
185              
186             /* Wake readers */
187 108 50         if (__atomic_load_n(&hdr->waiters, __ATOMIC_RELAXED) > 0)
188 0           syscall(SYS_futex, &hdr->wake_seq, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
189              
190 108           return pos;
191             }
192              
193             /* ================================================================
194             * Read — by relative position (0=latest) or absolute sequence
195             * ================================================================ */
196              
197             /* Read by absolute sequence number. Returns 1 if data for that seq was
198             * observed intact, 0 if not-yet-written / overwritten / mid-write. */
199 59           static inline int ring_read_seq(RingHandle *h, uint64_t seq, void *out) {
200 59           uint64_t head = __atomic_load_n(&h->hdr->head, __ATOMIC_ACQUIRE);
201 59 100         if (seq >= head) return 0; /* not yet written */
202 58 100         uint64_t oldest = (head > h->hdr->capacity) ? head - h->hdr->capacity : 0;
203 58 100         if (seq < oldest) return 0; /* already overwritten */
204              
205 57           uint64_t slot_idx = seq % h->hdr->capacity;
206 57           uint64_t expected = (seq + 1) << 1; /* even mark: pos=seq committed */
207              
208 57 50         for (int retry = 0; retry < 8; retry++) {
209 57           uint64_t s1 = __atomic_load_n(&h->seq[slot_idx], __ATOMIC_ACQUIRE);
210 57 50         if (s1 & 1) continue; /* writer in progress: spin and retry */
211 57 50         if (s1 != expected) return 0; /* stale epoch (overwritten) */
212 57           memcpy(out, ring_slot(h, seq), h->elem_size);
213 57           uint64_t s2 = __atomic_load_n(&h->seq[slot_idx], __ATOMIC_ACQUIRE);
214 57 50         if (s1 == s2) return 1; /* stable: no concurrent writer touched us */
215             }
216 0           return 0; /* too much contention to get a clean read */
217             }
218              
219             /* Read the nth most recent value (0=latest, 1=previous, ...).
220             * Returns 1 on success, 0 if n >= available entries or slot is unstable. */
221 56           static inline int ring_read_latest(RingHandle *h, uint32_t n, void *out) {
222 56           uint64_t head = __atomic_load_n(&h->hdr->head, __ATOMIC_ACQUIRE);
223 56 50         if (head == 0) return 0;
224 56           uint64_t avail = head < h->hdr->capacity ? head : h->hdr->capacity;
225 56 100         if (n >= avail) return 0;
226 54           return ring_read_seq(h, head - 1 - n, out);
227             }
228              
229             /* ================================================================
230             * Status
231             * ================================================================ */
232              
233 4           static inline uint64_t ring_head(RingHandle *h) {
234 4           return __atomic_load_n(&h->hdr->head, __ATOMIC_ACQUIRE);
235             }
236              
237 12           static inline uint64_t ring_size(RingHandle *h) {
238 12           uint64_t head = __atomic_load_n(&h->hdr->head, __ATOMIC_ACQUIRE);
239 12           return head < h->hdr->capacity ? head : h->hdr->capacity;
240             }
241              
242             /* ================================================================
243             * Wait — block until new data arrives
244             * ================================================================ */
245              
246 2           static inline void ring_make_deadline(double t, struct timespec *dl) {
247 2           clock_gettime(CLOCK_MONOTONIC, dl);
248 2           dl->tv_sec += (time_t)t;
249 2           dl->tv_nsec += (long)((t - (double)(time_t)t) * 1e9);
250 2 50         if (dl->tv_nsec >= 1000000000L) { dl->tv_sec++; dl->tv_nsec -= 1000000000L; }
251 2           }
252              
253 3           static inline int ring_remaining(const struct timespec *dl, struct timespec *rem) {
254             struct timespec now;
255 3           clock_gettime(CLOCK_MONOTONIC, &now);
256 3           rem->tv_sec = dl->tv_sec - now.tv_sec;
257 3           rem->tv_nsec = dl->tv_nsec - now.tv_nsec;
258 3 100         if (rem->tv_nsec < 0) { rem->tv_sec--; rem->tv_nsec += 1000000000L; }
259 3           return rem->tv_sec >= 0;
260             }
261              
262 2           static inline int ring_wait(RingHandle *h, uint64_t expected_count, double timeout) {
263 2 50         if (__atomic_load_n(&h->hdr->count, __ATOMIC_ACQUIRE) != expected_count) return 1;
264 2 50         if (timeout == 0) return 0;
265              
266             struct timespec dl, rem;
267 2           int has_dl = (timeout > 0);
268 2 50         if (has_dl) ring_make_deadline(timeout, &dl);
269              
270 0           for (;;) {
271 2           __atomic_add_fetch(&h->hdr->waiters, 1, __ATOMIC_RELEASE);
272 2           uint32_t seq = __atomic_load_n(&h->hdr->wake_seq, __ATOMIC_ACQUIRE);
273 2           uint64_t cur = __atomic_load_n(&h->hdr->count, __ATOMIC_ACQUIRE);
274 2 50         if (cur == expected_count) {
275 2           struct timespec *pts = NULL;
276 2 50         if (has_dl) {
277 2 50         if (!ring_remaining(&dl, &rem)) {
278 0           __atomic_sub_fetch(&h->hdr->waiters, 1, __ATOMIC_RELAXED);
279 0           return 0;
280             }
281 2           pts = &rem;
282             }
283 2           syscall(SYS_futex, &h->hdr->wake_seq, FUTEX_WAIT, seq, pts, NULL, 0);
284             }
285 2           __atomic_sub_fetch(&h->hdr->waiters, 1, __ATOMIC_RELAXED);
286 2 100         if (__atomic_load_n(&h->hdr->count, __ATOMIC_ACQUIRE) != expected_count) return 1;
287 1 50         if (has_dl && !ring_remaining(&dl, &rem)) return 0;
    50          
288             }
289             }
290              
291             /* ================================================================
292             * Create / Open / Close
293             * ================================================================ */
294              
295             #define RING_ERR(fmt, ...) do { if (errbuf) snprintf(errbuf, RING_ERR_BUFLEN, fmt, ##__VA_ARGS__); } while(0)
296              
297             /* Layout offsets:
298             * seq_off = sizeof(RingHeader) (128)
299             * data_off = sizeof(RingHeader) + capacity * sizeof(uint64_t)
300             * total = data_off + capacity * elem_size
301             */
302 18           static inline uint64_t ring_seq_off(void) { return sizeof(RingHeader); }
303 35           static inline uint64_t ring_data_off(uint64_t capacity) {
304 35           return sizeof(RingHeader) + capacity * sizeof(uint64_t);
305             }
306              
307 16           static inline void ring_init_header(void *base, uint64_t total,
308             uint32_t elem_size, uint32_t variant_id,
309             uint64_t capacity) {
310 16           RingHeader *hdr = (RingHeader *)base;
311 16           memset(base, 0, (size_t)total);
312 16           hdr->magic = RING_MAGIC;
313 16           hdr->version = RING_VERSION;
314 16           hdr->elem_size = elem_size;
315 16           hdr->variant_id = variant_id;
316 16           hdr->capacity = capacity;
317 16           hdr->total_size = total;
318 16           hdr->seq_off = ring_seq_off();
319 16           hdr->data_off = ring_data_off(capacity);
320 16           __atomic_thread_fence(__ATOMIC_SEQ_CST);
321 16           }
322              
323             /* Validate a mapped header (shared by ring_create reopen and ring_open_fd). */
324 2           static inline int ring_validate_header(const RingHeader *hdr, uint64_t file_size,
325             uint32_t expected_variant) {
326 2 50         if (hdr->magic != RING_MAGIC) return 0;
327 2 50         if (hdr->version != RING_VERSION) return 0;
328 2 50         if (hdr->variant_id != expected_variant) return 0;
329 2 50         if (hdr->elem_size == 0 || hdr->capacity == 0) return 0;
    50          
330             /* capacity * 8 + capacity * elem_size + header must fit in uint64_t */
331 2 50         if (hdr->capacity > (UINT64_MAX - sizeof(RingHeader)) / (sizeof(uint64_t) + hdr->elem_size)) return 0;
332 2 50         if (hdr->total_size != file_size) return 0;
333 2 50         if (hdr->seq_off != ring_seq_off()) return 0;
334 2 50         if (hdr->data_off != ring_data_off(hdr->capacity)) return 0;
335 2 50         if (hdr->total_size != hdr->data_off + hdr->capacity * hdr->elem_size) return 0;
336 2           return 1;
337             }
338              
339 18           static inline RingHandle *ring_setup(void *base, size_t ms, const char *path, int bfd) {
340 18           RingHeader *hdr = (RingHeader *)base;
341 18           RingHandle *h = (RingHandle *)calloc(1, sizeof(RingHandle));
342 18 50         if (!h) { munmap(base, ms); return NULL; }
343 18           h->hdr = hdr;
344 18           h->seq = (uint64_t *)((uint8_t *)base + hdr->seq_off);
345 18           h->data = (uint8_t *)base + hdr->data_off;
346 18           h->mmap_size = ms;
347 18           h->elem_size = hdr->elem_size;
348 18 100         h->path = path ? strdup(path) : NULL;
349 18           h->notify_fd = -1;
350 18           h->backing_fd = bfd;
351 18           return h;
352             }
353              
354 10           static RingHandle *ring_create(const char *path, uint64_t capacity,
355             uint32_t elem_size, uint32_t variant_id,
356             char *errbuf) {
357 10 50         if (errbuf) errbuf[0] = '\0';
358 10 50         if (capacity == 0) { RING_ERR("capacity must be > 0"); return NULL; }
    0          
359 10 50         if (elem_size == 0) { RING_ERR("elem_size must be > 0"); return NULL; }
    0          
360 10 50         if (capacity > (UINT64_MAX - sizeof(RingHeader)) / (sizeof(uint64_t) + elem_size)) {
361 0 0         RING_ERR("capacity * elem_size overflow"); return NULL;
362             }
363              
364 10           uint64_t total = ring_data_off(capacity) + capacity * elem_size;
365 10           int anonymous = (path == NULL);
366 10           int fd = -1;
367             size_t map_size;
368             void *base;
369              
370 10 100         if (anonymous) {
371 7           map_size = (size_t)total;
372 7           base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
373 7 50         if (base == MAP_FAILED) { RING_ERR("mmap: %s", strerror(errno)); return NULL; }
    0          
374             } else {
375 3           fd = open(path, O_RDWR|O_CREAT, 0666);
376 4 50         if (fd < 0) { RING_ERR("open: %s", strerror(errno)); return NULL; }
    0          
377 3 50         if (flock(fd, LOCK_EX) < 0) { RING_ERR("flock: %s", strerror(errno)); close(fd); return NULL; }
    0          
378             struct stat st;
379 3 50         if (fstat(fd, &st) < 0) { RING_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; }
    0          
380 3           int is_new = (st.st_size == 0);
381 3 100         if (!is_new && (uint64_t)st.st_size < sizeof(RingHeader)) {
    50          
382 0 0         RING_ERR("%s: file too small (%lld)", path, (long long)st.st_size);
383 0           flock(fd, LOCK_UN); close(fd); return NULL;
384             }
385 3 100         if (is_new && ftruncate(fd, (off_t)total) < 0) {
    50          
386 0 0         RING_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL;
387             }
388 3 100         map_size = is_new ? (size_t)total : (size_t)st.st_size;
389 3           base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
390 3 50         if (base == MAP_FAILED) { RING_ERR("mmap: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; }
    0          
391 3 100         if (!is_new) {
392 1 50         if (!ring_validate_header((RingHeader *)base, (uint64_t)st.st_size, variant_id)) {
393 0 0         RING_ERR("invalid ring file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
394             }
395 1           flock(fd, LOCK_UN); close(fd);
396 1           return ring_setup(base, map_size, path, -1);
397             }
398             }
399 9           ring_init_header(base, total, elem_size, variant_id, capacity);
400 9 100         if (fd >= 0) { flock(fd, LOCK_UN); close(fd); }
401 9           return ring_setup(base, map_size, path, -1);
402             }
403              
404 7           static RingHandle *ring_create_memfd(const char *name, uint64_t capacity,
405             uint32_t elem_size, uint32_t variant_id,
406             char *errbuf) {
407 7 50         if (errbuf) errbuf[0] = '\0';
408 7 50         if (capacity == 0) { RING_ERR("capacity must be > 0"); return NULL; }
    0          
409 7 50         if (elem_size == 0) { RING_ERR("elem_size must be > 0"); return NULL; }
    0          
410 7 50         if (capacity > (UINT64_MAX - sizeof(RingHeader)) / (sizeof(uint64_t) + elem_size)) {
411 0 0         RING_ERR("capacity * elem_size overflow"); return NULL;
412             }
413 7           uint64_t total = ring_data_off(capacity) + capacity * elem_size;
414 7 50         int fd = memfd_create(name ? name : "ring", MFD_CLOEXEC | MFD_ALLOW_SEALING);
415 7 50         if (fd < 0) { RING_ERR("memfd_create: %s", strerror(errno)); return NULL; }
    0          
416 7 50         if (ftruncate(fd, (off_t)total) < 0) { RING_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL; }
    0          
417 7           (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
418 7           void *base = mmap(NULL, (size_t)total, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
419 7 50         if (base == MAP_FAILED) { RING_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; }
    0          
420 7           ring_init_header(base, total, elem_size, variant_id, capacity);
421 7           return ring_setup(base, (size_t)total, NULL, fd);
422             }
423              
424 1           static RingHandle *ring_open_fd(int fd, uint32_t variant_id, char *errbuf) {
425 1 50         if (errbuf) errbuf[0] = '\0';
426             struct stat st;
427 1 50         if (fstat(fd, &st) < 0) { RING_ERR("fstat: %s", strerror(errno)); return NULL; }
    0          
428 1 50         if ((uint64_t)st.st_size < sizeof(RingHeader)) { RING_ERR("too small"); return NULL; }
    0          
429 1           size_t ms = (size_t)st.st_size;
430 1           void *base = mmap(NULL, ms, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
431 1 50         if (base == MAP_FAILED) { RING_ERR("mmap: %s", strerror(errno)); return NULL; }
    0          
432 1 50         if (!ring_validate_header((RingHeader *)base, (uint64_t)st.st_size, variant_id)) {
433 0 0         RING_ERR("invalid ring"); munmap(base, ms); return NULL;
434             }
435 1           int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
436 1 50         if (myfd < 0) { RING_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; }
    0          
437 1           return ring_setup(base, ms, NULL, myfd);
438             }
439              
440 18           static void ring_destroy(RingHandle *h) {
441 18 50         if (!h) return;
442 18 100         if (h->notify_fd >= 0) close(h->notify_fd);
443 18 100         if (h->backing_fd >= 0) close(h->backing_fd);
444 18 50         if (h->hdr) munmap(h->hdr, h->mmap_size);
445 18           free(h->path);
446 18           free(h);
447             }
448              
449             /* NOT concurrency-safe — caller must ensure no concurrent writers/readers. */
450 1           static void ring_clear(RingHandle *h) {
451 1           uint64_t cap = h->hdr->capacity;
452             /* Reset per-slot seq: otherwise new writes at pos=0 look stale against
453             * old high seq marks. */
454 6 100         for (uint64_t i = 0; i < cap; i++)
455 5           __atomic_store_n(&h->seq[i], 0, __ATOMIC_RELAXED);
456 1           __atomic_store_n(&h->hdr->head, 0, __ATOMIC_RELEASE);
457 1           __atomic_store_n(&h->hdr->count, 0, __ATOMIC_RELEASE);
458 1           __atomic_add_fetch(&h->hdr->wake_seq, 1, __ATOMIC_RELEASE);
459             /* Wake any ring_wait callers parked with timeout=-1 so they re-check. */
460 1 50         if (__atomic_load_n(&h->hdr->waiters, __ATOMIC_RELAXED) > 0)
461 0           syscall(SYS_futex, &h->hdr->wake_seq, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
462 1           }
463              
464 2           static int ring_create_eventfd(RingHandle *h) {
465 2 50         if (h->notify_fd >= 0) return h->notify_fd;
466 2           int efd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
467 2 50         if (efd < 0) return -1;
468 2           h->notify_fd = efd; return efd;
469             }
470 2           static int ring_notify(RingHandle *h) {
471 2 50         if (h->notify_fd < 0) return 0;
472 2           uint64_t v = 1; return write(h->notify_fd, &v, sizeof(v)) == sizeof(v);
473             }
474 2           static int64_t ring_eventfd_consume(RingHandle *h) {
475 2 50         if (h->notify_fd < 0) return -1;
476 2           uint64_t v = 0;
477 2 50         if (read(h->notify_fd, &v, sizeof(v)) != sizeof(v)) return -1;
478 2           return (int64_t)v;
479             }
480 1           static int ring_msync(RingHandle *h) { return msync(h->hdr, h->mmap_size, MS_SYNC); }
481              
482             #endif /* RING_H */