Line data Source code
1 : /*
2 : * MIT License
3 : *
4 : * Copyright (c) 2026 - A bunch of nerds
5 : *
6 : * Permission is hereby granted, free of charge, to any person obtaining a copy
7 : * of this software and associated documentation files (the "Software"), to
8 : * deal in the Software without restriction, including without limitation the
9 : * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 : * sell copies of the Software, and to permit persons to whom the Software is
11 : * furnished to do so, subject to the following conditions:
12 : *
13 : * The above copyright notice and this permission notice shall be included in
14 : * all copies or substantial portions of the Software.
15 : *
16 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 : * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 : * DEALINGS IN THE SOFTWARE.
23 : */
24 :
25 : // Internal: The lock-free handle index with per-slot pins (see cpintable.h).
26 :
27 : #include "internal/cpintable.h"
28 :
29 : #include <internal/ctlsmodel.h>
30 : #include <internal/test_helpers/cpintable.h>
31 : #include <stdlib.h>
32 :
33 : // The stripe this thread pins on, stored as stripe + 1 so 0 means "not
34 : // assigned yet". The TLS model comes from ctlsmodel.h: initial-exec with glibc
35 : // and on FreeBSD keeps __tls_get_addr off the pin path, and other C libraries
36 : // get the general model (musl refuses to dlopen() initial-exec objects).
37 : #if defined(CMEMPOOL_DYNAMIC_TLS) && CMEMPOOL_DYNAMIC_TLS
38 : static __thread unsigned pin_stripe_id;
39 : #else
40 : static __thread unsigned pin_stripe_id
41 : __attribute__((tls_model("initial-exec")));
42 : #endif
43 : // Hands out stripe ids, so concurrent threads pin on different cache lines.
44 : static _Atomic unsigned pin_stripe_next = 1;
45 :
46 : // Claims a stripe id for the calling thread from pin_stripe_next and stores
47 : // it in pin_stripe_id, on the thread's first pin or unpin. Gives the id. It's
48 : // out of line so the two hot callers keep the shape they'd have without it.
49 : // An id of 0 after the counter wraps becomes 1; a stored 0 would make the
50 : // thread claim again on every call and release on another stripe than it
51 : // pinned on.
52 1659 : static __attribute__((noinline)) unsigned pin_stripe_claim(void) {
53 1659 : unsigned id =
54 1659 : atomic_fetch_add_explicit(&pin_stripe_next, 1, memory_order_relaxed);
55 1659 : if (id == 0) id = 1;
56 1659 : pin_stripe_id = id;
57 1659 : return id;
58 : }
59 :
60 : // Gives the stripe index of the calling thread, claiming an id on first use.
61 : // Pin and unpin use it so concurrent threads write different cache lines.
62 540662 : static inline unsigned pin_stripe_self(void) {
63 540662 : unsigned id = pin_stripe_id;
64 1659 : if (id == 0) id = pin_stripe_claim();
65 540662 : return (id - 1u) % CCOL_PIN_STRIPES;
66 : }
67 :
68 : // Packs a generation and the live bit into one state word, so a resolve
69 : // checks both with one load and can't straddle a retire.
70 279683 : static inline uint64_t pin_state(uint32_t gen, bool live) {
71 279683 : return ((uint64_t)gen << 1) | (live ? 1u : 0u);
72 : }
73 :
74 : // Gives the slot of idx, or NULL when idx is out of range or its chunk doesn't
75 : // exist yet. Every entry point except publish starts with it; it reads the
76 : // chunk pointer with acquire.
77 563149 : static ccol_pin_slot *pin_slot_lookup(ccol_pintable *t, uint32_t idx) {
78 563149 : uint32_t chunk_idx = idx / CCOL_PIN_CHUNK_SLOTS;
79 563149 : if (chunk_idx >= CCOL_PIN_MAX_CHUNKS) return NULL;
80 563147 : ccol_pin_chunk *chunk =
81 563147 : atomic_load_explicit(&t->chunks[chunk_idx], memory_order_acquire);
82 563147 : if (!chunk) return NULL;
83 563143 : return &chunk->slots[idx % CCOL_PIN_CHUNK_SLOTS];
84 : }
85 :
86 : #ifdef RUNNING_UNIT_TESTS
87 : // Test hook: Makes the next publish fail before it stores anything.
88 : static atomic_bool pin_force_publish_failure;
89 :
90 : // Test hook: Makes the next stripe-block allocation of a publish fail.
91 : static _Atomic bool pin_force_stripe_alloc_failure = false;
92 :
93 : // Test hook: Makes the next stripe-block allocation of a publish fail, the only
94 : // way to get a published chunk whose slot never went live.
95 1 : void ccol__pintable_force_next_stripe_alloc_failure_for_tests(void) {
96 1 : atomic_store(&pin_force_stripe_alloc_failure, true);
97 1 : }
98 :
99 : // Test hook: Makes the next publish fail before it stores anything, so the
100 : // tests of the owning modules reach their rollback paths.
101 28 : void ccol__pintable_force_next_publish_failure_for_tests(void) {
102 28 : atomic_store(&pin_force_publish_failure, true);
103 28 : }
104 : #endif
105 :
106 : // Publishes ptr at idx under generation gen, so a resolve can find it; an
107 : // owning module calls it when it acquires a handle, under its writer lock.
108 : // Allocates the chunk and the stripe block on first use. Gives false, storing
109 : // nothing, for gen 0, an index above the ceiling or a failed allocation. The
110 : // writer lock means two publishes never race, so a relaxed load finds an
111 : // existing chunk; the chunk, the stripes and the state are stored with
112 : // release, the state last, so a reader that sees it live sees ptr.
113 9215 : bool ccol_pintable_publish(ccol_pintable *t, uint32_t idx, uint32_t gen,
114 : void *ptr) {
115 9215 : if (gen == 0) return false;
116 : #ifdef RUNNING_UNIT_TESTS
117 9214 : if (atomic_exchange(&pin_force_publish_failure, false)) return false;
118 : #endif
119 9186 : uint32_t chunk_idx = idx / CCOL_PIN_CHUNK_SLOTS;
120 9186 : if (chunk_idx >= CCOL_PIN_MAX_CHUNKS) return false;
121 :
122 9185 : ccol_pin_chunk *chunk =
123 9185 : atomic_load_explicit(&t->chunks[chunk_idx], memory_order_relaxed);
124 9185 : if (!chunk) {
125 140 : chunk = calloc(1, sizeof(*chunk));
126 140 : if (!chunk) return false;
127 140 : atomic_store_explicit(&t->chunks[chunk_idx], chunk, memory_order_release);
128 : }
129 :
130 9185 : ccol_pin_slot *slot = &chunk->slots[idx % CCOL_PIN_CHUNK_SLOTS];
131 9185 : ccol_pin_stripe *stripes =
132 9185 : atomic_load_explicit(&slot->stripes, memory_order_relaxed);
133 9185 : if (!stripes) {
134 : #ifdef RUNNING_UNIT_TESTS
135 246 : if (atomic_exchange(&pin_force_stripe_alloc_failure, false)) return false;
136 : #endif
137 245 : stripes = calloc(CCOL_PIN_STRIPES, sizeof(*stripes));
138 245 : if (!stripes) return false;
139 245 : atomic_store_explicit(&slot->stripes, stripes, memory_order_release);
140 : }
141 :
142 9184 : atomic_store_explicit(&slot->ptr, ptr, memory_order_relaxed);
143 9184 : atomic_store_explicit(&slot->state, pin_state(gen, true),
144 : memory_order_release);
145 9184 : return true;
146 : }
147 :
148 : // Clears the live bit of idx so no new pin can find it; a destroy calls it
149 : // under the owning module's writer lock before waiting for the pins. The
150 : // generation stays, so this occupancy's handle differs from the next one's.
151 : // The store is seq_cst: It pairs with the pin in ccol_pintable_pin().
152 9084 : void ccol_pintable_retire(ccol_pintable *t, uint32_t idx) {
153 9084 : ccol_pin_slot *slot = pin_slot_lookup(t, idx);
154 0 : if (!slot) return;
155 9084 : uint64_t st = atomic_load_explicit(&slot->state, memory_order_relaxed);
156 9084 : atomic_store_explicit(&slot->state, st & ~(uint64_t)1, memory_order_seq_cst);
157 : }
158 :
159 : // Resolves a handle and pins its object on the calling thread's stripe, so a
160 : // public call can use the object while a concurrent destroy waits. Gives the
161 : // pointer, or NULL with no pin. The pin increment and the state re-check after
162 : // it are seq_cst, and so are the retire store and the read of the pin count in
163 : // ccol_pintable_pins(). With one total order over the four, either the destroy
164 : // sees this pin and waits, or this call sees the retire and backs out. Acquire
165 : // and release alone let both reads miss the other side's write, and the object
166 : // is freed while a caller holds it. x86-64 passes a weaker version almost
167 : // every time, so don't relax any of the four on the strength of a green run.
168 270544 : void *ccol_pintable_pin(ccol_pintable *t, uint64_t handle) {
169 270544 : if (handle == 0) return NULL;
170 270504 : uint32_t idx = (uint32_t)(handle >> 32);
171 270504 : uint32_t gen = (uint32_t)(handle & 0xFFFFFFFFu);
172 :
173 270504 : ccol_pin_slot *slot = pin_slot_lookup(t, idx);
174 5 : if (!slot) return NULL;
175 :
176 270499 : uint64_t want = pin_state(gen, true);
177 270499 : if (atomic_load_explicit(&slot->state, memory_order_acquire) != want)
178 : return NULL;
179 :
180 270484 : ccol_pin_stripe *stripes =
181 270484 : atomic_load_explicit(&slot->stripes, memory_order_acquire);
182 270484 : if (!stripes) return NULL;
183 :
184 270484 : unsigned stripe = pin_stripe_self();
185 :
186 270484 : atomic_fetch_add_explicit(&stripes[stripe].count, 1, memory_order_seq_cst);
187 :
188 270484 : if (atomic_load_explicit(&slot->state, memory_order_seq_cst) != want) {
189 0 : atomic_fetch_sub_explicit(&stripes[stripe].count, 1, memory_order_release);
190 0 : return NULL;
191 : }
192 :
193 270484 : return atomic_load_explicit(&slot->ptr, memory_order_relaxed);
194 : }
195 :
196 : // Releases a pin from the calling thread's stripe when a public call ends. A
197 : // zero handle never got a pin, so it does nothing; decrementing slot 0 for it
198 : // would let a drain finish while a real caller holds that object.
199 270179 : void ccol_pintable_unpin(ccol_pintable *t, uint64_t handle) {
200 270179 : if (handle == 0) return;
201 270178 : uint32_t idx = (uint32_t)(handle >> 32);
202 270178 : ccol_pin_slot *slot = pin_slot_lookup(t, idx);
203 0 : if (!slot) return;
204 270178 : ccol_pin_stripe *stripes =
205 270178 : atomic_load_explicit(&slot->stripes, memory_order_acquire);
206 270178 : if (!stripes) return;
207 270179 : atomic_fetch_sub_explicit(&stripes[pin_stripe_self()].count, 1,
208 : memory_order_release);
209 : }
210 :
211 : // Gives the pins outstanding against idx, which a destroy waits to reach 0.
212 : // It sums the stripes (seq_cst loads) in an unsigned accumulator and clamps
213 : // the signed total at 0: One stripe may read negative, and stripes can drift
214 : // apart without bound while their sum stays right, so a signed partial sum
215 : // could overflow.
216 13381 : size_t ccol_pintable_pins(ccol_pintable *t, uint32_t idx) {
217 13381 : ccol_pin_slot *slot = pin_slot_lookup(t, idx);
218 1 : if (!slot) return 0;
219 13380 : ccol_pin_stripe *stripes =
220 13380 : atomic_load_explicit(&slot->stripes, memory_order_acquire);
221 13380 : if (!stripes) return 0;
222 : uintptr_t accumulated = 0;
223 120411 : for (unsigned i = 0; i < CCOL_PIN_STRIPES; ++i) {
224 107032 : accumulated += (uintptr_t)atomic_load_explicit(&stripes[i].count,
225 : memory_order_seq_cst);
226 : }
227 13379 : ptrdiff_t total = (ptrdiff_t)accumulated;
228 13379 : return total > 0 ? (size_t)total : 0;
229 : }
230 :
231 : // Gives the pins of the index a handle names, for owners that hold a handle.
232 : // A zero handle names no slot, so it gives 0 and not slot 0's count.
233 10 : size_t ccol_pintable_pins_for(ccol_pintable *t, uint64_t handle) {
234 10 : if (handle == 0) return 0;
235 9 : return ccol_pintable_pins(t, (uint32_t)(handle >> 32));
236 : }
237 :
238 : // Frees every chunk and stripe block of t at process teardown, so a leak
239 : // checker doesn't report them. Each chunk is unpublished before it's freed, so
240 : // a racing resolve answers NULL instead of reading freed memory.
241 216 : void ccol_pintable_dispose(ccol_pintable *t) {
242 221400 : for (unsigned c = 0; c < CCOL_PIN_MAX_CHUNKS; ++c) {
243 221184 : ccol_pin_chunk *chunk =
244 221184 : atomic_load_explicit(&t->chunks[c], memory_order_acquire);
245 221184 : if (!chunk) continue;
246 128 : atomic_store_explicit(&t->chunks[c], NULL, memory_order_release);
247 8320 : for (unsigned i = 0; i < CCOL_PIN_CHUNK_SLOTS; ++i) {
248 8192 : ccol_pin_stripe *stripes =
249 8192 : atomic_load_explicit(&chunk->slots[i].stripes, memory_order_acquire);
250 8192 : atomic_store_explicit(&chunk->slots[i].stripes, NULL,
251 : memory_order_release);
252 8192 : free(stripes);
253 : }
254 128 : free(chunk);
255 : }
256 216 : }
257 :
258 : // Drops the pins of the index a handle names, for a fork child handler. A
259 : // zero handle names no slot, so it leaves slot 0's pins alone.
260 2 : void ccol_pintable_reset_for(ccol_pintable *t, uint64_t handle) {
261 2 : if (handle == 0) return;
262 1 : ccol_pintable_reset(t, (uint32_t)(handle >> 32));
263 : }
264 :
265 : // Zeroes every stripe of idx. Only a fork child handler calls it, because a
266 : // pin held by a thread that didn't survive the fork can never be released.
267 2 : void ccol_pintable_reset(ccol_pintable *t, uint32_t idx) {
268 2 : ccol_pin_slot *slot = pin_slot_lookup(t, idx);
269 0 : if (!slot) return;
270 2 : ccol_pin_stripe *stripes =
271 2 : atomic_load_explicit(&slot->stripes, memory_order_acquire);
272 2 : if (!stripes) return;
273 18 : for (unsigned i = 0; i < CCOL_PIN_STRIPES; ++i)
274 16 : atomic_store_explicit(&stripes[i].count, 0, memory_order_release);
275 : }
|