dsu.h

filter: Statementstmt 64.4% 292 / 453 Branchbran 41.0% 151 / 368 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 53.9% 443 / 821 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Data/DisjointSet/Shared.pm ↑ Summary Shared.xs »
1 /*
2 * dsu.h -- Shared-memory union-find (disjoint-set) for Linux
3 *
4 * Maintains a partition of a fixed universe of N integer elements (0..N-1)
5 * into disjoint sets. union(a,b) merges the two sets containing a and b;
6 * find(x) returns the canonical representative (root) of x's set; connected
7 * tests whether two elements are in the same set. Path compression (path
8 * halving) on find plus union by size give near-constant amortized time per
9 * operation. The parent/size arrays live in a shared mapping so several
10 * processes share one structure; a write-preferring futex rwlock with
11 * reader-slot dead-process recovery guards mutation.
12 *
13 * NOTE: find / connected / set_size perform path compression -- they MUTATE
14 * the structure -- so every accessor that calls dsu_find acquires the WRITE
15 * lock. Only num_sets / capacity are true read-only operations.
16 *
17 * Layout: Header -> reader_slots[1024] -> occ bitmap -> parent[n] (uint32) -> size[n] (uint32)
18 */
19  
20 #ifndef DSU_H
21 #define DSU_H
22  
23 #include <stddef.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <time.h>
31 #include <limits.h>
32 #include <signal.h>
33 #include <stdio.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 #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
42 #error "dsu.h: requires little-endian architecture"
43 #endif
44  
45  
46 /* ================================================================
47 * Constants
48 * ================================================================ */
49  
50 #define DSU_MAGIC 0x55534444U /* "DDSU" (little-endian) */
51 #define DSU_VERSION 2 /* 2: added the occupancy bitmap region (layout change) */
52 #define DSU_ERR_BUFLEN (PATH_MAX + 256)
53 #define DSU_READER_SLOTS 1024 /* max concurrent reader processes for dead-process recovery */
54  
55 /* Occupancy bitmap: one bit per reader slot, set when a process claims a slot and
56 * cleared on clean release. A writer scans these DSU_OCC_WORDS words to visit
57 * only OCCUPIED slots (O(words + live readers)) instead of all DSU_READER_SLOTS. */
58 #define DSU_OCC_WORDS (((DSU_READER_SLOTS) + 63) / 64) /* 16 for 1024 slots */
59 #define DSU_OCC_BYTES ((uint64_t)DSU_OCC_WORDS * 8) /* 128 bytes */
60 #define DSU_MAX_N (1u << 31) /* 2.1B elements: keeps n*8 well within size_t and size[] sums within uint32 */
61 #define DSU_OP_RESET 1u /* hdr->op: a reset is in progress */
62  
63 #define DSU_ERR(fmt, ...) do { if (errbuf) snprintf(errbuf, DSU_ERR_BUFLEN, fmt, ##__VA_ARGS__); } while (0)
64  
65 /* ================================================================
66 * Structs
67 * ================================================================ */
68  
69 /* Per-process slot for dead-process recovery. In the reader-slots-only rwlock a
70 * reader's ENTIRE contribution to the shared lock is `rdepth` in its OWN slot --
71 * there is no separate shared reader counter to fall out of sync with it -- so a
72 * dead reader's contribution is exactly this one word, which a draining writer
73 * neutralises by clearing the slot's pid (the scan then ignores the slot). No
74 * orphaned counter can exist, so there is no quiescent force-reset and sustained
75 * readers cannot starve a writer. _rsv1/_rsv2 are kept only to preserve the
76 * 16-byte slot size across the already-released builds. */
77 typedef struct {
78 uint32_t pid; /* 0 = unclaimed */
79 uint32_t rdepth; /* read-locks THIS process currently holds (recursion-safe) */
80 uint32_t _rsv1; /* reserved (was waiters_parked); unused, kept for layout size */
81 uint32_t _rsv2; /* reserved (was writers_parked); unused, kept for layout size */
82 } DsuReaderSlot;
83  
84 struct DsuHeader {
85 uint32_t magic, version; /* 0,4 */
86 uint32_t _pad0; /* 8 */
87 uint32_t _pad1; /* 12 */
88  
89 /* ---- configuration / partition state ---- */
90 uint32_t n; /* 16 number of elements = capacity */
91 uint32_t num_sets; /* 20 current count of disjoint sets */
92 uint32_t _pad2; /* 24 */
93 uint32_t _pad3; /* 28 */
94  
95 /* ---- offsets / size ---- */
96 uint64_t total_size; /* 32 */
97 uint64_t reader_slots_off; /* 40 */
98 uint64_t parent_off; /* 48 */
99 uint64_t size_off; /* 56 */
100  
101 /* ---- lock + stats ---- */
102 uint32_t wlock; /* 64 WRITER word ONLY: 0 (free) or WRITER_BIT|pid. NOT a reader count. */
103 uint32_t rwait; /* 68 parked-waiter hint (readers+writers blocked on wlock); over-count-safe */
104 uint32_t drain_seq; /* 72 futex bumped by a reader releasing under a draining writer (wakes it) */
105 uint32_t slotless_rdepth; /* 76 readers holding with no reader-slot (documented residual) */
106 uint64_t stat_ops; /* 80 */
107 uint32_t op; /* 88 DSU_OP_* in progress, 0 = none (was padding) */
108 uint8_t _pad[164]; /* 92..255 */
109 };
110 typedef struct DsuHeader DsuHeader;
111  
112 _Static_assert(sizeof(DsuHeader) == 256, "DsuHeader must be 256 bytes");
113  
114 /* ---- Process-local handle ---- */
115  
116 typedef struct DsuHandle {
117 DsuHeader *hdr;
118 DsuReaderSlot *reader_slots; /* DSU_READER_SLOTS entries */
119 void *base; /* mmap base */
120 uint32_t n; /* cached capacity (hdr->n is peer-writable; snapshot at attach) */
121 uint32_t *parent; /* cached parent[] base from trusted layout, not hdr->parent_off */
122 uint32_t *size; /* cached size[] base from trusted layout, not hdr->size_off */
123 uint64_t *occ; /* DSU_OCC_WORDS-word slot-occupancy bitmap (trusted layout offset) */
124 size_t mmap_size;
125 char *path; /* backing file path (strdup'd) */
126 int backing_fd; /* memfd or reopened-fd to close on destroy, -1 for file/anon */
127 uint32_t my_slot_idx; /* UINT32_MAX if all slots taken (no recovery for this handle) */
128 uint32_t cached_pid; /* getpid() cached at last slot claim */
129 uint32_t cached_fork_gen; /* dsu_fork_gen value at last slot claim */
130 uint32_t slotless_held; /* read-locks this process holds with no reader-slot */
131 } DsuHandle;
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 DSU_RWLOCK_SPIN_LIMIT 32
155 #define DSU_LOCK_TIMEOUT_SEC 2 /* FUTEX_WAIT timeout for stale-lock detection / drain re-scan */
156  
157 0 static inline void dsu_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 DSU_RWLOCK_WRITER_BIT 0x80000000U
169 #define DSU_RWLOCK_PID_MASK 0x7FFFFFFFU
170 #define DSU_RWLOCK_WR(pid) (DSU_RWLOCK_WRITER_BIT | ((uint32_t)(pid) & DSU_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 dsu_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 dsu_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 !dsu_pid_is_zombie(pid); /* kill() also succeeds for a zombie -> treat as dead */
198 }
199  
200 static const struct timespec dsu_lock_timeout = { DSU_LOCK_TIMEOUT_SEC, 0 };
201  
202 /* Process-global fork-generation counter. Incremented in the pthread_atfork
203 * child callback so every open handle detects a fork transition on the next
204 * lock call without paying a getpid() syscall on the hot path. */
205 static uint32_t dsu_fork_gen = 1;
206 static pthread_once_t dsu_atfork_once = PTHREAD_ONCE_INIT;
207 0 static void dsu_on_fork_child(void) {
208 0 __atomic_add_fetch(&dsu_fork_gen, 1, __ATOMIC_RELAXED);
209 0 }
210 4 static void dsu_atfork_init(void) {
211 4 pthread_atfork(NULL, NULL, dsu_on_fork_child);
212 4 }
213  
214 /* Occupancy bitmap: set a slot's bit when it is claimed, clear it on clean
215 * release. SEQ_CST so a set bit is ordered before the slot's rdepth can go
216 * non-zero (bit set in claim, which precedes any rdlock), letting a writer's
217 * SEQ_CST bitmap scan never miss a slot a committed reader holds. */
218 24 static inline void dsu_occ_set(DsuHandle *h, uint32_t s) {
219 24 __atomic_fetch_or(&h->occ[s >> 6], (uint64_t)1 << (s & 63), __ATOMIC_SEQ_CST);
220 24 }
221 24 static inline void dsu_occ_clear(DsuHandle *h, uint32_t s) {
222 24 __atomic_fetch_and(&h->occ[s >> 6], ~((uint64_t)1 << (s & 63)), __ATOMIC_SEQ_CST);
223 24 }
224  
225 /* Ensure this process owns a reader slot. Called from the lock helpers so
226 * that fork()'d children pick up their own slot lazily instead of sharing
227 * the parent's. Hot-path is a single relaxed load + compare; only on a
228 * fork-generation mismatch do we touch getpid() and scan slots. */
229 14888 static inline void dsu_claim_reader_slot(DsuHandle *h) {
230 14888 uint32_t cur_gen = __atomic_load_n(&dsu_fork_gen, __ATOMIC_RELAXED);
231 14888 ▶ 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)) 14864 24 14888
if (__builtin_expect(cur_gen == h->cached_fork_gen && h->my_slot_idx != UINT32_MAX, 1)) 14864 0 14864
232 14864 return;
233 /* Cold path -- register the atfork hook once per process, then claim. */
234 24 pthread_once(&dsu_atfork_once, dsu_atfork_init);
235 /* Re-read after pthread_once: dsu_on_fork_child may have bumped it. */
236 24 cur_gen = __atomic_load_n(&dsu_fork_gen, __ATOMIC_RELAXED);
237 24 uint32_t now_pid = (uint32_t)getpid();
238 24 h->cached_pid = now_pid;
239 24 ▶ 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 */ 24 0 24
240 24 h->cached_fork_gen = cur_gen;
241 24 h->my_slot_idx = UINT32_MAX;
242 24 uint32_t start = now_pid % DSU_READER_SLOTS;
243 /* Pass 1: take a free slot. */
244 26 ▶ for (uint32_t i = 0; i < DSU_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < DSU_READER_SLOTS; i++) { 26 0 26
245 26 uint32_t s = (start + i) % DSU_READER_SLOTS;
246 26 uint32_t expected = 0;
247 26 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[s].pid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[s].pid, 24 2 26
248 &expected, now_pid, 0,
249 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
250 /* Fresh owner holds no read locks yet; clear any stale rdepth left by
251 * a dead predecessor (its contribution is dropped as we take over). */
252 24 __atomic_store_n(&h->reader_slots[s].rdepth, 0, __ATOMIC_RELAXED);
253 24 dsu_occ_set(h, s); /* mark occupied BEFORE any rdlock can bump rdepth */
254 24 h->my_slot_idx = s;
255 24 return;
256 }
257 }
258 /* Pass 2: no free slot -- reclaim one whose owner is dead. Safe to take even
259 * if its rdepth>0: clearing pid drops the dead reader's entire contribution
260 * (a writer scan ignores rdepth when pid==0) and we reset rdepth to 0 as we
261 * claim it. */
262 0 ▶ for (uint32_t i = 0; i < DSU_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < DSU_READER_SLOTS; i++) { 0 0 0
263 0 uint32_t dpid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
264 0 ▶ if (dpid == 0 || dpid == now_pid || dsu_pid_alive(dpid)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (dpid == 0 || dpid == now_pid || dsu_pid_alive(dpid)) continue; 0 0 0
if (dpid == 0 || dpid == now_pid || dsu_pid_alive(dpid)) continue; 0 0 0
if (dpid == 0 || dpid == now_pid || dsu_pid_alive(dpid)) continue; 0 0 0
265 0 uint32_t expected = dpid;
266 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
267 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
268 0 __atomic_store_n(&h->reader_slots[i].rdepth, 0, __ATOMIC_RELAXED);
269 0 dsu_occ_set(h, i);
270 0 h->my_slot_idx = i;
271 0 return;
272 }
273 }
274 /* Table full -- leave my_slot_idx = UINT32_MAX so this handle takes the
275 * slotless path (lock still works; recovery of THIS reader's death is the
276 * documented slotless limitation). */
277 }
278  
279 /* Wait until no live reader holds the lock; the caller owns wlock, so no NEW
280 * reader can join (they see wlock!=0 and yield). The SEQ_CST wlock CAS + the
281 * SEQ_CST rdepth loads below are the writer side of the Dekker handshake. */
282 12863 static inline void dsu_rwlock_drain(DsuHandle *h) {
283 12863 DsuHeader *hdr = h->hdr;
284 0 for (;;) {
285 12863 uint32_t v = __atomic_load_n(&hdr->drain_seq, __ATOMIC_ACQUIRE); /* snapshot BEFORE scan */
286 12863 int busy = 0;
287 /* Visit only OCCUPIED slots via the occupancy bitmap (SEQ_CST: a committed
288 * reader's bit -- set in claim, before its rdepth++ -- is ordered before
289 * this scan, so no held slot is skipped). O(DSU_OCC_WORDS + live readers)
290 * instead of O(DSU_READER_SLOTS). */
291 218671 ▶ for (uint32_t w = 0; w < DSU_OCC_WORDS; w++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t w = 0; w < DSU_OCC_WORDS; w++) { 205808 12863 218671
292 205808 uint64_t word = __atomic_load_n(&h->occ[w], __ATOMIC_SEQ_CST);
293 218693 ▶ while (word) {
Branch: 1 branch
BranchTrueFalseTotal
while (word) { 12885 205808 218693
294 12885 uint32_t i = (w << 6) + (uint32_t)__builtin_ctzll(word);
295 12885 word &= word - 1; /* consume this bit (local copy) */
296 12885 uint32_t rd = __atomic_load_n(&h->reader_slots[i].rdepth, __ATOMIC_SEQ_CST);
297 12885 ▶ if (rd == 0) continue; /* occupied but not read-locking now */
Branch: 1 branch
BranchTrueFalseTotal
if (rd == 0) continue; /* occupied but not read-locking now */ 12885 0 12885
298 0 uint32_t pid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
299 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
300 0 ▶ if (!dsu_pid_alive(pid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_pid_alive(pid)) { 0 0 0
301 /* Dead reader: drop its pid so the slot no longer counts. Leave
302 * the occ bit set (harmless -- a later scan hits pid==0 and skips,
303 * a re-claim re-sets it) to avoid racing a concurrent claimant. */
304 0 uint32_t ep = pid;
305 0 __atomic_compare_exchange_n(&h->reader_slots[i].pid, &ep, 0,
306 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
307 0 continue;
308 }
309 0 busy = 1; /* live reader still holding */
310 }
311 }
312 /* A live slotless reader keeps us waiting; a crashed slotless reader that
313 * cannot be attributed to a pid is the documented slotless limitation. */
314 12863 ▶ 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 12863 12863
315 0 busy = 1;
316 12863 ▶ if (!busy)
Branch: 1 branch
BranchTrueFalseTotal
if (!busy) 12863 0 12863
317 12863 return; /* exclusive: wlock held + every rdepth 0 */
318 /* Wait for a reader to release (drain_seq bump) or time out to re-scan
319 * (which reclaims any newly-dead slotted reader). */
320 0 syscall(SYS_futex, &hdr->drain_seq, FUTEX_WAIT, v, &dsu_lock_timeout, NULL, 0);
321 }
322 }
323  
324 /* 1 if this process holds a read lock on the segment (through any handle). Such a
325 * lock predates the current wlock holder, whose drain could then never have
326 * finished: it died before mutating anything. */
327 0 static int dsu_self_reading(DsuHandle *h) {
328 0 ▶ if (h->slotless_held) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (h->slotless_held) return 1; 0 0 0
329 0 uint32_t me = (uint32_t)getpid();
330 0 ▶ for (uint32_t i = 0; i < DSU_READER_SLOTS; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < DSU_READER_SLOTS; i++) 0 0 0
331 0 ▶ if (__atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE) == me &&
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE) == me && 0 0 0
332 0 ▶ __atomic_load_n(&h->reader_slots[i].rdepth, __ATOMIC_ACQUIRE) != 0)
Branch: 1 branch
BranchTrueFalseTotal
__atomic_load_n(&h->reader_slots[i].rdepth, __ATOMIC_ACQUIRE) != 0) 0 0 0
333 0 return 1;
334 0 return 0;
335 }
336  
337 static void dsu_repair_locked(DsuHandle *h);
338  
339 /* Force-recover a stale WRITE lock left by a dead writer (held or mid-drain).
340 * CAS to OUR pid to hold the lock while repairing shared state, then release.
341 * Using our pid (not a bare WRITER_BIT sentinel) means a subsequent recovering
342 * process can detect and re-recover if we crash mid-recovery. */
343 0 static inline void dsu_recover_stale_lock(DsuHandle *h, uint32_t observed_wlock) {
344 0 DsuHeader *hdr = h->hdr;
345 0 uint32_t mypid = DSU_RWLOCK_WR((uint32_t)getpid());
346 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
347 mypid, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED))
348 0 return;
349 0 ▶ if (!dsu_self_reading(h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_self_reading(h)) { 0 0 0
350 0 dsu_rwlock_drain(h);
351 0 dsu_repair_locked(h);
352 }
353 0 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_SEQ_CST);
354 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
355 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
356 }
357  
358 /* Inspect the writer word after a futex-wait timeout. If a dead writer holds
359 * it, force-recover. Dead READERS need no action here: only a writer that owns
360 * wlock drains readers, and it clears dead readers inline in its own scan. */
361 0 static inline void dsu_recover_after_timeout(DsuHandle *h) {
362 0 uint32_t val = __atomic_load_n(&h->hdr->wlock, __ATOMIC_RELAXED);
363 0 ▶ if (val >= DSU_RWLOCK_WRITER_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (val >= DSU_RWLOCK_WRITER_BIT) { 0 0 0
364 0 uint32_t pid = val & DSU_RWLOCK_PID_MASK;
365 0 ▶ if (!dsu_pid_alive(pid))
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_pid_alive(pid)) 0 0 0
366 0 dsu_recover_stale_lock(h, val);
367 }
368 0 }
369  
370 /* Bump/drop the parked-waiter hint. Both readers (blocked at the gate) and
371 * writers (blocked acquiring wlock) wait on the wlock futex and use this, so
372 * wrunlock/recover know whether a FUTEX_WAKE is worth a syscall. A waiter
373 * SIGKILLed while parked leaves rwait over-counted -> at most a spurious wake
374 * (harmless); it can never under-count, so no wakeup is lost. */
375 0 static inline void dsu_park(DsuHandle *h) {
376 0 __atomic_add_fetch(&h->hdr->rwait, 1, __ATOMIC_SEQ_CST);
377 0 }
378 0 static inline void dsu_unpark(DsuHandle *h) {
379 0 __atomic_sub_fetch(&h->hdr->rwait, 1, __ATOMIC_RELAXED);
380 0 }
381  
382 /* Publish (inc) / retract (dec) this reader's presence -- its ENTIRE
383 * contribution to the lock. A slotted reader uses its slot's rdepth; a reader
384 * that could not claim a slot uses the global slotless_rdepth. inc() is SEQ_CST
385 * so the wlock re-check that follows it in rdlock forms a Dekker handshake with
386 * the writer's SEQ_CST wlock-store + rdepth-scan. leave() peels slotless first
387 * so a slot claimed mid-hold cannot misattribute the decrement. */
388 2025 static inline void dsu_rdepth_inc(DsuHandle *h) {
389 2025 ▶ if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->my_slot_idx != UINT32_MAX) { 2025 0 2025
390 2025 __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_SEQ_CST);
391 } else {
392 0 __atomic_add_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_SEQ_CST);
393 0 h->slotless_held++;
394 }
395 2025 }
396 2025 static inline void dsu_rdepth_dec(DsuHandle *h) {
397 2025 ▶ if (h->slotless_held > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->slotless_held > 0) { 0 2025 2025
398 0 h->slotless_held--;
399 0 __atomic_sub_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_SEQ_CST);
400 2025 ▶ } else if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (h->my_slot_idx != UINT32_MAX) { 2025 0 2025
401 2025 __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_SEQ_CST);
402 }
403 2025 }
404  
405 /* Wake a writer that may be draining readers (it waits on drain_seq). Called
406 * after every rdepth decrement so a released read lock lets the writer re-scan
407 * promptly instead of waiting out its timeout. */
408 2025 static inline void dsu_reader_wake_drain(DsuHandle *h) {
409 2025 ▶ 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 2025 2025
410 0 __atomic_add_fetch(&h->hdr->drain_seq, 1, __ATOMIC_RELEASE);
411 0 syscall(SYS_futex, &h->hdr->drain_seq, FUTEX_WAKE, 1, NULL, NULL, 0);
412 }
413 2025 }
414  
415 2025 static inline void dsu_rwlock_rdlock(DsuHandle *h) {
416 2025 dsu_claim_reader_slot(h);
417 2025 DsuHeader *hdr = h->hdr;
418 2025 for (int spin = 0; ; spin++) {
419 2025 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_ACQUIRE);
420 2025 ▶ if (cur == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur == 0) { 2025 0 2025
421 /* Optimistically take the read: publish rdepth, then re-check wlock.
422 * SEQ_CST inc + SEQ_CST load vs the writer's SEQ_CST wlock CAS +
423 * SEQ_CST rdepth scan: by the single total order of SEQ_CST ops the
424 * two sides cannot both miss each other, so we never hold
425 * concurrently with a writer. */
426 2025 dsu_rdepth_inc(h);
427 2025 ▶ if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0) 2025 0 2025
428 2025 return; /* no writer after our publish -> we hold the read lock */
429 /* A writer appeared during our publish -- yield to it (write-preferring). */
430 0 dsu_rdepth_dec(h);
431 0 dsu_reader_wake_drain(h); /* let the draining writer see rdepth drop */
432 0 spin = 0;
433 0 continue;
434 }
435 /* wlock != 0: a writer holds or is acquiring. Recover if it is dead. */
436 0 if (cur >= DSU_RWLOCK_WRITER_BIT &&
437 0 !dsu_pid_alive(cur & DSU_RWLOCK_PID_MASK)) {
438 0 dsu_recover_stale_lock(h, cur);
439 0 spin = 0;
440 0 continue;
441 }
442 0 ▶ if (__builtin_expect(spin < DSU_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < DSU_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
443 0 dsu_rwlock_spin_pause();
444 0 continue;
445 }
446 0 dsu_park(h);
447 0 cur = __atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST);
448 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
449 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
450 &dsu_lock_timeout, NULL, 0);
451 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
452 0 dsu_unpark(h);
453 0 dsu_recover_after_timeout(h);
454 0 spin = 0;
455 0 continue;
456 }
457 }
458 0 dsu_unpark(h);
459 0 spin = 0;
460 }
461 }
462  
463 2025 static inline void dsu_rwlock_rdunlock(DsuHandle *h) {
464 2025 dsu_rdepth_dec(h); /* RELEASE: drop our entire contribution */
465 2025 dsu_reader_wake_drain(h); /* if a writer is draining, wake it to re-scan */
466 2025 }
467  
468 12863 static inline void dsu_rwlock_wrlock(DsuHandle *h) {
469 12863 dsu_claim_reader_slot(h); /* refresh cached_pid across fork */
470 12863 DsuHeader *hdr = h->hdr;
471 /* Encode PID in the wlock word itself (0x80000000 | pid) to eliminate any
472 * crash window between acquiring the lock and storing the owner. */
473 12863 uint32_t mypid = DSU_RWLOCK_WR(h->cached_pid);
474 /* Phase 1: acquire the writer word (mutual exclusion among writers). */
475 12863 for (int spin = 0; ; spin++) {
476 12863 uint32_t expected = 0;
477 12863 ▶ if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid, 12863 0 12863
478 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED))
479 12863 break;
480 /* Contended: expected now holds the current wlock value. */
481 0 if (expected >= DSU_RWLOCK_WRITER_BIT &&
482 0 !dsu_pid_alive(expected & DSU_RWLOCK_PID_MASK)) {
483 0 dsu_recover_stale_lock(h, expected);
484 0 spin = 0;
485 0 continue;
486 }
487 0 ▶ if (__builtin_expect(spin < DSU_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < DSU_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
488 0 dsu_rwlock_spin_pause();
489 0 continue;
490 }
491 0 dsu_park(h);
492 0 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST);
493 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
494 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
495 &dsu_lock_timeout, NULL, 0);
496 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
497 0 dsu_unpark(h);
498 0 dsu_recover_after_timeout(h);
499 0 spin = 0;
500 0 continue;
501 }
502 }
503 0 dsu_unpark(h);
504 0 spin = 0;
505 }
506 /* Phase 2: drain the readers that were already holding when we won the CAS. */
507 12863 dsu_rwlock_drain(h);
508 12863 }
509  
510 12863 static inline void dsu_rwlock_wrunlock(DsuHandle *h) {
511 12863 DsuHeader *hdr = h->hdr;
512 12863 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_RELEASE);
513 /* Count the operation and order unlock before checking the waiter hint. */
514 12863 __atomic_fetch_add(&hdr->stat_ops, 1, __ATOMIC_SEQ_CST);
515 12863 ▶ 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 12863 12863
516 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
517 12863 }
518  
519 /* ================================================================
520 * Layout math + create / open / destroy
521 *
522 * Layout: Header -> reader_slots[1024] -> occ bitmap -> parent[n] (uint32) -> size[n] (uint32)
523 * Both arrays are 4-byte words; the reader-slot region and the 8-byte-word occ
524 * bitmap are multiples of 4 bytes, so parent_off and size_off are naturally
525 * 4-byte aligned.
526 * ================================================================ */
527  
528 /* Single source of truth for the mmap region layout offsets:
529 * Header -> reader_slots[] -> occ bitmap -> parent[] -> size[]. */
530 typedef struct { uint64_t reader_slots, occ, parent, size; } DsuLayout;
531  
532 131 static inline DsuLayout dsu_layout(uint32_t n) {
533 DsuLayout L;
534 131 L.reader_slots = sizeof(DsuHeader);
535 131 L.occ = L.reader_slots + (uint64_t)DSU_READER_SLOTS * sizeof(DsuReaderSlot);
536 131 L.parent = L.occ + DSU_OCC_BYTES;
537 131 L.size = L.parent + (uint64_t)n * sizeof(uint32_t);
538 131 return L;
539 }
540  
541 69 static inline uint64_t dsu_total_size(uint32_t n) {
542 69 DsuLayout L = dsu_layout(n);
543 69 return L.size + (uint64_t)n * sizeof(uint32_t); /* parent[n] + size[n] */
544 }
545  
546 /* Return the cached, trusted-layout array bases. We deliberately do NOT read
547 * hdr->parent_off / hdr->size_off here: those live in the peer-writable header
548 * and a lock-violating peer that corrupted them after we attached could aim the
549 * base pointer anywhere, turning an in-range p[x] into an OOB read/write. Both
550 * were validated == dsu_layout(n) at attach and are re-derived from cached n. */
551 21496 static inline uint32_t *dsu_parent(DsuHandle *h) {
552 21496 return h->parent;
553 }
554  
555 3074 static inline uint32_t *dsu_size(DsuHandle *h) {
556 3074 return h->size;
557 }
558  
559 /* ================================================================
560 * Union-find core (callers hold the WRITE lock -- find compresses)
561 * ================================================================ */
562  
563 /* Find the root of x with path halving (every other node on the path is
564 * relinked to its grandparent). MUTATING -- the caller must hold the write
565 * lock. x must already be range-checked (< n) by the XS layer. */
566 20555 static inline uint32_t dsu_find(DsuHandle *h, uint32_t x) {
567 20555 uint32_t *p = dsu_parent(h);
568 20555 uint32_t n = h->n; /* cached at attach; hdr->n is peer-writable */
569 20555 ▶ if (x >= n) return x; /* callers range-check; be defensive */
Branch: 1 branch
BranchTrueFalseTotal
if (x >= n) return x; /* callers range-check; be defensive */ 0 20555 20555
570 35799 ▶ while (p[x] != x) {
Branch: 1 branch
BranchTrueFalseTotal
while (p[x] != x) { 15244 20555 35799
571 /* parent[] values come from the (possibly attacker-tampered) backing
572 * file. Bound each before using it as an index so a poisoned parent
573 * cannot drive an out-of-bounds read or path-halving write (CWE-787);
574 * on a bad value stop and return the current node as a pseudo-root. */
575 15244 uint32_t px = p[x];
576 15244 ▶ if (px >= n) break;
Branch: 1 branch
BranchTrueFalseTotal
if (px >= n) break; 0 15244 15244
577 15244 uint32_t gpx = p[px];
578 15244 ▶ if (gpx >= n) break;
Branch: 1 branch
BranchTrueFalseTotal
if (gpx >= n) break; 0 15244 15244
579 15244 p[x] = gpx; /* path halving */
580 15244 x = gpx;
581 }
582 20555 return x;
583 }
584  
585 /* Union the sets containing a and b by size (the larger-sized root wins, so
586 * the tree stays shallow). Returns 1 if the two were in different sets and
587 * are now merged, 0 if they were already in the same set. Caller holds the
588 * write lock; a and b are range-checked. */
589 2032 static inline int dsu_union_locked(DsuHandle *h, uint32_t a, uint32_t b) {
590 2032 uint32_t ra = dsu_find(h, a), rb = dsu_find(h, b);
591 2032 ▶ if (ra == rb) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (ra == rb) return 0; 1094 938 2032
592 938 uint32_t *p = dsu_parent(h);
593 938 uint32_t *sz = dsu_size(h);
594 938 ▶ if (sz[ra] < sz[rb]) { uint32_t t = ra; ra = rb; rb = t; }
Branch: 1 branch
BranchTrueFalseTotal
if (sz[ra] < sz[rb]) { uint32_t t = ra; ra = rb; rb = t; } 281 657 938
595 938 p[rb] = ra;
596 938 sz[ra] += sz[rb];
597 938 h->hdr->num_sets--;
598 938 return 1;
599 }
600  
601 /* Whether a and b are in the same set (mutates via path compression). */
602 5656 static inline int dsu_connected_locked(DsuHandle *h, uint32_t a, uint32_t b) {
603 5656 return dsu_find(h, a) == dsu_find(h, b);
604 }
605  
606 /* Size of the set containing x (mutates via path compression). */
607 2133 static inline uint32_t dsu_set_size_locked(DsuHandle *h, uint32_t x) {
608 2133 return dsu_size(h)[dsu_find(h, x)];
609 }
610  
611 /* Reset to all singletons: parent[i]=i, size[i]=1, num_sets=n.
612 * Caller holds the write lock. */
613 3 static inline void dsu_reset_locked(DsuHandle *h) {
614 3 uint32_t *p = dsu_parent(h);
615 3 uint32_t *sz = dsu_size(h);
616 3 uint32_t n = h->n; /* cached at attach; hdr->n is peer-writable */
617 3 h->hdr->op = DSU_OP_RESET;
618 3 __atomic_thread_fence(__ATOMIC_RELEASE);
619 51 ▶ for (uint32_t i = 0; i < n; i++) { p[i] = i; sz[i] = 1; }
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < n; i++) { p[i] = i; sz[i] = 1; } 48 3 51
620 3 h->hdr->num_sets = n;
621 3 __atomic_thread_fence(__ATOMIC_RELEASE);
622 3 h->hdr->op = 0;
623 3 }
624  
625 /* A reset killed part-way left its op word set: run it again from scratch.
626 * Otherwise the parent links are authoritative (a union links with one store):
627 * re-derive every root's size and the set count from them. Idempotent. */
628 0 static void dsu_repair_locked(DsuHandle *h) {
629 0 ▶ if (h->hdr->op == DSU_OP_RESET) { dsu_reset_locked(h); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (h->hdr->op == DSU_OP_RESET) { dsu_reset_locked(h); return; } 0 0 0
630 0 uint32_t *p = dsu_parent(h), *sz = dsu_size(h), n = h->n, sets = 0;
631 0 ▶ for (uint32_t i = 0; i < n; i++) if (p[i] >= n) p[i] = i; /* corrupt link */
Branch: 2 branches
BranchTrueFalseTotal
for (uint32_t i = 0; i < n; i++) if (p[i] >= n) p[i] = i; /* corrupt link */ 0 0 0
for (uint32_t i = 0; i < n; i++) if (p[i] >= n) p[i] = i; /* corrupt link */ 0 0 0
632 0 ▶ for (uint32_t i = 0; i < n; i++) dsu_find(h, i); /* halving breaks any cycle */
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < n; i++) dsu_find(h, i); /* halving breaks any cycle */ 0 0 0
633 0 ▶ for (uint32_t i = 0; i < n; i++) if (p[i] == i) { sz[i] = 0; sets++; }
Branch: 2 branches
BranchTrueFalseTotal
for (uint32_t i = 0; i < n; i++) if (p[i] == i) { sz[i] = 0; sets++; } 0 0 0
for (uint32_t i = 0; i < n; i++) if (p[i] == i) { sz[i] = 0; sets++; } 0 0 0
634 0 ▶ for (uint32_t i = 0; i < n; i++) sz[dsu_find(h, i)]++;
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < n; i++) sz[dsu_find(h, i)]++; 0 0 0
635 0 h->hdr->num_sets = sets;
636 }
637  
638 /* ================================================================
639 * Validate args + header init / setup / open / destroy
640 * ================================================================ */
641  
642 /* Validate create args. Single source of truth: the XS layer does NOT
643 * duplicate this range check. */
644 34 static int dsu_validate_create_args(uint64_t n, char *errbuf) {
645 34 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 34 0 34
646 34 ▶ if (n < 1) { DSU_ERR("n must be >= 1"); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (n < 1) { DSU_ERR("n must be >= 1"); return 0; } 2 32 34
if (n < 1) { DSU_ERR("n must be >= 1"); return 0; } 2 0 2
647 32 ▶ if (n > DSU_MAX_N) { DSU_ERR("n must be <= %u", (unsigned)DSU_MAX_N); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (n > DSU_MAX_N) { DSU_ERR("n must be <= %u", (unsigned)DSU_MAX_N); return 0; } 0 32 32
if (n > DSU_MAX_N) { DSU_ERR("n must be <= %u", (unsigned)DSU_MAX_N); return 0; } 0 0 0
648 32 return 1;
649 }
650  
651 25 static inline void dsu_init_header(void *base, uint32_t n, uint64_t total_size) {
652 25 DsuLayout L = dsu_layout(n);
653 25 DsuHeader *hdr = (DsuHeader *)base;
654 /* Explicitly zero the header + reader-slot region (lock-recovery state);
655 the parent/size arrays are initialized explicitly below. */
656 25 memset(base, 0, (size_t)L.parent);
657 25 hdr->version = DSU_VERSION;
658 25 hdr->n = n;
659 25 hdr->num_sets = n;
660 25 hdr->total_size = total_size;
661 25 hdr->reader_slots_off = L.reader_slots;
662 25 hdr->parent_off = L.parent;
663 25 hdr->size_off = L.size;
664 {
665 25 uint32_t *p = (uint32_t *)((char *)base + L.parent);
666 25 uint32_t *sz = (uint32_t *)((char *)base + L.size);
667 2563 ▶ for (uint32_t i = 0; i < n; i++) { p[i] = i; sz[i] = 1; }
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < n; i++) { p[i] = i; sz[i] = 1; } 2538 25 2563
668 }
669 /* Publish magic LAST, as a release store: it is the commit point, so a
670 creator killed before it leaves magic==0 and never a file mistaken for
671 a valid one. A kill during the field stores leaves one to remove by
672 hand. */
673 25 __atomic_store_n(&hdr->magic, DSU_MAGIC, __ATOMIC_RELEASE);
674 25 __atomic_thread_fence(__ATOMIC_SEQ_CST);
675 25 }
676  
677 31 static inline DsuHandle *dsu_setup(void *base, size_t map_size,
678 const char *path, int backing_fd) {
679 31 DsuHeader *hdr = (DsuHeader *)base;
680 31 DsuHandle *h = (DsuHandle *)calloc(1, sizeof(DsuHandle));
681 31 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 31 31
682 0 munmap(base, map_size);
683 0 ▶ if (backing_fd >= 0) close(backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (backing_fd >= 0) close(backing_fd); 0 0 0
684 0 return NULL;
685 }
686 31 h->hdr = hdr;
687 31 h->base = base;
688 31 h->reader_slots = (DsuReaderSlot *)((uint8_t *)base + sizeof(DsuHeader)); /* trusted layout, not the peer-writable header offset */
689 /* Snapshot capacity ONCE into a local and re-verify it against the mapping
690 * size before trusting it: a write-peer can flip hdr->n in the window
691 * between dsu_validate_header and here (after flock(LOCK_UN)/close on the
692 * create-attach path, or after F_DUPFD_CLOEXEC on the open_fd path), so the
693 * earlier validation does not pin the value we cache. Derive array bases
694 * from the TRUSTED layout of the verified local. All hot-path
695 * bounds/indexing use these cached copies so a later peer edit to hdr->n /
696 * hdr->parent_off / hdr->size_off cannot drive OOB access. */
697 {
698 31 uint32_t n = __atomic_load_n(&hdr->n, __ATOMIC_ACQUIRE);
699 31 ▶ if (n < 1 || n > DSU_MAX_N || dsu_total_size(n) != (uint64_t)map_size) {
Branch: 3 branches
BranchTrueFalseTotal
if (n < 1 || n > DSU_MAX_N || dsu_total_size(n) != (uint64_t)map_size) { 31 0 31
if (n < 1 || n > DSU_MAX_N || dsu_total_size(n) != (uint64_t)map_size) { 31 0 31
if (n < 1 || n > DSU_MAX_N || dsu_total_size(n) != (uint64_t)map_size) { 0 31 31
700 0 munmap(base, map_size);
701 0 ▶ if (backing_fd >= 0) close(backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (backing_fd >= 0) close(backing_fd); 0 0 0
702 0 free(h);
703 0 return NULL;
704 }
705 31 DsuLayout L = dsu_layout(n);
706 31 h->n = n;
707 31 h->occ = (uint64_t *)((uint8_t *)base + L.occ); /* trusted layout offset */
708 31 h->parent = (uint32_t *)((uint8_t *)base + L.parent);
709 31 h->size = (uint32_t *)((uint8_t *)base + L.size);
710 }
711 31 h->mmap_size = map_size;
712 31 ▶ h->path = path ? strdup(path) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
h->path = path ? strdup(path) : NULL; 10 21 31
713 31 h->backing_fd = backing_fd;
714 31 h->my_slot_idx = UINT32_MAX;
715 31 return h;
716 }
717  
718 /* Validate a mapped header (shared by dsu_create reopen and dsu_open_fd).
719 * Stored n wins on reopen; require total_size == the size n implies and ==
720 * the actual file size, and all offsets to match the canonical layout. */
721 10 static inline int dsu_validate_header(const DsuHeader *hdr, uint64_t file_size) {
722 10 ▶ if (hdr->magic != DSU_MAGIC) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->magic != DSU_MAGIC) return 0; 4 6 10
723 6 ▶ if (hdr->version != DSU_VERSION) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->version != DSU_VERSION) return 0; 0 6 6
724 6 ▶ if (hdr->n < 1 || hdr->n > DSU_MAX_N) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (hdr->n < 1 || hdr->n > DSU_MAX_N) return 0; 6 0 6
if (hdr->n < 1 || hdr->n > DSU_MAX_N) return 0; 0 6 6
725 6 ▶ if (hdr->num_sets < 1 || hdr->num_sets > hdr->n) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (hdr->num_sets < 1 || hdr->num_sets > hdr->n) return 0; 6 0 6
if (hdr->num_sets < 1 || hdr->num_sets > hdr->n) return 0; 0 6 6
726 6 ▶ if (hdr->total_size != file_size) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->total_size != file_size) return 0; 0 6 6
727 6 ▶ if (hdr->total_size != dsu_total_size(hdr->n)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->total_size != dsu_total_size(hdr->n)) return 0; 0 6 6
728 6 DsuLayout L = dsu_layout(hdr->n);
729 6 ▶ 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 6 6
730 6 ▶ if (hdr->parent_off != L.parent) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->parent_off != L.parent) return 0; 0 6 6
731 6 ▶ if (hdr->size_off != L.size) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->size_off != L.size) return 0; 0 6 6
732 6 return 1;
733 }
734  
735 /* Securely obtain a fd: create exclusively (O_CREAT|O_EXCL|O_NOFOLLOW at mode,
736 * default 0600), or attach an existing file (O_RDWR|O_NOFOLLOW, no O_CREAT). */
737 14 static int dsu_secure_open(const char *path, mode_t mode, char *errbuf) {
738 14 ▶ for (int attempt = 0; attempt < 100; attempt++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int attempt = 0; attempt < 100; attempt++) { 14 0 14
739 14 int fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, mode);
740 14 ▶ if (fd >= 0) return fd; /* apply the exact mode under flock, before initialization */
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) return fd; /* apply the exact mode under flock, before initialization */ 6 8 14
741 8 ▶ if (errno != EEXIST) { DSU_ERR("create %s: %s", path, strerror(errno)); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (errno != EEXIST) { DSU_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 8 8
if (errno != EEXIST) { DSU_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 0 0
742 8 fd = open(path, O_RDWR|O_NOFOLLOW|O_CLOEXEC);
743 8 ▶ if (fd >= 0) return fd;
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) return fd; 8 0 8
744 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
745 0 ▶ DSU_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */ 0 0 0
746 0 return -1;
747 }
748 0 ▶ DSU_ERR("open %s: create/attach kept racing", path);
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("open %s: create/attach kept racing", path); 0 0 0
749 0 return -1;
750 }
751  
752 /* True iff the whole file is zero -- what an abandoned mid-init
753 creator leaves. Lets recovery re-init only a provably-empty file, never
754 one that merely starts with a zero word. Cold path, so a byte scan is
755 fine. Read, not mapped: a read fault on a tmpfs hole allocates the page. */
756 2 static int dsu_file_is_zero(int fd, uint64_t size) {
757 char buf[16384];
758 5 ▶ for (uint64_t off = 0; off < size; ) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t off = 0; off < size; ) { 4 1 5
759 4 ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
760 4 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 4 4
761 33795 ▶ 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 33791 33792
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 33792 3 33795
762 3 off += (uint64_t)n;
763 }
764 1 return 1;
765 }
766  
767 /* A sparse segment would SIGBUS at the first write the filesystem cannot back. */
768 10 static int dsu_reserve(int fd, uint64_t size) {
769 10 const char *sp = getenv("DATA_DISJOINTSET_SHARED_SPARSE");
770 10 ▶ if (sp && *sp && strcmp(sp, "0")) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (sp && *sp && strcmp(sp, "0")) return 0; 0 10 10
if (sp && *sp && strcmp(sp, "0")) return 0; 0 0 0
if (sp && *sp && strcmp(sp, "0")) return 0; 0 0 0
771 /* Before Linux 6.11 tmpfs gives up at any pending signal and undoes the allocation, so a
772 * periodic one could keep it from ever completing; SIGSTOP cannot be blocked. */
773 sigset_t all, old;
774 10 sigfillset(&all);
775 10 sigprocmask(SIG_BLOCK, &all, &old);
776 int e;
777 10 ▶ 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 10 10
778 10 sigprocmask(SIG_SETMASK, &old, NULL);
779 10 ▶ if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 10 10
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
780 0 errno = e;
781 0 return -1;
782 }
783  
784 30 static DsuHandle *dsu_create(const char *path, uint64_t n_in, mode_t mode, char *errbuf) {
785 30 ▶ if (!dsu_validate_create_args(n_in, errbuf)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_validate_create_args(n_in, errbuf)) return NULL; 1 29 30
786 29 uint32_t n = (uint32_t)n_in;
787  
788 29 uint64_t total = dsu_total_size(n);
789 29 int anonymous = (path == NULL);
790 29 int fd = -1;
791 size_t map_size;
792 void *base;
793  
794 29 ▶ if (anonymous) {
Branch: 1 branch
BranchTrueFalseTotal
if (anonymous) { 15 14 29
795 15 map_size = (size_t)total;
796 15 base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
797 15 ▶ if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); return NULL; } 0 15 15
if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); return NULL; } 0 0 0
798 } else {
799 14 fd = dsu_secure_open(path, mode, errbuf);
800 22 ▶ if (fd < 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return NULL; 0 14 14
801 14 ▶ if (flock(fd, LOCK_EX) < 0) { DSU_ERR("flock: %s", strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (flock(fd, LOCK_EX) < 0) { DSU_ERR("flock: %s", strerror(errno)); close(fd); return NULL; } 0 14 14
if (flock(fd, LOCK_EX) < 0) { DSU_ERR("flock: %s", strerror(errno)); close(fd); return NULL; } 0 0 0
802 struct stat st;
803 14 ▶ if (fstat(fd, &st) < 0) { DSU_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { DSU_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; } 0 14 14
if (fstat(fd, &st) < 0) { DSU_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; } 0 0 0
804 14 int is_new = (st.st_size == 0);
805 14 ▶ if (!is_new && (uint64_t)st.st_size < sizeof(DsuHeader)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!is_new && (uint64_t)st.st_size < sizeof(DsuHeader)) { 8 6 14
if (!is_new && (uint64_t)st.st_size < sizeof(DsuHeader)) { 1 7 8
806 1 ▶ DSU_ERR("%s: file too small (%lld)", path, (long long)st.st_size);
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("%s: file too small (%lld)", path, (long long)st.st_size); 1 0 1
807 1 flock(fd, LOCK_UN); close(fd); return NULL;
808 }
809 13 ▶ 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)) { 6 7 13
if (is_new && (st.st_uid != geteuid() || fchmod(fd, mode) < 0)) { 6 0 6
if (is_new && (st.st_uid != geteuid() || fchmod(fd, mode) < 0)) { 0 6 6
810 0 ▶ DSU_ERR("%s: refusing to initialize file not owned by us", path);
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("%s: refusing to initialize file not owned by us", path); 0 0 0
811 0 flock(fd, LOCK_UN); close(fd); return NULL;
812 }
813 13 ▶ if (is_new && ftruncate(fd, (off_t)total) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_new && ftruncate(fd, (off_t)total) < 0) { 6 7 13
if (is_new && ftruncate(fd, (off_t)total) < 0) { 0 6 6
814 0 ▶ DSU_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("ftruncate: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; 0 0 0
815 }
816 13 ▶ if (is_new && dsu_reserve(fd, total) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_new && dsu_reserve(fd, total) < 0) { 6 7 13
if (is_new && dsu_reserve(fd, total) < 0) { 0 6 6
817 0 ▶ DSU_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno)); 0 0 0
818 0 if (ftruncate(fd, 0) < 0) { /* best effort */ }
819 0 flock(fd, LOCK_UN); close(fd); return NULL;
820 }
821 13 ▶ 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; 7 6 13
822 13 base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
823 13 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 13 13
824 0 ▶ DSU_ERR("mmap: %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("mmap: %s", strerror(errno)); 0 0 0
825 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
826 0 flock(fd, LOCK_UN); close(fd); return NULL;
827 }
828 13 ▶ if (!is_new) {
Branch: 1 branch
BranchTrueFalseTotal
if (!is_new) { 7 6 13
829 7 ▶ if (!dsu_validate_header((DsuHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_validate_header((DsuHeader *)base, (uint64_t)st.st_size)) { 4 3 7
830 /* Recover an abandoned mid-init file: a creator killed
831 * between the ftruncate and the header init leaves a
832 * full-size, all-zero (magic==0) file that would brick every
833 * future open of this path. Re-initialize ONLY when it is
834 * exactly our size, still uninitialized, and owned by us;
835 * anything else still errors. */
836 4 ▶ if (((DsuHeader *)base)->magic == 0 && (uint64_t)st.st_size == total
Branch: 2 branches
BranchTrueFalseTotal
if (((DsuHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 3 1 4
if (((DsuHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 2 1 3
837 2 ▶ && st.st_uid == geteuid() && dsu_file_is_zero(fd, map_size)) {
Branch: 2 branches
BranchTrueFalseTotal
&& st.st_uid == geteuid() && dsu_file_is_zero(fd, map_size)) { 2 0 2
&& st.st_uid == geteuid() && dsu_file_is_zero(fd, map_size)) { 1 1 2
838 1 ▶ if (fchmod(fd, mode) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fchmod(fd, mode) < 0) { 0 1 1
839 0 ▶ DSU_ERR("%s: fchmod: %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("%s: fchmod: %s", path, strerror(errno)); 0 0 0
840 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
841 }
842 1 ▶ if (dsu_reserve(fd, total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (dsu_reserve(fd, total) < 0) { 0 1 1
843 0 ▶ DSU_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total, strerror(errno)); 0 0 0
844 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
845 }
846 1 dsu_init_header(base, n, total);
847 1 flock(fd, LOCK_UN); close(fd);
848 1 return dsu_setup(base, map_size, path, -1);
849 }
850 3 ▶ if (((DsuHeader *)base)->magic == 0 && (uint64_t)st.st_size == total
Branch: 2 branches
BranchTrueFalseTotal
if (((DsuHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 2 1 3
if (((DsuHeader *)base)->magic == 0 && (uint64_t)st.st_size == total 1 1 2
851 1 ▶ && st.st_uid == geteuid()) {
Branch: 1 branch
BranchTrueFalseTotal
&& st.st_uid == geteuid()) { 1 0 1
852 1 ▶ DSU_ERR("%s: incomplete disjoint-set file left by an interrupted create; remove it and retry", path);
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("%s: incomplete disjoint-set file left by an interrupted create; remove it and retry", path); 1 0 1
853 1 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
854 }
855 2 ▶ DSU_ERR("invalid disjoint-set file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("invalid disjoint-set file"); munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL; 2 0 2
856 }
857 3 flock(fd, LOCK_UN); close(fd);
858 3 return dsu_setup(base, map_size, path, -1);
859 }
860 }
861 21 dsu_init_header(base, n, total);
862 21 ▶ if (fd >= 0) { flock(fd, LOCK_UN); close(fd); }
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { flock(fd, LOCK_UN); close(fd); } 6 15 21
863 21 return dsu_setup(base, map_size, path, -1);
864 }
865  
866 4 static DsuHandle *dsu_create_memfd(const char *name, uint64_t n_in, char *errbuf) {
867 4 ▶ if (!dsu_validate_create_args(n_in, errbuf)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_validate_create_args(n_in, errbuf)) return NULL; 1 3 4
868 3 uint32_t n = (uint32_t)n_in;
869  
870 3 uint64_t total = dsu_total_size(n);
871 3 ▶ int fd = memfd_create(name ? name : "dsu", MFD_CLOEXEC | MFD_ALLOW_SEALING);
Branch: 1 branch
BranchTrueFalseTotal
int fd = memfd_create(name ? name : "dsu", MFD_CLOEXEC | MFD_ALLOW_SEALING); 2 1 3
872 3 ▶ if (fd < 0) { DSU_ERR("memfd_create: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0) { DSU_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 3 3
if (fd < 0) { DSU_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 0 0
873 3 ▶ if (ftruncate(fd, (off_t)total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total) < 0) { 0 3 3
874 0 ▶ DSU_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL; 0 0 0
875 }
876 3 ▶ if (dsu_reserve(fd, total) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (dsu_reserve(fd, total) < 0) { 0 3 3
877 0 ▶ DSU_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total, strerror(errno)); 0 0 0
878 0 close(fd); return NULL;
879 }
880 3 (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
881 3 void *base = mmap(NULL, (size_t)total, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
882 3 ▶ if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; } 0 3 3
if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; } 0 0 0
883 3 dsu_init_header(base, n, total);
884 3 return dsu_setup(base, (size_t)total, NULL, fd);
885 }
886  
887 4 static DsuHandle *dsu_open_fd(int fd, char *errbuf) {
888 4 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 4 0 4
889 struct stat st;
890 4 ▶ if (fstat(fd, &st) < 0) { DSU_ERR("fstat: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { DSU_ERR("fstat: %s", strerror(errno)); return NULL; } 0 4 4
if (fstat(fd, &st) < 0) { DSU_ERR("fstat: %s", strerror(errno)); return NULL; } 0 0 0
891 4 ▶ if ((uint64_t)st.st_size < sizeof(DsuHeader)) { DSU_ERR("too small"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(DsuHeader)) { DSU_ERR("too small"); return NULL; } 1 3 4
if ((uint64_t)st.st_size < sizeof(DsuHeader)) { DSU_ERR("too small"); return NULL; } 1 0 1
892 /* before mmap: a creator may truncate the file until it has set magic */
893 uint32_t magic;
894 3 ▶ if (pread(fd, &magic, sizeof magic, offsetof(DsuHeader, magic)) != (ssize_t)sizeof magic || magic != DSU_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(DsuHeader, magic)) != (ssize_t)sizeof magic || magic != DSU_MAGIC) { 3 0 3
if (pread(fd, &magic, sizeof magic, offsetof(DsuHeader, magic)) != (ssize_t)sizeof magic || magic != DSU_MAGIC) { 0 3 3
895 0 ▶ DSU_ERR("invalid disjoint-set table"); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("invalid disjoint-set table"); return NULL; 0 0 0
896 }
897 3 size_t ms = (size_t)st.st_size;
898 3 void *base = mmap(NULL, ms, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
899 3 ▶ if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); return NULL; } 0 3 3
if (base == MAP_FAILED) { DSU_ERR("mmap: %s", strerror(errno)); return NULL; } 0 0 0
900 3 ▶ if (!dsu_validate_header((DsuHeader *)base, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!dsu_validate_header((DsuHeader *)base, (uint64_t)st.st_size)) { 0 3 3
901 0 ▶ DSU_ERR("invalid disjoint-set table"); munmap(base, ms); return NULL;
Branch: 1 branch
BranchTrueFalseTotal
DSU_ERR("invalid disjoint-set table"); munmap(base, ms); return NULL; 0 0 0
902 }
903 3 int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
904 3 ▶ if (myfd < 0) { DSU_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (myfd < 0) { DSU_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; } 0 3 3
if (myfd < 0) { DSU_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; } 0 0 0
905 3 return dsu_setup(base, ms, NULL, myfd);
906 }
907  
908 31 static void dsu_destroy(DsuHandle *h) {
909 31 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 31 31
910 /* Release our reader slot on clean teardown (else short-lived-reader churn
911 * exhausts the slot table); skip if a read lock is still held (rdepth>0). */
912 31 ▶ 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 && 31 0 31
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 24 7 31
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 24 0 24
913 24 ▶ h->cached_fork_gen == __atomic_load_n(&dsu_fork_gen, __ATOMIC_RELAXED) &&
Branch: 1 branch
BranchTrueFalseTotal
h->cached_fork_gen == __atomic_load_n(&dsu_fork_gen, __ATOMIC_RELAXED) && 24 0 24
914 24 ▶ __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) { 24 0 24
915 /* Clear our occ bit BEFORE freeing the slot: we still own the pid so no
916 * claimant can take the slot mid-clear, and rdepth==0 so no writer needs
917 * to see us. (A crash skips this -> the bit is reclaimed lazily by a
918 * writer scan / re-claim, same as the pid.) */
919 24 dsu_occ_clear(h, h->my_slot_idx);
920 24 uint32_t expected = h->cached_pid;
921 24 __atomic_compare_exchange_n(&h->reader_slots[h->my_slot_idx].pid,
922 &expected, 0, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
923 }
924 31 ▶ if (h->backing_fd >= 0) close(h->backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->backing_fd >= 0) close(h->backing_fd); 6 25 31
925 31 ▶ if (h->base) munmap(h->base, h->mmap_size);
Branch: 1 branch
BranchTrueFalseTotal
if (h->base) munmap(h->base, h->mmap_size); 31 0 31
926 31 free(h->path);
927 31 free(h);
928 }
929  
930 2 static inline int dsu_msync(DsuHandle *h) {
931 2 ▶ if (!h || !h->base) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!h || !h->base) return 0; 2 0 2
if (!h || !h->base) return 0; 0 2 2
932 2 return msync(h->base, h->mmap_size, MS_SYNC);
933 }
934  
935 #endif /* DSU_H */
« blib/lib/Data/DisjointSet/Shared.pm ↑ Summary Shared.xs »