cbf.h

filter: Statementstmt 72.1% 383 / 531 Branchbran 46.8% 209 / 446 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 60.5% 592 / 977 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xxhash.h ↑ Summary Shared.xs »
1 /*
2 * cbf.h -- Shared-memory counting Bloom filter for Linux
3 *
4 * Probabilistic set membership WITH DELETE and occurrence counts: tells you
5 * whether an item is "definitely not" or "probably" in the set, in a fixed
6 * amount of memory, with a tunable false-positive rate and no false negatives.
7 * Each item is hashed once (XXH3-128); the two 64-bit halves drive k probes
8 * (Kirsch-Mitzenmacher double hashing) into a power-of-two array of 4-bit
9 * saturating counters. add increments the k counters, remove decrements them,
10 * contains is true when all k are nonzero, and count_of returns their minimum
11 * (an occurrence estimate 0..15). The array lives in a shared mapping so several
12 * processes share one filter; a write-preferring futex rwlock with reader-slot
13 * dead-process recovery guards mutation. Two filters of equal geometry can be
14 * merged (counter-wise saturating add -> union with summed counts).
15 *
16 * Layout: Header -> reader_slots[1024] -> counters[m_ctr/2] (two 4-bit per byte)
17 */
18  
19 #ifndef CBF_H
20 #define CBF_H
21  
22 #include <stddef.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <time.h>
30 #include <limits.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <math.h>
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36 #include <sys/file.h>
37 #include <sys/syscall.h>
38 #include <linux/futex.h>
39 #include <pthread.h>
40  
41 #define XXH_INLINE_ALL
42 #include "xxhash.h"
43  
44 #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
45 #error "cbf.h: requires little-endian architecture"
46 #endif
47  
48  
49 /* ================================================================
50 * Constants
51 * ================================================================ */
52  
53 #define CBF_MAGIC 0x53464243U /* "CBFS" (little-endian) */
54 #define CBF_VERSION 2 /* 2: added the occupancy bitmap region (layout change) */
55 #define CBF_ERR_BUFLEN (PATH_MAX + 256)
56 #ifndef CBF_READER_SLOTS
57 #define CBF_READER_SLOTS 1024 /* max concurrent reader processes for dead-process recovery */
58 #endif
59 /* Occupancy bitmap: one bit per reader slot, set when a process claims a slot and
60 * cleared on clean release. A writer scans these CBF_OCC_WORDS words to visit
61 * only OCCUPIED slots (O(words + live readers)) instead of all CBF_READER_SLOTS. */
62 #define CBF_OCC_WORDS (((CBF_READER_SLOTS) + 63) / 64) /* 16 for 1024 slots */
63 #define CBF_OCC_BYTES ((uint64_t)CBF_OCC_WORDS * 8) /* 128 bytes */
64 #define CBF_MIN_CTR 64 /* floor on the counter count (power of two) */
65 #define CBF_MAX_CTR 0x4000000000ULL /* 2^38 counters = 128 GiB counter-array cap (4-bit) */
66 #define CBF_CTR_MAX 15 /* 4-bit saturating counter ceiling */
67 #define CBF_MIN_K 1
68 #define CBF_MAX_K 32
69  
70 #define CBF_ERR(fmt, ...) do { if (errbuf) snprintf(errbuf, CBF_ERR_BUFLEN, fmt, ##__VA_ARGS__); } while (0)
71  
72 /* ================================================================
73 * Structs
74 * ================================================================ */
75  
76 /* Per-process slot for dead-process recovery. In the reader-slots-only rwlock a
77 * reader's ENTIRE contribution to the shared lock is `rdepth` in its OWN slot --
78 * there is no separate shared reader counter to fall out of sync with it -- so a
79 * dead reader's contribution is exactly this one word, which a draining writer
80 * neutralises by clearing the slot's pid (the scan then ignores the slot). No
81 * orphaned counter can exist, so there is no quiescent force-reset and sustained
82 * readers cannot starve a writer. _rsv1/_rsv2 are kept only to preserve the
83 * 16-byte slot size across the already-released builds. */
84 typedef struct {
85 uint32_t pid; /* 0 = unclaimed */
86 uint32_t rdepth; /* read-locks THIS process currently holds (recursion-safe) */
87 uint32_t _rsv1; /* reserved (was waiters_parked); unused, kept for layout size */
88 uint32_t _rsv2; /* reserved (was writers_parked); unused, kept for layout size */
89 } CbfReaderSlot;
90  
91 struct CbfHeader {
92 uint32_t magic, version; /* 0,4 */
93 uint32_t k; /* 8 number of hash probes per item */
94 uint32_t _pad0; /* 12 */
95 uint64_t m_ctr; /* 16 counter count m (power of two) */
96 uint64_t m_mask; /* 24 m_ctr - 1 (probe index mask) */
97 uint64_t capacity; /* 32 configured item capacity n (for stats) */
98 double fp_rate; /* 40 configured target false-positive rate (for stats) */
99 uint64_t total_size; /* 48 */
100 uint64_t reader_slots_off; /* 56 */
101 uint64_t ctr_off; /* 64 */
102 uint32_t wlock; /* 72 WRITER word ONLY: 0 (free) or WRITER_BIT|pid. NOT a reader count. */
103 uint32_t rwait; /* 76 parked-waiter hint (readers+writers blocked on wlock); over-count-safe */
104 uint32_t drain_seq; /* 80 futex bumped by a reader releasing under a draining writer (wakes it) */
105 uint32_t slotless_rdepth; /* readers holding with no reader-slot (documented residual) */
106 uint64_t stat_ops; /* 88 write-lock protected */
107 uint8_t sealed; /* 96 0 = mutable, 1 = frozen (read-only; lock-free reads) */
108 uint8_t _pad[159]; /* 97..255 */
109 };
110 typedef struct CbfHeader CbfHeader;
111  
112 _Static_assert(sizeof(CbfHeader) == 256, "CbfHeader must be 256 bytes");
113  
114 /* ---- Process-local handle ---- */
115  
116 typedef struct CbfHandle {
117 CbfHeader *hdr;
118 CbfReaderSlot *reader_slots; /* CBF_READER_SLOTS entries */
119 uint64_t *occ; /* CBF_OCC_WORDS-word slot-occupancy bitmap (trusted layout offset) */
120 void *base; /* mmap base */
121 uint64_t ctr_off; /* validated counter-array offset, cached: never re-read from the peer-writable header */
122 uint32_t k; /* validated probe count, cached: never re-read from the peer-writable header */
123 size_t mmap_size;
124 char *path; /* backing file path (strdup'd) */
125 int backing_fd; /* memfd or reopened-fd to close on destroy, -1 for file/anon */
126 uint32_t my_slot_idx; /* UINT32_MAX if all slots taken (no recovery for this handle) */
127 uint32_t cached_pid; /* getpid() cached at last slot claim */
128 uint32_t cached_fork_gen; /* cbf_fork_gen value at last slot claim */
129 uint32_t slotless_held; /* read-locks this process holds with no reader-slot */
130 int readonly; /* 1 = frozen O_RDONLY/PROT_READ view: lock-free reads, mutation croaks */
131 } CbfHandle;
132  
133 /* ================================================================
134 * Futex-based write-preferring read-write lock (reader-slots-only)
135 * with dead-process recovery
136 *
137 * The reader count is NOT stored in a shared counter. It is DISTRIBUTED across
138 * per-process reader slots: each slot's `rdepth` is that process's entire
139 * contribution to the lock. A reader publishes its presence in its own slot and
140 * then re-checks the writer word; a writer publishes the writer word and then
141 * scans every slot until all live readers' rdepth reach 0. Sequentially-
142 * consistent store+load on each side (a Dekker handshake) gives mutual exclusion.
143 *
144 * Because a reader's whole contribution is ONE atomic word owned by ONE process,
145 * a crashed reader is recovered by clearing that one slot (CAS its pid to 0) --
146 * there is no second counter to strand, no orphaned +1, and therefore no
147 * quiescent force-reset. A reader killed anywhere in rdlock/rdunlock leaves at
148 * most `rdepth>0` in its dead slot, which the draining writer clears directly, so
149 * sustained read traffic can never starve a writer. Write-preference is inherent
150 * in the gate (new readers see wlock!=0 and yield), so there is no reader-count
151 * yield hack.
152 * ================================================================ */
153  
154 #define CBF_RWLOCK_SPIN_LIMIT 32
155 #define CBF_LOCK_TIMEOUT_SEC 2 /* FUTEX_WAIT timeout for stale-lock detection / drain re-scan */
156  
157 0 static inline void cbf_rwlock_spin_pause(void) {
158 #if defined(__x86_64__) || defined(__i386__)
159 0 __asm__ volatile("pause" ::: "memory");
160 #elif defined(__aarch64__)
161 __asm__ volatile("yield" ::: "memory");
162 #else
163 __asm__ volatile("" ::: "memory");
164 #endif
165 0 }
166  
167 /* Writer word encoding: WRITER_BIT|pid when write-locked, 0 when free. */
168 #define CBF_RWLOCK_WRITER_BIT 0x80000000U
169 #define CBF_RWLOCK_PID_MASK 0x7FFFFFFFU
170 #define CBF_RWLOCK_WR(pid) (CBF_RWLOCK_WRITER_BIT | ((uint32_t)(pid) & CBF_RWLOCK_PID_MASK))
171  
172 /* A zombie (dead but not yet reaped) still answers kill(pid,0) as alive, so a
173 * process that crashed while holding the lock and lingers unreaped would never
174 * be recovered. Treat /proc/<pid>/stat state 'Z' as dead. Linux-only (as is
175 * this module); if /proc is unreadable we fall back to "alive" (safe: we never
176 * force-recover a possibly-live holder). */
177 0 static inline int cbf_pid_is_zombie(uint32_t pid) {
178 char path[32], buf[256];
179 0 snprintf(path, sizeof(path), "/proc/%u/stat", (unsigned)pid);
180 0 int fd = open(path, O_RDONLY | O_CLOEXEC);
181 0 ▶ if (fd < 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return 0; 0 0 0
182 0 ssize_t n = read(fd, buf, sizeof(buf) - 1);
183 0 close(fd);
184 0 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 0 0
185 0 buf[n] = '\0';
186 /* "pid (comm) state ..."; comm may contain ')', so scan to the last one. */
187 0 char *rp = strrchr(buf, ')');
188 0 ▶ if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */
Branch: 2 branches
BranchTrueFalseTotal
if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */ 0 0 0
if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */ 0 0 0
189 0 ▶ return rp[1] == ' ' && rp[2] == 'Z';
Branch: 2 branches
BranchTrueFalseTotal
return rp[1] == ' ' && rp[2] == 'Z'; 0 0 0
return rp[1] == ' ' && rp[2] == 'Z'; 0 0 0
190 }
191 /* 1 if alive or unknown, 0 if definitely dead. Cannot detect PID reuse: a
192 * recycled PID reports "alive" and the slot is not reclaimed until that
193 * process exits. See "Crash Safety" in the POD. */
194 0 static inline int cbf_pid_alive(uint32_t pid) {
195 0 ▶ if (pid == 0) return 0; /* no owner recorded, treat as dead */
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) return 0; /* no owner recorded, treat as dead */ 0 0 0
196 0 ▶ if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */
Branch: 2 branches
BranchTrueFalseTotal
if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */ 0 0 0
if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */ 0 0 0
197 0 return !cbf_pid_is_zombie(pid); /* kill() also succeeds for a zombie -> treat as dead */
198 }
199  
200 /* Force-recover a stale WRITE lock left by a dead writer (held or mid-drain).
201 * CAS to OUR pid to hold the lock while fixing shared state, then release.
202 * Using our pid (not a bare WRITER_BIT sentinel) means a subsequent recovering
203 * process can detect and re-recover if we crash mid-recovery. */
204 0 static inline void cbf_recover_stale_lock(CbfHandle *h, uint32_t observed_wlock) {
205 0 CbfHeader *hdr = h->hdr;
206 0 uint32_t mypid = CBF_RWLOCK_WR((uint32_t)getpid());
207 0 ▶ if (!__atomic_compare_exchange_n(&hdr->wlock, &observed_wlock,
Branch: 1 branch
BranchTrueFalseTotal
if (!__atomic_compare_exchange_n(&hdr->wlock, &observed_wlock, 0 0 0
208 mypid, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
209 0 return;
210 /* We now hold the write lock as mypid. No additional shared state needs
211 * repair here (this module has no seqlock); just release the lock. */
212 0 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_SEQ_CST);
213 0 ▶ if (__atomic_load_n(&hdr->rwait, __ATOMIC_SEQ_CST) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->rwait, __ATOMIC_SEQ_CST) > 0) 0 0 0
214 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
215 }
216  
217 static const struct timespec cbf_lock_timeout = { CBF_LOCK_TIMEOUT_SEC, 0 };
218  
219 /* Process-global fork-generation counter. Incremented in the pthread_atfork
220 * child callback so every open handle detects a fork transition on the next
221 * lock call without paying a getpid() syscall on the hot path. */
222 static uint32_t cbf_fork_gen = 1;
223 static pthread_once_t cbf_atfork_once = PTHREAD_ONCE_INIT;
224 0 static void cbf_on_fork_child(void) {
225 0 __atomic_add_fetch(&cbf_fork_gen, 1, __ATOMIC_RELAXED);
226 0 }
227 4 static void cbf_atfork_init(void) {
228 4 pthread_atfork(NULL, NULL, cbf_on_fork_child);
229 4 }
230  
231 /* Occupancy bitmap: set a slot's bit when it is claimed, clear it on clean
232 * release. SEQ_CST so a set bit is ordered before the slot's rdepth can go
233 * non-zero (bit set in claim, which precedes any rdlock), letting a writer's
234 * SEQ_CST bitmap scan never miss a slot a committed reader holds. */
235 39 static inline void cbf_occ_set(CbfHandle *h, uint32_t s) {
236 39 __atomic_fetch_or(&h->occ[s >> 6], (uint64_t)1 << (s & 63), __ATOMIC_SEQ_CST);
237 39 }
238 39 static inline void cbf_occ_clear(CbfHandle *h, uint32_t s) {
239 39 __atomic_fetch_and(&h->occ[s >> 6], ~((uint64_t)1 << (s & 63)), __ATOMIC_SEQ_CST);
240 39 }
241  
242 /* Ensure this process owns a reader slot. Called from the lock helpers so that
243 * fork()'d children pick up their own slot lazily instead of sharing the
244 * parent's. Hot-path is a single relaxed load + compare; only on a
245 * fork-generation mismatch do we touch getpid() and scan slots. */
246 69980 static inline void cbf_claim_reader_slot(CbfHandle *h) {
247 69980 uint32_t cur_gen = __atomic_load_n(&cbf_fork_gen, __ATOMIC_RELAXED);
248 69980 ▶ if (__builtin_expect(cur_gen == h->cached_fork_gen && h->my_slot_idx != UINT32_MAX, 1))
Branch: 2 branches
BranchTrueFalseTotal
if (__builtin_expect(cur_gen == h->cached_fork_gen && h->my_slot_idx != UINT32_MAX, 1)) 69941 39 69980
if (__builtin_expect(cur_gen == h->cached_fork_gen && h->my_slot_idx != UINT32_MAX, 1)) 69941 0 69941
249 69941 return;
250 /* Cold path -- register the atfork hook once per process, then claim. */
251 39 pthread_once(&cbf_atfork_once, cbf_atfork_init);
252 /* Re-read after pthread_once: cbf_on_fork_child may have bumped it. */
253 39 cur_gen = __atomic_load_n(&cbf_fork_gen, __ATOMIC_RELAXED);
254 39 uint32_t now_pid = (uint32_t)getpid();
255 39 h->cached_pid = now_pid;
256 39 ▶ if (cur_gen != h->cached_fork_gen) h->slotless_held = 0; /* fork: child holds none of the parent's slotless read locks */
Branch: 1 branch
BranchTrueFalseTotal
if (cur_gen != h->cached_fork_gen) h->slotless_held = 0; /* fork: child holds none of the parent's slotless read locks */ 39 0 39
257 39 h->cached_fork_gen = cur_gen;
258 39 h->my_slot_idx = UINT32_MAX;
259 39 uint32_t start = now_pid % CBF_READER_SLOTS;
260 /* Pass 1: take a free slot. */
261 41 ▶ for (uint32_t i = 0; i < CBF_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < CBF_READER_SLOTS; i++) { 41 0 41
262 41 uint32_t s = (start + i) % CBF_READER_SLOTS;
263 41 uint32_t expected = 0;
264 41 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[s].pid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[s].pid, 39 2 41
265 &expected, now_pid, 0,
266 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
267 /* Fresh owner holds no read locks yet; clear any stale rdepth left by
268 * a dead predecessor (its contribution is dropped as we take over). */
269 39 __atomic_store_n(&h->reader_slots[s].rdepth, 0, __ATOMIC_RELAXED);
270 39 cbf_occ_set(h, s); /* mark occupied BEFORE any rdlock can bump rdepth */
271 39 h->my_slot_idx = s;
272 39 return;
273 }
274 }
275 /* Pass 2: no free slot -- reclaim one whose owner is dead. Safe to take even
276 * if its rdepth>0: clearing pid drops the dead reader's entire contribution
277 * (a writer scan ignores rdepth when pid==0) and we reset rdepth to 0 as we
278 * claim it. */
279 0 ▶ for (uint32_t i = 0; i < CBF_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < CBF_READER_SLOTS; i++) { 0 0 0
280 0 uint32_t dpid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
281 0 ▶ if (dpid == 0 || dpid == now_pid || cbf_pid_alive(dpid)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (dpid == 0 || dpid == now_pid || cbf_pid_alive(dpid)) continue; 0 0 0
if (dpid == 0 || dpid == now_pid || cbf_pid_alive(dpid)) continue; 0 0 0
if (dpid == 0 || dpid == now_pid || cbf_pid_alive(dpid)) continue; 0 0 0
282 0 uint32_t expected = dpid;
283 0 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[i].pid, &expected, now_pid, 0,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[i].pid, &expected, now_pid, 0, 0 0 0
284 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
285 0 __atomic_store_n(&h->reader_slots[i].rdepth, 0, __ATOMIC_RELAXED);
286 0 cbf_occ_set(h, i);
287 0 h->my_slot_idx = i;
288 0 return;
289 }
290 }
291 /* Table full -- leave my_slot_idx = UINT32_MAX so this handle takes the
292 * slotless path (lock still works; recovery of THIS reader's death is the
293 * documented slotless limitation). */
294 }
295  
296 /* Inspect the writer word after a futex-wait timeout. If a dead writer holds
297 * it, force-recover. Dead READERS need no action here: only a writer that owns
298 * wlock drains readers, and it clears dead readers inline in its own scan. */
299 0 static inline void cbf_recover_after_timeout(CbfHandle *h) {
300 0 uint32_t val = __atomic_load_n(&h->hdr->wlock, __ATOMIC_RELAXED);
301 0 ▶ if (val >= CBF_RWLOCK_WRITER_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (val >= CBF_RWLOCK_WRITER_BIT) { 0 0 0
302 0 uint32_t pid = val & CBF_RWLOCK_PID_MASK;
303 0 ▶ if (!cbf_pid_alive(pid))
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_pid_alive(pid)) 0 0 0
304 0 cbf_recover_stale_lock(h, val);
305 }
306 0 }
307  
308 /* Bump/drop the parked-waiter hint. Both readers (blocked at the gate) and
309 * writers (blocked acquiring wlock) wait on the wlock futex and use this, so
310 * wrunlock/recover know whether a FUTEX_WAKE is worth a syscall. A waiter
311 * SIGKILLed while parked leaves rwait over-counted -> at most a spurious wake
312 * (harmless). SEQ_CST publish/re-check pairs with unlock's store/hint check
313 * so a waiter and an unlocker cannot both miss each other. */
314 0 static inline void cbf_park(CbfHandle *h) {
315 0 __atomic_add_fetch(&h->hdr->rwait, 1, __ATOMIC_SEQ_CST);
316 0 }
317 0 static inline void cbf_unpark(CbfHandle *h) {
318 0 __atomic_sub_fetch(&h->hdr->rwait, 1, __ATOMIC_RELAXED);
319 0 }
320  
321 /* Publish (inc) / retract (dec) this reader's presence -- its ENTIRE
322 * contribution to the lock. A slotted reader uses its slot's rdepth; a reader
323 * that could not claim a slot uses the global slotless_rdepth. inc() is SEQ_CST
324 * so the wlock re-check that follows it in rdlock forms a Dekker handshake with
325 * the writer's SEQ_CST wlock-store + rdepth-scan. leave() peels slotless first
326 * so a slot claimed mid-hold cannot misattribute the decrement. */
327 31353 static inline void cbf_rdepth_inc(CbfHandle *h) {
328 31353 ▶ if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->my_slot_idx != UINT32_MAX) { 31353 0 31353
329 31353 __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_SEQ_CST);
330 } else {
331 0 __atomic_add_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_SEQ_CST);
332 0 h->slotless_held++;
333 }
334 31353 }
335 31353 static inline void cbf_rdepth_dec(CbfHandle *h) {
336 31353 ▶ if (h->slotless_held > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->slotless_held > 0) { 0 31353 31353
337 0 h->slotless_held--;
338 0 __atomic_sub_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_SEQ_CST);
339 31353 ▶ } else if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (h->my_slot_idx != UINT32_MAX) { 31353 0 31353
340 31353 __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_SEQ_CST);
341 }
342 31353 }
343  
344 /* Wake a writer that may be draining readers (it waits on drain_seq). Called
345 * after every rdepth decrement so a released read lock lets the writer re-scan
346 * promptly instead of waiting out its timeout. */
347 31353 static inline void cbf_reader_wake_drain(CbfHandle *h) {
348 31353 ▶ if (__atomic_load_n(&h->hdr->wlock, __ATOMIC_SEQ_CST) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&h->hdr->wlock, __ATOMIC_SEQ_CST) != 0) { 0 31353 31353
349 0 __atomic_add_fetch(&h->hdr->drain_seq, 1, __ATOMIC_RELEASE);
350 0 syscall(SYS_futex, &h->hdr->drain_seq, FUTEX_WAKE, 1, NULL, NULL, 0);
351 }
352 31353 }
353  
354 31353 static inline void cbf_rwlock_rdlock(CbfHandle *h) {
355 31353 cbf_claim_reader_slot(h);
356 31353 CbfHeader *hdr = h->hdr;
357 31353 for (int spin = 0; ; spin++) {
358 31353 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_ACQUIRE);
359 31353 ▶ if (cur == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur == 0) { 31353 0 31353
360 /* Optimistically take the read: publish rdepth, then re-check wlock.
361 * SEQ_CST inc + SEQ_CST load vs the writer's SEQ_CST wlock CAS +
362 * SEQ_CST rdepth scan: by the single total order of SEQ_CST ops the
363 * two sides cannot both miss each other, so we never hold
364 * concurrently with a writer. */
365 31353 cbf_rdepth_inc(h);
366 31353 ▶ if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0) 31353 0 31353
367 31353 return; /* no writer after our publish -> we hold the read lock */
368 /* A writer appeared during our publish -- yield to it (write-preferring). */
369 0 cbf_rdepth_dec(h);
370 0 cbf_reader_wake_drain(h); /* let the draining writer see rdepth drop */
371 0 spin = 0;
372 0 continue;
373 }
374 /* wlock != 0: a writer holds or is acquiring. Recover if it is dead. */
375 0 if (cur >= CBF_RWLOCK_WRITER_BIT &&
376 0 !cbf_pid_alive(cur & CBF_RWLOCK_PID_MASK)) {
377 0 cbf_recover_stale_lock(h, cur);
378 0 spin = 0;
379 0 continue;
380 }
381 0 ▶ if (__builtin_expect(spin < CBF_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < CBF_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
382 0 cbf_rwlock_spin_pause();
383 0 continue;
384 }
385 0 cbf_park(h);
386 0 cur = __atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST);
387 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
388 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
389 &cbf_lock_timeout, NULL, 0);
390 0 ▶ if (rc == -1 && errno == ETIMEDOUT) {
Branch: 2 branches
BranchTrueFalseTotal
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
391 0 cbf_unpark(h);
392 0 cbf_recover_after_timeout(h);
393 0 spin = 0;
394 0 continue;
395 }
396 }
397 0 cbf_unpark(h);
398 0 spin = 0;
399 }
400 }
401  
402 31353 static inline void cbf_rwlock_rdunlock(CbfHandle *h) {
403 31353 cbf_rdepth_dec(h); /* RELEASE: drop our entire contribution */
404 31353 cbf_reader_wake_drain(h); /* if a writer is draining, wake it to re-scan */
405 31353 }
406  
407 38627 static inline void cbf_rwlock_wrlock(CbfHandle *h) {
408 38627 cbf_claim_reader_slot(h); /* refresh cached_pid across fork */
409 38627 CbfHeader *hdr = h->hdr;
410 /* Encode PID in the wlock word itself (0x80000000 | pid) to eliminate any
411 * crash window between acquiring the lock and storing the owner. */
412 38627 uint32_t mypid = CBF_RWLOCK_WR(h->cached_pid);
413 /* Phase 1: acquire the writer word (mutual exclusion among writers). */
414 38627 for (int spin = 0; ; spin++) {
415 38627 uint32_t expected = 0;
416 38627 ▶ if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid, 38627 0 38627
417 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED))
418 38627 break;
419 /* Contended: expected now holds the current wlock value. */
420 0 if (expected >= CBF_RWLOCK_WRITER_BIT &&
421 0 !cbf_pid_alive(expected & CBF_RWLOCK_PID_MASK)) {
422 0 cbf_recover_stale_lock(h, expected);
423 0 spin = 0;
424 0 continue;
425 }
426 0 ▶ if (__builtin_expect(spin < CBF_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < CBF_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
427 0 cbf_rwlock_spin_pause();
428 0 continue;
429 }
430 0 cbf_park(h);
431 0 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST);
432 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
433 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
434 &cbf_lock_timeout, NULL, 0);
435 0 ▶ if (rc == -1 && errno == ETIMEDOUT) {
Branch: 2 branches
BranchTrueFalseTotal
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
436 0 cbf_unpark(h);
437 0 cbf_recover_after_timeout(h);
438 0 spin = 0;
439 0 continue;
440 }
441 }
442 0 cbf_unpark(h);
443 0 spin = 0;
444 }
445 /* Phase 2: we own wlock, so no NEW reader can join (they see wlock!=0 and
446 * yield). Drain the readers that were already holding when we won the CAS.
447 * The SEQ_CST CAS above + the SEQ_CST rdepth loads below are the writer side
448 * of the Dekker handshake. */
449 0 for (;;) {
450 38627 uint32_t v = __atomic_load_n(&hdr->drain_seq, __ATOMIC_ACQUIRE); /* snapshot BEFORE scan */
451 38627 int busy = 0;
452 /* Visit only OCCUPIED slots via the occupancy bitmap (SEQ_CST: a committed
453 * reader's bit -- set in claim, before its rdepth++ -- is ordered before
454 * this scan, so no held slot is skipped). O(CBF_OCC_WORDS + live readers)
455 * instead of O(CBF_READER_SLOTS). */
456 656659 ▶ for (uint32_t w = 0; w < CBF_OCC_WORDS; w++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t w = 0; w < CBF_OCC_WORDS; w++) { 618032 38627 656659
457 618032 uint64_t word = __atomic_load_n(&h->occ[w], __ATOMIC_SEQ_CST);
458 656664 ▶ while (word) {
Branch: 1 branch
BranchTrueFalseTotal
while (word) { 38632 618032 656664
459 38632 uint32_t i = (w << 6) + (uint32_t)__builtin_ctzll(word);
460 38632 word &= word - 1; /* consume this bit (local copy) */
461 38632 uint32_t rd = __atomic_load_n(&h->reader_slots[i].rdepth, __ATOMIC_SEQ_CST);
462 38632 ▶ if (rd == 0) continue; /* occupied but not read-locking now */
Branch: 1 branch
BranchTrueFalseTotal
if (rd == 0) continue; /* occupied but not read-locking now */ 38632 0 38632
463 0 uint32_t pid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
464 0 ▶ if (pid == 0) continue; /* stale rdepth on a freed slot */
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) continue; /* stale rdepth on a freed slot */ 0 0 0
465 0 ▶ if (!cbf_pid_alive(pid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_pid_alive(pid)) { 0 0 0
466 /* Dead reader: drop its pid so the slot no longer counts. Leave
467 * the occ bit set (harmless -- a later scan hits pid==0 and skips,
468 * a re-claim re-sets it) to avoid racing a concurrent claimant. */
469 0 uint32_t ep = pid;
470 0 __atomic_compare_exchange_n(&h->reader_slots[i].pid, &ep, 0,
471 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
472 0 continue;
473 }
474 0 busy = 1; /* live reader still holding */
475 }
476 }
477 /* A live slotless reader keeps us waiting; a crashed slotless reader that
478 * cannot be attributed to a pid is the documented slotless limitation. */
479 38627 ▶ if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0) 0 38627 38627
480 0 busy = 1;
481 38627 ▶ if (!busy)
Branch: 1 branch
BranchTrueFalseTotal
if (!busy) 38627 0 38627
482 38627 return; /* exclusive: wlock held + every rdepth 0 */
483 /* Wait for a reader to release (drain_seq bump) or time out to re-scan
484 * (which reclaims any newly-dead slotted reader). */
485 0 syscall(SYS_futex, &hdr->drain_seq, FUTEX_WAIT, v, &cbf_lock_timeout, NULL, 0);
486 }
487 }
488  
489 38627 static inline void cbf_rwlock_wrunlock(CbfHandle *h) {
490 38627 CbfHeader *hdr = h->hdr;
491 38627 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_SEQ_CST);
492 38627 ▶ if (__atomic_load_n(&hdr->rwait, __ATOMIC_SEQ_CST) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->rwait, __ATOMIC_SEQ_CST) > 0) 0 38627 38627
493 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
494 38627 }
495  
496 /* ================================================================
497 * Layout math + create / open / destroy
498 *
499 * Layout: Header -> reader_slots[1024] -> counters[m_ctr/2] (two 4-bit per byte)
500 * ================================================================ */
501  
502 /* Single source of truth for the mmap region layout offsets:
503 * Header -> reader_slots[] -> occ bitmap -> counters. */
504 typedef struct { uint64_t reader_slots, occ, counters; } CbfLayout;
505  
506 177 static inline CbfLayout cbf_layout(void) {
507 CbfLayout L;
508 177 L.reader_slots = sizeof(CbfHeader);
509 177 L.occ = L.reader_slots + (uint64_t)CBF_READER_SLOTS * sizeof(CbfReaderSlot);
510 177 L.counters = L.occ + CBF_OCC_BYTES;
511 177 L.counters = (L.counters + 7) & ~(uint64_t)7; /* 8-byte align the counter array */
512 177 return L;
513 }
514  
515 65 static inline uint64_t cbf_total_size(uint64_t m_ctr) {
516 65 CbfLayout L = cbf_layout();
517 65 return L.counters + (m_ctr / 2); /* 4-bit counters, two per byte; m_ctr is a power of two >= 64 -> exact bytes */
518 }
519  
520 /* round v up to the next power of two (64-bit), with a floor of CBF_MIN_CTR */
521 55 static inline uint64_t cbf_next_pow2_u64(uint64_t v) {
522 55 ▶ if (v <= CBF_MIN_CTR) return CBF_MIN_CTR;
Branch: 1 branch
BranchTrueFalseTotal
if (v <= CBF_MIN_CTR) return CBF_MIN_CTR; 2 53 55
523 53 return 1ULL << (64 - __builtin_clzll(v - 1));
524 }
525  
526 47 static inline void cbf_init_header(void *base, uint32_t k, uint64_t m_ctr,
527 uint64_t capacity, double fp_rate, uint64_t total) {
528 47 CbfLayout L = cbf_layout();
529 47 CbfHeader *hdr = (CbfHeader *)base;
530 /* Explicitly zero the header + reader-slot region (lock-recovery state); the
531 counter array relies on the fresh mapping being OS zero-filled. */
532 47 memset(base, 0, (size_t)L.counters);
533 47 hdr->version = CBF_VERSION;
534 47 hdr->k = k;
535 47 hdr->m_ctr = m_ctr;
536 47 hdr->m_mask = m_ctr - 1;
537 47 hdr->capacity = capacity;
538 47 hdr->fp_rate = fp_rate;
539 47 hdr->total_size = total;
540 47 hdr->reader_slots_off = L.reader_slots;
541 47 hdr->ctr_off = L.counters;
542 /* Publish magic LAST, as a release store: it is the commit point, so a
543 creator killed before it leaves magic==0 and never a file mistaken for
544 a valid one. A kill during the field stores leaves one to remove by
545 hand. */
546 47 __atomic_store_n(&hdr->magic, CBF_MAGIC, __ATOMIC_RELEASE);
547 47 __atomic_thread_fence(__ATOMIC_SEQ_CST);
548 47 }
549  
550 /* ---- 4-bit saturating counters: two per byte, low nibble = even index ---- */
551 76787 static inline uint8_t *cbf_counters(CbfHandle *h) {
552 76787 return (uint8_t *)((char *)h->base + h->ctr_off);
553 }
554 530050 static inline uint32_t cbf_ctr_get(const uint8_t *c, uint64_t i) {
555 530050 return (c[i >> 1] >> ((unsigned)(i & 1) << 2)) & 0xFu;
556 }
557 332593 static inline void cbf_ctr_set(uint8_t *c, uint64_t i, uint32_t v) {
558 332593 unsigned sh = (unsigned)(i & 1) << 2;
559 332593 c[i >> 1] = (uint8_t)((c[i >> 1] & ~(0xFu << sh)) | ((v & 0xFu) << sh));
560 332593 }
561  
562 /* Layer B trusted bound: the number of counter BYTES guaranteed to lie within
563 * the real mapping. Derived from the process-local mmap_size (fixed at attach
564 * time, not peer-writable) and the SAME ctr_off cbf_counters() uses, so a peer
565 * sharing the backing file that corrupts the header (m_ctr / m_mask / ctr_off)
566 * after attach-time validation can never drive an access outside the mapping.
567 * For a valid filter this equals m_ctr/2 exactly, so every clamp against it
568 * below is a never-taken branch in normal use. */
569 76787 static inline uint64_t cbf_ctr_bytes_max(CbfHandle *h) {
570 76787 uint64_t off = h->ctr_off;
571 76787 ▶ if (off >= h->mmap_size) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (off >= h->mmap_size) return 0; 0 76787 76787
572 76787 return h->mmap_size - off;
573 }
574  
575 55 static inline CbfHandle *cbf_setup(void *base, size_t map_size,
576 const char *path, int backing_fd) {
577 55 CbfHeader *hdr = (CbfHeader *)base;
578 55 CbfHandle *h = (CbfHandle *)calloc(1, sizeof(CbfHandle));
579 55 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 55 55
580 0 munmap(base, map_size);
581 0 ▶ if (backing_fd >= 0) close(backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (backing_fd >= 0) close(backing_fd); 0 0 0
582 0 return NULL;
583 }
584 55 h->hdr = hdr;
585 55 h->base = base;
586 55 h->reader_slots = (CbfReaderSlot *)((uint8_t *)base + sizeof(CbfHeader)); /* trusted layout, not the peer-writable header offset */
587 55 h->occ = (uint64_t *)((uint8_t *)base + cbf_layout().occ); /* trusted layout offset */
588 55 h->ctr_off = hdr->ctr_off; /* single validated read; bound and pointer stay consistent */
589 55 h->k = hdr->k; /* validated in [CBF_MIN_K,CBF_MAX_K] at attach; never re-trust the peer field */
590 55 h->mmap_size = map_size;
591 55 ▶ h->path = path ? strdup(path) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
h->path = path ? strdup(path) : NULL; 19 36 55
592 55 h->backing_fd = backing_fd;
593 55 h->my_slot_idx = UINT32_MAX;
594 55 return h;
595 }
596  
597 /* Validate a mapped header (shared by cbf_create reopen and cbf_open_fd). */
598 14 static inline int cbf_validate_header(const CbfHeader *hdr, uint64_t file_size) {
599 14 ▶ if (__atomic_load_n(&hdr->magic, __ATOMIC_ACQUIRE) != CBF_MAGIC) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->magic, __ATOMIC_ACQUIRE) != CBF_MAGIC) return 0; 4 10 14
600 10 ▶ if (hdr->version != CBF_VERSION) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->version != CBF_VERSION) return 0; 0 10 10
601 10 ▶ if (hdr->k < CBF_MIN_K || hdr->k > CBF_MAX_K) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (hdr->k < CBF_MIN_K || hdr->k > CBF_MAX_K) return 0; 10 0 10
if (hdr->k < CBF_MIN_K || hdr->k > CBF_MAX_K) return 0; 0 10 10
602 10 ▶ if (hdr->m_ctr < CBF_MIN_CTR || hdr->m_ctr > CBF_MAX_CTR) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (hdr->m_ctr < CBF_MIN_CTR || hdr->m_ctr > CBF_MAX_CTR) return 0; 10 0 10
if (hdr->m_ctr < CBF_MIN_CTR || hdr->m_ctr > CBF_MAX_CTR) return 0; 0 10 10
603 10 ▶ if ((hdr->m_ctr & (hdr->m_ctr - 1)) != 0) return 0; /* power of two */
Branch: 1 branch
BranchTrueFalseTotal
if ((hdr->m_ctr & (hdr->m_ctr - 1)) != 0) return 0; /* power of two */ 0 10 10
604 10 ▶ if (hdr->m_mask != hdr->m_ctr - 1) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->m_mask != hdr->m_ctr - 1) return 0; 0 10 10
605 10 ▶ if (hdr->capacity == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->capacity == 0) return 0; 0 10 10
606 10 ▶ if (!(hdr->fp_rate > 0.0 && hdr->fp_rate < 1.0)) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!(hdr->fp_rate > 0.0 && hdr->fp_rate < 1.0)) return 0; 10 0 10
if (!(hdr->fp_rate > 0.0 && hdr->fp_rate < 1.0)) return 0; 0 10 10
607 10 ▶ if (hdr->total_size != file_size) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->total_size != file_size) return 0; 0 10 10
608 10 ▶ if (hdr->total_size != cbf_total_size(hdr->m_ctr)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->total_size != cbf_total_size(hdr->m_ctr)) return 0; 0 10 10
609 10 CbfLayout L = cbf_layout();
610 10 ▶ if (hdr->reader_slots_off != L.reader_slots) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->reader_slots_off != L.reader_slots) return 0; 0 10 10
611 10 ▶ if (hdr->ctr_off != L.counters) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->ctr_off != L.counters) return 0; 0 10 10
612 10 return 1;
613 }
614  
615 /* validate args + compute the geometry (k, m_ctr) */
616 56 static int cbf_validate_create_args(uint64_t capacity, double fp_rate,
617 uint32_t *k_out, uint64_t *m_bits_out, char *errbuf) {
618 56 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 56 0 56
619 56 ▶ if (capacity < 1) { CBF_ERR("capacity must be >= 1"); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (capacity < 1) { CBF_ERR("capacity must be >= 1"); return 0; } 0 56 56
if (capacity < 1) { CBF_ERR("capacity must be >= 1"); return 0; } 0 0 0
620 56 ▶ if (!(fp_rate > 0.0 && fp_rate < 1.0)) { CBF_ERR("fp_rate must be between 0 and 1 (exclusive)"); return 0; }
Branch: 3 branches
BranchTrueFalseTotal
if (!(fp_rate > 0.0 && fp_rate < 1.0)) { CBF_ERR("fp_rate must be between 0 and 1 (exclusive)"); return 0; } 56 0 56
if (!(fp_rate > 0.0 && fp_rate < 1.0)) { CBF_ERR("fp_rate must be between 0 and 1 (exclusive)"); return 0; } 0 56 56
if (!(fp_rate > 0.0 && fp_rate < 1.0)) { CBF_ERR("fp_rate must be between 0 and 1 (exclusive)"); return 0; } 0 0 0
621  
622 /* k = round(-log2(fp_rate)) clamped to [1, 32] */
623 56 long kl = lround(-log2(fp_rate));
624 56 ▶ if (kl < CBF_MIN_K) kl = CBF_MIN_K;
Branch: 1 branch
BranchTrueFalseTotal
if (kl < CBF_MIN_K) kl = CBF_MIN_K; 0 56 56
625 56 ▶ if (kl > CBF_MAX_K) kl = CBF_MAX_K;
Branch: 1 branch
BranchTrueFalseTotal
if (kl > CBF_MAX_K) kl = CBF_MAX_K; 0 56 56
626 56 uint32_t k = (uint32_t)kl;
627  
628 /* m_opt = ceil(capacity * k / ln2); reject if it would exceed the counter-
629 * array cap (otherwise the filter would be silently undersized -> fp_rate
630 * broken); m_ctr = next_pow2(m_opt), floor CBF_MIN_CTR. */
631 56 double m_opt_d = ceil((double)capacity * (double)k / M_LN2);
632 56 ▶ if (m_opt_d > (double)CBF_MAX_CTR) { CBF_ERR("capacity too large for the counter-array cap"); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (m_opt_d > (double)CBF_MAX_CTR) { CBF_ERR("capacity too large for the counter-array cap"); return 0; } 1 55 56
if (m_opt_d > (double)CBF_MAX_CTR) { CBF_ERR("capacity too large for the counter-array cap"); return 0; } 1 0 1
633 55 uint64_t m_ctr = cbf_next_pow2_u64((uint64_t)m_opt_d);
634  
635 55 *k_out = k;
636 55 *m_bits_out = m_ctr;
637 55 return 1;
638 }
639  
640 /* Securely obtain a fd for a path-backed segment: create it exclusively
641 * (O_CREAT|O_EXCL|O_NOFOLLOW at `mode`, default 0600 = owner-only), or, if it
642 * already exists, attach to it (O_RDWR|O_NOFOLLOW, no O_CREAT). O_EXCL blocks a
643 * pre-seeded or hard-linked file and O_NOFOLLOW a symlink swap, so a local
644 * attacker can no longer redirect or poison the backing store through the path.
645 * Cross-user sharing is opt-in via a wider `mode` (e.g. 0660); the caller still
646 * validates the file's contents via cbf_validate_header. */
647 20 static int cbf_secure_open(const char *path, mode_t mode, char *errbuf) {
648 20 ▶ for (int attempt = 0; attempt < 100; attempt++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int attempt = 0; attempt < 100; attempt++) { 20 0 20
649 20 int fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, mode);
650 20 ▶ if (fd >= 0) { (void)fchmod(fd, mode); return fd; } /* exact mode: umask narrowed the O_EXCL create */
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { (void)fchmod(fd, mode); return fd; } /* exact mode: umask narrowed the O_EXCL create */ 11 9 20
651 9 ▶ if (errno != EEXIST) { CBF_ERR("create %s: %s", path, strerror(errno)); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (errno != EEXIST) { CBF_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 9 9
if (errno != EEXIST) { CBF_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 0 0
652 9 fd = open(path, O_RDWR|O_NOFOLLOW|O_CLOEXEC);
653 9 ▶ if (fd >= 0) return fd;
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) return fd; 9 0 9
654 0 ▶ if (errno == ENOENT) continue; /* creator unlinked between our two opens; retry */
Branch: 1 branch
BranchTrueFalseTotal
if (errno == ENOENT) continue; /* creator unlinked between our two opens; retry */ 0 0 0
655 0 ▶ CBF_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */ 0 0 0
656 0 return -1;
657 }
658 0 ▶ CBF_ERR("open %s: create/attach kept racing", path);
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("open %s: create/attach kept racing", path); 0 0 0
659 0 return -1;
660 }
661  
662 /* True iff the whole file is zero -- what an abandoned mid-init
663 creator leaves. Lets recovery re-init only a provably-empty file, never
664 one that merely starts with a zero word. Cold path, so a byte scan is
665 fine. Read, not mapped: a read fault on a tmpfs hole allocates the page. */
666 2 static int cbf_file_is_zero(int fd, uint64_t size) {
667 char buf[16384];
668 5 ▶ for (uint64_t off = 0; off < size; ) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t off = 0; off < size; ) { 4 1 5
669 4 ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
670 4 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 4 4
671 49923 ▶ for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0;
Branch: 2 branches
BranchTrueFalseTotal
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 1 49919 49920
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 49920 3 49923
672 3 off += (uint64_t)n;
673 }
674 1 return 1;
675 }
676  
677 /* Opt-in (DATA_COUNTINGBLOOMFILTER_SHARED_SPARSE=0): reserving commits memory this module otherwise fills lazily. */
678 14 static int cbf_reserve(int fd, uint64_t size) {
679 14 const char *sp = getenv("DATA_COUNTINGBLOOMFILTER_SHARED_SPARSE");
680 14 ▶ if (!sp || strcmp(sp, "0")) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!sp || strcmp(sp, "0")) return 0; 0 14 14
if (!sp || strcmp(sp, "0")) return 0; 0 0 0
681 /* Before Linux 6.11 tmpfs gives up at any pending signal and undoes the allocation, so a
682 * periodic one could keep it from ever completing; SIGSTOP cannot be blocked. */
683 sigset_t all, old;
684 0 sigfillset(&all);
685 0 sigprocmask(SIG_BLOCK, &all, &old);
686 int e;
687 0 ▶ do e = posix_fallocate(fd, 0, (off_t)size); while (e == EINTR);
Branch: 1 branch
BranchTrueFalseTotal
do e = posix_fallocate(fd, 0, (off_t)size); while (e == EINTR); 0 0 0
688 0 sigprocmask(SIG_SETMASK, &old, NULL);
689 0 ▶ if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
690 0 errno = e;
691 0 return -1;
692 }
693  
694 54 static CbfHandle *cbf_create(const char *path, uint64_t capacity, double fp_rate, mode_t mode, char *errbuf) {
695 uint32_t k;
696 uint64_t m_ctr;
697 54 ▶ if (!cbf_validate_create_args(capacity, fp_rate, &k, &m_ctr, errbuf)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_validate_create_args(capacity, fp_rate, &k, &m_ctr, errbuf)) return NULL; 1 53 54
698  
699 53 uint64_t total = cbf_total_size(m_ctr);
700 53 int anonymous = (path == NULL);
701 53 int fd = -1;
702 size_t map_size;
703 void *base;
704  
705 53 ▶ if (anonymous) {
Branch: 1 branch
BranchTrueFalseTotal
if (anonymous) { 33 20 53
706 33 map_size = (size_t)total;
707 33 base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
708 33 ▶ if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 33 33
if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 0 0
709 } else {
710 20 fd = cbf_secure_open(path, mode, errbuf);
711 29 ▶ if (fd < 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return NULL; 0 20 20
712 20 ▶ if (flock(fd, LOCK_EX) < 0) { CBF_ERR("flock: %s", strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (flock(fd, LOCK_EX) < 0) { CBF_ERR("flock: %s", strerror(errno)); close(fd); return NULL; } 0 20 20
if (flock(fd, LOCK_EX) < 0) { CBF_ERR("flock: %s", strerror(errno)); close(fd); return NULL; } 0 0 0
713 struct stat st;
714 20 ▶ if (fstat(fd, &st) < 0) { CBF_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { CBF_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; } 0 20 20
if (fstat(fd, &st) < 0) { CBF_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; } 0 0 0
715 20 int is_new = (st.st_size == 0);
716 20 ▶ if (!is_new && (uint64_t)st.st_size < sizeof(CbfHeader)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!is_new && (uint64_t)st.st_size < sizeof(CbfHeader)) { 9 11 20
if (!is_new && (uint64_t)st.st_size < sizeof(CbfHeader)) { 1 8 9
717 1 ▶ CBF_ERR("%s: file too small (%lld)", path, (long long)st.st_size);
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: file too small (%lld)", path, (long long)st.st_size); 1 0 1
718 1 flock(fd, LOCK_UN); close(fd); return NULL;
719 }
720 19 ▶ if (is_new && (st.st_uid != geteuid() || fchmod(fd, mode) < 0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (is_new && (st.st_uid != geteuid() || fchmod(fd, mode) < 0)) { 11 8 19
if (is_new && (st.st_uid != geteuid() || fchmod(fd, mode) < 0)) { 11 0 11
if (is_new && (st.st_uid != geteuid() || fchmod(fd, mode) < 0)) { 0 11 11
721 0 ▶ CBF_ERR("%s: refusing to initialize file not owned by us", path);
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: refusing to initialize file not owned by us", path); 0 0 0
722 0 flock(fd, LOCK_UN); close(fd); return NULL;
723 }
724 19 ▶ if (is_new && ftruncate(fd, (off_t)total) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_new && ftruncate(fd, (off_t)total) < 0) { 11 8 19
if (is_new && ftruncate(fd, (off_t)total) < 0) { 0 11 11
725 0 ▶ CBF_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; 0 0 0
726 }
727 19 ▶ if (is_new && cbf_reserve(fd, total) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_new && cbf_reserve(fd, total) < 0) { 11 8 19
if (is_new && cbf_reserve(fd, total) < 0) { 0 11 11
728 0 ▶ CBF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno)); 0 0 0
729 0 if (ftruncate(fd, 0) < 0) { /* best effort */ }
730 0 flock(fd, LOCK_UN); close(fd); return NULL;
731 }
732 19 ▶ map_size = is_new ? (size_t)total : (size_t)st.st_size;
Branch: 1 branch
BranchTrueFalseTotal
map_size = is_new ? (size_t)total : (size_t)st.st_size; 8 11 19
733 19 base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
734 19 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 19 19
735 0 ▶ CBF_ERR("mmap: %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("mmap: %s", strerror(errno)); 0 0 0
736 0 ▶ if (is_new && ftruncate(fd, 0) < 0) { /* best effort */ }
Branch: 1 branch
BranchTrueFalseTotal
if (is_new && ftruncate(fd, 0) < 0) { /* best effort */ } 0 0 0
737 0 flock(fd, LOCK_UN); close(fd); return NULL;
738 }
739 19 ▶ if (!is_new) {
Branch: 1 branch
BranchTrueFalseTotal
if (!is_new) { 8 11 19
740 8 ▶ if (!cbf_validate_header((CbfHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_validate_header((CbfHeader *)base, (uint64_t)st.st_size)) { 4 4 8
741 /* Recover an abandoned mid-init file: a creator killed
742 * between the ftruncate and the header init leaves a
743 * full-size, all-zero (magic==0) file that would brick every
744 * future open of this path. Re-initialize ONLY when it is
745 * exactly our size, still uninitialized, and owned by us;
746 * anything else still errors. */
747 4 ▶ if (((CbfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total
Branch: 2 branches
BranchTrueFalseTotal
if (((CbfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 3 1 4
if (((CbfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 2 1 3
748 2 ▶ && st.st_uid == geteuid() && cbf_file_is_zero(fd, map_size)) {
Branch: 2 branches
BranchTrueFalseTotal
&& st.st_uid == geteuid() && cbf_file_is_zero(fd, map_size)) { 2 0 2
&& st.st_uid == geteuid() && cbf_file_is_zero(fd, map_size)) { 1 1 2
749 1 ▶ if (fchmod(fd, mode) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fchmod(fd, mode) < 0) { 0 1 1
750 0 ▶ CBF_ERR("%s: fchmod: %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: fchmod: %s", path, strerror(errno)); 0 0 0
751 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
752 }
753 1 ▶ if (cbf_reserve(fd, total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cbf_reserve(fd, total) < 0) { 0 1 1
754 0 ▶ CBF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno)); 0 0 0
755 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
756 }
757 1 cbf_init_header(base, k, m_ctr, capacity, fp_rate, total);
758 1 flock(fd, LOCK_UN); close(fd);
759 1 return cbf_setup(base, map_size, path, -1);
760 }
761 3 ▶ if (((CbfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total
Branch: 2 branches
BranchTrueFalseTotal
if (((CbfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 2 1 3
if (((CbfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 1 1 2
762 1 ▶ && st.st_uid == geteuid()) {
Branch: 1 branch
BranchTrueFalseTotal
&& st.st_uid == geteuid()) { 1 0 1
763 1 ▶ CBF_ERR("%s: incomplete counting Bloom filter file left by an interrupted create; remove it and retry", path);
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: incomplete counting Bloom filter file left by an interrupted create; remove it and retry", path); 1 0 1
764 1 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
765 }
766 2 ▶ CBF_ERR("invalid counting Bloom filter file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("invalid counting Bloom filter file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL; 2 0 2
767 }
768 4 ▶ if (__atomic_load_n(&((CbfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&((CbfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) { 1 3 4
769 1 ▶ CBF_ERR("%s is frozen (read-only); open it with new_readonly", path);
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s is frozen (read-only); open it with new_readonly", path); 1 0 1
770 1 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
771 }
772 3 flock(fd, LOCK_UN); close(fd);
773 3 return cbf_setup(base, map_size, path, -1);
774 }
775 }
776 44 cbf_init_header(base, k, m_ctr, capacity, fp_rate, total);
777 44 ▶ if (fd >= 0) { flock(fd, LOCK_UN); close(fd); }
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { flock(fd, LOCK_UN); close(fd); } 11 33 44
778 44 return cbf_setup(base, map_size, path, -1);
779 }
780  
781 2 static CbfHandle *cbf_create_memfd(const char *name, uint64_t capacity, double fp_rate, char *errbuf) {
782 uint32_t k;
783 uint64_t m_ctr;
784 2 ▶ if (!cbf_validate_create_args(capacity, fp_rate, &k, &m_ctr, errbuf)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_validate_create_args(capacity, fp_rate, &k, &m_ctr, errbuf)) return NULL; 0 2 2
785  
786 2 uint64_t total = cbf_total_size(m_ctr);
787 2 ▶ int fd = memfd_create(name ? name : "bloom", MFD_CLOEXEC | MFD_ALLOW_SEALING);
Branch: 1 branch
BranchTrueFalseTotal
int fd = memfd_create(name ? name : "bloom", MFD_CLOEXEC | MFD_ALLOW_SEALING); 1 1 2
788 2 ▶ if (fd < 0) { CBF_ERR("memfd_create: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0) { CBF_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 2 2
if (fd < 0) { CBF_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 0 0
789 2 ▶ if (ftruncate(fd, (off_t)total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total) < 0) { 0 2 2
790 0 ▶ CBF_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL; 0 0 0
791 }
792 2 ▶ if (cbf_reserve(fd, total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cbf_reserve(fd, total) < 0) { 0 2 2
793 0 ▶ CBF_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total, strerror(errno)); 0 0 0
794 0 close(fd); return NULL;
795 }
796 2 (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
797 2 void *base = mmap(NULL, (size_t)total, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
798 2 ▶ if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; } 0 2 2
if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; } 0 0 0
799 2 cbf_init_header(base, k, m_ctr, capacity, fp_rate, total);
800 2 return cbf_setup(base, (size_t)total, NULL, fd);
801 }
802  
803 2 static CbfHandle *cbf_open_fd(int fd, char *errbuf) {
804 2 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 2 0 2
805 struct stat st;
806 2 ▶ if (fstat(fd, &st) < 0) { CBF_ERR("fstat: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { CBF_ERR("fstat: %s", strerror(errno)); return NULL; } 0 2 2
if (fstat(fd, &st) < 0) { CBF_ERR("fstat: %s", strerror(errno)); return NULL; } 0 0 0
807 2 ▶ if ((uint64_t)st.st_size < sizeof(CbfHeader)) { CBF_ERR("too small"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(CbfHeader)) { CBF_ERR("too small"); return NULL; } 1 1 2
if ((uint64_t)st.st_size < sizeof(CbfHeader)) { CBF_ERR("too small"); return NULL; } 1 0 1
808 /* before mmap: a creator may truncate the file until it has set magic */
809 uint32_t magic;
810 1 ▶ if (pread(fd, &magic, sizeof magic, offsetof(CbfHeader, magic)) != (ssize_t)sizeof magic || magic != CBF_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(CbfHeader, magic)) != (ssize_t)sizeof magic || magic != CBF_MAGIC) { 1 0 1
if (pread(fd, &magic, sizeof magic, offsetof(CbfHeader, magic)) != (ssize_t)sizeof magic || magic != CBF_MAGIC) { 0 1 1
811 0 ▶ CBF_ERR("invalid counting Bloom filter table"); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("invalid counting Bloom filter table"); return NULL; 0 0 0
812 }
813 1 size_t ms = (size_t)st.st_size;
814 1 void *base = mmap(NULL, ms, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
815 1 ▶ if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 1 1
if (base == MAP_FAILED) { CBF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 0 0
816 1 ▶ if (!cbf_validate_header((CbfHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_validate_header((CbfHeader *)base, (uint64_t)st.st_size)) { 0 1 1
817 0 ▶ CBF_ERR("invalid counting Bloom filter table"); munmap(base, ms); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("invalid counting Bloom filter table"); munmap(base, ms); return NULL; 0 0 0
818 }
819 1 ▶ if (__atomic_load_n(&((CbfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&((CbfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) { 0 1 1
820 0 ▶ CBF_ERR("this counting Bloom filter is frozen (read-only); open it with new_readonly");
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("this counting Bloom filter is frozen (read-only); open it with new_readonly"); 0 0 0
821 0 munmap(base, ms); return NULL;
822 }
823 1 int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
824 1 ▶ if (myfd < 0) { CBF_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (myfd < 0) { CBF_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; } 0 1 1
if (myfd < 0) { CBF_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; } 0 0 0
825 1 return cbf_setup(base, ms, NULL, myfd);
826 }
827  
828 55 static void cbf_destroy(CbfHandle *h) {
829 55 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 55 55
830 /* Release our reader slot on clean teardown (else short-lived-reader churn
831 * exhausts the slot table); skip if a read lock is still held (rdepth>0). */
832 55 ▶ if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid &&
Branch: 3 branches
BranchTrueFalseTotal
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 55 0 55
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 39 16 55
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 39 0 39
833 39 ▶ h->cached_fork_gen == __atomic_load_n(&cbf_fork_gen, __ATOMIC_RELAXED) &&
Branch: 1 branch
BranchTrueFalseTotal
h->cached_fork_gen == __atomic_load_n(&cbf_fork_gen, __ATOMIC_RELAXED) && 39 0 39
834 39 ▶ __atomic_load_n(&h->reader_slots[h->my_slot_idx].rdepth, __ATOMIC_ACQUIRE) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
__atomic_load_n(&h->reader_slots[h->my_slot_idx].rdepth, __ATOMIC_ACQUIRE) == 0) { 39 0 39
835 /* Clear our occ bit BEFORE freeing the slot: we still own the pid so no
836 * claimant can take the slot mid-clear, and rdepth==0 so no writer needs
837 * to see us. (A crash skips this -> the bit is reclaimed lazily by a
838 * writer scan / re-claim, same as the pid.) */
839 39 cbf_occ_clear(h, h->my_slot_idx);
840 39 uint32_t expected = h->cached_pid;
841 39 __atomic_compare_exchange_n(&h->reader_slots[h->my_slot_idx].pid,
842 &expected, 0, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
843 }
844 55 ▶ if (h->backing_fd >= 0) close(h->backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->backing_fd >= 0) close(h->backing_fd); 3 52 55
845 55 ▶ if (h->base) munmap(h->base, h->mmap_size);
Branch: 1 branch
BranchTrueFalseTotal
if (h->base) munmap(h->base, h->mmap_size); 55 0 55
846 55 free(h->path);
847 55 free(h);
848 }
849  
850 4 static inline int cbf_msync(CbfHandle *h) {
851 4 ▶ if (!h || !h->base) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!h || !h->base) return 0; 4 0 4
if (!h || !h->base) return 0; 0 4 4
852 4 return msync(h->base, h->mmap_size, MS_SYNC);
853 }
854  
855 /* Open a FROZEN (sealed) file read-only: O_RDONLY + PROT_READ, no lock ever.
856 * A sealed file is immutable and no read path writes the mapping, so queries
857 * take no reader-slot / rwlock traffic and any number of processes can share
858 * one PROT_READ mapping (same architecture; the magic rejects a wrong-endian
859 * file). */
860 6 static CbfHandle *cbf_open_readonly(const char *path, char *errbuf) {
861 6 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 6 0 6
862 6 int fd = open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC);
863 6 ▶ if (fd < 0) { CBF_ERR("open %s: %s", path, strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0) { CBF_ERR("open %s: %s", path, strerror(errno)); return NULL; } 1 5 6
if (fd < 0) { CBF_ERR("open %s: %s", path, strerror(errno)); return NULL; } 1 0 1
864 struct stat st;
865 5 ▶ if (fstat(fd, &st) < 0) { CBF_ERR("fstat %s: %s", path, strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { CBF_ERR("fstat %s: %s", path, strerror(errno)); close(fd); return NULL; } 0 5 5
if (fstat(fd, &st) < 0) { CBF_ERR("fstat %s: %s", path, strerror(errno)); close(fd); return NULL; } 0 0 0
866 5 ▶ if ((uint64_t)st.st_size < sizeof(CbfHeader)) { CBF_ERR("%s: file too small", path); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(CbfHeader)) { CBF_ERR("%s: file too small", path); close(fd); return NULL; } 0 5 5
if ((uint64_t)st.st_size < sizeof(CbfHeader)) { CBF_ERR("%s: file too small", path); close(fd); return NULL; } 0 0 0
867 /* before mmap: a creator may truncate the file until it has set magic */
868 uint32_t magic;
869 5 ▶ if (pread(fd, &magic, sizeof magic, offsetof(CbfHeader, magic)) != (ssize_t)sizeof magic || magic != CBF_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(CbfHeader, magic)) != (ssize_t)sizeof magic || magic != CBF_MAGIC) { 5 0 5
if (pread(fd, &magic, sizeof magic, offsetof(CbfHeader, magic)) != (ssize_t)sizeof magic || magic != CBF_MAGIC) { 0 5 5
870 0 ▶ CBF_ERR("%s: invalid counting Bloom filter file", path); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: invalid counting Bloom filter file", path); close(fd); return NULL; 0 0 0
871 }
872 5 size_t ms = (size_t)st.st_size;
873 5 void *base = mmap(NULL, ms, PROT_READ, MAP_SHARED, fd, 0);
874 5 close(fd); /* the mapping keeps the file; a read-only view needs no fd (no msync/ftruncate) */
875 5 ▶ if (base == MAP_FAILED) { CBF_ERR("mmap %s: %s", path, strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CBF_ERR("mmap %s: %s", path, strerror(errno)); return NULL; } 0 5 5
if (base == MAP_FAILED) { CBF_ERR("mmap %s: %s", path, strerror(errno)); return NULL; } 0 0 0
876 5 ▶ if (!cbf_validate_header((CbfHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cbf_validate_header((CbfHeader *)base, (uint64_t)st.st_size)) { 0 5 5
877 0 ▶ CBF_ERR("%s: invalid counting Bloom filter file", path); munmap(base, ms); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s: invalid counting Bloom filter file", path); munmap(base, ms); return NULL; 0 0 0
878 }
879 5 ▶ if (!__atomic_load_n(&((CbfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!__atomic_load_n(&((CbfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) { 1 4 5
880 1 ▶ CBF_ERR("%s is not frozen: call ->freeze on the producer before opening read-only", path);
Branch: 1 branch
BranchTrueFalseTotal
CBF_ERR("%s is not frozen: call ->freeze on the producer before opening read-only", path); 1 0 1
881 1 munmap(base, ms); return NULL;
882 }
883 4 CbfHandle *h = cbf_setup(base, ms, path, -1); /* munmaps on OOM */
884 4 ▶ if (!h) { CBF_ERR("out of memory"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (!h) { CBF_ERR("out of memory"); return NULL; } 0 4 4
if (!h) { CBF_ERR("out of memory"); return NULL; } 0 0 0
885 4 h->readonly = 1;
886 4 return h;
887 }
888  
889 /* Seal a filter: make it permanently immutable so it can be shipped and opened
890 * read-only. Takes the write lock so no add/remove is in flight, publishes the
891 * seal, then flushes it (file/memfd-backed). Afterwards every mutator croaks
892 * and a read-write reopen is refused. */
893 2 static int cbf_freeze(CbfHandle *h) {
894 2 cbf_rwlock_wrlock(h);
895 2 __atomic_store_n(&h->hdr->sealed, 1, __ATOMIC_RELEASE);
896 2 cbf_rwlock_wrunlock(h);
897 2 ▶ if (h->path || h->backing_fd >= 0) return cbf_msync(h); /* durability for file/memfd-backed */
Branch: 2 branches
BranchTrueFalseTotal
if (h->path || h->backing_fd >= 0) return cbf_msync(h); /* durability for file/memfd-backed */ 0 2 2
if (h->path || h->backing_fd >= 0) return cbf_msync(h); /* durability for file/memfd-backed */ 0 0 0
898 0 return 0; /* anonymous: the seal lives in shared memory (visible to forks); nothing to flush */
899 }
900  
901 /* ================================================================
902 * Counting Bloom filter operations (callers hold the lock) -- double hashing
903 * (Kirsch-Mitzenmacher): one XXH3-128 hash drives all k probes, each of which
904 * indexes a 4-bit saturating counter. A probe idx reaches counter byte
905 * (idx >> 1); the highest a masked probe can reach is (mask >> 1).
906 * ================================================================ */
907  
908 76762 static inline void cbf_indices(CbfHandle *h, const void *item, size_t len,
909 uint64_t *h1, uint64_t *h2) {
910 (void)h;
911 76762 XXH128_hash_t hh = XXH3_128bits(item, len);
912 76762 *h1 = hh.low64;
913 76762 *h2 = hh.high64 | 1ULL; /* force odd so the k probes spread over the pow2 table */
914 76762 }
915  
916 /* increment k counters (saturating at 15); return 1 if the item was probably NEW
917 * (at least one counter was 0 before), else 0. If two of the k probes alias the
918 * same counter it is incremented once per probe -- add/remove stay symmetric. */
919 41875 static int cbf_add_locked(CbfHandle *h, const void *item, size_t len) {
920 uint64_t h1, h2;
921 41875 cbf_indices(h, item, len, &h1, &h2);
922 41875 uint64_t mask = h->hdr->m_mask;
923 41875 uint32_t k = h->k;
924 41875 uint8_t *c = cbf_counters(h);
925 /* Layer B: the highest counter BYTE any masked probe reaches is (mask >> 1).
926 * m_mask lives in the shared segment, so a peer sharing the backing file
927 * could widen it past the real counter array after validation; bound it
928 * against the mapping. For a valid filter (mask == m_ctr-1) this is
929 * (m_ctr-1)/2 < m_ctr/2 bytes, so the branch is never taken. */
930 41875 ▶ if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0; 0 41875 41875
931 41875 int was_new = 0;
932 346970 ▶ for (uint32_t i = 0; i < k; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < k; i++) { 305095 41875 346970
933 305095 uint64_t idx = (h1 + (uint64_t)i * h2) & mask;
934 305095 uint32_t v = cbf_ctr_get(c, idx);
935 305095 ▶ if (v == 0) was_new = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (v == 0) was_new = 1; 248905 56190 305095
936 305095 ▶ if (v < CBF_CTR_MAX) cbf_ctr_set(c, idx, v + 1); /* saturate at 15 */
Branch: 1 branch
BranchTrueFalseTotal
if (v < CBF_CTR_MAX) cbf_ctr_set(c, idx, v + 1); /* saturate at 15 */ 305060 35 305095
937 }
938 41875 return was_new;
939 }
940  
941 /* return 1 if ALL k counters are > 0 (probably present), else 0 */
942 29338 static int cbf_contains_locked(CbfHandle *h, const void *item, size_t len) {
943 uint64_t h1, h2;
944 29338 cbf_indices(h, item, len, &h1, &h2);
945 29338 uint64_t mask = h->hdr->m_mask;
946 29338 uint32_t k = h->k;
947 29338 const uint8_t *c = cbf_counters(h);
948 /* Layer B: bound the highest reachable byte against the mapping (see
949 * cbf_add_locked). A corrupt mask cannot confirm membership -> "not
950 * present" is the safe answer; never-taken for a valid filter. */
951 29338 ▶ if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0; 0 29338 29338
952 167857 ▶ for (uint32_t i = 0; i < k; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < k; i++) { 149504 18353 167857
953 149504 uint64_t idx = (h1 + (uint64_t)i * h2) & mask;
954 149504 ▶ if (cbf_ctr_get(c, idx) == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (cbf_ctr_get(c, idx) == 0) return 0; 10985 138519 149504
955 }
956 18353 return 1;
957 }
958  
959 /* estimated occurrence count of (item,len): the MIN of its k counters (0..15).
960 * Collisions can only raise a counter, so min never under-counts a present item
961 * (it is an upper estimate); saturates at CBF_CTR_MAX. (caller holds a lock) */
962 2017 static int cbf_count_of_locked(CbfHandle *h, const void *item, size_t len) {
963 uint64_t h1, h2;
964 2017 cbf_indices(h, item, len, &h1, &h2);
965 2017 uint64_t mask = h->hdr->m_mask;
966 2017 uint32_t k = h->k;
967 2017 const uint8_t *c = cbf_counters(h);
968 2017 ▶ if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0; 0 2017 2017
969 2017 uint32_t mn = CBF_CTR_MAX;
970 22103 ▶ for (uint32_t i = 0; i < k; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < k; i++) { 20089 2014 22103
971 20089 uint64_t idx = (h1 + (uint64_t)i * h2) & mask;
972 20089 uint32_t v = cbf_ctr_get(c, idx);
973 20089 ▶ if (v < mn) mn = v;
Branch: 1 branch
BranchTrueFalseTotal
if (v < mn) mn = v; 2083 18006 20089
974 20089 ▶ if (mn == 0) return 0; /* absent -> short-circuit */
Branch: 1 branch
BranchTrueFalseTotal
if (mn == 0) return 0; /* absent -> short-circuit */ 3 20086 20089
975 }
976 2014 return (int)mn;
977 }
978  
979 /* remove one occurrence of (item,len): if present (all k counters > 0),
980 * decrement each (a saturated 15 stays stuck; never drops below 0) and return 1;
981 * if not present, change nothing and return 0.
982 * CAVEAT: like every counting Bloom filter, decrementing counters for an item
983 * never added -- or one whose k probes collide with present items -- can push a
984 * shared counter to 0 and cause a false negative for another item. Only remove
985 * items you actually added, and remove an item as many times as it was added. */
986 3532 static int cbf_remove_locked(CbfHandle *h, const void *item, size_t len) {
987 uint64_t h1, h2;
988 3532 cbf_indices(h, item, len, &h1, &h2);
989 3532 uint64_t mask = h->hdr->m_mask;
990 3532 uint32_t k = h->k;
991 3532 uint8_t *c = cbf_counters(h);
992 3532 ▶ if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if ((mask >> 1) >= cbf_ctr_bytes_max(h)) return 0; 0 3532 3532
993 /* present-check FIRST: never decrement unless all k counters are > 0, so a
994 * remove of an absent item is a true no-op (no false negatives introduced) */
995 31212 ▶ for (uint32_t i = 0; i < k; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < k; i++) { 27682 3530 31212
996 27682 uint64_t idx = (h1 + (uint64_t)i * h2) & mask;
997 27682 ▶ if (cbf_ctr_get(c, idx) == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (cbf_ctr_get(c, idx) == 0) return 0; 2 27680 27682
998 }
999 31210 ▶ for (uint32_t i = 0; i < k; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < k; i++) { 27680 3530 31210
1000 27680 uint64_t idx = (h1 + (uint64_t)i * h2) & mask;
1001 27680 uint32_t v = cbf_ctr_get(c, idx);
1002 27680 ▶ if (v > 0 && v < CBF_CTR_MAX) cbf_ctr_set(c, idx, v - 1); /* saturated stays stuck */
Branch: 2 branches
BranchTrueFalseTotal
if (v > 0 && v < CBF_CTR_MAX) cbf_ctr_set(c, idx, v - 1); /* saturated stays stuck */ 27680 0 27680
if (v > 0 && v < CBF_CTR_MAX) cbf_ctr_set(c, idx, v - 1); /* saturated stays stuck */ 27533 147 27680
1003 }
1004 3530 return 1;
1005 }
1006  
1007 /* count nonzero counters across the whole array -- the counting analogue of a
1008 * Bloom popcount, used for the distinct-item estimate. (caller holds a lock) */
1009 11 static uint64_t cbf_nonzero_count_locked(CbfHandle *h) {
1010 11 const uint8_t *c = cbf_counters(h);
1011 11 uint64_t bytes = h->hdr->m_ctr / 2;
1012 11 uint64_t bytes_max = cbf_ctr_bytes_max(h); /* Layer B: clamp scan to the mapping */
1013 11 ▶ if (bytes > bytes_max) bytes = bytes_max;
Branch: 1 branch
BranchTrueFalseTotal
if (bytes > bytes_max) bytes = bytes_max; 0 11 11
1014 11 uint64_t n = 0;
1015 172043 ▶ for (uint64_t b = 0; b < bytes; b++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t b = 0; b < bytes; b++) { 172032 11 172043
1016 172032 uint8_t byte = c[b];
1017 172032 ▶ if (byte & 0x0F) n++;
Branch: 1 branch
BranchTrueFalseTotal
if (byte & 0x0F) n++; 33875 138157 172032
1018 172032 ▶ if (byte & 0xF0) n++;
Branch: 1 branch
BranchTrueFalseTotal
if (byte & 0xF0) n++; 33737 138295 172032
1019 }
1020 11 return n;
1021 }
1022  
1023 /* estimate the number of distinct items added, from a pre-computed nonzero-counter
1024 count X. n_est = -(m/k) * ln(1 - X/m); saturated -> capacity. (holds a lock) */
1025 11 static uint64_t cbf_count_from_nonzero(CbfHandle *h, uint64_t X) {
1026 11 uint64_t m_ctr = h->hdr->m_ctr;
1027 11 uint32_t k = h->k;
1028 11 ▶ if (X >= m_ctr) return h->hdr->capacity; /* saturated */
Branch: 1 branch
BranchTrueFalseTotal
if (X >= m_ctr) return h->hdr->capacity; /* saturated */ 0 11 11
1029 11 double n_est = -((double)m_ctr / (double)k) * log(1.0 - (double)X / (double)m_ctr);
1030 11 ▶ if (n_est < 0.0) n_est = 0.0;
Branch: 1 branch
BranchTrueFalseTotal
if (n_est < 0.0) n_est = 0.0; 0 11 11
1031 11 return (uint64_t)(n_est + 0.5);
1032 }
1033  
1034 /* estimate the number of distinct items added (scans the array). (holds a lock) */
1035 6 static uint64_t cbf_count_locked(CbfHandle *h) {
1036 6 return cbf_count_from_nonzero(h, cbf_nonzero_count_locked(h));
1037 }
1038  
1039 /* merge src counters into dst (caller guarantees equal m_ctr): counter-wise
1040 * saturating add. src_bytes is how many counter bytes the src buffer holds. */
1041 6 static void cbf_merge_counters(CbfHandle *dst, const uint8_t *src, uint64_t src_bytes) {
1042 6 uint8_t *c = cbf_counters(dst);
1043 6 uint64_t bytes = dst->hdr->m_ctr / 2;
1044 6 uint64_t bytes_max = cbf_ctr_bytes_max(dst); /* Layer B: clamp writes to dst mapping */
1045 6 ▶ if (bytes > bytes_max) bytes = bytes_max;
Branch: 1 branch
BranchTrueFalseTotal
if (bytes > bytes_max) bytes = bytes_max; 0 6 6
1046 6 ▶ if (bytes > src_bytes) bytes = src_bytes; /* ...and reads to the src buffer */
Branch: 1 branch
BranchTrueFalseTotal
if (bytes > src_bytes) bytes = src_bytes; /* ...and reads to the src buffer */ 0 6 6
1047 98310 ▶ for (uint64_t b = 0; b < bytes; b++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t b = 0; b < bytes; b++) { 98304 6 98310
1048 98304 uint32_t lo = (uint32_t)(c[b] & 0x0F) + (uint32_t)(src[b] & 0x0F);
1049 98304 uint32_t hi = (uint32_t)((c[b] >> 4) & 0x0F) + (uint32_t)((src[b] >> 4) & 0x0F);
1050 98304 ▶ if (lo > CBF_CTR_MAX) lo = CBF_CTR_MAX; /* saturate each nibble at 15 */
Branch: 1 branch
BranchTrueFalseTotal
if (lo > CBF_CTR_MAX) lo = CBF_CTR_MAX; /* saturate each nibble at 15 */ 3 98301 98304
1051 98304 ▶ if (hi > CBF_CTR_MAX) hi = CBF_CTR_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if (hi > CBF_CTR_MAX) hi = CBF_CTR_MAX; 4 98300 98304
1052 98304 c[b] = (uint8_t)(lo | (hi << 4));
1053 }
1054 6 }
1055  
1056 /* reset all counters to 0 (caller holds the write lock) */
1057 1 static inline void cbf_clear_locked(CbfHandle *h) {
1058 1 uint64_t bytes = h->hdr->m_ctr / 2;
1059 1 uint64_t bytes_max = cbf_ctr_bytes_max(h); /* Layer B: clamp memset to the mapping */
1060 1 ▶ if (bytes > bytes_max) bytes = bytes_max;
Branch: 1 branch
BranchTrueFalseTotal
if (bytes > bytes_max) bytes = bytes_max; 0 1 1
1061 1 memset(cbf_counters(h), 0, (size_t)bytes);
1062 1 }
1063  
1064 #endif /* CBF_H */
« xxhash.h ↑ Summary Shared.xs »