cuckoo.h

filter: Statementstmt 74.2% 392 / 528 Branchbran 49.3% 222 / 450 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 62.7% 614 / 978 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xxhash.h ↑ Summary Shared.xs »
1 /*
2 * cuckoo.h -- Shared-memory Cuckoo filter for Linux
3 *
4 * Approximate set membership WITH delete: tells you whether an item is
5 * "definitely not" or "probably" in the set, in a fixed amount of memory, with
6 * a tiny false-positive rate -- and unlike a Bloom filter it supports removal.
7 * Each item is hashed once (XXH3-128); a 16-bit fingerprint plus two candidate
8 * buckets (partial-key cuckoo hashing) drive a bucketed open-addressed table of
9 * CF_SLOTS fingerprint slots per bucket. The table lives in a shared mapping so
10 * several processes share one filter; a write-preferring futex rwlock with
11 * reader-slot dead-process recovery guards mutation. The filter has a bounded
12 * capacity: add returns false when the table is full, leaving the
13 * fingerprint table unchanged.
14 *
15 * Layout: Header -> reader_slots[1024] -> occ bitmap -> slots[num_buckets * CF_SLOTS]
16 */
17  
18 #ifndef CUCKOO_H
19 #define CUCKOO_H
20  
21 #include <stddef.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <time.h>
29 #include <limits.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <math.h>
33 #include <sys/mman.h>
34 #include <sys/stat.h>
35 #include <sys/file.h>
36 #include <sys/syscall.h>
37 #include <linux/futex.h>
38 #include <pthread.h>
39  
40 #define XXH_INLINE_ALL
41 #include "xxhash.h"
42  
43 #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
44 #error "cuckoo.h: requires little-endian architecture"
45 #endif
46  
47  
48 /* ================================================================
49 * Constants
50 * ================================================================ */
51  
52 #define CF_MAGIC 0x4B4F4F43U /* "COOK" (little-endian) */
53 #define CF_VERSION 2 /* 2: added the occupancy bitmap region (layout change) */
54 #define CF_ERR_BUFLEN (PATH_MAX + 256)
55 #define CF_READER_SLOTS 1024 /* max concurrent reader processes for dead-process recovery */
56 /* Occupancy bitmap: one bit per reader slot, set when a process claims a slot and
57 * cleared on clean release. A writer scans these CF_OCC_WORDS words to visit
58 * only OCCUPIED slots (O(words + live readers)) instead of all CF_READER_SLOTS. */
59 #define CF_OCC_WORDS (((CF_READER_SLOTS) + 63) / 64) /* 16 for 1024 slots */
60 #define CF_OCC_BYTES ((uint64_t)CF_OCC_WORDS * 8) /* 128 bytes */
61 #define CF_SLOTS 4 /* fingerprint slots per bucket */
62 #define CF_MAX_KICKS 500 /* cuckoo eviction bound before declaring the table full */
63 #define CF_MIN_BUCKETS 2 /* floor on the bucket count (power of two) */
64 #define CF_MAX_BUCKETS 0x4000000000ULL /* 2^38 buckets cap (2^38*4*2 = 2 TiB slot array) */
65  
66 #define CF_ERR(fmt, ...) do { if (errbuf) snprintf(errbuf, CF_ERR_BUFLEN, fmt, ##__VA_ARGS__); } while (0)
67  
68 /* ================================================================
69 * Structs
70 * ================================================================ */
71  
72 /* Per-process slot for dead-process recovery. In the reader-slots-only rwlock a
73 * reader's ENTIRE contribution to the shared lock is `rdepth` in its OWN slot --
74 * there is no separate shared reader counter to fall out of sync with it -- so a
75 * dead reader's contribution is exactly this one word, which a draining writer
76 * neutralises by clearing the slot's pid (the scan then ignores the slot). No
77 * orphaned counter can exist, so there is no quiescent force-reset and sustained
78 * readers cannot starve a writer. _rsv1/_rsv2 are kept only to preserve the
79 * 16-byte slot size across the already-released builds. */
80 typedef struct {
81 uint32_t pid; /* 0 = unclaimed */
82 uint32_t rdepth; /* read-locks THIS process currently holds (recursion-safe) */
83 uint32_t _rsv1; /* reserved (was waiters_parked); unused, kept for layout size */
84 uint32_t _rsv2; /* reserved (was writers_parked); unused, kept for layout size */
85 } CfReaderSlot;
86  
87 struct CfHeader {
88 uint32_t magic, version; /* 0,4 */
89 uint32_t _pad0; /* 8 */
90 uint32_t _pad1; /* 12 */
91 uint64_t num_buckets; /* 16 bucket count (power of two) */
92 uint64_t bucket_mask; /* 24 num_buckets - 1 (bucket index mask) */
93 uint64_t capacity; /* 32 configured item capacity (for stats) */
94 uint64_t count; /* 40 live fingerprint count (maintained on add/remove) */
95 uint64_t rng_state; /* 48 xorshift64 state for eviction victim choice */
96 uint64_t total_size; /* 56 */
97 uint64_t reader_slots_off; /* 64 */
98 uint64_t slots_off; /* 72 */
99 uint32_t wlock; /* 80 WRITER word ONLY: 0 (free) or WRITER_BIT|pid. NOT a reader count. */
100 uint32_t rwait; /* 84 parked-waiter hint (readers+writers blocked on wlock); over-count-safe */
101 uint32_t drain_seq; /* 88 futex bumped by a reader releasing under a draining writer (wakes it) */
102 uint32_t slotless_rdepth; /* 92 readers holding with no reader-slot (documented residual) */
103 uint64_t stat_ops; /* 96 */
104 uint8_t sealed; /* 104 0 = mutable, 1 = frozen (read-only; lock-free reads) */
105 uint8_t _pad[151]; /* 105..255 */
106 };
107 typedef struct CfHeader CfHeader;
108  
109 _Static_assert(sizeof(CfHeader) == 256, "CfHeader must be 256 bytes");
110  
111 /* ---- Process-local handle ---- */
112  
113 typedef struct CfHandle {
114 CfHeader *hdr;
115 CfReaderSlot *reader_slots; /* CF_READER_SLOTS entries */
116 uint64_t *occ; /* CF_OCC_WORDS-word slot-occupancy bitmap (trusted layout offset) */
117 void *base; /* mmap base */
118 size_t mmap_size;
119 char *path; /* backing file path (strdup'd) */
120 int backing_fd; /* memfd or reopened-fd to close on destroy, -1 for file/anon */
121 uint32_t my_slot_idx; /* UINT32_MAX if all slots taken (no recovery for this handle) */
122 uint32_t cached_pid; /* getpid() cached at last slot claim */
123 uint32_t cached_fork_gen; /* cf_fork_gen value at last slot claim */
124 uint32_t slotless_held; /* read-locks this process holds with no reader-slot */
125 int readonly; /* 1 = frozen O_RDONLY/PROT_READ view: lock-free reads, mutation croaks */
126 } CfHandle;
127  
128 /* ================================================================
129 * Futex-based write-preferring read-write lock (reader-slots-only)
130 * with dead-process recovery
131 *
132 * The reader count is NOT stored in a shared counter. It is DISTRIBUTED across
133 * per-process reader slots: each slot's `rdepth` is that process's entire
134 * contribution to the lock. A reader publishes its presence in its own slot and
135 * then re-checks the writer word; a writer publishes the writer word and then
136 * scans every slot until all live readers' rdepth reach 0. Sequentially-
137 * consistent store+load on each side (a Dekker handshake) gives mutual exclusion.
138 *
139 * Because a reader's whole contribution is ONE atomic word owned by ONE process,
140 * a crashed reader is recovered by clearing that one slot (CAS its pid to 0) --
141 * there is no second counter to strand, no orphaned +1, and therefore no
142 * quiescent force-reset. A reader killed anywhere in rdlock/rdunlock leaves at
143 * most `rdepth>0` in its dead slot, which the draining writer clears directly, so
144 * sustained read traffic can never starve a writer. Write-preference is inherent
145 * in the gate (new readers see wlock!=0 and yield), so there is no reader-count
146 * yield hack.
147 * ================================================================ */
148  
149 #define CF_RWLOCK_SPIN_LIMIT 32
150 #define CF_LOCK_TIMEOUT_SEC 2 /* FUTEX_WAIT timeout for stale-lock detection / drain re-scan */
151  
152 0 static inline void cf_rwlock_spin_pause(void) {
153 #if defined(__x86_64__) || defined(__i386__)
154 0 __asm__ volatile("pause" ::: "memory");
155 #elif defined(__aarch64__)
156 __asm__ volatile("yield" ::: "memory");
157 #else
158 __asm__ volatile("" ::: "memory");
159 #endif
160 0 }
161  
162 /* Writer word encoding: WRITER_BIT|pid when write-locked, 0 when free. */
163 #define CF_RWLOCK_WRITER_BIT 0x80000000U
164 #define CF_RWLOCK_PID_MASK 0x7FFFFFFFU
165 #define CF_RWLOCK_WR(pid) (CF_RWLOCK_WRITER_BIT | ((uint32_t)(pid) & CF_RWLOCK_PID_MASK))
166  
167 /* A zombie (dead but not yet reaped) still answers kill(pid,0) as alive, so a
168 * process that crashed while holding the lock and lingers unreaped would never
169 * be recovered. Treat /proc/<pid>/stat state 'Z' as dead. Linux-only (as is
170 * this module); if /proc is unreadable we fall back to "alive" (safe: we never
171 * force-recover a possibly-live holder). */
172 0 static inline int cf_pid_is_zombie(uint32_t pid) {
173 char path[32], buf[256];
174 0 snprintf(path, sizeof(path), "/proc/%u/stat", (unsigned)pid);
175 0 int fd = open(path, O_RDONLY | O_CLOEXEC);
176 0 ▶ if (fd < 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return 0; 0 0 0
177 0 ssize_t n = read(fd, buf, sizeof(buf) - 1);
178 0 close(fd);
179 0 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 0 0
180 0 buf[n] = '\0';
181 /* "pid (comm) state ..."; comm may contain ')', so scan to the last one. */
182 0 char *rp = strrchr(buf, ')');
183 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
184 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
185 }
186 /* 1 if alive or unknown, 0 if definitely dead. Cannot detect PID reuse: a
187 * recycled PID reports "alive" and the slot is not reclaimed until that
188 * process exits. See "Crash Safety" in the POD. */
189 2 static inline int cf_pid_alive(uint32_t pid) {
190 2 ▶ 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 2 2
191 2 ▶ 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 */ 2 0 2
if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */ 2 0 2
192 0 return !cf_pid_is_zombie(pid); /* kill() also succeeds for a zombie -> treat as dead */
193 }
194  
195 /* Force-recover a stale WRITE lock left by a dead writer (held or mid-drain).
196 * CAS to OUR pid to hold the lock while fixing shared state, then release.
197 * Using our pid (not a bare WRITER_BIT sentinel) means a subsequent recovering
198 * process can detect and re-recover if we crash mid-recovery. */
199 static inline __attribute__((always_inline)) void cf_rwlock_drain_readers(CfHandle *h);
200 static void cf_recount(CfHandle *h);
201  
202 2 static inline void cf_recover_stale_lock(CfHandle *h, uint32_t observed_wlock) {
203 2 CfHeader *hdr = h->hdr;
204 2 uint32_t mypid = CF_RWLOCK_WR((uint32_t)getpid());
205 2 ▶ if (!__atomic_compare_exchange_n(&hdr->wlock, &observed_wlock,
Branch: 1 branch
BranchTrueFalseTotal
if (!__atomic_compare_exchange_n(&hdr->wlock, &observed_wlock, 0 2 2
206 mypid, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED))
207 0 return;
208 /* A dead writer may have stored a slot without updating count, or vice versa. */
209 2 ▶ if (!__atomic_load_n(&hdr->sealed, __ATOMIC_ACQUIRE)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!__atomic_load_n(&hdr->sealed, __ATOMIC_ACQUIRE)) { 2 0 2
210 cf_rwlock_drain_readers(h);
211 2 cf_recount(h);
212 }
213 2 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_RELEASE);
214 2 ▶ if (__atomic_load_n(&hdr->rwait, __ATOMIC_RELAXED) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->rwait, __ATOMIC_RELAXED) > 0) 0 2 2
215 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
216 }
217  
218 static const struct timespec cf_lock_timeout = { CF_LOCK_TIMEOUT_SEC, 0 };
219  
220 /* Process-global fork-generation counter. Incremented in the pthread_atfork
221 * child callback so every open handle detects a fork transition on the next
222 * lock call without paying a getpid() syscall on the hot path. */
223 static uint32_t cf_fork_gen = 1;
224 static pthread_once_t cf_atfork_once = PTHREAD_ONCE_INIT;
225 0 static void cf_on_fork_child(void) {
226 0 __atomic_add_fetch(&cf_fork_gen, 1, __ATOMIC_RELAXED);
227 0 }
228 6 static void cf_atfork_init(void) {
229 6 pthread_atfork(NULL, NULL, cf_on_fork_child);
230 6 }
231  
232 /* Occupancy bitmap: set a slot's bit when it is claimed, clear it on clean
233 * release. SEQ_CST so a set bit is ordered before the slot's rdepth can go
234 * non-zero (bit set in claim, which precedes any rdlock), letting a writer's
235 * SEQ_CST bitmap scan never miss a slot a committed reader holds. */
236 30 static inline void cf_occ_set(CfHandle *h, uint32_t s) {
237 30 __atomic_fetch_or(&h->occ[s >> 6], (uint64_t)1 << (s & 63), __ATOMIC_SEQ_CST);
238 30 }
239 30 static inline void cf_occ_clear(CfHandle *h, uint32_t s) {
240 30 __atomic_fetch_and(&h->occ[s >> 6], ~((uint64_t)1 << (s & 63)), __ATOMIC_SEQ_CST);
241 30 }
242  
243 /* Ensure this process owns a reader slot. Called from the lock helpers so that
244 * fork()'d children pick up their own slot lazily instead of sharing the
245 * parent's. Hot-path is a single relaxed load + compare; only on a
246 * fork-generation mismatch do we touch getpid() and scan slots. */
247 52743 static inline void cf_claim_reader_slot(CfHandle *h) {
248 52743 uint32_t cur_gen = __atomic_load_n(&cf_fork_gen, __ATOMIC_RELAXED);
249 52743 ▶ 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)) 52713 30 52743
if (__builtin_expect(cur_gen == h->cached_fork_gen && h->my_slot_idx != UINT32_MAX, 1)) 52713 0 52713
250 52713 return;
251 /* Cold path -- register the atfork hook once per process, then claim. */
252 30 pthread_once(&cf_atfork_once, cf_atfork_init);
253 /* Re-read after pthread_once: cf_on_fork_child may have bumped it. */
254 30 cur_gen = __atomic_load_n(&cf_fork_gen, __ATOMIC_RELAXED);
255 30 uint32_t now_pid = (uint32_t)getpid();
256 30 h->cached_pid = now_pid;
257 30 ▶ 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 */ 30 0 30
258 30 h->cached_fork_gen = cur_gen;
259 30 h->my_slot_idx = UINT32_MAX;
260 30 uint32_t start = now_pid % CF_READER_SLOTS;
261 /* Pass 1: take a free slot. */
262 34 ▶ for (uint32_t i = 0; i < CF_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < CF_READER_SLOTS; i++) { 34 0 34
263 34 uint32_t s = (start + i) % CF_READER_SLOTS;
264 34 uint32_t expected = 0;
265 34 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[s].pid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[s].pid, 30 4 34
266 &expected, now_pid, 0,
267 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
268 /* Fresh owner holds no read locks yet; clear any stale rdepth left by
269 * a dead predecessor (its contribution is dropped as we take over). */
270 30 __atomic_store_n(&h->reader_slots[s].rdepth, 0, __ATOMIC_RELAXED);
271 30 cf_occ_set(h, s); /* mark occupied BEFORE any rdlock can bump rdepth */
272 30 h->my_slot_idx = s;
273 30 return;
274 }
275 }
276 /* Pass 2: no free slot -- reclaim one whose owner is dead. Safe to take even
277 * if its rdepth>0: clearing pid drops the dead reader's entire contribution
278 * (a writer scan ignores rdepth when pid==0) and we reset rdepth to 0 as we
279 * claim it. */
280 0 ▶ for (uint32_t i = 0; i < CF_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < CF_READER_SLOTS; i++) { 0 0 0
281 0 uint32_t dpid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
282 0 ▶ if (dpid == 0 || dpid == now_pid || cf_pid_alive(dpid)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (dpid == 0 || dpid == now_pid || cf_pid_alive(dpid)) continue; 0 0 0
if (dpid == 0 || dpid == now_pid || cf_pid_alive(dpid)) continue; 0 0 0
if (dpid == 0 || dpid == now_pid || cf_pid_alive(dpid)) continue; 0 0 0
283 0 uint32_t expected = dpid;
284 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
285 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
286 0 __atomic_store_n(&h->reader_slots[i].rdepth, 0, __ATOMIC_RELAXED);
287 0 cf_occ_set(h, i);
288 0 h->my_slot_idx = i;
289 0 return;
290 }
291 }
292 /* Table full -- leave my_slot_idx = UINT32_MAX so this handle takes the
293 * slotless path (lock still works; recovery of THIS reader's death is the
294 * documented slotless limitation). */
295 }
296  
297 /* Inspect the writer word after a futex-wait timeout. If a dead writer holds
298 * it, force-recover. Dead READERS need no action here: only a writer that owns
299 * wlock drains readers, and it clears dead readers inline in its own scan. */
300 0 static inline void cf_recover_after_timeout(CfHandle *h) {
301 0 uint32_t val = __atomic_load_n(&h->hdr->wlock, __ATOMIC_RELAXED);
302 0 ▶ if (val >= CF_RWLOCK_WRITER_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (val >= CF_RWLOCK_WRITER_BIT) { 0 0 0
303 0 uint32_t pid = val & CF_RWLOCK_PID_MASK;
304 0 ▶ if (!cf_pid_alive(pid))
Branch: 1 branch
BranchTrueFalseTotal
if (!cf_pid_alive(pid)) 0 0 0
305 0 cf_recover_stale_lock(h, val);
306 }
307 0 }
308  
309 /* Bump/drop the parked-waiter hint. Both readers (blocked at the gate) and
310 * writers (blocked acquiring wlock) wait on the wlock futex and use this, so
311 * wrunlock/recover know whether a FUTEX_WAKE is worth a syscall. A waiter
312 * SIGKILLed while parked leaves rwait over-counted -> at most a spurious wake
313 * (harmless); it can never under-count, so no wakeup is lost. */
314 0 static inline void cf_park(CfHandle *h) {
315 0 __atomic_add_fetch(&h->hdr->rwait, 1, __ATOMIC_RELAXED);
316 0 }
317 0 static inline void cf_unpark(CfHandle *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 26873 static inline void cf_rdepth_inc(CfHandle *h) {
328 26873 ▶ if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->my_slot_idx != UINT32_MAX) { 26873 0 26873
329 26873 __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 26873 }
335 26873 static inline void cf_rdepth_dec(CfHandle *h) {
336 26873 ▶ if (h->slotless_held > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->slotless_held > 0) { 0 26873 26873
337 0 h->slotless_held--;
338 0 __atomic_sub_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_RELEASE);
339 26873 ▶ } else if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (h->my_slot_idx != UINT32_MAX) { 26873 0 26873
340 26873 __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_RELEASE);
341 }
342 26873 }
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 26873 static inline void cf_reader_wake_drain(CfHandle *h) {
348 26873 ▶ if (__atomic_load_n(&h->hdr->wlock, __ATOMIC_ACQUIRE) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&h->hdr->wlock, __ATOMIC_ACQUIRE) != 0) { 0 26873 26873
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 26873 }
353  
354 26873 static inline void cf_rwlock_rdlock(CfHandle *h) {
355 26873 cf_claim_reader_slot(h);
356 26873 CfHeader *hdr = h->hdr;
357 26875 for (int spin = 0; ; spin++) {
358 26875 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_ACQUIRE);
359 26875 ▶ if (cur == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur == 0) { 26873 2 26875
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 26873 cf_rdepth_inc(h);
366 26873 ▶ if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0) 26873 0 26873
367 26873 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 cf_rdepth_dec(h);
370 0 cf_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 4 if (cur >= CF_RWLOCK_WRITER_BIT &&
376 2 !cf_pid_alive(cur & CF_RWLOCK_PID_MASK)) {
377 2 cf_recover_stale_lock(h, cur);
378 2 spin = 0;
379 2 continue;
380 }
381 0 ▶ if (__builtin_expect(spin < CF_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < CF_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
382 0 cf_rwlock_spin_pause();
383 0 continue;
384 }
385 0 cf_park(h);
386 0 cur = __atomic_load_n(&hdr->wlock, __ATOMIC_RELAXED);
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 &cf_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 cf_unpark(h);
392 0 cf_recover_after_timeout(h);
393 0 spin = 0;
394 0 continue;
395 }
396 }
397 0 cf_unpark(h);
398 0 spin = 0;
399 }
400 }
401  
402 26873 static inline void cf_rwlock_rdunlock(CfHandle *h) {
403 26873 cf_rdepth_dec(h); /* RELEASE: drop our entire contribution */
404 26873 cf_reader_wake_drain(h); /* if a writer is draining, wake it to re-scan */
405 26873 }
406  
407 /* Caller owns wlock via a SEQ_CST CAS; drain readers before touching the table. */
408 static inline __attribute__((always_inline)) void cf_rwlock_drain_readers(CfHandle *h) {
409 2 CfHeader *hdr = h->hdr;
410 0 for (;;) {
411 25872 uint32_t v = __atomic_load_n(&hdr->drain_seq, __ATOMIC_ACQUIRE); /* snapshot BEFORE scan */
412 25872 int busy = 0;
413 /* Visit only OCCUPIED slots via the occupancy bitmap (SEQ_CST: a committed
414 * reader's bit -- set in claim, before its rdepth++ -- is ordered before
415 * this scan, so no held slot is skipped). O(CF_OCC_WORDS + live readers)
416 * instead of O(CF_READER_SLOTS). */
417 439824 ▶ for (uint32_t w = 0; w < CF_OCC_WORDS; w++) {
Branch: 2 branches
BranchTrueFalseTotal
for (uint32_t w = 0; w < CF_OCC_WORDS; w++) { 413920 25870 439790
for (uint32_t w = 0; w < CF_OCC_WORDS; w++) { 32 2 34
418 413952 uint64_t word = __atomic_load_n(&h->occ[w], __ATOMIC_SEQ_CST);
419 439828 ▶ while (word) {
Branch: 2 branches
BranchTrueFalseTotal
while (word) { 25874 413920 439794
while (word) { 2 32 34
420 25876 uint32_t i = (w << 6) + (uint32_t)__builtin_ctzll(word);
421 25876 word &= word - 1; /* consume this bit (local copy) */
422 25876 uint32_t rd = __atomic_load_n(&h->reader_slots[i].rdepth, __ATOMIC_SEQ_CST);
423 25876 ▶ if (rd == 0) continue; /* occupied but not read-locking now */
Branch: 2 branches
BranchTrueFalseTotal
if (rd == 0) continue; /* occupied but not read-locking now */ 25874 0 25874
if (rd == 0) continue; /* occupied but not read-locking now */ 2 0 2
424 0 uint32_t pid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
425 0 ▶ if (pid == 0) continue; /* stale rdepth on a freed slot */
Branch: 2 branches
BranchTrueFalseTotal
if (pid == 0) continue; /* stale rdepth on a freed slot */ 0 0 0
if (pid == 0) continue; /* stale rdepth on a freed slot */ 0 0 0
426 0 ▶ if (!cf_pid_alive(pid)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!cf_pid_alive(pid)) { 0 0 0
if (!cf_pid_alive(pid)) { 0 0 0
427 /* Dead reader: drop its pid so the slot no longer counts. Leave
428 * the occ bit set (harmless -- a later scan hits pid==0 and skips,
429 * a re-claim re-sets it) to avoid racing a concurrent claimant. */
430 0 uint32_t ep = pid;
431 0 __atomic_compare_exchange_n(&h->reader_slots[i].pid, &ep, 0,
432 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
433 0 continue;
434 }
435 0 busy = 1; /* live reader still holding */
436 }
437 }
438 /* A live slotless reader keeps us waiting; a crashed slotless reader that
439 * cannot be attributed to a pid is the documented slotless limitation. */
440 25872 ▶ if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0)
Branch: 2 branches
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0) 0 25870 25870
if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0) 0 2 2
441 0 busy = 1;
442 25872 ▶ if (!busy)
Branch: 2 branches
BranchTrueFalseTotal
if (!busy) 25870 0 25870
if (!busy) 2 0 2
443 25872 return; /* exclusive: wlock held + every rdepth 0 */
444 /* Wait for a reader to release (drain_seq bump) or time out to re-scan
445 * (which reclaims any newly-dead slotted reader). */
446 0 syscall(SYS_futex, &hdr->drain_seq, FUTEX_WAIT, v, &cf_lock_timeout, NULL, 0);
447 }
448 }
449  
450 25870 static inline void cf_rwlock_wrlock(CfHandle *h) {
451 25870 cf_claim_reader_slot(h); /* refresh cached_pid across fork */
452 25870 CfHeader *hdr = h->hdr;
453 /* Encode PID in the wlock word itself (0x80000000 | pid) to eliminate any
454 * crash window between acquiring the lock and storing the owner. */
455 25870 uint32_t mypid = CF_RWLOCK_WR(h->cached_pid);
456 /* Phase 1: acquire the writer word (mutual exclusion among writers). */
457 25870 for (int spin = 0; ; spin++) {
458 25870 uint32_t expected = 0;
459 25870 ▶ if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid, 25870 0 25870
460 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED))
461 25870 break;
462 /* Contended: expected now holds the current wlock value. */
463 0 if (expected >= CF_RWLOCK_WRITER_BIT &&
464 0 !cf_pid_alive(expected & CF_RWLOCK_PID_MASK)) {
465 0 cf_recover_stale_lock(h, expected);
466 0 spin = 0;
467 0 continue;
468 }
469 0 ▶ if (__builtin_expect(spin < CF_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < CF_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
470 0 cf_rwlock_spin_pause();
471 0 continue;
472 }
473 0 cf_park(h);
474 0 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_RELAXED);
475 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
476 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
477 &cf_lock_timeout, NULL, 0);
478 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
479 0 cf_unpark(h);
480 0 cf_recover_after_timeout(h);
481 0 spin = 0;
482 0 continue;
483 }
484 }
485 0 cf_unpark(h);
486 0 spin = 0;
487 }
488 cf_rwlock_drain_readers(h);
489 25870 }
490  
491 25870 static inline void cf_rwlock_wrunlock(CfHandle *h) {
492 25870 CfHeader *hdr = h->hdr;
493 25870 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_RELEASE);
494 25870 ▶ if (__atomic_load_n(&hdr->rwait, __ATOMIC_RELAXED) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->rwait, __ATOMIC_RELAXED) > 0) 0 25870 25870
495 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
496 25870 }
497  
498 /* ================================================================
499 * Layout math + create / open / destroy
500 *
501 * Layout: Header -> reader_slots[1024] -> occ bitmap -> slots[num_buckets * CF_SLOTS]
502 * ================================================================ */
503  
504 /* Single source of truth for the mmap region layout offsets:
505 * Header -> reader_slots[] -> occ bitmap -> slots[]. */
506 typedef struct { uint64_t reader_slots, occ, slots; } CfLayout;
507  
508 221936 static inline CfLayout cf_layout(void) {
509 CfLayout L;
510 221936 L.reader_slots = sizeof(CfHeader);
511 221936 L.occ = L.reader_slots + (uint64_t)CF_READER_SLOTS * sizeof(CfReaderSlot);
512 221936 L.slots = L.occ + CF_OCC_BYTES;
513 221936 L.slots = (L.slots + 7) & ~(uint64_t)7; /* 8-byte align the slot array */
514 221936 return L;
515 }
516  
517 52 static inline uint64_t cf_total_size(uint64_t num_buckets) {
518 52 CfLayout L = cf_layout();
519 /* num_buckets * CF_SLOTS uint16_t fingerprint slots */
520 52 return L.slots + num_buckets * (uint64_t)CF_SLOTS * sizeof(uint16_t);
521 }
522  
523 /* round v up to the next power of two (64-bit), with a floor of CF_MIN_BUCKETS */
524 40 static inline uint64_t cf_next_pow2_u64(uint64_t v) {
525 40 ▶ if (v <= CF_MIN_BUCKETS) return CF_MIN_BUCKETS;
Branch: 1 branch
BranchTrueFalseTotal
if (v <= CF_MIN_BUCKETS) return CF_MIN_BUCKETS; 6 34 40
526 34 return 1ULL << (64 - __builtin_clzll(v - 1));
527 }
528  
529 30 static inline void cf_init_header(void *base, uint64_t num_buckets,
530 uint64_t capacity, uint64_t total) {
531 30 CfLayout L = cf_layout();
532 30 CfHeader *hdr = (CfHeader *)base;
533 /* Zero the header + reader-slot region (lock-recovery state); the slot
534 array relies on the fresh mapping being OS zero-filled (0 = empty slot). */
535 30 memset(base, 0, (size_t)L.slots);
536 30 hdr->version = CF_VERSION;
537 30 hdr->num_buckets = num_buckets;
538 30 hdr->bucket_mask = num_buckets - 1;
539 30 hdr->capacity = capacity;
540 30 hdr->count = 0;
541 /* Deterministic, non-zero seed for the eviction-victim RNG. */
542 30 hdr->rng_state = 0x9e3779b97f4a7c15ULL ^ (capacity * 0x2545F4914F6CDD1DULL);
543 30 ▶ if (hdr->rng_state == 0) hdr->rng_state = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->rng_state == 0) hdr->rng_state = 1; 0 30 30
544 30 hdr->total_size = total;
545 30 hdr->reader_slots_off = L.reader_slots;
546 30 hdr->slots_off = L.slots;
547 /* Publish magic LAST, as a release store: it is the commit point, so a
548 creator killed before it leaves magic==0 and never a file mistaken for
549 a valid one. A kill during the field stores leaves one to remove by
550 hand. */
551 30 __atomic_store_n(&hdr->magic, CF_MAGIC, __ATOMIC_RELEASE);
552 30 __atomic_thread_fence(__ATOMIC_SEQ_CST);
553 30 }
554  
555 110882 static inline uint16_t *cf_slots(CfHandle *h) {
556 /* Layer B: locate the slot array via the trusted compile-time layout, NOT
557 * the attacker-writable hdr->slots_off -- a peer that corrupts slots_off in
558 * shared memory must not be able to relocate the base outside the mapping.
559 * Validation at open guarantees hdr->slots_off == cf_layout().slots for a
560 * valid filter, so this is identical for valid data. */
561 110882 return (uint16_t *)((char *)h->base + cf_layout().slots);
562 }
563  
564 39 static inline CfHandle *cf_setup(void *base, size_t map_size,
565 const char *path, int backing_fd) {
566 39 CfHeader *hdr = (CfHeader *)base;
567 39 CfHandle *h = (CfHandle *)calloc(1, sizeof(CfHandle));
568 39 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 39 39
569 0 munmap(base, map_size);
570 0 ▶ if (backing_fd >= 0) close(backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (backing_fd >= 0) close(backing_fd); 0 0 0
571 0 return NULL;
572 }
573 39 h->hdr = hdr;
574 39 h->base = base;
575 39 h->reader_slots = (CfReaderSlot *)((uint8_t *)base + cf_layout().reader_slots);
576 39 h->occ = (uint64_t *)((uint8_t *)base + cf_layout().occ); /* trusted layout offset */
577 39 h->mmap_size = map_size;
578 39 ▶ h->path = path ? strdup(path) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
h->path = path ? strdup(path) : NULL; 20 19 39
579 39 ▶ if (path && !h->path) {
Branch: 2 branches
BranchTrueFalseTotal
if (path && !h->path) { 20 19 39
if (path && !h->path) { 0 20 20
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 free(h);
583 0 return NULL;
584 }
585 39 h->backing_fd = backing_fd;
586 39 h->my_slot_idx = UINT32_MAX;
587 39 return h;
588 }
589  
590 /* Validate a mapped header (shared by cf_create reopen and cf_open_fd). */
591 16 static inline int cf_validate_header(const CfHeader *hdr, uint64_t file_size) {
592 16 ▶ if (hdr->magic != CF_MAGIC) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->magic != CF_MAGIC) return 0; 4 12 16
593 12 ▶ if (hdr->version != CF_VERSION) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->version != CF_VERSION) return 0; 0 12 12
594 12 ▶ if (hdr->num_buckets < CF_MIN_BUCKETS || hdr->num_buckets > CF_MAX_BUCKETS) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (hdr->num_buckets < CF_MIN_BUCKETS || hdr->num_buckets > CF_MAX_BUCKETS) return 0; 12 0 12
if (hdr->num_buckets < CF_MIN_BUCKETS || hdr->num_buckets > CF_MAX_BUCKETS) return 0; 0 12 12
595 12 ▶ if ((hdr->num_buckets & (hdr->num_buckets - 1)) != 0) return 0; /* power of two */
Branch: 1 branch
BranchTrueFalseTotal
if ((hdr->num_buckets & (hdr->num_buckets - 1)) != 0) return 0; /* power of two */ 0 12 12
596 12 ▶ if (hdr->bucket_mask != hdr->num_buckets - 1) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->bucket_mask != hdr->num_buckets - 1) return 0; 0 12 12
597 12 ▶ if (hdr->capacity == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->capacity == 0) return 0; 0 12 12
598 12 ▶ if (hdr->rng_state == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->rng_state == 0) return 0; 0 12 12
599 12 ▶ if (hdr->count > hdr->num_buckets * (uint64_t)CF_SLOTS) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->count > hdr->num_buckets * (uint64_t)CF_SLOTS) return 0; 0 12 12
600 12 ▶ if (hdr->total_size != file_size) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->total_size != file_size) return 0; 0 12 12
601 12 ▶ if (hdr->total_size != cf_total_size(hdr->num_buckets)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->total_size != cf_total_size(hdr->num_buckets)) return 0; 0 12 12
602 12 CfLayout L = cf_layout();
603 12 ▶ 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 12 12
604 12 ▶ if (hdr->slots_off != L.slots) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->slots_off != L.slots) return 0; 0 12 12
605 12 return 1;
606 }
607  
608 /* validate args + compute the geometry (num_buckets) */
609 41 static int cf_validate_create_args(uint64_t capacity,
610 uint64_t *num_buckets_out, char *errbuf) {
611 41 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 41 0 41
612 41 ▶ if (capacity < 1) { CF_ERR("capacity must be >= 1"); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (capacity < 1) { CF_ERR("capacity must be >= 1"); return 0; } 0 41 41
if (capacity < 1) { CF_ERR("capacity must be >= 1"); return 0; } 0 0 0
613  
614 /* Size for the target load factor: num_buckets =
615 next_pow2(ceil(capacity / CF_SLOTS / 0.95)), floor CF_MIN_BUCKETS.
616 Reject (don't silently cap) a capacity that would exceed the bucket cap,
617 else the filter would be undersized and overflow at the requested load. */
618 41 double want_d = ceil((double)capacity / (double)CF_SLOTS / 0.95);
619 41 ▶ if (want_d > (double)CF_MAX_BUCKETS) { CF_ERR("capacity too large for the bucket cap"); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (want_d > (double)CF_MAX_BUCKETS) { CF_ERR("capacity too large for the bucket cap"); return 0; } 1 40 41
if (want_d > (double)CF_MAX_BUCKETS) { CF_ERR("capacity too large for the bucket cap"); return 0; } 1 0 1
620 40 uint64_t num_buckets = cf_next_pow2_u64((uint64_t)want_d); /* next_pow2 floors at CF_MIN_BUCKETS */
621  
622 40 *num_buckets_out = num_buckets;
623 40 return 1;
624 }
625  
626 /* Securely obtain a fd: create exclusively (O_CREAT|O_EXCL|O_NOFOLLOW at mode,
627 * default 0600), or attach an existing file (O_RDWR|O_NOFOLLOW, no O_CREAT). */
628 22 static int cf_secure_open(const char *path, mode_t mode, char *errbuf) {
629 22 ▶ for (int attempt = 0; attempt < 100; attempt++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int attempt = 0; attempt < 100; attempt++) { 22 0 22
630 22 int fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, mode);
631 22 ▶ 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 11 22
632 11 ▶ if (errno != EEXIST) { CF_ERR("create %s: %s", path, strerror(errno)); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (errno != EEXIST) { CF_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 11 11
if (errno != EEXIST) { CF_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 0 0
633 11 fd = open(path, O_RDWR|O_NOFOLLOW|O_CLOEXEC);
634 11 ▶ if (fd >= 0) return fd;
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) return fd; 11 0 11
635 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
636 0 ▶ CF_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */ 0 0 0
637 0 return -1;
638 }
639 0 ▶ CF_ERR("open %s: create/attach kept racing", path);
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("open %s: create/attach kept racing", path); 0 0 0
640 0 return -1;
641 }
642  
643 /* True iff the whole file is zero -- what an abandoned mid-init
644 creator leaves. Lets recovery re-init only a provably-empty file, never
645 one that merely starts with a zero word. Cold path, so a byte scan is
646 fine. Read, not mapped: a read fault on a tmpfs hole allocates the page. */
647 2 static int cf_file_is_zero(int fd, uint64_t size) {
648 char buf[16384];
649 9 ▶ for (uint64_t off = 0; off < size; ) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t off = 0; off < size; ) { 8 1 9
650 8 ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
651 8 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 8 8
652 99079 ▶ 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 99071 99072
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 99072 7 99079
653 7 off += (uint64_t)n;
654 }
655 1 return 1;
656 }
657  
658 /* Opt-in (DATA_CUCKOOFILTER_SHARED_SPARSE=0): reserving commits memory this module otherwise fills lazily. */
659 14 static int cf_reserve(int fd, uint64_t size) {
660 14 const char *sp = getenv("DATA_CUCKOOFILTER_SHARED_SPARSE");
661 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
662 /* Before Linux 6.11 tmpfs gives up at any pending signal and undoes the allocation, so a
663 * periodic one could keep it from ever completing; SIGSTOP cannot be blocked. */
664 sigset_t all, old;
665 0 sigfillset(&all);
666 0 sigprocmask(SIG_BLOCK, &all, &old);
667 int e;
668 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
669 0 sigprocmask(SIG_SETMASK, &old, NULL);
670 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
671 0 errno = e;
672 0 return -1;
673 }
674  
675 39 static CfHandle *cf_create(const char *path, uint64_t capacity, mode_t mode, char *errbuf) {
676 uint64_t num_buckets;
677 39 ▶ if (!cf_validate_create_args(capacity, &num_buckets, errbuf)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!cf_validate_create_args(capacity, &num_buckets, errbuf)) return NULL; 1 38 39
678  
679 38 uint64_t total = cf_total_size(num_buckets);
680 38 int anonymous = (path == NULL);
681 38 int fd = -1;
682 size_t map_size;
683 void *base;
684  
685 38 ▶ if (anonymous) {
Branch: 1 branch
BranchTrueFalseTotal
if (anonymous) { 16 22 38
686 16 map_size = (size_t)total;
687 16 base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
688 16 ▶ if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 16 16
if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 0 0
689 } else {
690 22 fd = cf_secure_open(path, mode, errbuf);
691 33 ▶ if (fd < 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return NULL; 0 22 22
692 22 ▶ if (flock(fd, LOCK_EX) < 0) { CF_ERR("flock: %s", strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (flock(fd, LOCK_EX) < 0) { CF_ERR("flock: %s", strerror(errno)); close(fd); return NULL; } 0 22 22
if (flock(fd, LOCK_EX) < 0) { CF_ERR("flock: %s", strerror(errno)); close(fd); return NULL; } 0 0 0
693 struct stat st;
694 22 ▶ if (fstat(fd, &st) < 0) { CF_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { CF_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; } 0 22 22
if (fstat(fd, &st) < 0) { CF_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; } 0 0 0
695 22 int is_new = (st.st_size == 0);
696 22 ▶ if (!is_new && (uint64_t)st.st_size < sizeof(CfHeader)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!is_new && (uint64_t)st.st_size < sizeof(CfHeader)) { 11 11 22
if (!is_new && (uint64_t)st.st_size < sizeof(CfHeader)) { 1 10 11
697 1 ▶ CF_ERR("%s: file too small (%lld)", path, (long long)st.st_size);
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: file too small (%lld)", path, (long long)st.st_size); 1 0 1
698 1 flock(fd, LOCK_UN); close(fd); return NULL;
699 }
700 21 ▶ 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 10 21
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
701 0 ▶ CF_ERR("%s: refusing to initialize file not owned by us", path);
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: refusing to initialize file not owned by us", path); 0 0 0
702 0 flock(fd, LOCK_UN); close(fd); return NULL;
703 }
704 21 ▶ if (is_new && ftruncate(fd, (off_t)total) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_new && ftruncate(fd, (off_t)total) < 0) { 11 10 21
if (is_new && ftruncate(fd, (off_t)total) < 0) { 0 11 11
705 0 ▶ CF_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; 0 0 0
706 }
707 21 ▶ if (is_new && cf_reserve(fd, total) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_new && cf_reserve(fd, total) < 0) { 11 10 21
if (is_new && cf_reserve(fd, total) < 0) { 0 11 11
708 0 ▶ CF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno)); 0 0 0
709 0 if (ftruncate(fd, 0) < 0) { /* best effort */ }
710 0 flock(fd, LOCK_UN); close(fd); return NULL;
711 }
712 21 ▶ 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; 10 11 21
713 21 base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
714 21 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 21 21
715 0 ▶ CF_ERR("mmap: %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("mmap: %s", strerror(errno)); 0 0 0
716 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
717 0 flock(fd, LOCK_UN); close(fd); return NULL;
718 }
719 21 ▶ if (!is_new) {
Branch: 1 branch
BranchTrueFalseTotal
if (!is_new) { 10 11 21
720 10 ▶ if (!cf_validate_header((CfHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cf_validate_header((CfHeader *)base, (uint64_t)st.st_size)) { 4 6 10
721 /* Recover an abandoned mid-init file: a creator killed
722 * between the ftruncate and the header init leaves a
723 * full-size, all-zero (magic==0) file that would brick every
724 * future open of this path. Re-initialize ONLY when it is
725 * exactly our size, still uninitialized, and owned by us;
726 * anything else still errors. */
727 4 ▶ if (((CfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total
Branch: 2 branches
BranchTrueFalseTotal
if (((CfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 3 1 4
if (((CfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 2 1 3
728 2 ▶ && st.st_uid == geteuid() && cf_file_is_zero(fd, map_size)) {
Branch: 2 branches
BranchTrueFalseTotal
&& st.st_uid == geteuid() && cf_file_is_zero(fd, map_size)) { 2 0 2
&& st.st_uid == geteuid() && cf_file_is_zero(fd, map_size)) { 1 1 2
729 1 ▶ if (fchmod(fd, mode) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fchmod(fd, mode) < 0) { 0 1 1
730 0 ▶ CF_ERR("%s: fchmod: %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: fchmod: %s", path, strerror(errno)); 0 0 0
731 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
732 }
733 1 ▶ if (cf_reserve(fd, total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cf_reserve(fd, total) < 0) { 0 1 1
734 0 ▶ CF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno)); 0 0 0
735 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
736 }
737 1 cf_init_header(base, num_buckets, capacity, total);
738 1 flock(fd, LOCK_UN); close(fd);
739 1 return cf_setup(base, map_size, path, -1);
740 }
741 3 ▶ if (((CfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total
Branch: 2 branches
BranchTrueFalseTotal
if (((CfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 2 1 3
if (((CfHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 1 1 2
742 1 ▶ && st.st_uid == geteuid()) {
Branch: 1 branch
BranchTrueFalseTotal
&& st.st_uid == geteuid()) { 1 0 1
743 1 ▶ CF_ERR("%s: incomplete Cuckoo filter file left by an interrupted create; remove it and retry", path);
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: incomplete Cuckoo filter file left by an interrupted create; remove it and retry", path); 1 0 1
744 1 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
745 }
746 2 ▶ CF_ERR("invalid Cuckoo filter file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("invalid Cuckoo filter file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL; 2 0 2
747 }
748 6 ▶ if (__atomic_load_n(&((CfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&((CfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) { 1 5 6
749 1 ▶ CF_ERR("%s is frozen (read-only); open it with new_readonly", path);
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s is frozen (read-only); open it with new_readonly", path); 1 0 1
750 1 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
751 }
752 5 flock(fd, LOCK_UN); close(fd);
753 5 return cf_setup(base, map_size, path, -1);
754 }
755 }
756 27 cf_init_header(base, num_buckets, capacity, total);
757 27 ▶ if (fd >= 0) { flock(fd, LOCK_UN); close(fd); }
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { flock(fd, LOCK_UN); close(fd); } 11 16 27
758 27 return cf_setup(base, map_size, path, -1);
759 }
760  
761 2 static CfHandle *cf_create_memfd(const char *name, uint64_t capacity, char *errbuf) {
762 uint64_t num_buckets;
763 2 ▶ if (!cf_validate_create_args(capacity, &num_buckets, errbuf)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!cf_validate_create_args(capacity, &num_buckets, errbuf)) return NULL; 0 2 2
764  
765 2 uint64_t total = cf_total_size(num_buckets);
766 2 ▶ int fd = memfd_create(name ? name : "cuckoo", MFD_CLOEXEC | MFD_ALLOW_SEALING);
Branch: 1 branch
BranchTrueFalseTotal
int fd = memfd_create(name ? name : "cuckoo", MFD_CLOEXEC | MFD_ALLOW_SEALING); 1 1 2
767 2 ▶ if (fd < 0) { CF_ERR("memfd_create: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0) { CF_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 2 2
if (fd < 0) { CF_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 0 0
768 2 ▶ if (ftruncate(fd, (off_t)total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total) < 0) { 0 2 2
769 0 ▶ CF_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL; 0 0 0
770 }
771 2 ▶ if (cf_reserve(fd, total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cf_reserve(fd, total) < 0) { 0 2 2
772 0 ▶ CF_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total, strerror(errno)); 0 0 0
773 0 close(fd); return NULL;
774 }
775 2 (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
776 2 void *base = mmap(NULL, (size_t)total, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
777 2 ▶ if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; } 0 2 2
if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; } 0 0 0
778 2 cf_init_header(base, num_buckets, capacity, total);
779 2 return cf_setup(base, (size_t)total, NULL, fd);
780 }
781  
782 3 static CfHandle *cf_open_fd(int fd, char *errbuf) {
783 3 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 3 0 3
784 struct stat st;
785 3 ▶ if (fstat(fd, &st) < 0) { CF_ERR("fstat: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { CF_ERR("fstat: %s", strerror(errno)); return NULL; } 0 3 3
if (fstat(fd, &st) < 0) { CF_ERR("fstat: %s", strerror(errno)); return NULL; } 0 0 0
786 3 ▶ if ((uint64_t)st.st_size < sizeof(CfHeader)) { CF_ERR("too small"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(CfHeader)) { CF_ERR("too small"); return NULL; } 1 2 3
if ((uint64_t)st.st_size < sizeof(CfHeader)) { CF_ERR("too small"); return NULL; } 1 0 1
787 /* before mmap: a creator may truncate the file until it has set magic */
788 uint32_t magic;
789 2 ▶ if (pread(fd, &magic, sizeof magic, offsetof(CfHeader, magic)) != (ssize_t)sizeof magic || magic != CF_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(CfHeader, magic)) != (ssize_t)sizeof magic || magic != CF_MAGIC) { 2 0 2
if (pread(fd, &magic, sizeof magic, offsetof(CfHeader, magic)) != (ssize_t)sizeof magic || magic != CF_MAGIC) { 0 2 2
790 0 ▶ CF_ERR("invalid Cuckoo filter table"); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("invalid Cuckoo filter table"); return NULL; 0 0 0
791 }
792 2 size_t ms = (size_t)st.st_size;
793 2 void *base = mmap(NULL, ms, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
794 2 ▶ if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 2 2
if (base == MAP_FAILED) { CF_ERR("mmap: %s", strerror(errno)); return NULL; } 0 0 0
795 2 ▶ if (!cf_validate_header((CfHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cf_validate_header((CfHeader *)base, (uint64_t)st.st_size)) { 0 2 2
796 0 ▶ CF_ERR("invalid Cuckoo filter table"); munmap(base, ms); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("invalid Cuckoo filter table"); munmap(base, ms); return NULL; 0 0 0
797 }
798 2 ▶ if (__atomic_load_n(&((CfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&((CfHeader *)base)->sealed, __ATOMIC_ACQUIRE)) { 1 1 2
799 1 ▶ CF_ERR("this Cuckoo filter is frozen (read-only); open it with new_readonly");
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("this Cuckoo filter is frozen (read-only); open it with new_readonly"); 1 0 1
800 1 munmap(base, ms); return NULL;
801 }
802 1 int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
803 1 ▶ if (myfd < 0) { CF_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (myfd < 0) { CF_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; } 0 1 1
if (myfd < 0) { CF_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; } 0 0 0
804 1 return cf_setup(base, ms, NULL, myfd);
805 }
806  
807 39 static void cf_destroy(CfHandle *h) {
808 39 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 39 39
809 /* Release our reader slot on clean teardown (else short-lived-reader churn
810 * exhausts the slot table); skip if a read lock is still held (rdepth>0). */
811 39 ▶ 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 && 39 0 39
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 30 9 39
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 30 0 30
812 30 ▶ h->cached_fork_gen == __atomic_load_n(&cf_fork_gen, __ATOMIC_RELAXED) &&
Branch: 1 branch
BranchTrueFalseTotal
h->cached_fork_gen == __atomic_load_n(&cf_fork_gen, __ATOMIC_RELAXED) && 30 0 30
813 30 ▶ __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) { 30 0 30
814 /* Clear our occ bit BEFORE freeing the slot: we still own the pid so no
815 * claimant can take the slot mid-clear, and rdepth==0 so no writer needs
816 * to see us. (A crash skips this -> the bit is reclaimed lazily by a
817 * writer scan / re-claim, same as the pid.) */
818 30 cf_occ_clear(h, h->my_slot_idx);
819 30 uint32_t expected = h->cached_pid;
820 30 __atomic_compare_exchange_n(&h->reader_slots[h->my_slot_idx].pid,
821 &expected, 0, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
822 }
823 39 ▶ if (h->backing_fd >= 0) close(h->backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->backing_fd >= 0) close(h->backing_fd); 3 36 39
824 39 ▶ if (h->base) munmap(h->base, h->mmap_size);
Branch: 1 branch
BranchTrueFalseTotal
if (h->base) munmap(h->base, h->mmap_size); 39 0 39
825 39 free(h->path);
826 39 free(h);
827 }
828  
829 4 static inline int cf_msync(CfHandle *h) {
830 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
831 4 return msync(h->base, h->mmap_size, MS_SYNC);
832 }
833  
834 /* Open a FROZEN (sealed) file read-only: O_RDONLY + PROT_READ, no lock ever.
835 * A sealed file is immutable and no read path writes the mapping, so queries
836 * take no reader-slot / rwlock traffic and any number of processes can share
837 * one PROT_READ mapping (same architecture; the magic rejects a wrong-endian
838 * file). */
839 5 static CfHandle *cf_open_readonly(const char *path, char *errbuf) {
840 5 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 5 0 5
841 5 int fd = open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC);
842 5 ▶ if (fd < 0) { CF_ERR("open %s: %s", path, strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0) { CF_ERR("open %s: %s", path, strerror(errno)); return NULL; } 1 4 5
if (fd < 0) { CF_ERR("open %s: %s", path, strerror(errno)); return NULL; } 1 0 1
843 struct stat st;
844 4 ▶ if (fstat(fd, &st) < 0) { CF_ERR("fstat %s: %s", path, strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { CF_ERR("fstat %s: %s", path, strerror(errno)); close(fd); return NULL; } 0 4 4
if (fstat(fd, &st) < 0) { CF_ERR("fstat %s: %s", path, strerror(errno)); close(fd); return NULL; } 0 0 0
845 4 ▶ if ((uint64_t)st.st_size < sizeof(CfHeader)) { CF_ERR("%s: file too small", path); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(CfHeader)) { CF_ERR("%s: file too small", path); close(fd); return NULL; } 0 4 4
if ((uint64_t)st.st_size < sizeof(CfHeader)) { CF_ERR("%s: file too small", path); close(fd); return NULL; } 0 0 0
846 /* before mmap: a creator may truncate the file until it has set magic */
847 uint32_t magic;
848 4 ▶ if (pread(fd, &magic, sizeof magic, offsetof(CfHeader, magic)) != (ssize_t)sizeof magic || magic != CF_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(CfHeader, magic)) != (ssize_t)sizeof magic || magic != CF_MAGIC) { 4 0 4
if (pread(fd, &magic, sizeof magic, offsetof(CfHeader, magic)) != (ssize_t)sizeof magic || magic != CF_MAGIC) { 0 4 4
849 0 ▶ CF_ERR("%s: invalid Cuckoo filter file", path); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: invalid Cuckoo filter file", path); close(fd); return NULL; 0 0 0
850 }
851 4 size_t ms = (size_t)st.st_size;
852 4 void *base = mmap(NULL, ms, PROT_READ, MAP_SHARED, fd, 0);
853 4 close(fd); /* the mapping keeps the file; a read-only view needs no fd (no msync/ftruncate) */
854 4 ▶ if (base == MAP_FAILED) { CF_ERR("mmap %s: %s", path, strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { CF_ERR("mmap %s: %s", path, strerror(errno)); return NULL; } 0 4 4
if (base == MAP_FAILED) { CF_ERR("mmap %s: %s", path, strerror(errno)); return NULL; } 0 0 0
855 4 uint8_t sealed = __atomic_load_n(&((CfHeader *)base)->sealed, __ATOMIC_ACQUIRE);
856 4 ▶ if (!cf_validate_header((CfHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cf_validate_header((CfHeader *)base, (uint64_t)st.st_size)) { 0 4 4
857 0 ▶ CF_ERR("%s: invalid Cuckoo filter file", path); munmap(base, ms); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s: invalid Cuckoo filter file", path); munmap(base, ms); return NULL; 0 0 0
858 }
859 4 ▶ if (!sealed) {
Branch: 1 branch
BranchTrueFalseTotal
if (!sealed) { 1 3 4
860 1 ▶ CF_ERR("%s is not frozen: call ->freeze on the producer before opening read-only", path);
Branch: 1 branch
BranchTrueFalseTotal
CF_ERR("%s is not frozen: call ->freeze on the producer before opening read-only", path); 1 0 1
861 1 munmap(base, ms); return NULL;
862 }
863 3 CfHandle *h = cf_setup(base, ms, path, -1); /* munmaps on OOM */
864 3 ▶ if (!h) { CF_ERR("out of memory"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (!h) { CF_ERR("out of memory"); return NULL; } 0 3 3
if (!h) { CF_ERR("out of memory"); return NULL; } 0 0 0
865 3 h->readonly = 1;
866 3 return h;
867 }
868  
869 /* Seal a filter: make it permanently immutable so it can be shipped and opened
870 * read-only. Takes the write lock so no add/remove is in flight, publishes the
871 * seal, then flushes it (file/memfd-backed). Afterwards every mutator croaks
872 * and a read-write reopen is refused. */
873 2 static int cf_freeze(CfHandle *h) {
874 2 cf_rwlock_wrlock(h);
875 2 __atomic_store_n(&h->hdr->sealed, 1, __ATOMIC_RELEASE);
876 2 cf_rwlock_wrunlock(h);
877 2 ▶ if (h->path || h->backing_fd >= 0) return cf_msync(h); /* durability for file/memfd-backed */
Branch: 2 branches
BranchTrueFalseTotal
if (h->path || h->backing_fd >= 0) return cf_msync(h); /* durability for file/memfd-backed */ 0 2 2
if (h->path || h->backing_fd >= 0) return cf_msync(h); /* durability for file/memfd-backed */ 0 0 0
878 0 return 0; /* anonymous: the seal lives in shared memory (visible to forks); nothing to flush */
879 }
880  
881 /* ================================================================
882 * Cuckoo filter operations (callers hold the lock)
883 *
884 * Partial-key cuckoo hashing from a single XXH3-128 hash: a 16-bit non-zero
885 * fingerprint plus two candidate buckets i1 and i2 = alt(i1, fp), where alt is
886 * an XOR-based involution so alt(alt(i,fp),fp) == i and i1 != i2.
887 * ================================================================ */
888  
889 /* xorshift64 victim-choice RNG; advances and stores hdr->rng_state.
890 * Called only under the write lock. */
891 7540 static inline uint64_t cf_rng_next(CfHandle *h) {
892 7540 uint64_t x = h->hdr->rng_state;
893 7540 x ^= x << 13;
894 7540 x ^= x >> 7;
895 7540 x ^= x << 17;
896 7540 h->hdr->rng_state = x;
897 7540 return x;
898 }
899  
900 /* Spread a 16-bit fingerprint's bits across 64 bits (good integer mix). */
901 73321 static inline uint64_t cf_fp_mix(uint16_t fp) {
902 73321 return (uint64_t)fp * 0x9e3779b97f4a7c15ULL; /* golden-ratio mix; full 64 bits */
903 }
904  
905 /* Alternate bucket for (i, fp): involutive XOR displacement masked to the
906 * table. fh is forced non-zero so the alternate is always a different bucket
907 * (i1 != i2). Since num_buckets is a power of two and fh < num_buckets,
908 * i ^ fh stays < num_buckets, and alt(alt(i,fp),fp) == i. */
909 73321 static inline uint64_t cf_alt(CfHandle *h, uint64_t i, uint16_t fp) {
910 73321 uint64_t mask = h->hdr->bucket_mask;
911 73321 uint64_t fh = cf_fp_mix(fp) & mask;
912 73321 ▶ if (fh == 0) fh = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (fh == 0) fh = 1; 556 72765 73321
913 73321 return (i ^ fh) & mask;
914 }
915  
916 /* Buckets that physically fit in the mapping, derived from the trusted
917 * process-local mmap_size and the compile-time layout -- NOT from the
918 * attacker-writable header geometry (num_buckets/bucket_mask/slots_off).
919 * For any filter that passed validation at open this equals hdr->num_buckets
920 * (mmap_size == cf_layout().slots + num_buckets*CF_SLOTS*2), so bounding
921 * against it never changes behavior for valid data. */
922 110882 static inline uint64_t cf_phys_buckets(CfHandle *h) {
923 110882 uint64_t base_off = cf_layout().slots;
924 110882 ▶ if (h->mmap_size <= base_off) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (h->mmap_size <= base_off) return 0; 0 110882 110882
925 110882 return (uint64_t)(h->mmap_size - base_off) / ((uint64_t)CF_SLOTS * sizeof(uint16_t));
926 }
927  
928 /* Cold path: called only while recovering a dead writer, with readers drained. */
929 2 static void cf_recount(CfHandle *h) {
930 2 uint16_t *slots = cf_slots(h);
931 2 uint64_t n = cf_phys_buckets(h) * CF_SLOTS, count = 0;
932 18 ▶ for (uint64_t i = 0; i < n; i++) count += slots[i] != 0;
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t i = 0; i < n; i++) count += slots[i] != 0; 16 2 18
933 2 h->hdr->count = count;
934 2 }
935  
936 /* pointer to bucket i's CF_SLOTS fingerprint slots.
937 * Layer B: the bucket index i is derived from hdr->bucket_mask (attacker-
938 * writable), so fold any out-of-range i back into the physically-mapped bucket
939 * range before indexing -- the returned pointer can then never fall outside the
940 * mapping. i & (phys-1) <= phys-1 < phys for any i (AND only clears bits), so
941 * this is in-bounds regardless of the corrupted value; for valid data i < phys
942 * already, so it is a no-op. */
943 110879 static inline uint16_t *cf_bucket(CfHandle *h, uint64_t i) {
944 110879 uint64_t phys = cf_phys_buckets(h);
945 110879 ▶ if (phys && i >= phys) i &= (phys - 1);
Branch: 2 branches
BranchTrueFalseTotal
if (phys && i >= phys) i &= (phys - 1); 110879 0 110879
if (phys && i >= phys) i &= (phys - 1); 0 110879 110879
946 110879 return cf_slots(h) + i * (uint64_t)CF_SLOTS;
947 }
948  
949 /* slot index of fp in bucket i, or -1 if absent */
950 45227 static inline int cf_bucket_find(CfHandle *h, uint64_t i, uint16_t fp) {
951 45227 uint16_t *b = cf_bucket(h, i);
952 170006 ▶ for (int j = 0; j < CF_SLOTS; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (int j = 0; j < CF_SLOTS; j++) 143124 26882 170006
953 143124 ▶ if (b[j] == fp) return j;
Branch: 1 branch
BranchTrueFalseTotal
if (b[j] == fp) return j; 18345 124779 143124
954 26882 return -1;
955 }
956  
957 /* place fp in a free (0) slot of bucket i: return 1 if placed, 0 if full */
958 44431 static inline int cf_bucket_insert(CfHandle *h, uint64_t i, uint16_t fp) {
959 44431 uint16_t *b = cf_bucket(h, i);
960 113137 ▶ for (int j = 0; j < CF_SLOTS; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int j = 0; j < CF_SLOTS; j++) { 104063 9074 113137
961 104063 ▶ if (b[j] == 0) { b[j] = fp; return 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (b[j] == 0) { b[j] = fp; return 1; } 35357 68706 104063
962 }
963 9074 return 0;
964 }
965  
966 /* derive the fingerprint and the two candidate buckets for (item,len) */
967 66239 static inline void cf_hash(CfHandle *h, const void *item, size_t len,
968 uint16_t *fp_out, uint64_t *i1_out, uint64_t *i2_out) {
969 66239 XXH128_hash_t hh = XXH3_128bits(item, len);
970 66239 uint16_t fp = (uint16_t)(hh.high64 & 0xFFFF);
971 66239 ▶ if (fp == 0) fp = 1; /* 0 means empty slot; never use it */
Branch: 1 branch
BranchTrueFalseTotal
if (fp == 0) fp = 1; /* 0 means empty slot; never use it */ 0 66239 66239
972 66239 uint64_t i1 = (uint64_t)(hh.low64 & h->hdr->bucket_mask);
973 66239 *fp_out = fp;
974 66239 *i1_out = i1;
975 66239 *i2_out = cf_alt(h, i1, fp);
976 66239 }
977  
978 /* Add (item,len). Returns 1 on success, 0 if the table is full.
979 *
980 * ATOMIC: on failure the table is byte-identical to before, so a failed add can
981 * never introduce a false negative -- every fingerprint that was present stays
982 * present. The eviction path records every swap and rolls them back in reverse
983 * if CF_MAX_KICKS is exhausted. (hdr->rng_state and the ops counter still
984 * advance; only the fingerprint table is restored.) */
985 35360 static int cf_add_locked(CfHandle *h, const void *item, size_t len) {
986 uint16_t fp;
987 uint64_t i1, i2;
988 35360 cf_hash(h, item, len, &fp, &i1, &i2);
989  
990 35360 ▶ if (cf_bucket_insert(h, i1, fp) || cf_bucket_insert(h, i2, fp)) {
Branch: 2 branches
BranchTrueFalseTotal
if (cf_bucket_insert(h, i1, fp) || cf_bucket_insert(h, i2, fp)) { 1989 33371 35360
if (cf_bucket_insert(h, i1, fp) || cf_bucket_insert(h, i2, fp)) { 1531 458 1989
991 34902 h->hdr->count++;
992 34902 return 1;
993 }
994  
995 /* Both candidate buckets are full -> cuckoo eviction with a recorded
996 * path so an exhausted run can be rolled back to a byte-identical state. */
997 uint64_t path_i[CF_MAX_KICKS];
998 uint8_t path_j[CF_MAX_KICKS];
999 458 ▶ uint64_t i = (cf_rng_next(h) & 1) ? i1 : i2;
Branch: 1 branch
BranchTrueFalseTotal
uint64_t i = (cf_rng_next(h) & 1) ? i1 : i2; 231 227 458
1000 458 uint16_t carried = fp;
1001 7085 ▶ for (int n = 0; n < CF_MAX_KICKS; n++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int n = 0; n < CF_MAX_KICKS; n++) { 7082 3 7085
1002 7082 uint8_t j = (uint8_t)(cf_rng_next(h) % CF_SLOTS);
1003 7082 path_i[n] = i;
1004 7082 path_j[n] = j;
1005 7082 uint16_t tmp = cf_bucket(h, i)[j]; /* swap carried into slot j */
1006 7082 cf_bucket(h, i)[j] = carried;
1007 7082 carried = tmp;
1008 7082 i = cf_alt(h, i, carried); /* follow the evicted fingerprint */
1009 7082 ▶ if (cf_bucket_insert(h, i, carried)) { /* free slot in the new bucket? */
Branch: 1 branch
BranchTrueFalseTotal
if (cf_bucket_insert(h, i, carried)) { /* free slot in the new bucket? */ 455 6627 7082
1010 455 h->hdr->count++;
1011 455 return 1; /* placed -> committed */
1012 }
1013 }
1014 /* Exhausted: roll back every swap in reverse so the table is unchanged.
1015 * After undoing step 0, carried == fp and nothing was modified. */
1016 1503 ▶ for (int n = CF_MAX_KICKS - 1; n >= 0; n--) {
Branch: 1 branch
BranchTrueFalseTotal
for (int n = CF_MAX_KICKS - 1; n >= 0; n--) { 1500 3 1503
1017 1500 uint16_t tmp = cf_bucket(h, path_i[n])[path_j[n]];
1018 1500 cf_bucket(h, path_i[n])[path_j[n]] = carried;
1019 1500 carried = tmp;
1020 }
1021 3 return 0; /* full; fingerprint table restored */
1022 }
1023  
1024 /* return 1 if (item,len) is probably present, else 0 (definitely absent) */
1025 26843 static int cf_contains_locked(CfHandle *h, const void *item, size_t len) {
1026 uint16_t fp;
1027 uint64_t i1, i2;
1028 26843 cf_hash(h, item, len, &fp, &i1, &i2);
1029 26843 ▶ return cf_bucket_find(h, i1, fp) >= 0 || cf_bucket_find(h, i2, fp) >= 0;
Branch: 2 branches
BranchTrueFalseTotal
return cf_bucket_find(h, i1, fp) >= 0 || cf_bucket_find(h, i2, fp) >= 0; 14162 12681 26843
return cf_bucket_find(h, i1, fp) >= 0 || cf_bucket_find(h, i2, fp) >= 0; 1653 12509 14162
1030 }
1031  
1032 /* Number of stored fingerprints matching (item,len) across its two candidate
1033 * buckets: 0 .. 2*CF_SLOTS. Since add stores a fresh copy each time and a given
1034 * fingerprint can only ever live in these two buckets, this is the item's
1035 * occurrence count -- how many times it was added minus removed -- capped at the
1036 * structural ceiling 2*CF_SLOTS (== 8). Probabilistic like contains(): a distinct
1037 * item whose 16-bit fingerprint collides AND maps into a candidate bucket inflates
1038 * the result (the remove() caveat). Guards i2 == i1 (a fingerprint can map both
1039 * candidates to the same bucket) so those 4 slots are not double-counted. */
1040 23 static int cf_count_of_locked(CfHandle *h, const void *item, size_t len) {
1041 uint16_t fp;
1042 uint64_t i1, i2;
1043 23 cf_hash(h, item, len, &fp, &i1, &i2);
1044 23 int n = 0;
1045 23 uint16_t *b = cf_bucket(h, i1);
1046 115 ▶ for (int j = 0; j < CF_SLOTS; j++) if (b[j] == fp) n++;
Branch: 2 branches
BranchTrueFalseTotal
for (int j = 0; j < CF_SLOTS; j++) if (b[j] == fp) n++; 33 59 92
for (int j = 0; j < CF_SLOTS; j++) if (b[j] == fp) n++; 92 23 115
1047 23 ▶ if (i2 != i1) {
Branch: 1 branch
BranchTrueFalseTotal
if (i2 != i1) { 23 0 23
1048 23 b = cf_bucket(h, i2);
1049 115 ▶ for (int j = 0; j < CF_SLOTS; j++) if (b[j] == fp) n++;
Branch: 2 branches
BranchTrueFalseTotal
for (int j = 0; j < CF_SLOTS; j++) if (b[j] == fp) n++; 42 50 92
for (int j = 0; j < CF_SLOTS; j++) if (b[j] == fp) n++; 92 23 115
1050 }
1051 23 return n;
1052 }
1053  
1054 /* remove ONE matching fingerprint of (item,len): clear the slot, return 1 if
1055 * found, else 0. Removing an item that was never added (or one whose 16-bit
1056 * fingerprint collides with a present item) can delete the wrong fingerprint --
1057 * standard cuckoo-filter caveat; only remove items you added. */
1058 4013 static int cf_remove_locked(CfHandle *h, const void *item, size_t len) {
1059 uint16_t fp;
1060 uint64_t i1, i2;
1061 4013 cf_hash(h, item, len, &fp, &i1, &i2);
1062 4013 uint64_t b = i1;
1063 4013 int j = cf_bucket_find(h, b, fp);
1064 4013 ▶ if (j < 0) j = cf_bucket_find(h, b = i2, fp);
Branch: 1 branch
BranchTrueFalseTotal
if (j < 0) j = cf_bucket_find(h, b = i2, fp); 209 3804 4013
1065 4013 ▶ if (j < 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (j < 0) return 0; 2 4011 4013
1066 4011 cf_bucket(h, b)[j] = 0;
1067 /* An add killed between its slot store and count++ left the count short: never wrap it. */
1068 4011 __atomic_signal_fence(__ATOMIC_SEQ_CST);
1069 4011 ▶ if (h->hdr->count) h->hdr->count--;
Branch: 1 branch
BranchTrueFalseTotal
if (h->hdr->count) h->hdr->count--; 4011 0 4011
1070 4011 return 1;
1071 }
1072  
1073 /* reset all slots to 0, count = 0 (caller holds the write lock) */
1074 1 static inline void cf_clear_locked(CfHandle *h) {
1075 /* Layer B: bound the memset length by the physically-mapped bucket count so
1076 * a corrupted hdr->num_buckets can't drive an out-of-bounds write. For
1077 * valid data num_buckets == phys, so the clamp is a no-op. */
1078 1 uint64_t nb = h->hdr->num_buckets, phys = cf_phys_buckets(h);
1079 1 ▶ if (nb > phys) nb = phys;
Branch: 1 branch
BranchTrueFalseTotal
if (nb > phys) nb = phys; 0 1 1
1080 1 memset(cf_slots(h), 0, (size_t)(nb * (uint64_t)CF_SLOTS * sizeof(uint16_t)));
1081 1 h->hdr->count = 0;
1082 1 }
1083  
1084 #endif /* CUCKOO_H */
« xxhash.h ↑ Summary Shared.xs »