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 deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : 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 all
14 : 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 FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : // The fixed-size pool (cmempool) and the ranged pool (crmempool).
26 :
27 : #include <cmempool.h>
28 : #include <internal/ctlsmodel.h>
29 : #include <internal/test_helpers/cmempool.h>
30 : #include <stdatomic.h>
31 : #include <stdio.h>
32 : #include <stdlib.h>
33 : #include <string.h>
34 : // The library half of the link-time layout check in cmempool.h: Only the tag of
35 : // this build's layout exists. It's a scalar and not an array, so its debug
36 : // info is the same under GCC and Clang and the ABI corpus doesn't differ.
37 : #if CMEMPOOL_COMPACT_LAYOUT
38 : const char cmempool__built_with_compact_layout = 0;
39 : #else
40 : const char cmempool__built_with_fast_layout = 0;
41 : #endif
42 :
43 : // Every live pool points cmempool_mark here, so a sanity check can spot a bad
44 : // handle.
45 : const char *cmempool_mark_value = "cmempool";
46 :
47 : // A free entry seen as its free-list link.
48 : typedef uintptr_t *mp_addr;
49 :
50 : struct ccol_mp_magazine;
51 :
52 : // A pool entry has no header: Its state is one byte of the status array at
53 : // upper_addr_limit, and a free entry keeps the free-list link in its first
54 : // bytes. The bytes of the whole stride belong to the holder of the entry.
55 : // MP_HAS_CACHE(mp) evaluates to true when mp has a thread cache, the test every
56 : // allocation and free starts with. MP_ENTRY_INDEX(mp, c_entry) evaluates to
57 : // the index of the entry at address c_entry, which the status lookups need: A
58 : // shift in the default layout, a multiply by a reciprocal in the compact one,
59 : // whose product needs twice the address width (__uint128_t on 64-bit
60 : // targets).
61 : #if CMEMPOOL_COMPACT_LAYOUT
62 : #define MP_HAS_CACHE(mp) ((mp)->has_cache)
63 : #if UINTPTR_MAX > 0xFFFFFFFFu
64 : typedef __uint128_t mp_wide;
65 : #define MP_WIDE_BITS 64
66 : #else
67 : typedef uint64_t mp_wide;
68 : #define MP_WIDE_BITS 32
69 : #endif
70 : #define MP_ENTRY_INDEX(mp, c_entry) \
71 : (size_t)((uintptr_t)(((mp_wide)((c_entry) - (mp)->lower_addr_limit) * \
72 : (mp)->entry_index_magic) >> \
73 : MP_WIDE_BITS) >> \
74 : (mp)->entry_index_shift)
75 : #else
76 : #define MP_HAS_CACHE(mp) ((mp)->max_magazines != 0)
77 : #define MP_ENTRY_INDEX(mp, c_entry) \
78 : (size_t)(((c_entry) - (mp)->lower_addr_limit) >> (mp)->entry_shift)
79 : #endif
80 :
81 : // Evaluates to the status byte of entry idx of mp, as an lvalue, so the
82 : // alloc and free paths can read and mark an entry.
83 : #define MP_ENTRY_STATUS(mp, idx) (((uint8_t *)(mp)->upper_addr_limit)[(idx)])
84 :
85 : // The header of a dynamic fallback entry, right before the address the caller
86 : // gets. Such an entry is outside the pool's buffer, so it can't use the status
87 : // array. We read it only for an address the pool's registry of live dynamic
88 : // entries holds; any other address may have no allocation in front of it.
89 : typedef struct {
90 : size_t user_size;
91 : size_t elem_status;
92 : } mp_dynamic_header;
93 :
94 : // The bytes in front of a dynamic entry, rounded to the entry alignment so the
95 : // caller's address stays aligned (as long as the allocator gives memory
96 : // aligned for any type, as malloc() does).
97 : #define DYNAMIC_ENTRY_PREFIX_SIZE cmempool__align_up(sizeof(mp_dynamic_header))
98 :
99 : // Evaluate to the header, the raw allocated block and the recorded user size
100 : // of a dynamic entry, from the address the caller holds; the dynamic alloc,
101 : // free and realloc paths need them.
102 : #define DYNAMIC_ENTRY_HEADER(entry) \
103 : ((mp_dynamic_header *)((uint8_t *)(entry) - DYNAMIC_ENTRY_PREFIX_SIZE))
104 :
105 : #define DYNAMIC_ENTRY_RAW_BLOCK(entry) \
106 : ((void *)((uint8_t *)(entry) - DYNAMIC_ENTRY_PREFIX_SIZE))
107 :
108 : static inline bool valid_mempool_addr(cmempool *mp, uintptr_t c_entry);
109 :
110 : static inline __attribute__((always_inline)) void *mempool_serve_locked(
111 : cmempool *mp);
112 :
113 : // Evaluates to the user size recorded in a dynamic entry's header (see the
114 : // group above).
115 : #define DYNAMIC_ENTRY_USER_SIZE(entry) (DYNAMIC_ENTRY_HEADER(entry)->user_size)
116 :
117 : // A fixed-size pool. The fields up to entry_shift (and has_cache in the
118 : // compact layout) are the hot line that every allocation and free reads; on
119 : // LP64 they are exactly 64 bytes. free_inst and free_elem_count belong there,
120 : // because a pool without a thread cache reaches them on every call.
121 : struct cmempool {
122 : // Points at cmempool_mark_value while the pool is alive.
123 : const char *cmempool_mark;
124 : #if CMEMPOOL_COMPACT_LAYOUT
125 : // Turns an entry's byte offset into its index in the compact layout, where
126 : // the stride isn't a power of two.
127 : uintptr_t entry_index_magic;
128 : #else
129 : size_t max_magazines;
130 : #endif
131 : size_t extended_elem_size;
132 : // The entries span [lower, upper); the status array starts at upper.
133 : uintptr_t lower_addr_limit;
134 : uintptr_t upper_addr_limit;
135 : void *free_inst;
136 : size_t free_elem_count;
137 : bool should_use_locks;
138 : bool fallback_to_dynamic_memory;
139 : bool is_preallocated;
140 : // log2 of the stride in the default layout (0 in the compact one). A uint8_t
141 : // among the flags, so it fits into padding of the hot line.
142 : uint8_t entry_shift;
143 : #if CMEMPOOL_COMPACT_LAYOUT
144 : bool has_cache;
145 : uint8_t entry_index_shift;
146 : #endif
147 :
148 : #if CMEMPOOL_COMPACT_LAYOUT
149 : size_t max_magazines;
150 : #endif
151 : // Cold fields: Construction, teardown and introspection.
152 : size_t magazine_capacity;
153 : // What the caller asked for. total_elem_count adds the thread-cache reserve,
154 : // which keeps the advertised count available to every thread; concurrent
155 : // callers can briefly hold a few more than advertised, never more than the
156 : // total. Every public count is in terms of the advertised one.
157 : size_t advertised_elem_count;
158 : size_t total_elem_count;
159 : // Live dynamic entries. Changed under the pool lock with release; atomic
160 : // because a ranged pool reads it in every tier without their locks.
161 : _Atomic size_t active_dynamic_memory_buffer_count;
162 : // Magazines handed out, against max_magazines. An unlink must decrement it,
163 : // or exited threads fill the budget and the pool locks on every call. A plain
164 : // size_t read under the lock, because an _Atomic qualifier here slows the
165 : // cached allocate-and-free path although that path never reads it.
166 : size_t live_magazines;
167 : struct ccol_mp_magazine *magazines;
168 : ccol_memmgmt_procs *m_procs;
169 : void *objects;
170 : // The registry of live dynamic entries, NULL until the first one; the pool
171 : // lock guards it.
172 : uintptr_t *dynamic_entries;
173 : ccol__mutex lock;
174 : };
175 :
176 : // The two states of a pool entry, as one byte in the status array.
177 : typedef enum { mp_status_free = 0, mp_status_taken = 1 } mp_entry_status;
178 :
179 : // Word-wide markers in the header of a dynamic entry, picked to stand out in a
180 : // memory dump. Static, so they can't collide with an application symbol at
181 : // static-link time.
182 : #if UINTPTR_MAX == UINT32_MAX
183 : static const size_t elem_is_not_a_pool_member = 0xfadeface;
184 : static const size_t elem_is_freed_dynamic_member = 0xdeadc0de;
185 : #elif UINTPTR_MAX == UINT64_MAX
186 : static const size_t elem_is_not_a_pool_member = 0xfadefacefadeface;
187 : static const size_t elem_is_freed_dynamic_member = 0xdeadc0dedeadc0de;
188 : #else
189 : #error "Unexpected pointer size"
190 : #endif
191 :
192 : // The registry of live dynamic fallback entries. A free of an address outside
193 : // the pool's buffer is either one of its dynamic entries or a caller error,
194 : // and the registry answers from the address alone, before the header in front
195 : // of it is read. It's an open-addressing set with linear probing and
196 : // backward-shift deletion (no tombstones), kept at most half full. The slot
197 : // index is the high bits of a multiplicative hash, because the low bits of an
198 : // aligned address are constant. The table stores its shift in the word before
199 : // slot 0, so the pool needs one pointer. MP_DYNAMIC_SET_MIN_CAPACITY is the
200 : // smallest table, MP_ADDR_BITS the address width and MP_ADDR_HASH_MUL the
201 : // Fibonacci multiplier of the hash.
202 : #define MP_DYNAMIC_SET_MIN_CAPACITY 16u
203 : #define MP_ADDR_BITS (sizeof(uintptr_t) * CHAR_BIT)
204 : #if UINTPTR_MAX == UINT32_MAX
205 : #define MP_ADDR_HASH_MUL ((uintptr_t)0x9E3779B9u)
206 : #else
207 : #define MP_ADDR_HASH_MUL ((uintptr_t)0x9E3779B97F4A7C15ull)
208 : #endif
209 :
210 : // Gives the shift that reduces a hash to a slot index of mp's registry; the
211 : // table has 1 << (address bits - shift) slots. The registry helpers need it to
212 : // size and index the table, and it's stored in the word before slot 0.
213 19890 : static inline unsigned mp_dynamic_set_shift(const cmempool *mp) {
214 19890 : return (unsigned)mp->dynamic_entries[-1];
215 : }
216 :
217 : // Gives the home slot of key in mp's registry, from the high bits of a
218 : // multiplicative hash. Every probe of the registry starts there.
219 8965 : static inline size_t mp_dynamic_set_home(const cmempool *mp, uintptr_t key) {
220 8965 : return (size_t)((key * MP_ADDR_HASH_MUL) >> mp_dynamic_set_shift(mp));
221 : }
222 :
223 : // Gives the slot count of mp's registry, or 0 when it has none yet. The
224 : // registry helpers use it as their probe mask and their "not found" answer.
225 14414 : static inline size_t mp_dynamic_set_capacity(const cmempool *mp) {
226 14414 : if (!mp->dynamic_entries) return 0;
227 10925 : return (size_t)1 << (MP_ADDR_BITS - mp_dynamic_set_shift(mp));
228 : }
229 :
230 : // Writes key into the first empty slot of its probe sequence. Insert and
231 : // growth use it; the table must have room and must not hold key yet.
232 4792 : static void mp_dynamic_set_place(cmempool *mp, uintptr_t key) {
233 4792 : size_t mask = mp_dynamic_set_capacity(mp) - 1;
234 4792 : size_t i = mp_dynamic_set_home(mp, key);
235 6178 : while (mp->dynamic_entries[i] != 0) i = (i + 1) & mask;
236 4792 : mp->dynamic_entries[i] = key;
237 4792 : }
238 :
239 : // Looks key up in mp's registry, for the free path's ownership check and for
240 : // removal. Gives the slot that holds key, or the capacity when it's absent.
241 : // Needs mp->lock.
242 3435 : static size_t mp_dynamic_set_find_locked(const cmempool *mp, uintptr_t key) {
243 10305 : size_t cap = mp_dynamic_set_capacity(mp);
244 3435 : if (cap == 0) return 0;
245 3435 : size_t mask = cap - 1;
246 3874 : for (size_t i = mp_dynamic_set_home(mp, key);; i = (i + 1) & mask) {
247 3874 : uintptr_t k = mp->dynamic_entries[i];
248 3874 : if (k == key) return i;
249 446 : if (k == 0) return cap;
250 : }
251 : }
252 :
253 : // Tells whether key is a live dynamic entry of mp. A ranged pool asks this to
254 : // find which tier owns an address outside every buffer. Needs mp->lock.
255 691 : static bool mp_dynamic_set_contains_locked(const cmempool *mp, uintptr_t key) {
256 1382 : return mp_dynamic_set_find_locked(mp, key) != mp_dynamic_set_capacity(mp);
257 : }
258 :
259 : // Records key, a dynamic entry about to be handed out, in mp's registry, so a
260 : // later free can prove it's ours before reading its header. It grows the table
261 : // (through mp's allocator) to keep it at most half full. Gives false when the
262 : // growth can't be allocated; the caller then gives the entry back and fails
263 : // the allocation. Needs mp->lock; the live count doesn't include key yet.
264 2752 : static __attribute__((noinline)) bool mp_dynamic_set_insert_locked(
265 : cmempool *mp, uintptr_t key) {
266 2752 : size_t live = atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
267 : memory_order_relaxed);
268 2752 : size_t old_cap = mp_dynamic_set_capacity(mp);
269 2752 : if ((live + 1) * 2 > old_cap) {
270 62 : if (old_cap > SIZE_MAX / 4 / sizeof(uintptr_t)) return false;
271 62 : size_t new_cap = old_cap ? old_cap * 2 : MP_DYNAMIC_SET_MIN_CAPACITY;
272 70 : uintptr_t new_shift =
273 8 : old_cap ? mp->dynamic_entries[-1] - 1 : MP_ADDR_BITS - 4u;
274 62 : uintptr_t *fresh = (uintptr_t *)ccol__mem_calloc(mp->m_procs, new_cap + 1,
275 : sizeof(uintptr_t));
276 62 : if (!fresh) return false;
277 62 : fresh[0] = new_shift;
278 62 : uintptr_t *old = mp->dynamic_entries;
279 62 : mp->dynamic_entries = fresh + 1;
280 4142 : for (size_t i = 0; i < old_cap; ++i) {
281 4080 : if (old[i] != 0) mp_dynamic_set_place(mp, old[i]);
282 : }
283 62 : if (old) ccol__mem_free(mp->m_procs, old - 1);
284 : }
285 2752 : mp_dynamic_set_place(mp, key);
286 2752 : return true;
287 : }
288 :
289 : // Removes key from mp's registry when a dynamic entry is freed; the removal is
290 : // also the ownership check, so a second free of the same entry fails. Later
291 : // members of the cluster shift back into the hole when it lies on their probe
292 : // path, so the table never holds tombstones. Gives false when key isn't a live
293 : // dynamic entry of mp. Needs mp->lock.
294 2744 : static __attribute__((noinline)) bool mp_dynamic_set_remove_locked(
295 : cmempool *mp, uintptr_t key) {
296 2744 : size_t cap = mp_dynamic_set_capacity(mp);
297 2744 : size_t i = mp_dynamic_set_find_locked(mp, key);
298 2744 : if (i == cap) return false;
299 2739 : size_t mask = cap - 1;
300 3477 : for (size_t j = (i + 1) & mask;; j = (j + 1) & mask) {
301 3477 : uintptr_t k = mp->dynamic_entries[j];
302 3477 : if (k == 0) break;
303 738 : size_t home = mp_dynamic_set_home(mp, k);
304 738 : if (((j - home) & mask) >= ((j - i) & mask)) {
305 144 : mp->dynamic_entries[i] = k;
306 144 : i = j;
307 : }
308 : }
309 2739 : mp->dynamic_entries[i] = 0;
310 2739 : return true;
311 : }
312 :
313 : // Frees mp's registry table. Only a destroy calls it, once no dynamic entry
314 : // is live.
315 1008 : static void mp_dynamic_set_release(cmempool *mp) {
316 1008 : if (mp->dynamic_entries) ccol__mem_free(mp->m_procs, mp->dynamic_entries - 1);
317 1008 : mp->dynamic_entries = NULL;
318 1008 : }
319 :
320 : // Hands out one dynamic fallback entry of user_size bytes owned by mp. A pool
321 : // that ran out uses it when its fallback is on, and so does the pseudo pool of
322 : // a ranged pool. It allocates the header and the entry through mp's allocator,
323 : // records the entry in the registry and bumps the live count (release). Gives
324 : // NULL when the allocator refuses or the size can't carry the header. Needs
325 : // mp->lock when the pool locks.
326 2758 : static __attribute__((noinline)) void *mempool_alloc_dynamic_locked(
327 : cmempool *mp, size_t user_size) {
328 2758 : if (user_size > SIZE_MAX - DYNAMIC_ENTRY_PREFIX_SIZE) return NULL;
329 5516 : void *raw_block =
330 2758 : ccol__mem_alloc(mp->m_procs, DYNAMIC_ENTRY_PREFIX_SIZE + user_size);
331 2758 : if (!raw_block) return NULL;
332 2752 : void *result = (uint8_t *)raw_block + DYNAMIC_ENTRY_PREFIX_SIZE;
333 2752 : if (!mp_dynamic_set_insert_locked(mp, (uintptr_t)result)) {
334 0 : ccol__mem_free(mp->m_procs, raw_block);
335 0 : return NULL;
336 : }
337 2752 : mp_dynamic_header *dyn = DYNAMIC_ENTRY_HEADER(result);
338 2752 : dyn->user_size = user_size;
339 2752 : dyn->elem_status = elem_is_not_a_pool_member;
340 2752 : atomic_store_explicit(
341 : &mp->active_dynamic_memory_buffer_count,
342 : atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
343 : memory_order_relaxed) +
344 : 1,
345 : memory_order_release);
346 2752 : return result;
347 : }
348 :
349 : // The thread cache. Each thread keeps a magazine of free entries per pool, so
350 : // the common allocation and free take no lock and no atomic read-modify-write;
351 : // only refilling an empty magazine and flushing a full one touch the shared
352 : // list under the pool lock. A pool asked for N entries allocates N + R slots,
353 : // R being the most all caches can hold, so N stay available to any thread. R
354 : // is at most N/2 and shrinks as a proportion for large pools.
355 : //
356 : // The most magazines one pool hands out, the most entries one magazine holds,
357 : // the smallest pool that gets a cache, and the reserve as N divided by this
358 : // divisor (deeper magazines hit their refill and flush boundaries less
359 : // often).
360 : #define CCOL_MP_MAGAZINE_LIMIT 16u
361 : #define CCOL_MP_CAPACITY_LIMIT 128u
362 : #define CCOL_MP_MIN_CACHED_POOL 8u
363 : #define CCOL_MP_RESERVE_DIVISOR 2u
364 : // A thread's direct-mapped cache of magazines, so a ranged pool working across
365 : // tiers doesn't thrash one slot. A power of two, so mempool_tls_slot() can
366 : // mask.
367 : #define CCOL_MP_TLS_SLOTS 8u
368 : _Static_assert(CCOL_MP_TLS_SLOTS > 0u &&
369 : (CCOL_MP_TLS_SLOTS & (CCOL_MP_TLS_SLOTS - 1u)) == 0,
370 : "mempool_tls_slot() reduces with a mask, which only covers the "
371 : "whole slot array while this is a power of two; zero satisfies "
372 : "the power-of-two test on its own and must be excluded, since "
373 : "it would make the mask every bit");
374 :
375 : // One thread's magazine for one pool. It's bigger than a cache line, so two
376 : // magazines never share one.
377 : typedef struct ccol_mp_magazine {
378 : // Cleared (release) by whoever unlinks it from its pool; the owning thread
379 : // frees an orphaned magazine on seeing NULL (acquire), so the unlink must be
380 : // visible first.
381 : _Atomic(cmempool *) pool;
382 : // Written only by the owning thread, read relaxed by the introspection
383 : // functions, so cmempool_used_count() is exact at no cost to the fast path.
384 : _Atomic size_t count;
385 : size_t capacity;
386 : struct ccol_mp_magazine *next_in_pool;
387 : struct ccol_mp_magazine *prev_in_pool;
388 : struct ccol_mp_magazine *next_in_thread;
389 : // Kept here because an orphaned magazine outlives its pool's m_procs; NULL
390 : // for the default allocator.
391 : ccol_free free_proc;
392 : // Sized for this pool's magazine capacity.
393 : void *slots[];
394 : } ccol_mp_magazine;
395 :
396 : // A thread's whole cache state in one object, so a call resolves one
397 : // thread-local and not several. A key destructor only runs for a thread whose
398 : // key value is set, so armed records that the thread set it; under
399 : // CCOL__EMULATE_DARWIN_TLS the state is the key's value instead.
400 : typedef struct {
401 : ccol_mp_magazine *mags;
402 : // The reap clears every slot that points at a magazine before freeing it,
403 : // so a magazine's own pool field is the whole hit test.
404 : ccol_mp_magazine *cache[CCOL_MP_TLS_SLOTS];
405 : bool armed;
406 : } mp_tls_state;
407 :
408 : // The thread's cache state, with the TLS model of ctlsmodel.h. initial-exec
409 : // keeps a __tls_get_addr call off every allocation and free; build with
410 : // -DCMEMPOOL_DYNAMIC_TLS=1 when a dlopen() into a full static TLS block must
411 : // work. Under CCOL__EMULATE_DARWIN_TLS there's no __thread object.
412 : #if defined(CCOL__EMULATE_DARWIN_TLS)
413 : #elif defined(CMEMPOOL_DYNAMIC_TLS) && CMEMPOOL_DYNAMIC_TLS
414 : static __thread mp_tls_state mp_tls;
415 : #else
416 : static __thread mp_tls_state mp_tls __attribute__((tls_model("initial-exec")));
417 : #endif
418 :
419 : // The key whose destructor drains a thread's magazines at exit.
420 : static ccol__thread_ls_key mp_tls_key;
421 : // Serializes a thread's exit drain against a pool destroy, so the drain never
422 : // locks a freed pool. Taken before any pool lock.
423 : static ccol__mutex mp_registry_lock;
424 : // Serializes arming a thread against the deletion of the key at unload. A leaf
425 : // that may be taken with a pool lock held. It can't be the registry lock: A
426 : // pool's allocator may be another pool that arms the thread, and arming under
427 : // the registry lock would deadlock with an exit drain.
428 : static ccol__mutex mp_arm_lock;
429 : // True while the key exists and a thread may arm it; it goes false under the
430 : // arm lock at unload.
431 : static atomic_bool mp_cache_live;
432 : // Creates the locks and the key once.
433 : static ccol__once_flag mp_cache_once = CCOL__ONCE_INIT;
434 :
435 : static void mp_tls_drain(void *arg);
436 :
437 : // Gives the calling thread's cache state, which every cache path starts from.
438 : // Under CCOL__EMULATE_DARWIN_TLS it's the key's heap block: NULL when the
439 : // thread has none or the cache is gone (mp_cache_live false). Elsewhere it's
440 : // the __thread object and the callers' NULL tests fold away.
441 : #if defined(CCOL__EMULATE_DARWIN_TLS)
442 : static inline __attribute__((always_inline)) mp_tls_state *mp_tls_cur(void) {
443 : if (!atomic_load_explicit(&mp_cache_live, memory_order_acquire)) return NULL;
444 : return (mp_tls_state *)ccol__thread_ls_get(mp_tls_key);
445 : }
446 : #else
447 12140 : static inline __attribute__((always_inline)) mp_tls_state *mp_tls_cur(void) {
448 12140 : return &mp_tls;
449 : }
450 : #endif
451 :
452 : // Creates the registry lock, the arm lock and the key, then sets mp_cache_live.
453 : // mp_cache_available() runs it once; any failure leaves the cache off.
454 2 : static void mp_cache_init(void) {
455 2 : if (ccol__mutex_init(mp_registry_lock) != 0) return;
456 2 : if (ccol__mutex_init(mp_arm_lock) != 0) return;
457 2 : if (ccol__thread_ls_key_create(mp_tls_key, mp_tls_drain) != 0) return;
458 2 : atomic_store(&mp_cache_live, true);
459 : }
460 :
461 : // Tells whether a new pool may get a thread cache: true from the moment the key
462 : // exists until the module unloads. A pool created while it's false (for
463 : // example after PTHREAD_KEYS_MAX) runs without a cache instead of failing.
464 715 : static bool mp_cache_available(void) {
465 715 : ccol__call_once(mp_cache_once, mp_cache_init);
466 715 : return atomic_load(&mp_cache_live);
467 : }
468 :
469 : // Works out the magazine count, the magazine capacity and the reserve for a
470 : // pool of elem_count entries, which the constructor needs to size the block.
471 : // Pools below CCOL_MP_MIN_CACHED_POOL get none; that gate is separate from the
472 : // clamps, which would otherwise force a magazine onto a one-element pool and a
473 : // reserve of N. A reserve that would overflow leaves all three at 0.
474 714 : static void mempool_cache_geometry(size_t elem_count, size_t *max_magazines,
475 : size_t *capacity, size_t *reserve) {
476 714 : *max_magazines = 0;
477 714 : *capacity = 0;
478 714 : *reserve = 0;
479 714 : if (elem_count < CCOL_MP_MIN_CACHED_POOL) return;
480 :
481 599 : size_t mags = elem_count / CCOL_MP_MIN_CACHED_POOL;
482 599 : if (mags > CCOL_MP_MAGAZINE_LIMIT) mags = CCOL_MP_MAGAZINE_LIMIT;
483 202 : if (mags == 0) mags = 1;
484 :
485 599 : size_t cap = elem_count / (CCOL_MP_RESERVE_DIVISOR * mags);
486 599 : if (cap > CCOL_MP_CAPACITY_LIMIT) cap = CCOL_MP_CAPACITY_LIMIT;
487 594 : if (cap == 0) cap = 1;
488 :
489 599 : if (mags > SIZE_MAX / cap) return;
490 599 : size_t r = mags * cap;
491 599 : if (r > SIZE_MAX - elem_count) return;
492 :
493 941 : *max_magazines = mags;
494 941 : *capacity = cap;
495 941 : *reserve = r;
496 : }
497 :
498 : // Gives the entries of mp handed out to callers right now: What left the
499 : // shared free list minus what sits in the magazines. The allocation limit and
500 : // cmempool_used_count() need it. Needs mp->lock; the magazine counts are read
501 : // relaxed.
502 14117 : static size_t mempool_live_count_locked(cmempool *mp) {
503 14117 : size_t live = mp->total_elem_count - mp->free_elem_count;
504 26344 : for (ccol_mp_magazine *mag = mp->magazines; mag; mag = mag->next_in_pool) {
505 12227 : size_t cached = atomic_load_explicit(&mag->count, memory_order_relaxed);
506 12227 : live = (live > cached) ? (live - cached) : 0;
507 : }
508 14117 : return live;
509 : }
510 :
511 : // Moves entries from mp's free list into mag until it's full, so the next
512 : // allocations of that thread take no lock. List corruption is reported through
513 : // *corrupt so the caller can unlock before asserting. Needs mp->lock, and
514 : // changes the free list, free_elem_count and mag's count.
515 : // The budget is free_elem_count minus the reserve: An entry in another
516 : // thread's magazine counts as handed out, because nothing checks the budget
517 : // again before it's popped. Charging only this magazine would let several
518 : // magazines each overshoot together. The bound can't be exact, because the
519 : // locked path must keep serving while callers hold fewer than advertised; this
520 : // keeps the overshoot to a few entries.
521 4491 : static void mempool_magazine_refill_locked(cmempool *mp, ccol_mp_magazine *mag,
522 : bool *corrupt) {
523 4491 : size_t count = atomic_load_explicit(&mag->count, memory_order_relaxed);
524 4491 : size_t reserve = mp->total_elem_count - mp->advertised_elem_count;
525 4491 : if (mp->free_elem_count <= reserve) return;
526 3233 : size_t budget = mp->free_elem_count - reserve;
527 :
528 65653 : while (budget > 0 && count < mag->capacity && mp->free_inst) {
529 62420 : void *entry = mp->free_inst;
530 187260 : if (!valid_mempool_addr(mp, (uintptr_t)entry) ||
531 62420 : MP_ENTRY_STATUS(mp, MP_ENTRY_INDEX(mp, (uintptr_t)entry)) !=
532 : mp_status_free) {
533 0 : *corrupt = true;
534 0 : return;
535 : }
536 62420 : --budget;
537 62420 : mp->free_inst = *(void **)entry;
538 62420 : --mp->free_elem_count;
539 62420 : mag->slots[count++] = entry;
540 62420 : atomic_store_explicit(&mag->count, count, memory_order_relaxed);
541 : }
542 : }
543 :
544 : // Gives how_many of mag's entries back to mp's free list, when a magazine is
545 : // full or its thread exits. Callers flush half of a full magazine, so a caller
546 : // at the full mark doesn't lock on every second call. Cached entries are
547 : // already marked free, so only the links change. Needs mp->lock.
548 6251 : static void mempool_magazine_flush_locked(cmempool *mp, ccol_mp_magazine *mag,
549 : size_t how_many) {
550 6251 : size_t count = atomic_load_explicit(&mag->count, memory_order_relaxed);
551 61817 : while (how_many-- > 0 && count > 0) {
552 55566 : void *entry = mag->slots[--count];
553 55566 : atomic_store_explicit(&mag->count, count, memory_order_relaxed);
554 55566 : *(void **)entry = mp->free_inst;
555 55566 : mp->free_inst = entry;
556 55566 : ++mp->free_elem_count;
557 : }
558 6251 : }
559 :
560 : // Frees a magazine through the free_proc it stored, because an orphaned
561 : // magazine can outlive its pool's procs.
562 1317 : static void mempool_magazine_free(ccol_mp_magazine *mag) {
563 1317 : if (mag->free_proc)
564 86 : mag->free_proc(mag);
565 : else
566 1231 : ccol__default_mem_free(mag);
567 : }
568 :
569 : // Drops an orphaned magazine (its pool was destroyed) from this thread's list
570 : // at *link, clears the direct-map slots that point at it and frees it, so
571 : // dead magazines don't pile up. No lock: An orphan is unlinked from its pool
572 : // before its pool pointer is cleared, so this thread is its only owner, and
573 : // the destroy has already taken it off live_magazines.
574 461 : static void mempool_tls_reap(mp_tls_state *tls, ccol_mp_magazine **link,
575 : ccol_mp_magazine *mag) {
576 461 : *link = mag->next_in_thread;
577 4149 : for (size_t i = 0; i < CCOL_MP_TLS_SLOTS; ++i) {
578 3688 : if (tls->cache[i] == mag) tls->cache[i] = NULL;
579 : }
580 461 : mempool_magazine_free(mag);
581 461 : }
582 :
583 : // Gives the direct-map slot of a pool, from address bits 8 to 10. The tiers of
584 : // a ranged pool are separate allocations a fixed distance apart, and the low
585 : // bits above the alignment alias for common strides; these bits spread the
586 : // tiers best over measured layouts, at the cost of one shift and one mask.
587 : static inline __attribute__((always_inline)) size_t
588 188730 : mempool_tls_slot(const cmempool *mp) {
589 188730 : return (size_t)(((uintptr_t)mp >> 8) & (uintptr_t)(CCOL_MP_TLS_SLOTS - 1));
590 : }
591 :
592 : // Gives this thread's magazine for mp when the direct map holds it, else
593 : // NULL. It's the hit every call after a thread's first touch of a pool takes,
594 : // inlined into the fast paths; the miss path stays out of line. Reads the
595 : // thread's cache state and the magazine's pool pointer (acquire).
596 : static inline __attribute__((always_inline)) ccol_mp_magazine *
597 187231 : mempool_tls_magazine_hit(cmempool *mp) {
598 187231 : mp_tls_state *tls = mp_tls_cur();
599 187231 : if (!tls) return NULL;
600 187231 : size_t slot = mempool_tls_slot(mp);
601 187231 : ccol_mp_magazine *mag = tls->cache[slot];
602 362731 : if (__builtin_expect(
603 175500 : mag && atomic_load_explicit(&mag->pool, memory_order_acquire) == mp,
604 : 1))
605 : return mag;
606 : return NULL;
607 : }
608 :
609 : // Finds this thread's magazine for mp after a direct-map miss, by walking the
610 : // thread's list, caches it in the direct map and gives it, or NULL. Magazines
611 : // of destroyed pools are reaped on the way. No lock. A reap calls an allocator
612 : // that may be another cached pool and reap inside this walk, so the walk
613 : // restarts from the head after each reap.
614 12140 : static ccol_mp_magazine *mempool_tls_magazine_find(cmempool *mp) {
615 12140 : mp_tls_state *tls = mp_tls_cur();
616 12140 : if (!tls) return NULL;
617 12140 : ccol_mp_magazine *mag;
618 :
619 12140 : ccol_mp_magazine **link = &tls->mags;
620 12856 : while ((mag = *link) != NULL) {
621 899 : cmempool *owner = atomic_load_explicit(&mag->pool, memory_order_acquire);
622 899 : if (!owner) {
623 461 : mempool_tls_reap(tls, link, mag);
624 461 : link = &tls->mags;
625 461 : continue;
626 : }
627 438 : if (owner == mp) {
628 183 : tls->cache[mempool_tls_slot(mp)] = mag;
629 183 : return mag;
630 : }
631 255 : link = &mag->next_in_thread;
632 : }
633 : return NULL;
634 : }
635 :
636 : // Builds a magazine for this thread and claims one of mp's magazines, the
637 : // first time a thread uses a cached pool. Gives it, or NULL for "use the
638 : // locked path" (no key value, no memory, or no magazine left).
639 : // The thread first arms the key under mp_arm_lock while mp_cache_live holds,
640 : // because a magazine held without a key value is never drained at exit; the
641 : // arm lock orders that against the key's deletion at unload. The magazine is
642 : // complete before it's linked, because the teardown walk clears the pool
643 : // pointer of every magazine it reaches. The allocation runs outside the pool
644 : // lock, and the claim checks live_magazines again under it, linking the
645 : // magazine into mp's list and the thread's list.
646 1716 : static __attribute__((noinline)) ccol_mp_magazine *mempool_tls_magazine_create(
647 : cmempool *mp) {
648 1716 : mp_tls_state *tls = mp_tls_cur();
649 :
650 : #if defined(CCOL__EMULATE_DARWIN_TLS)
651 : if (!tls) {
652 : tls = (mp_tls_state *)calloc(1, sizeof(*tls));
653 : if (!tls) return NULL;
654 : bool set = false;
655 : ccol__mutex_lock(mp_arm_lock);
656 : if (atomic_load_explicit(&mp_cache_live, memory_order_relaxed) &&
657 : ccol__thread_ls_set(mp_tls_key, tls) == 0)
658 : set = true;
659 : ccol__mutex_unlock(mp_arm_lock);
660 : if (!set) {
661 : free(tls);
662 : return NULL;
663 : }
664 : }
665 : #else
666 1716 : if (!tls->armed) {
667 1236 : ccol__mutex_lock(mp_arm_lock);
668 2072 : if (atomic_load_explicit(&mp_cache_live, memory_order_relaxed) &&
669 836 : ccol__thread_ls_set(mp_tls_key, (void *)1) == 0)
670 836 : tls->armed = true;
671 1236 : ccol__mutex_unlock(mp_arm_lock);
672 1236 : if (!tls->armed) return NULL;
673 : }
674 : #endif
675 :
676 1316 : ccol_mp_magazine *mag = ccol__mem_calloc(
677 : mp->m_procs, 1, sizeof(*mag) + mp->magazine_capacity * sizeof(void *));
678 1316 : if (!mag) return NULL;
679 :
680 1316 : mag->capacity = mp->magazine_capacity;
681 1316 : mag->free_proc = mp->m_procs ? mp->m_procs->free : NULL;
682 1316 : atomic_store_explicit(&mag->pool, mp, memory_order_release);
683 :
684 1316 : bool claimed = false;
685 1316 : ccol__mutex_lock(mp->lock);
686 1316 : if (mp->live_magazines < mp->max_magazines) {
687 1316 : ++mp->live_magazines;
688 1316 : mag->next_in_pool = mp->magazines;
689 1316 : if (mp->magazines) mp->magazines->prev_in_pool = mag;
690 1316 : mp->magazines = mag;
691 1316 : claimed = true;
692 : }
693 1316 : ccol__mutex_unlock(mp->lock);
694 :
695 1316 : if (!claimed) {
696 0 : mempool_magazine_free(mag);
697 0 : return NULL;
698 : }
699 :
700 1316 : mag->next_in_thread = tls->mags;
701 1316 : tls->mags = mag;
702 1316 : tls->cache[mempool_tls_slot(mp)] = mag;
703 1316 : return mag;
704 : }
705 :
706 : // Unlinks mag from mp's list and gives its slot back to live_magazines, when a
707 : // thread exits or the pool is destroyed. Needs mp->lock.
708 1314 : static void mempool_magazine_unlink_locked(cmempool *mp,
709 : ccol_mp_magazine *mag) {
710 1314 : if (mag->prev_in_pool)
711 20 : mag->prev_in_pool->next_in_pool = mag->next_in_pool;
712 : else
713 1294 : mp->magazines = mag->next_in_pool;
714 1314 : if (mag->next_in_pool) mag->next_in_pool->prev_in_pool = mag->prev_in_pool;
715 1314 : mag->next_in_pool = NULL;
716 1314 : mag->prev_in_pool = NULL;
717 1314 : --mp->live_magazines;
718 : }
719 :
720 : // Drains this thread's magazines at its exit; it's the key's destructor, so
721 : // cached entries aren't lost to their pools and the magazines don't leak. It
722 : // flushes and unlinks each magazine under mp_registry_lock and its pool's lock
723 : // (so a destroy can't free the pool between the pointer read and the lock),
724 : // then frees it. Freeing a magazine may call another cached pool's allocator,
725 : // which builds a new magazine on this thread, so it loops until the list stays
726 : // empty. Under CCOL__EMULATE_DARWIN_TLS arg is the state block, and it frees
727 : // it; elsewhere it clears armed.
728 836 : static void mp_tls_drain(void *arg) {
729 : #if defined(CCOL__EMULATE_DARWIN_TLS)
730 : mp_tls_state *tls = (mp_tls_state *)arg;
731 : if (!tls) return;
732 : #else
733 836 : mp_tls_state *tls = &mp_tls;
734 836 : (void)arg;
735 : #endif
736 836 : ccol_mp_magazine *mag;
737 1674 : while ((mag = tls->mags) != NULL) {
738 838 : tls->mags = NULL;
739 7542 : for (size_t i = 0; i < CCOL_MP_TLS_SLOTS; ++i) tls->cache[i] = NULL;
740 1694 : while (mag) {
741 856 : ccol_mp_magazine *next = mag->next_in_thread;
742 856 : ccol__mutex_lock(mp_registry_lock);
743 856 : cmempool *mp = atomic_load_explicit(&mag->pool, memory_order_acquire);
744 856 : if (mp) {
745 854 : ccol__mutex_lock(mp->lock);
746 854 : mempool_magazine_flush_locked(
747 854 : mp, mag, atomic_load_explicit(&mag->count, memory_order_relaxed));
748 854 : mempool_magazine_unlink_locked(mp, mag);
749 854 : ccol__mutex_unlock(mp->lock);
750 : }
751 856 : ccol__mutex_unlock(mp_registry_lock);
752 2550 : mempool_magazine_free(mag);
753 : mag = next;
754 : }
755 : }
756 : #if defined(CCOL__EMULATE_DARWIN_TLS)
757 : free(tls);
758 : #else
759 836 : tls->armed = false;
760 : #endif
761 836 : }
762 :
763 : // Shuts the thread cache down at unload (dlclose() and exit), because the key
764 : // holds a destructor address that would be unmapped. It drains the calling
765 : // thread, then, under mp_arm_lock, clears mp_cache_live and deletes the key,
766 : // so a thread that outlives a dlclose() never runs unmapped drain code; its
767 : // magazines are leaked. Existing pools keep working through their locked paths
768 : // and new pools get no cache. A second run returns at once.
769 3 : __attribute__((destructor)) static void mp_cache_fini(void) {
770 3 : if (!atomic_load(&mp_cache_live)) return;
771 : #if defined(CCOL__EMULATE_DARWIN_TLS)
772 : mp_tls_state *tls = mp_tls_cur();
773 : if (tls) {
774 : (void)ccol__thread_ls_set(mp_tls_key, NULL);
775 : mp_tls_drain(tls);
776 : }
777 : #else
778 2 : mp_tls_drain(NULL);
779 : #endif
780 2 : ccol__mutex_lock(mp_arm_lock);
781 2 : atomic_store(&mp_cache_live, false);
782 2 : ccol__thread_ls_key_delete(mp_tls_key);
783 2 : ccol__mutex_unlock(mp_arm_lock);
784 : }
785 :
786 : static void *mempool_alloc_locked(cmempool *mp);
787 : static void mempool_free_locked(cmempool *mp, void *entry);
788 :
789 : // Allocates an entry for a thread whose inlined pop failed: No magazine in the
790 : // direct map, or an empty one (mag, possibly NULL). The pool has a cache and
791 : // no lock is held. Gives the entry, or NULL for an exhausted pool. Apart from
792 : // creating a magazine once, it costs at most one critical section: A thread
793 : // the pool refuses a magazine is served under the same lock, and an empty
794 : // magazine whose refill yields nothing is served under the refill's lock. That
795 : // answer is final. Kept out of line, because inlining it slows pools without a
796 : // cache.
797 9863 : static __attribute__((noinline)) void *mempool_alloc_from_cache_slow(
798 : cmempool *mp, ccol_mp_magazine *mag) {
799 9863 : void *served;
800 9863 : if (!mag) {
801 6741 : mag = mempool_tls_magazine_find(mp);
802 6741 : if (!mag) {
803 6587 : ccol__mutex_lock(mp->lock);
804 6587 : bool budget_available = mp->live_magazines < mp->max_magazines;
805 6587 : served = budget_available ? NULL : mempool_serve_locked(mp);
806 6587 : ccol__mutex_unlock(mp->lock);
807 6587 : if (!budget_available) return served;
808 1466 : mag = mempool_tls_magazine_create(mp);
809 1466 : if (!mag) return mempool_alloc_locked(mp);
810 : }
811 : }
812 :
813 4542 : if (atomic_load_explicit(&mag->count, memory_order_relaxed) == 0) {
814 4490 : bool corrupt = false;
815 4490 : served = NULL;
816 4490 : ccol__mutex_lock(mp->lock);
817 4491 : mempool_magazine_refill_locked(mp, mag, &corrupt);
818 4491 : bool refilled =
819 4491 : atomic_load_explicit(&mag->count, memory_order_relaxed) != 0;
820 4491 : if (!corrupt && !refilled) served = mempool_serve_locked(mp);
821 4491 : ccol__mutex_unlock(mp->lock);
822 4487 : if (corrupt) {
823 0 : ccol__assert(false);
824 : }
825 4487 : if (!refilled) return served;
826 : }
827 :
828 3282 : size_t count = atomic_load_explicit(&mag->count, memory_order_relaxed);
829 3282 : void *entry = mag->slots[--count];
830 3282 : atomic_store_explicit(&mag->count, count, memory_order_relaxed);
831 3282 : MP_ENTRY_STATUS(mp, MP_ENTRY_INDEX(mp, (uintptr_t)entry)) =
832 : (uint8_t)mp_status_taken;
833 3282 : return entry;
834 : }
835 :
836 : // Allocates an entry for cmempool_alloc_entry() on a cached pool by popping
837 : // this thread's magazine, or through the slow path. The __builtin_expect hints
838 : // keep the pop right after the lookup at the 64-byte aligned start of the entry
839 : // point; placed elsewhere it can split across two cache lines. Every other
840 : // case tail-jumps out, so there's no frame.
841 93927 : static inline __attribute__((always_inline)) void *mempool_alloc_from_cache(
842 : cmempool *mp) {
843 187854 : ccol_mp_magazine *mag = mempool_tls_magazine_hit(mp);
844 93927 : if (__builtin_expect(mag != NULL, 1)) {
845 87186 : size_t count = atomic_load_explicit(&mag->count, memory_order_relaxed);
846 87186 : if (__builtin_expect(count != 0, 1)) {
847 84066 : void *entry = mag->slots[--count];
848 84066 : atomic_store_explicit(&mag->count, count, memory_order_relaxed);
849 84066 : MP_ENTRY_STATUS(mp, MP_ENTRY_INDEX(mp, (uintptr_t)entry)) =
850 : (uint8_t)mp_status_taken;
851 84066 : return entry;
852 : }
853 : }
854 9861 : return mempool_alloc_from_cache_slow(mp, mag);
855 : }
856 :
857 : // Frees an entry (index idx) that can't just be pushed onto this thread's
858 : // magazine. A thread with no magazine that the pool refuses gives the entry
859 : // back to the shared list under one lock, rereading the status there; a full
860 : // magazine flushes half under the lock first. What can't be parked goes to
861 : // the locked path. mag is the direct-map result, possibly NULL.
862 10796 : static __attribute__((noinline)) void mempool_free_to_cache_slow(
863 : cmempool *mp, void *entry, size_t idx, ccol_mp_magazine *mag) {
864 10796 : if (!mag) {
865 5399 : mag = mempool_tls_magazine_find(mp);
866 5399 : if (!mag) {
867 5370 : bool corrupt = false;
868 5370 : ccol__mutex_lock(mp->lock);
869 5370 : bool budget_available = mp->live_magazines < mp->max_magazines;
870 5370 : if (!budget_available) {
871 5120 : if (MP_ENTRY_STATUS(mp, idx) != mp_status_taken) {
872 : corrupt = true;
873 : } else {
874 5120 : MP_ENTRY_STATUS(mp, idx) = (uint8_t)mp_status_free;
875 5120 : *(void **)entry = mp->free_inst;
876 5120 : mp->free_inst = entry;
877 5120 : ++mp->free_elem_count;
878 : }
879 : }
880 5370 : ccol__mutex_unlock(mp->lock);
881 5370 : if (corrupt) {
882 0 : ccol__assert(false);
883 : }
884 5370 : if (!budget_available) return;
885 250 : mag = mempool_tls_magazine_create(mp);
886 250 : if (!mag) {
887 200 : mempool_free_locked(mp, entry);
888 200 : return;
889 : }
890 : }
891 : }
892 :
893 5476 : size_t count = atomic_load_explicit(&mag->count, memory_order_relaxed);
894 5476 : if (count == mag->capacity) {
895 5397 : size_t half = mag->capacity / 2;
896 5397 : if (half == 0) half = 1;
897 5397 : ccol__mutex_lock(mp->lock);
898 5397 : mempool_magazine_flush_locked(mp, mag, half);
899 5397 : ccol__mutex_unlock(mp->lock);
900 5397 : count = atomic_load_explicit(&mag->count, memory_order_relaxed);
901 : }
902 5476 : if (count >= mag->capacity) {
903 0 : mempool_free_locked(mp, entry);
904 0 : return;
905 : }
906 :
907 5476 : MP_ENTRY_STATUS(mp, idx) = (uint8_t)mp_status_free;
908 5476 : mag->slots[count++] = entry;
909 5476 : atomic_store_explicit(&mag->count, count, memory_order_relaxed);
910 : }
911 :
912 : // Frees an entry for cmempool__free_entry() on a cached pool by pushing it onto
913 : // this thread's magazine, or through the slow or locked path. The tests run in
914 : // the order of the locked path: The bounds check first (it also sends dynamic
915 : // entries to the locked path), then the status byte. The bounds are immutable,
916 : // but the status byte is read with no lock, so two threads freeing one entry at
917 : // the same instant can slip past; that's a data race in the caller anyway.
918 93312 : static inline __attribute__((always_inline)) void mempool_free_to_cache(
919 : cmempool *mp, void *entry, uintptr_t c_entry) {
920 78703 : if (__builtin_expect(!valid_mempool_addr(mp, c_entry), 0)) {
921 7 : mempool_free_locked(mp, entry);
922 7 : return;
923 : }
924 :
925 93305 : size_t idx = MP_ENTRY_INDEX(mp, c_entry);
926 78696 : if (__builtin_expect(MP_ENTRY_STATUS(mp, idx) != mp_status_taken, 0)) {
927 1 : ccol__assert(false);
928 : }
929 :
930 93304 : ccol_mp_magazine *mag = mempool_tls_magazine_hit(mp);
931 93304 : if (__builtin_expect(mag != NULL, 1)) {
932 87905 : size_t count = atomic_load_explicit(&mag->count, memory_order_relaxed);
933 87905 : if (__builtin_expect(count < mag->capacity, 1)) {
934 82508 : MP_ENTRY_STATUS(mp, idx) = (uint8_t)mp_status_free;
935 82508 : mag->slots[count++] = entry;
936 82508 : atomic_store_explicit(&mag->count, count, memory_order_relaxed);
937 82508 : return;
938 : }
939 : }
940 10796 : mempool_free_to_cache_slow(mp, entry, idx, mag);
941 : }
942 :
943 : #ifdef RUNNING_UNIT_TESTS
944 :
945 : // Test hook: Overwrites the status byte of entry in mp, so a corruption test
946 : // can prove the pool catches a state no correct call sequence produces.
947 1 : void cmempool__corrupt_entry_status_for_tests(cmempool *mp, void *entry,
948 : unsigned char value) {
949 1 : if (!mp || !entry) return;
950 3 : if (!valid_mempool_addr(mp, (uintptr_t)entry)) return;
951 1 : MP_ENTRY_STATUS(mp, MP_ENTRY_INDEX(mp, (uintptr_t)entry)) = value;
952 : }
953 :
954 : // Test hook: Gives the magazines mp has handed out (under its lock), so a test
955 : // can see that a thread's exit gives its slot back.
956 41 : size_t cmempool__live_magazines_for_tests(cmempool *mp) {
957 41 : if (!mp) return 0;
958 41 : size_t n;
959 41 : if (mp->should_use_locks) ccol__mutex_lock(mp->lock);
960 41 : n = mp->live_magazines;
961 41 : if (mp->should_use_locks) ccol__mutex_unlock(mp->lock);
962 : return n;
963 : }
964 :
965 : // Test hook: Gives the magazines the calling thread holds, so a test can see
966 : // that orphans get reaped.
967 5 : size_t cmempool__thread_magazines_for_tests(void) {
968 5 : size_t n = 0;
969 5 : mp_tls_state *tls = mp_tls_cur();
970 7 : for (ccol_mp_magazine *mag = tls ? tls->mags : NULL; mag;
971 2 : mag = mag->next_in_thread)
972 2 : n++;
973 5 : return n;
974 : }
975 :
976 : // Test hook: Runs the unload handler while the code stays mapped.
977 1 : void cmempool__unload_cache_for_tests(void) { mp_cache_fini(); }
978 :
979 : // Test hook: Gives the slots above mp's advertised count; 0 without a cache.
980 52 : size_t cmempool__reserve_for_tests(cmempool *mp) {
981 52 : if (!mp) return 0;
982 52 : return mp->total_elem_count - mp->advertised_elem_count;
983 : }
984 : #endif
985 :
986 : // Destroys mp, the body of cmempool_destroy(); NULL does nothing. It cuts
987 : // loose every magazine first, under mp_registry_lock and then mp->lock, so an
988 : // exit drain can't lock a destroyed mutex. Each magazine is unlinked before its
989 : // pool pointer is cleared, because its owner frees it on seeing NULL; its
990 : // entries aren't drained, since the owner writes them unsynchronized. It
991 : // asserts when dynamic entries are still live, then frees the registry, the
992 : // block (unless preallocated) and the pool through its allocator.
993 957 : void cmempool__destroy(cmempool *mp) {
994 957 : if (mp) {
995 957 : if (mp->max_magazines != 0) {
996 590 : ccol__mutex_lock(mp_registry_lock);
997 590 : ccol__mutex_lock(mp->lock);
998 590 : ccol_mp_magazine *mag = mp->magazines;
999 1050 : while (mag) {
1000 460 : ccol_mp_magazine *next = mag->next_in_pool;
1001 460 : mempool_magazine_unlink_locked(mp, mag);
1002 460 : atomic_store_explicit(&mag->pool, NULL, memory_order_release);
1003 460 : mag = next;
1004 : }
1005 590 : ccol__mutex_unlock(mp->lock);
1006 590 : ccol__mutex_unlock(mp_registry_lock);
1007 : }
1008 :
1009 957 : if (mp->fallback_to_dynamic_memory) {
1010 61 : if (cmempool_dynamic_allocs_count(mp) > 0) {
1011 2 : ccol__assert(false);
1012 : }
1013 : }
1014 :
1015 955 : mp_dynamic_set_release(mp);
1016 :
1017 955 : if (mp->should_use_locks) {
1018 741 : ccol__mutex_destroy(mp->lock);
1019 : }
1020 :
1021 955 : if (!mp->is_preallocated && mp->objects) {
1022 883 : ccol__mem_free(mp->m_procs, mp->objects);
1023 : }
1024 :
1025 955 : if (mp->m_procs) {
1026 410 : ccol_free free_func = mp->m_procs->free;
1027 410 : free_func(mp->m_procs);
1028 410 : free_func(mp);
1029 : } else {
1030 545 : ccol__default_mem_free(mp);
1031 : }
1032 : }
1033 955 : }
1034 :
1035 : // Gives the stride for elem_size at run time, the same value as
1036 : // cmempool__stride() (which exists separately because an array size must be a
1037 : // constant expression): Raised to sizeof(mp_addr), aligned and, in the default
1038 : // layout, rounded to a power of two. Gives 0 when no stride fits, which
1039 : // callers treat as a bad elem_size.
1040 2070 : static size_t mp_stride_for(size_t elem_size) {
1041 2070 : if (elem_size < sizeof(mp_addr)) elem_size = sizeof(mp_addr);
1042 750 : if (!cmempool__align_up_fits(elem_size)) return 0;
1043 2134 : size_t base = cmempool__align_up(elem_size);
1044 : #if CMEMPOOL_COMPACT_LAYOUT
1045 : return base;
1046 : #else
1047 2134 : size_t stride = 1;
1048 13755 : while (stride < base) {
1049 11572 : if (stride > SIZE_MAX / 2) return 0;
1050 11572 : stride <<= 1;
1051 : }
1052 : return stride;
1053 : #endif
1054 : }
1055 :
1056 : // Computes the bytes of a block of count slots (strides plus status bytes)
1057 : // into *out. The allocator gets one pre-multiplied size and can't catch a wrap
1058 : // itself, so this check must. Gives false on overflow; it matches
1059 : // cmempool__buffer_params_fit().
1060 1541 : static bool mp_block_bytes(size_t count, size_t stride, size_t *out) {
1061 599 : if (count == 0 || stride > (SIZE_MAX - count) / count) return false;
1062 1540 : *out = count * stride + count;
1063 1540 : return true;
1064 : }
1065 :
1066 : #if CMEMPOOL_COMPACT_LAYOUT
1067 : // Finds a multiplier and shift (into *magic and *shift) that turn a division
1068 : // by a compact stride into a multiply and a shift, so the compact layout can
1069 : // index entries without dividing. A slightly wrong reciprocal gives a
1070 : // neighbouring index and corrupts another entry's status, so the result is
1071 : // proved exhaustively: Both functions never go down, so agreeing at every
1072 : // multiple of the stride and the byte below it means agreeing everywhere, which
1073 : // also makes the bounds test reject an address between entries. Gives false
1074 : // when no shift works, and the pool isn't built.
1075 : static bool mp_build_reciprocal(size_t stride, size_t count, uintptr_t *magic,
1076 : uint8_t *shift) {
1077 : if (stride == 0 || count == 0) return false;
1078 : for (uint8_t s = 0; s < MP_WIDE_BITS; ++s) {
1079 : mp_wide candidate = (((mp_wide)1 << (MP_WIDE_BITS + s)) / stride) + 1;
1080 : if ((candidate >> MP_WIDE_BITS) != 0) continue;
1081 : uintptr_t m = (uintptr_t)candidate;
1082 :
1083 : bool ok = true;
1084 : for (size_t i = 0; i <= count && ok; ++i) {
1085 : uintptr_t at = (uintptr_t)i * (uintptr_t)stride;
1086 : uintptr_t high_at = (uintptr_t)(((mp_wide)at * m) >> MP_WIDE_BITS);
1087 : if ((size_t)(high_at >> s) != i) {
1088 : ok = false;
1089 : } else if (i > 0) {
1090 : uintptr_t high_below =
1091 : (uintptr_t)(((mp_wide)(at - 1) * m) >> MP_WIDE_BITS);
1092 : if ((size_t)(high_below >> s) != i - 1) ok = false;
1093 : }
1094 : }
1095 : if (ok) {
1096 : *magic = m;
1097 : *shift = s;
1098 : return true;
1099 : }
1100 : }
1101 : return false;
1102 : }
1103 : #endif
1104 :
1105 : #if !CMEMPOOL_COMPACT_LAYOUT
1106 : // Gives log2 of a power of two; the default layout stores it as the index
1107 : // shift.
1108 996 : static uint8_t mp_log2_exact(size_t v) {
1109 996 : uint8_t r = 0;
1110 6102 : while ((size_t)1 << r < v) ++r;
1111 996 : return r;
1112 : }
1113 : #endif
1114 :
1115 : // Lays out mp->objects as elem_count entries of extended_elem_size bytes plus
1116 : // their status bytes, marks them free, threads them onto the free list and
1117 : // fills the pool's scalar fields. Both constructors finish with it. Gives
1118 : // false only in the compact layout, when no reciprocal can be proved.
1119 996 : static bool cmempool_init_internal_scalars(cmempool *mp, size_t elem_count,
1120 : size_t extended_elem_size,
1121 : bool fallback_to_dynamic_memory) {
1122 996 : uintptr_t base = (uintptr_t)mp->objects;
1123 :
1124 996 : mp->cmempool_mark = cmempool_mark_value;
1125 996 : mp->extended_elem_size = extended_elem_size;
1126 : #if CMEMPOOL_COMPACT_LAYOUT
1127 : mp->entry_shift = 0;
1128 : if (!mp_build_reciprocal(extended_elem_size, elem_count,
1129 : &mp->entry_index_magic, &mp->entry_index_shift)) {
1130 : return false;
1131 : }
1132 : #else
1133 996 : mp->entry_shift = mp_log2_exact(extended_elem_size);
1134 : #endif
1135 996 : mp->total_elem_count = elem_count;
1136 996 : mp->fallback_to_dynamic_memory = fallback_to_dynamic_memory;
1137 996 : mp->active_dynamic_memory_buffer_count = 0;
1138 996 : mp->lower_addr_limit = base;
1139 996 : mp->upper_addr_limit = base + extended_elem_size * elem_count;
1140 996 : mp->free_elem_count = elem_count;
1141 :
1142 996 : uint8_t *status = (uint8_t *)mp->upper_addr_limit;
1143 1041738 : for (size_t i = 0; i < elem_count; ++i) {
1144 1040742 : void *entry = (void *)(base + i * extended_elem_size);
1145 1040742 : status[i] = (uint8_t)mp_status_free;
1146 1040742 : *(void **)entry = (i == elem_count - 1)
1147 : ? NULL
1148 1040742 : : (void *)(base + (i + 1) * extended_elem_size);
1149 : }
1150 :
1151 996 : mp->free_inst = mp->objects;
1152 996 : return true;
1153 : }
1154 :
1155 : // Creates a heap-backed pool of elem_count entries of elem_size bytes; it's
1156 : // the constructor behind cmempool_create() and the tiers of a ranged pool.
1157 : // Gives the pool, or NULL with *err set. The block holds the entries and their
1158 : // status bytes and is sized before the cache geometry, so an impossible size
1159 : // is reported as a bad request. A pool that locks gets a thread cache and its
1160 : // reserve when mp_cache_available() says so. The reserve is our addition, so
1161 : // when the block with it overflows or can't be allocated, the pool is built
1162 : // without a cache at exactly the requested size.
1163 970 : cmempool *cmempool_create_mp(size_t elem_count, size_t elem_size,
1164 : bool fallback_to_dynamic_memory,
1165 : bool single_threaded,
1166 : ccol_memmgmt_procs *mmgmt_procs, char **err) {
1167 970 : if (err) {
1168 363 : *err = NULL;
1169 : }
1170 :
1171 970 : if (elem_count == 0 || elem_size == 0) {
1172 3 : if (err) {
1173 3 : *err = CCOL__ERR_STR("elem_count or elem_size is zero");
1174 : }
1175 3 : return NULL;
1176 1932 : } else if (mp_stride_for(elem_size) == 0) {
1177 2 : if (err) {
1178 2 : *err = CCOL__ERR_STR(
1179 : "elem_size is too large: the stride rounding would "
1180 : "overflow size_t");
1181 : }
1182 2 : return NULL;
1183 965 : } else if (elem_size < sizeof(mp_addr)) {
1184 : elem_size = sizeof(mp_addr);
1185 : }
1186 :
1187 965 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err)) {
1188 1 : return NULL;
1189 : }
1190 :
1191 964 : cmempool *mp = (cmempool *)ccol__mem_calloc(mmgmt_procs, 1, sizeof(cmempool));
1192 964 : if (!mp) {
1193 11 : if (err) {
1194 11 : *err = CCOL__ERR_STR("failed to allocate memory pool struct");
1195 : }
1196 11 : return NULL;
1197 : }
1198 :
1199 953 : if (!ccol__populate_mem_mgmt_procs(mp, mmgmt_procs, err)) {
1200 11 : ccol__mem_free(mmgmt_procs, mp);
1201 11 : return NULL;
1202 : }
1203 :
1204 942 : size_t extended_elem_size = mp_stride_for(elem_size);
1205 942 : if (extended_elem_size == 0) {
1206 0 : if (err) {
1207 0 : *err = CCOL__ERR_STR("elem_size is too large for a pool entry");
1208 : }
1209 0 : cmempool_destroy(mp);
1210 0 : return NULL;
1211 : }
1212 :
1213 942 : size_t asked_bytes = 0;
1214 1883 : if (!mp_block_bytes(elem_count, extended_elem_size, &asked_bytes)) {
1215 1 : if (err) {
1216 1 : *err = CCOL__ERR_STR(
1217 : "elem_count and elem_size are too large: the entries and their "
1218 : "status bytes would overflow size_t");
1219 : }
1220 1 : cmempool_destroy(mp);
1221 1 : return NULL;
1222 : }
1223 :
1224 941 : size_t max_magazines = 0, magazine_capacity = 0, reserve = 0;
1225 941 : if (!single_threaded && mp_cache_available())
1226 714 : mempool_cache_geometry(elem_count, &max_magazines, &magazine_capacity,
1227 : &reserve);
1228 :
1229 941 : size_t slot_count = elem_count + reserve;
1230 941 : size_t slot_bytes = asked_bytes;
1231 941 : if (reserve > 0 &&
1232 599 : !mp_block_bytes(slot_count, extended_elem_size, &slot_bytes)) {
1233 0 : max_magazines = 0;
1234 0 : magazine_capacity = 0;
1235 0 : reserve = 0;
1236 0 : slot_count = elem_count;
1237 0 : slot_bytes = asked_bytes;
1238 : }
1239 :
1240 941 : mp->objects = ccol__mem_calloc(mp->m_procs, 1, slot_bytes);
1241 941 : if (!mp->objects && reserve > 0) {
1242 3 : max_magazines = 0;
1243 3 : magazine_capacity = 0;
1244 3 : reserve = 0;
1245 3 : slot_count = elem_count;
1246 3 : slot_bytes = asked_bytes;
1247 3 : mp->objects = ccol__mem_calloc(mp->m_procs, 1, slot_bytes);
1248 : }
1249 941 : if (!mp->objects) {
1250 8 : if (err) {
1251 8 : *err = CCOL__ERR_STR("failed to allocate memory pool data area");
1252 : }
1253 8 : cmempool_destroy(mp);
1254 8 : return NULL;
1255 : }
1256 :
1257 933 : mp->should_use_locks = !single_threaded;
1258 :
1259 933 : if (mp->should_use_locks) {
1260 712 : if (ccol__mutex_init(mp->lock) != 0) {
1261 0 : if (err) {
1262 0 : *err = CCOL__ERR_STR("failed to initialize the mutex");
1263 : }
1264 0 : mp->should_use_locks = false;
1265 0 : cmempool_destroy(mp);
1266 0 : return NULL;
1267 : }
1268 : }
1269 :
1270 933 : mp->max_magazines = max_magazines;
1271 : #if CMEMPOOL_COMPACT_LAYOUT
1272 : mp->has_cache = (max_magazines != 0);
1273 : #endif
1274 933 : mp->magazine_capacity = magazine_capacity;
1275 933 : mp->advertised_elem_count = elem_count;
1276 :
1277 933 : if (!cmempool_init_internal_scalars(mp, slot_count, extended_elem_size,
1278 : fallback_to_dynamic_memory)) {
1279 0 : if (err) {
1280 0 : *err = CCOL__ERR_STR(
1281 : "no verified reciprocal exists for this element size and count");
1282 : }
1283 0 : cmempool_destroy(mp);
1284 0 : return NULL;
1285 : }
1286 :
1287 : return mp;
1288 : }
1289 :
1290 : // Creates a pool on the caller's buffer, which it never frees; embedded code
1291 : // and the tiers of a preallocated ranged pool use it. Gives the pool, or NULL
1292 : // with *err set. The buffer must be aligned, because entry 0 sits at its start
1293 : // and the stride only carries that alignment on. The elem_size checks run in
1294 : // the same order as in cmempool_create_mp(). Each element costs its stride
1295 : // plus a status byte, which is what the buffer macro sizes for. Such a pool
1296 : // has no cache.
1297 71 : cmempool *cmempool_create_from_preallocated_buffer_mp(
1298 : void *buffer, size_t buf_size, size_t elem_size,
1299 : bool fallback_to_dynamic_memory, bool single_threaded,
1300 : ccol_memmgmt_procs *mmgmt_procs, char **err) {
1301 71 : if (err) {
1302 32 : *err = NULL;
1303 : }
1304 :
1305 71 : if (!buffer) {
1306 1 : if (err) {
1307 1 : *err = CCOL__ERR_STR("buffer is not acceptable");
1308 : }
1309 1 : return NULL;
1310 : }
1311 :
1312 70 : if ((uintptr_t)buffer % cmempool__entry_align != 0) {
1313 1 : if (err) {
1314 1 : *err = CCOL__ERR_STR("buffer must be aligned to at least 16 bytes");
1315 : }
1316 1 : return NULL;
1317 : }
1318 :
1319 69 : if (elem_size == 0) {
1320 1 : if (err) {
1321 1 : *err = CCOL__ERR_STR("elem_size is zero");
1322 : }
1323 1 : return NULL;
1324 135 : } else if (mp_stride_for(elem_size) == 0) {
1325 1 : if (err) {
1326 1 : *err = CCOL__ERR_STR(
1327 : "elem_size is too large: the stride rounding would "
1328 : "overflow size_t");
1329 : }
1330 1 : return NULL;
1331 67 : } else if (elem_size < sizeof(mp_addr)) {
1332 : elem_size = sizeof(mp_addr);
1333 : }
1334 :
1335 67 : size_t extended_elem_size = mp_stride_for(elem_size);
1336 67 : size_t elem_count = buf_size / (extended_elem_size + 1);
1337 67 : if (elem_count == 0) {
1338 1 : if (err) {
1339 1 : *err = CCOL__ERR_STR("calculated elem_count is zero");
1340 : }
1341 1 : return NULL;
1342 : }
1343 :
1344 66 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err)) {
1345 1 : return NULL;
1346 : }
1347 :
1348 65 : cmempool *mp = (cmempool *)ccol__mem_calloc(mmgmt_procs, 1, sizeof(cmempool));
1349 65 : if (!mp) {
1350 1 : if (err) {
1351 1 : *err = CCOL__ERR_STR("failed to allocate cmempool struct");
1352 : }
1353 1 : return NULL;
1354 : }
1355 :
1356 64 : if (!ccol__populate_mem_mgmt_procs(mp, mmgmt_procs, err)) {
1357 1 : ccol__mem_free(mmgmt_procs, mp);
1358 1 : return NULL;
1359 : }
1360 :
1361 63 : mp->is_preallocated = true;
1362 63 : mp->objects = buffer;
1363 :
1364 63 : mp->should_use_locks = !single_threaded;
1365 :
1366 63 : if (mp->should_use_locks) {
1367 44 : if (ccol__mutex_init(mp->lock) != 0) {
1368 0 : if (err) {
1369 0 : *err = CCOL__ERR_STR("failed to init the rw lock");
1370 : }
1371 0 : mp->should_use_locks = false;
1372 0 : cmempool_destroy(mp);
1373 0 : return NULL;
1374 : }
1375 : }
1376 :
1377 63 : mp->advertised_elem_count = elem_count;
1378 :
1379 63 : if (!cmempool_init_internal_scalars(mp, elem_count, extended_elem_size,
1380 : fallback_to_dynamic_memory)) {
1381 0 : if (err) {
1382 0 : *err = CCOL__ERR_STR(
1383 : "no verified reciprocal exists for this element size and count");
1384 : }
1385 0 : cmempool_destroy(mp);
1386 0 : return NULL;
1387 : }
1388 :
1389 : return mp;
1390 : }
1391 :
1392 : // Allocates from mp's shared state: Pops the head of the free list, or makes a
1393 : // dynamic fallback entry when the pool is empty and the fallback is on. Every
1394 : // allocation path that misses the thread cache ends here. locked tells whether
1395 : // the caller holds mp->lock (a constant at every call), so a corruption assert
1396 : // can unlock first. Gives the entry or NULL. A cached pool treats a free list
1397 : // it can only serve from its reserve as empty, so it never hands out more than
1398 : // advertised; a pool without a cache skips that check.
1399 287926 : static inline __attribute__((always_inline)) void *mempool_serve(cmempool *mp,
1400 : bool locked) {
1401 287926 : void *result = NULL;
1402 :
1403 287926 : bool can_serve = mp->free_inst != NULL;
1404 284911 : if (can_serve && MP_HAS_CACHE(mp)) {
1405 6579 : can_serve = mempool_live_count_locked(mp) < mp->advertised_elem_count;
1406 : }
1407 :
1408 6579 : if (__builtin_expect(can_serve, 1)) {
1409 283796 : void *entry = mp->free_inst;
1410 :
1411 851388 : if (__builtin_expect(
1412 283796 : !valid_mempool_addr(mp, (uintptr_t)entry) ||
1413 283796 : MP_ENTRY_STATUS(mp, MP_ENTRY_INDEX(mp, (uintptr_t)entry)) !=
1414 : mp_status_free,
1415 : 0)) {
1416 0 : if (locked) {
1417 0 : ccol__mutex_unlock(mp->lock);
1418 : }
1419 0 : ccol__assert(false);
1420 : }
1421 :
1422 283796 : mp->free_inst = *(void **)entry;
1423 283796 : MP_ENTRY_STATUS(mp, MP_ENTRY_INDEX(mp, (uintptr_t)entry)) =
1424 : (uint8_t)mp_status_taken;
1425 283796 : result = entry;
1426 283796 : --mp->free_elem_count;
1427 4130 : } else if (mp->fallback_to_dynamic_memory) {
1428 2730 : result = mempool_alloc_dynamic_locked(mp, mp->extended_elem_size);
1429 : }
1430 :
1431 281547 : return result;
1432 : }
1433 :
1434 : // Allocates from the free list inside a critical section the caller holds;
1435 : // the thread-cache paths serve refused or empty-magazine requests with it.
1436 6379 : static inline __attribute__((always_inline)) void *mempool_serve_locked(
1437 : cmempool *mp) {
1438 17457 : return mempool_serve(mp, true);
1439 : }
1440 :
1441 : // Allocates from a pool without locks, for cmempool_alloc_entry(). This path
1442 : // and the locked one below each have their own function on a 64-byte
1443 : // boundary, so their speed doesn't depend on where the surrounding code ends;
1444 : // the entry point tail-jumps here and the constant lock argument drops every
1445 : // test of should_use_locks. Check the layout with objdump and callgrind after
1446 : // any change.
1447 135138 : static __attribute__((noinline, aligned(64))) void *mempool_alloc_unlocked(
1448 : cmempool *mp) {
1449 135138 : return mempool_serve(mp, false);
1450 : }
1451 :
1452 : // Allocates under mp->lock, for a locking pool without a cache and as the
1453 : // fallback of the cache paths.
1454 146396 : static __attribute__((noinline, aligned(64))) void *mempool_alloc_locked(
1455 : cmempool *mp) {
1456 146396 : ccol__mutex_lock(mp->lock);
1457 146409 : void *result = mempool_serve(mp, true);
1458 146409 : ccol__mutex_unlock(mp->lock);
1459 146392 : return result;
1460 : }
1461 :
1462 : // Allocates an entry from mp: From the thread cache, the free list or the
1463 : // dynamic fallback. Gives NULL when nothing can serve it; asserts on a NULL mp.
1464 : // It starts on a 64-byte boundary with the thread-cache hit as its
1465 : // fall-through. The cache test sits inside the lock test, since a
1466 : // single-threaded pool never has a cache.
1467 375263 : __attribute__((aligned(64))) void *cmempool_alloc_entry(cmempool *mp) {
1468 375263 : if (!mp) {
1469 0 : ccol__assert(false);
1470 : }
1471 :
1472 375263 : if (!mp->should_use_locks) {
1473 135138 : return mempool_alloc_unlocked(mp);
1474 : }
1475 :
1476 240125 : if (MP_HAS_CACHE(mp)) {
1477 187851 : return mempool_alloc_from_cache(mp);
1478 : }
1479 146198 : return mempool_alloc_locked(mp);
1480 : }
1481 :
1482 : // Allocates an entry and zeroes its whole stride, which all belongs to the
1483 : // caller; for callers that need zeroed memory.
1484 132110 : void *cmempool_calloc_entry(cmempool *mp) {
1485 132110 : void *result = cmempool_alloc_entry(mp);
1486 :
1487 132110 : if (result) {
1488 132106 : memset(result, 0, mp->extended_elem_size);
1489 : }
1490 :
1491 132110 : return result;
1492 : }
1493 :
1494 : // Tells whether c_entry is the start of one of mp's entries. Every free and
1495 : // the corruption checks use it to tell a pool entry from anything else. An
1496 : // address partway into an entry is rejected too, since its index names a
1497 : // neighbour: The offset must be a multiple of the stride (one mask in the
1498 : // default layout, a multiply back in the compact one). Both bounds are compared
1499 : // explicitly; the pseudo pool has an empty range.
1500 787957 : static inline bool valid_mempool_addr(cmempool *mp, uintptr_t c_entry) {
1501 776186 : if (c_entry < mp->lower_addr_limit || c_entry >= mp->upper_addr_limit) {
1502 : return false;
1503 : }
1504 762098 : uintptr_t off = c_entry - mp->lower_addr_limit;
1505 : #if CMEMPOOL_COMPACT_LAYOUT
1506 : return (uintptr_t)MP_ENTRY_INDEX(mp, c_entry) *
1507 : (uintptr_t)mp->extended_elem_size ==
1508 : off;
1509 : #else
1510 424829 : return (off & (mp->extended_elem_size - 1)) == 0;
1511 : #endif
1512 : }
1513 :
1514 : // Releases a dynamic entry that the free path has already removed from mp's
1515 : // registry (the removal is the ownership check, so a second free finds it
1516 : // gone). It drops the live count (release), marks the header freed so a
1517 : // memory dump shows it, and frees the block. Needs mp->lock when the pool
1518 : // locks.
1519 : static inline __attribute__((always_inline)) void
1520 2739 : mempool_release_dynamic_locked(cmempool *mp, void *entry) {
1521 2739 : mp_dynamic_header *dyn = DYNAMIC_ENTRY_HEADER(entry);
1522 :
1523 2739 : atomic_store_explicit(
1524 : &mp->active_dynamic_memory_buffer_count,
1525 : atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
1526 : memory_order_relaxed) -
1527 : 1,
1528 : memory_order_release);
1529 2739 : dyn->elem_status = elem_is_freed_dynamic_member;
1530 2739 : ccol__mem_free(mp->m_procs, DYNAMIC_ENTRY_RAW_BLOCK(entry));
1531 : }
1532 :
1533 : // Frees entry when it's a live dynamic entry of mp. A ranged pool asks each
1534 : // tier in turn with it. Gives false, touching nothing, otherwise. Needs
1535 : // mp->lock when the pool locks.
1536 392 : static __attribute__((noinline)) bool mempool_free_dynamic_locked(cmempool *mp,
1537 : void *entry) {
1538 392 : if (!mp_dynamic_set_remove_locked(mp, (uintptr_t)entry)) return false;
1539 389 : mempool_release_dynamic_locked(mp, entry);
1540 : return true;
1541 : }
1542 :
1543 : // Frees entry to mp's shared state; every free that misses the thread cache
1544 : // ends here. Ownership comes from the address: Inside the buffer it's a pool
1545 : // entry (a status other than taken is a double free or corruption and
1546 : // asserts); outside it can only be a live dynamic entry, which the registry
1547 : // decides before anything is read through the address. locked means the caller
1548 : // holds mp->lock, and this function releases it (also before any assert).
1549 280265 : static inline __attribute__((always_inline)) void mempool_free_body(
1550 : cmempool *mp, void *entry, bool locked) {
1551 280265 : uintptr_t c_entry = (uintptr_t)entry;
1552 :
1553 277913 : if (__builtin_expect(valid_mempool_addr(mp, c_entry), 1)) {
1554 277912 : size_t idx = MP_ENTRY_INDEX(mp, c_entry);
1555 277912 : if (__builtin_expect(MP_ENTRY_STATUS(mp, idx) != mp_status_taken, 0)) {
1556 2 : if (locked) {
1557 0 : ccol__mutex_unlock(mp->lock);
1558 : }
1559 2 : ccol__assert(false);
1560 : }
1561 :
1562 277910 : MP_ENTRY_STATUS(mp, idx) = (uint8_t)mp_status_free;
1563 277910 : *(void **)entry = mp->free_inst;
1564 277910 : mp->free_inst = entry;
1565 277910 : ++mp->free_elem_count;
1566 277910 : if (locked) {
1567 143560 : ccol__mutex_unlock(mp->lock);
1568 : }
1569 277910 : return;
1570 : }
1571 :
1572 2353 : if (!mp->fallback_to_dynamic_memory ||
1573 2352 : atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
1574 : memory_order_relaxed) == 0) {
1575 1 : if (locked) {
1576 0 : ccol__mutex_unlock(mp->lock);
1577 : }
1578 1 : ccol__assert(false);
1579 : }
1580 :
1581 2352 : if (!mp_dynamic_set_remove_locked(mp, c_entry)) {
1582 2 : if (locked) {
1583 1 : ccol__mutex_unlock(mp->lock);
1584 : }
1585 2 : ccol__assert(false);
1586 : }
1587 :
1588 2350 : mempool_release_dynamic_locked(mp, entry);
1589 :
1590 2340 : if (locked) {
1591 2340 : ccol__mutex_unlock(mp->lock);
1592 : }
1593 : }
1594 :
1595 : // Frees on a pool without locks. Like the allocation paths, it and the locked
1596 : // path below sit on 64-byte boundaries (see mempool_alloc_unlocked()).
1597 134364 : static __attribute__((noinline, aligned(64))) void mempool_free_unlocked(
1598 : cmempool *mp, void *entry) {
1599 134364 : mempool_free_body(mp, entry, false);
1600 134360 : }
1601 :
1602 : // Frees under mp->lock, for a locking pool without a cache and as the fallback
1603 : // of the cache paths; mempool_free_body() releases the lock.
1604 145903 : static __attribute__((noinline, aligned(64))) void mempool_free_locked(
1605 : cmempool *mp, void *entry) {
1606 145903 : ccol__mutex_lock(mp->lock);
1607 145901 : mempool_free_body(mp, entry, true);
1608 145896 : }
1609 :
1610 : // Frees entry to mp through the right path; cmempool__free_entry() and the
1611 : // ranged free share it. Asserts on a NULL mp. The cache test sits inside the
1612 : // lock test, as in cmempool_alloc_entry().
1613 373376 : static inline __attribute__((always_inline)) void cmempool_free_entry_body(
1614 : cmempool *mp, void *entry) {
1615 373376 : if (!mp) {
1616 373376 : ccol__assert(false);
1617 : }
1618 :
1619 373376 : if (!mp->should_use_locks) {
1620 134364 : mempool_free_unlocked(mp, entry);
1621 134364 : return;
1622 : }
1623 :
1624 239012 : if (MP_HAS_CACHE(mp)) {
1625 93312 : mempool_free_to_cache(mp, entry, (uintptr_t)entry);
1626 : return;
1627 : }
1628 145700 : mempool_free_locked(mp, entry);
1629 : }
1630 :
1631 : // Frees entry back to mp, the body of cmempool_free_entry(). A NULL entry does
1632 : // nothing, like free(); a NULL pool or a bad mark asserts. It starts on a
1633 : // 64-byte boundary with the cache push as its fall-through.
1634 349151 : __attribute__((aligned(64))) void cmempool__free_entry(cmempool *mp,
1635 : void *entry) {
1636 349151 : if (!entry) {
1637 : return;
1638 : }
1639 :
1640 349150 : if (!mp) {
1641 1 : ccol__assert(false);
1642 : }
1643 :
1644 349149 : if (mp->cmempool_mark != cmempool_mark_value) {
1645 0 : ccol__assert(false);
1646 : }
1647 :
1648 349149 : cmempool_free_entry_body(mp, entry);
1649 : }
1650 :
1651 : // Gives the advertised count of mp, read under its lock. The slot count isn't
1652 : // reported, since the reserve can't be handed out on its own.
1653 8341 : size_t cmempool_total_capacity(cmempool *mp) {
1654 8341 : if (!mp) {
1655 0 : ccol__assert(false);
1656 : }
1657 :
1658 8341 : size_t result = 0;
1659 :
1660 8341 : if (mp->should_use_locks) {
1661 6271 : ccol__mutex_lock(mp->lock);
1662 : }
1663 :
1664 8341 : result = mp->advertised_elem_count;
1665 :
1666 8341 : if (mp->should_use_locks) {
1667 6271 : ccol__mutex_unlock(mp->lock);
1668 : }
1669 :
1670 8341 : return result;
1671 : }
1672 :
1673 : // Gives the entries of mp handed out to callers, read under the lock. Entries
1674 : // in a thread cache are subtracted (read relaxed, so possibly stale while
1675 : // their owner allocates, but never torn).
1676 7538 : size_t cmempool_used_count(cmempool *mp) {
1677 7538 : if (!mp) {
1678 0 : ccol__assert(false);
1679 : }
1680 :
1681 7538 : size_t result = 0;
1682 :
1683 7538 : if (mp->should_use_locks) {
1684 5449 : ccol__mutex_lock(mp->lock);
1685 : }
1686 :
1687 7538 : result = mempool_live_count_locked(mp);
1688 :
1689 7538 : if (mp->should_use_locks) {
1690 5449 : ccol__mutex_unlock(mp->lock);
1691 : }
1692 :
1693 7538 : return result;
1694 : }
1695 :
1696 : // Gives the live dynamic entries of mp, read under its lock; the destroy uses
1697 : // it for its leak assert.
1698 295 : size_t cmempool_dynamic_allocs_count(cmempool *mp) {
1699 295 : if (!mp) {
1700 0 : ccol__assert(false);
1701 : }
1702 :
1703 295 : size_t result = 0;
1704 :
1705 295 : if (mp->should_use_locks) {
1706 175 : ccol__mutex_lock(mp->lock);
1707 : }
1708 :
1709 295 : result = atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
1710 : memory_order_relaxed);
1711 :
1712 295 : if (mp->should_use_locks) {
1713 175 : ccol__mutex_unlock(mp->lock);
1714 : }
1715 :
1716 295 : return result;
1717 : }
1718 :
1719 : // The size limits of a ranged pool. The largest is the highest power of two a
1720 : // size_t holds, not SIZE_MAX / 2, which is one less than it.
1721 : static const size_t min_allowed_smallest_size = 16;
1722 : static const size_t max_allowed_largest_size = ccol__max_power_of_two_size;
1723 :
1724 : // A ranged pool: One cmempool per tier, plus a pseudo pool with an empty
1725 : // range that owns the shared fallback of
1726 : // crmempool_fallback_at_last_exhaustion.
1727 : struct crmempool {
1728 : cmempool **mem_pools;
1729 : cmempool pseudo_pool;
1730 : crmempool_fallback_policy fb_policy;
1731 : bool should_use_locks;
1732 : ccol_memmgmt_procs *m_procs;
1733 : size_t number_of_mempools;
1734 : size_t smallest_size;
1735 : size_t largest_size;
1736 : size_t smallest_elem_count;
1737 : // log2 of smallest_size, so the size-to-tier lookup shifts instead of
1738 : // dividing.
1739 : uint8_t smallest_size_power_of_two;
1740 : };
1741 :
1742 : // Destroys rmp, the body of crmempool_destroy(); NULL does nothing. It
1743 : // asserts when the shared fallback still holds live entries, then destroys
1744 : // each tier (which asserts the same way) and frees the rest through rmp's
1745 : // allocator.
1746 150 : void crmempool__destroy(crmempool *rmp) {
1747 150 : if (rmp) {
1748 150 : if (rmp->fb_policy == crmempool_fallback_at_last_exhaustion) {
1749 54 : if (cmempool_dynamic_allocs_count(&rmp->pseudo_pool) > 0) {
1750 1 : ccol__assert(false);
1751 : }
1752 : }
1753 :
1754 149 : if (rmp->mem_pools) {
1755 683 : for (size_t i = 0; i < rmp->number_of_mempools; ++i) {
1756 554 : if (rmp->mem_pools[i]) {
1757 554 : cmempool_destroy(rmp->mem_pools[i]);
1758 : }
1759 : }
1760 129 : ccol__mem_free(rmp->m_procs, rmp->mem_pools);
1761 : }
1762 :
1763 148 : if (rmp->fb_policy == crmempool_fallback_at_last_exhaustion) {
1764 53 : mp_dynamic_set_release(&rmp->pseudo_pool);
1765 53 : if (rmp->pseudo_pool.should_use_locks) {
1766 13 : ccol__mutex_destroy(rmp->pseudo_pool.lock);
1767 : }
1768 : }
1769 :
1770 148 : if (rmp->m_procs) {
1771 83 : ccol_free free_func = rmp->m_procs->free;
1772 83 : free_func(rmp->m_procs);
1773 83 : free_func(rmp);
1774 : } else {
1775 65 : ccol__default_mem_free(rmp);
1776 : }
1777 : }
1778 148 : }
1779 :
1780 : // Validates the size parameters of a ranged pool for both constructors and,
1781 : // on success, fills rmp's sizes, lock flag and tier count. It refuses zeros,
1782 : // exponents as wide as size_t, largest <= smallest, a count power below
1783 : // largest - smallest (every tier needs at least one element), an unknown
1784 : // policy and sizes beyond the limits; *err says which. Gives true on
1785 : // success.
1786 161 : static bool assess_r_mempool_create_inputs(
1787 : crmempool *rmp, uint8_t smallest_size_power_of_two,
1788 : uint8_t largest_size_power_of_two, uint8_t smallest_elem_count_power_of_two,
1789 : crmempool_fallback_policy fb_policy, bool single_threaded, char **err) {
1790 161 : if (smallest_size_power_of_two == 0 || largest_size_power_of_two == 0 ||
1791 : smallest_elem_count_power_of_two == 0) {
1792 3 : if (err) {
1793 3 : *err = CCOL__ERR_STR("zero sizes are not acceptable");
1794 : }
1795 3 : return false;
1796 : }
1797 :
1798 158 : if (largest_size_power_of_two >= sizeof(size_t) * CHAR_BIT ||
1799 158 : smallest_size_power_of_two >= sizeof(size_t) * CHAR_BIT ||
1800 : smallest_elem_count_power_of_two >= sizeof(size_t) * CHAR_BIT) {
1801 3 : if (err) {
1802 3 : *err = CCOL__ERR_STR("power of two exceeds size_t width");
1803 : }
1804 3 : return false;
1805 : }
1806 :
1807 155 : if (largest_size_power_of_two <= smallest_size_power_of_two ||
1808 152 : (smallest_elem_count_power_of_two <
1809 152 : (largest_size_power_of_two - smallest_size_power_of_two))) {
1810 4 : if (err) {
1811 4 : *err = CCOL__ERR_STR("inconsistent sizes are not acceptable");
1812 : }
1813 4 : return false;
1814 : }
1815 :
1816 151 : if (fb_policy < 0 || fb_policy >= crmempool__fallback_end_place_holder) {
1817 3 : if (err) {
1818 3 : *err = CCOL__ERR_STR("unknown fallback policy");
1819 : }
1820 3 : return false;
1821 : }
1822 :
1823 148 : size_t smallest_size = (size_t)1 << smallest_size_power_of_two;
1824 148 : size_t largest_size = (size_t)1 << largest_size_power_of_two;
1825 148 : size_t smallest_elem_count = (size_t)1 << smallest_elem_count_power_of_two;
1826 :
1827 148 : if (largest_size > max_allowed_largest_size ||
1828 148 : smallest_size < min_allowed_smallest_size) {
1829 1 : if (err) {
1830 1 : *err = CCOL__ERR_STR("sizes beyond limits are not acceptable");
1831 : }
1832 1 : return false;
1833 : }
1834 :
1835 147 : rmp->should_use_locks = !single_threaded;
1836 147 : rmp->smallest_size = smallest_size;
1837 147 : rmp->largest_size = largest_size;
1838 147 : rmp->smallest_elem_count = smallest_elem_count;
1839 147 : rmp->smallest_size_power_of_two = smallest_size_power_of_two;
1840 147 : rmp->number_of_mempools =
1841 147 : largest_size_power_of_two - smallest_size_power_of_two + 1;
1842 :
1843 147 : return true;
1844 : }
1845 :
1846 : // Sets up rmp's pseudo pool for both constructors. Under
1847 : // crmempool_fallback_at_last_exhaustion it becomes the owner of the shared
1848 : // fallback (with a lock when rmp locks), and its live count covers every
1849 : // dynamic entry of rmp. Gives false when the mutex can't be created.
1850 147 : static bool init_r_mempool_pseudo_pool(crmempool *rmp) {
1851 147 : memset(&rmp->pseudo_pool, 0, sizeof(cmempool));
1852 147 : rmp->pseudo_pool.m_procs = rmp->m_procs;
1853 147 : if (rmp->fb_policy == crmempool_fallback_at_last_exhaustion) {
1854 57 : if (rmp->should_use_locks) {
1855 15 : if (ccol__mutex_init(rmp->pseudo_pool.lock) != 0) {
1856 : return false;
1857 : }
1858 15 : rmp->pseudo_pool.should_use_locks = true;
1859 : }
1860 57 : rmp->pseudo_pool.fallback_to_dynamic_memory = true;
1861 57 : rmp->pseudo_pool.cmempool_mark = cmempool_mark_value;
1862 : }
1863 :
1864 : return true;
1865 : }
1866 :
1867 : // Builds the tiers of a heap-backed ranged pool: The pseudo pool and one
1868 : // cmempool per tier, the size doubling and the count halving each step. A tier
1869 : // falls back on its own only under crmempool_fallback_at_first_exhaustion.
1870 : // Gives false with *err set; the caller cleans up.
1871 136 : static bool init_r_mempool_internal_pools(crmempool *rmp, char **err) {
1872 136 : if (!init_r_mempool_pseudo_pool(rmp)) {
1873 0 : if (err) {
1874 0 : *err = CCOL__ERR_STR("failed to initialize the pseudo_pool");
1875 : }
1876 0 : return false;
1877 : }
1878 :
1879 136 : rmp->mem_pools = (cmempool **)ccol__mem_alloc(
1880 : rmp->m_procs, rmp->number_of_mempools * sizeof(cmempool *));
1881 136 : if (!rmp->mem_pools) {
1882 2 : if (err) {
1883 2 : *err = CCOL__ERR_STR("failed to allocate mem_pools array");
1884 : }
1885 2 : return false;
1886 : }
1887 134 : memset(rmp->mem_pools, 0, rmp->number_of_mempools * sizeof(cmempool *));
1888 :
1889 134 : size_t first_size = rmp->smallest_size;
1890 134 : size_t first_count = rmp->smallest_elem_count;
1891 :
1892 134 : for (size_t esize = first_size, ecount = first_count, index = 0;
1893 612 : index < rmp->number_of_mempools; esize *= 2, ecount /= 2, ++index) {
1894 1006 : rmp->mem_pools[index] = cmempool_create_mp(
1895 503 : ecount, esize, rmp->fb_policy == crmempool_fallback_at_first_exhaustion,
1896 503 : !rmp->should_use_locks, rmp->m_procs, err);
1897 503 : if (!rmp->mem_pools[index]) {
1898 : return false;
1899 : }
1900 : }
1901 :
1902 : return true;
1903 : }
1904 :
1905 : // Gives the index of the smallest tier that fits size (1 <= size <= largest);
1906 : // every ranged call that takes a size uses it. One shift and one bit scan do
1907 : // it, where a lookup table would need largest / smallest entries.
1908 40991 : static inline size_t crmempool_pool_index_for_size(crmempool *rmp,
1909 : size_t size) {
1910 40991 : size_t t = (size - 1) >> rmp->smallest_size_power_of_two;
1911 40991 : if (t == 0) {
1912 : return 0;
1913 : }
1914 25577 : return (size_t)(sizeof(unsigned long long) * CHAR_BIT) -
1915 25577 : (size_t)__builtin_clzll((unsigned long long)t);
1916 : }
1917 :
1918 : // Creates a heap-backed ranged pool, the constructor behind
1919 : // crmempool_create(): It validates the parameters, then builds the tiers.
1920 : // Gives the pool, or NULL with *err set; a partial pool is destroyed.
1921 155 : crmempool *crmempool_create_mp(uint8_t smallest_size_power_of_two,
1922 : uint8_t largest_size_power_of_two,
1923 : uint8_t smallest_elem_count_power_of_two,
1924 : crmempool_fallback_policy fb_policy,
1925 : bool single_threaded,
1926 : ccol_memmgmt_procs *mmgmt_procs, char **err) {
1927 155 : if (err) {
1928 98 : *err = NULL;
1929 : }
1930 :
1931 155 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err)) {
1932 1 : return NULL;
1933 : }
1934 :
1935 154 : crmempool *rmp =
1936 154 : (crmempool *)ccol__mem_calloc(mmgmt_procs, 1, sizeof(crmempool));
1937 154 : if (!rmp) {
1938 3 : if (err) {
1939 3 : *err = CCOL__ERR_STR("failed to allocate crmempool struct");
1940 : }
1941 3 : return NULL;
1942 : }
1943 :
1944 151 : if (!ccol__populate_mem_mgmt_procs(rmp, mmgmt_procs, err)) {
1945 2 : ccol__mem_free(mmgmt_procs, rmp);
1946 2 : return NULL;
1947 : }
1948 :
1949 149 : if (!assess_r_mempool_create_inputs(
1950 : rmp, smallest_size_power_of_two, largest_size_power_of_two,
1951 : smallest_elem_count_power_of_two, fb_policy, single_threaded, err)) {
1952 13 : crmempool_destroy(rmp);
1953 13 : return NULL;
1954 : }
1955 136 : rmp->fb_policy = fb_policy;
1956 :
1957 136 : if (!init_r_mempool_internal_pools(rmp, err)) {
1958 27 : crmempool_destroy(rmp);
1959 27 : return NULL;
1960 : }
1961 :
1962 : return rmp;
1963 : }
1964 :
1965 : // Builds the tiers of a ranged pool on the caller's buffer: Sets up the pseudo
1966 : // pool and carves one segment per tier, with the progression of
1967 : // init_r_mempool_internal_pools(). The whole expected size is computed first,
1968 : // each term and partial sum checked for overflow, and must equal
1969 : // preallocated_buffer_size, so a wrong buffer is refused before anything is
1970 : // written. Each segment's status region is rounded up so the next tier stays
1971 : // aligned. Gives false with *err set; the caller cleans up.
1972 11 : static bool init_preallocated_r_mempool_internal_pools(
1973 : crmempool *rmp, void *preallocated_buffer, size_t preallocated_buffer_size,
1974 : char **err) {
1975 11 : if (!init_r_mempool_pseudo_pool(rmp)) {
1976 0 : if (err) {
1977 0 : *err = CCOL__ERR_STR("failed to initialize the pseudo_pool");
1978 : }
1979 0 : return false;
1980 : }
1981 :
1982 11 : size_t first_size = rmp->smallest_size;
1983 11 : size_t first_count = rmp->smallest_elem_count;
1984 :
1985 11 : size_t expected_size = 0;
1986 11 : for (size_t esize = first_size, ecount = first_count, index = 0;
1987 59 : index < rmp->number_of_mempools; esize *= 2, ecount /= 2, ++index) {
1988 98 : if (mp_stride_for(esize) == 0) {
1989 0 : if (err) {
1990 0 : *err = CCOL__ERR_STR(
1991 : "requested configuration's buffer size overflows size_t");
1992 : }
1993 0 : return false;
1994 : }
1995 49 : size_t elem_extended_size = mp_stride_for(esize);
1996 49 : if (!cmempool__align_up_fits(ecount)) {
1997 0 : if (err) {
1998 0 : *err = CCOL__ERR_STR(
1999 : "requested configuration's buffer size overflows size_t");
2000 : }
2001 0 : return false;
2002 : }
2003 49 : size_t status_bytes = cmempool__align_up(ecount);
2004 49 : if (ecount != 0 &&
2005 49 : elem_extended_size > (SIZE_MAX - status_bytes) / ecount) {
2006 1 : if (err) {
2007 1 : *err = CCOL__ERR_STR(
2008 : "requested configuration's buffer size overflows size_t");
2009 : }
2010 1 : return false;
2011 : }
2012 48 : size_t term = ecount * elem_extended_size + status_bytes;
2013 48 : if (expected_size > SIZE_MAX - term) {
2014 0 : if (err) {
2015 0 : *err = CCOL__ERR_STR(
2016 : "requested configuration's buffer size overflows size_t");
2017 : }
2018 0 : return false;
2019 : }
2020 48 : expected_size += term;
2021 : }
2022 10 : if (expected_size != preallocated_buffer_size) {
2023 2 : if (err) {
2024 2 : *err = CCOL__ERR_STR("buffer sizes differ");
2025 : }
2026 2 : return false;
2027 : }
2028 :
2029 8 : rmp->mem_pools = (cmempool **)ccol__mem_calloc(
2030 : rmp->m_procs, rmp->number_of_mempools, sizeof(cmempool *));
2031 8 : if (!rmp->mem_pools) {
2032 0 : if (err) {
2033 0 : *err = CCOL__ERR_STR("failed to allocate mem_pools array");
2034 : }
2035 0 : return false;
2036 : }
2037 :
2038 : size_t cumulative_size = 0;
2039 :
2040 : for (size_t esize = first_size, ecount = first_count, index = 0;
2041 52 : index < rmp->number_of_mempools; esize *= 2, ecount /= 2, ++index) {
2042 44 : uint8_t *sub_buffer = (uint8_t *)preallocated_buffer + cumulative_size;
2043 44 : size_t sub_buffer_size =
2044 44 : ecount * mp_stride_for(esize) + cmempool__align_up(ecount);
2045 88 : rmp->mem_pools[index] = cmempool_create_from_preallocated_buffer_mp(
2046 : sub_buffer, sub_buffer_size, esize,
2047 44 : rmp->fb_policy == crmempool_fallback_at_first_exhaustion,
2048 44 : !rmp->should_use_locks, rmp->m_procs, err);
2049 44 : if (!rmp->mem_pools[index]) {
2050 : return false;
2051 : }
2052 44 : cumulative_size += sub_buffer_size;
2053 : }
2054 :
2055 : return true;
2056 : }
2057 :
2058 : // Creates a ranged pool on the caller's buffer, which it never frees, for code
2059 : // that avoids the heap. The alignment is checked once up front, so a bad
2060 : // buffer gets one clear error instead of a failure deep inside a tier. Gives
2061 : // the pool, or NULL with *err set.
2062 15 : crmempool *crmempool_create_from_preallocated_buffer_mp(
2063 : void *buffer, size_t buf_size, uint8_t smallest_size_power_of_two,
2064 : uint8_t largest_size_power_of_two, uint8_t smallest_elem_count_power_of_two,
2065 : crmempool_fallback_policy fb_policy, bool single_threaded,
2066 : ccol_memmgmt_procs *mmgmt_procs, char **err) {
2067 15 : if (err) {
2068 8 : *err = NULL;
2069 : }
2070 :
2071 15 : if (!buffer) {
2072 1 : if (err) {
2073 1 : *err = CCOL__ERR_STR("buffer is NULL");
2074 : }
2075 1 : return NULL;
2076 : }
2077 :
2078 14 : if ((uintptr_t)buffer % cmempool__entry_align != 0) {
2079 1 : if (err) {
2080 1 : *err = CCOL__ERR_STR("buffer must be aligned to at least 16 bytes");
2081 : }
2082 1 : return NULL;
2083 : }
2084 :
2085 13 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err)) {
2086 1 : return NULL;
2087 : }
2088 :
2089 12 : crmempool *rmp =
2090 12 : (crmempool *)ccol__mem_calloc(mmgmt_procs, 1, sizeof(crmempool));
2091 12 : if (!rmp) {
2092 0 : if (err) {
2093 0 : *err = CCOL__ERR_STR("failed to allocate crmempool struct");
2094 : }
2095 0 : return NULL;
2096 : }
2097 :
2098 12 : if (!ccol__populate_mem_mgmt_procs(rmp, mmgmt_procs, err)) {
2099 0 : ccol__mem_free(mmgmt_procs, rmp);
2100 0 : return NULL;
2101 : }
2102 :
2103 12 : if (!assess_r_mempool_create_inputs(
2104 : rmp, smallest_size_power_of_two, largest_size_power_of_two,
2105 : smallest_elem_count_power_of_two, fb_policy, single_threaded, err)) {
2106 1 : crmempool_destroy(rmp);
2107 1 : return NULL;
2108 : }
2109 11 : rmp->fb_policy = fb_policy;
2110 :
2111 11 : if (!init_preallocated_r_mempool_internal_pools(rmp, buffer, buf_size, err)) {
2112 3 : crmempool_destroy(rmp);
2113 3 : return NULL;
2114 : }
2115 :
2116 : return rmp;
2117 : }
2118 :
2119 : // Allocates a shared fallback entry of exactly elem_size bytes through the
2120 : // pseudo pool mp, once every tier is empty under
2121 : // crmempool_fallback_at_last_exhaustion. Takes mp's lock when it has one.
2122 : // The size isn't raised to sizeof(mp_addr): The entry is never on a free list,
2123 : // and the exact recorded size keeps the same-size shortcut of
2124 : // crmempool_realloc_entry() working. Gives NULL when the prefix would overflow
2125 : // or the allocator refuses.
2126 28 : static void *cmempool_pseudo_alloc_entry(cmempool *mp, size_t elem_size) {
2127 28 : void *result = NULL;
2128 :
2129 28 : if (elem_size > SIZE_MAX - DYNAMIC_ENTRY_PREFIX_SIZE) {
2130 : return NULL;
2131 : }
2132 :
2133 28 : if (mp->should_use_locks) {
2134 20 : ccol__mutex_lock(mp->lock);
2135 : }
2136 :
2137 28 : result = mempool_alloc_dynamic_locked(mp, elem_size);
2138 :
2139 28 : if (mp->should_use_locks) {
2140 20 : ccol__mutex_unlock(mp->lock);
2141 : }
2142 :
2143 : return result;
2144 : }
2145 :
2146 : // Allocates at least size bytes from rmp: From the smallest tier that fits,
2147 : // then from larger tiers, and last from the shared fallback under
2148 : // crmempool_fallback_at_last_exhaustion. Gives NULL for an invalid size or when
2149 : // nothing serves it. Asserts on a NULL rmp.
2150 32430 : void *crmempool_alloc_entry(crmempool *rmp, size_t size) {
2151 32430 : if (!rmp) {
2152 0 : ccol__assert(false);
2153 : }
2154 :
2155 32430 : if (size == 0 || size > rmp->largest_size) {
2156 : return NULL;
2157 : }
2158 :
2159 32426 : size_t pool_index = crmempool_pool_index_for_size(rmp, size);
2160 :
2161 : void *result = NULL;
2162 :
2163 33031 : for (; pool_index < rmp->number_of_mempools; ++pool_index) {
2164 32992 : result = cmempool_alloc_entry(rmp->mem_pools[pool_index]);
2165 32975 : if (result) {
2166 : break;
2167 : }
2168 : }
2169 :
2170 32409 : if (!result && rmp->fb_policy == crmempool_fallback_at_last_exhaustion) {
2171 28 : result = cmempool_pseudo_alloc_entry(&rmp->pseudo_pool, size);
2172 : }
2173 :
2174 : return result;
2175 : }
2176 :
2177 : // Allocates at least size bytes and zeroes the first size of them, for
2178 : // callers that need zeroed memory.
2179 1145 : void *crmempool_calloc_entry(crmempool *rmp, size_t size) {
2180 1145 : void *result = crmempool_alloc_entry(rmp, size);
2181 :
2182 1145 : if (result) {
2183 1142 : memset(result, 0, size);
2184 : }
2185 :
2186 1145 : return result;
2187 : }
2188 :
2189 : // Gives the bytes an entry of mp holds: The whole stride for a pool entry,
2190 : // the recorded size for a dynamic one. Realloc needs it to know how much to
2191 : // copy.
2192 7205 : static inline size_t entry_user_size(cmempool *mp, void *entry) {
2193 14055 : if (valid_mempool_addr(mp, (uintptr_t)entry)) {
2194 : return mp->extended_elem_size;
2195 : }
2196 355 : return DYNAMIC_ENTRY_USER_SIZE(entry);
2197 : }
2198 :
2199 : // Tells whether any tier or the pseudo pool of rmp holds a live dynamic entry,
2200 : // so the owner lookup can call an address outside every tier foreign without
2201 : // reading through it. It reads the atomic counts (acquire) without the tiers'
2202 : // locks.
2203 694 : static bool rmp_holds_dynamic_entries(crmempool *rmp) {
2204 694 : if (atomic_load_explicit(&rmp->pseudo_pool.active_dynamic_memory_buffer_count,
2205 : memory_order_acquire) > 0) {
2206 : return true;
2207 : }
2208 2039 : for (size_t i = 0; i < rmp->number_of_mempools; ++i) {
2209 2036 : if (rmp->mem_pools[i] &&
2210 2036 : atomic_load_explicit(
2211 : &rmp->mem_pools[i]->active_dynamic_memory_buffer_count,
2212 : memory_order_acquire) > 0) {
2213 : return true;
2214 : }
2215 : }
2216 : return false;
2217 : }
2218 :
2219 : // Gives the pool of rmp whose registry holds c_entry as a live dynamic entry,
2220 : // or NULL; realloc uses it to resolve an entry. Each registry is read under its
2221 : // own lock, one pool at a time. The answer can go stale after the unlock, so a
2222 : // free asks again under the lock.
2223 691 : static cmempool *rmp_dynamic_owner_of(crmempool *rmp, uintptr_t c_entry) {
2224 2081 : for (size_t i = 0; i <= rmp->number_of_mempools; ++i) {
2225 4158 : cmempool *mp =
2226 2079 : i < rmp->number_of_mempools ? rmp->mem_pools[i] : &rmp->pseudo_pool;
2227 2079 : if (!mp || !mp->fallback_to_dynamic_memory ||
2228 2042 : atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
2229 : memory_order_acquire) == 0) {
2230 1388 : continue;
2231 : }
2232 691 : if (mp->should_use_locks) ccol__mutex_lock(mp->lock);
2233 691 : bool found = mp_dynamic_set_contains_locked(mp, c_entry);
2234 691 : if (mp->should_use_locks) ccol__mutex_unlock(mp->lock);
2235 691 : if (found) return mp;
2236 : }
2237 : return NULL;
2238 : }
2239 :
2240 : // Frees entry when one of rmp's pools holds it as a live dynamic entry; the
2241 : // ranged free uses it for an address outside every tier. Each candidate is
2242 : // locked once and the free happens in that critical section. Gives false,
2243 : // having read nothing through entry, when no pool holds it.
2244 392 : static __attribute__((noinline)) bool rmp_free_dynamic(crmempool *rmp,
2245 : void *entry) {
2246 1176 : for (size_t i = 0; i <= rmp->number_of_mempools; ++i) {
2247 2346 : cmempool *mp =
2248 1173 : i < rmp->number_of_mempools ? rmp->mem_pools[i] : &rmp->pseudo_pool;
2249 1173 : if (!mp || !mp->fallback_to_dynamic_memory ||
2250 1108 : atomic_load_explicit(&mp->active_dynamic_memory_buffer_count,
2251 : memory_order_acquire) == 0) {
2252 781 : continue;
2253 : }
2254 392 : if (mp->should_use_locks) ccol__mutex_lock(mp->lock);
2255 393 : bool freed = mempool_free_dynamic_locked(mp, entry);
2256 392 : if (mp->should_use_locks) ccol__mutex_unlock(mp->lock);
2257 391 : if (freed) return true;
2258 : }
2259 : return false;
2260 : }
2261 :
2262 : // Gives the pool of rmp that owns entry, or NULL, and sets *is_dynamic to say
2263 : // whether it's a dynamic entry; realloc needs both. A tier is found from the
2264 : // address alone; an address outside every tier is looked up in the registries,
2265 : // and only when rmp holds dynamic entries at all.
2266 14419 : static cmempool *rmp_owner_of(crmempool *rmp, void *entry, bool *is_dynamic) {
2267 14419 : *is_dynamic = false;
2268 29436 : for (size_t i = 0; i < rmp->number_of_mempools; ++i) {
2269 28742 : cmempool *sub = rmp->mem_pools[i];
2270 51028 : if (sub && valid_mempool_addr(sub, (uintptr_t)entry)) return sub;
2271 : }
2272 :
2273 694 : if (!rmp_holds_dynamic_entries(rmp)) return NULL;
2274 :
2275 691 : cmempool *owner = rmp_dynamic_owner_of(rmp, (uintptr_t)entry);
2276 691 : if (!owner) return NULL;
2277 689 : *is_dynamic = true;
2278 689 : return owner;
2279 : }
2280 :
2281 : #ifdef RUNNING_UNIT_TESTS
2282 : // Test hook: Overwrites the status byte of entry in the tier that owns it, the
2283 : // ranged form of cmempool__corrupt_entry_status_for_tests().
2284 1 : void crmempool__corrupt_entry_status_for_tests(crmempool *rmp, void *entry,
2285 : unsigned char value) {
2286 1 : if (!rmp || !entry) return;
2287 1 : for (size_t i = 0; i < rmp->number_of_mempools; ++i) {
2288 1 : cmempool *sub = rmp->mem_pools[i];
2289 2 : if (sub && valid_mempool_addr(sub, (uintptr_t)entry)) {
2290 1 : MP_ENTRY_STATUS(sub, MP_ENTRY_INDEX(sub, (uintptr_t)entry)) = value;
2291 1 : return;
2292 : }
2293 : }
2294 : }
2295 : #endif
2296 :
2297 : // Frees entry back to rmp, the body of crmempool_free_entry(): To the tier
2298 : // that owns it, or as a live dynamic entry of one of rmp's pools. NULL does
2299 : // nothing; a NULL rmp or a foreign address asserts.
2300 24619 : void crmempool__free_entry(crmempool *rmp, void *entry) {
2301 24619 : if (!entry) {
2302 : return;
2303 : }
2304 :
2305 24619 : if (!rmp) {
2306 0 : ccol__assert(false);
2307 : }
2308 :
2309 47216 : for (size_t i = 0; i < rmp->number_of_mempools; ++i) {
2310 46824 : cmempool *sub = rmp->mem_pools[i];
2311 88442 : if (sub && valid_mempool_addr(sub, (uintptr_t)entry)) {
2312 24227 : cmempool_free_entry_body(sub, entry);
2313 24227 : return;
2314 : }
2315 : }
2316 :
2317 392 : if (!rmp_free_dynamic(rmp, entry)) {
2318 3 : ccol__assert(false);
2319 : }
2320 : }
2321 :
2322 : // Resizes addr to at least size bytes (NULL allocates). Ownership and status
2323 : // are checked first, so the no-move answer never returns a free or foreign
2324 : // entry. When the entry already holds what the tier for size gives, or exactly
2325 : // size bytes, it comes back unmoved. Otherwise a new entry gets the smaller of
2326 : // the two real sizes (read from both entries, never from the ideal tier) and
2327 : // the old one is freed. When the allocation fails but size fits in what addr
2328 : // holds, addr comes back unmoved, as realloc(3) does. An invalid size or a
2329 : // failure gives NULL and leaves addr alone.
2330 7231 : void *crmempool_realloc_entry(crmempool *rmp, void *addr, size_t size) {
2331 7231 : if (!rmp) {
2332 0 : ccol__assert(false);
2333 : }
2334 :
2335 7231 : if (size == 0 || size > rmp->largest_size) {
2336 : return NULL;
2337 : }
2338 :
2339 7227 : cmempool *owner = NULL;
2340 7227 : bool owner_is_dynamic = false;
2341 7227 : size_t held = 0;
2342 :
2343 7227 : if (addr) {
2344 7225 : owner = rmp_owner_of(rmp, addr, &owner_is_dynamic);
2345 7223 : if (!owner) {
2346 5 : ccol__assert(false);
2347 : }
2348 7218 : if (!owner_is_dynamic &&
2349 6884 : MP_ENTRY_STATUS(owner, MP_ENTRY_INDEX(owner, (uintptr_t)addr)) !=
2350 : mp_status_taken) {
2351 2 : ccol__assert(false);
2352 : }
2353 :
2354 14432 : held = owner_is_dynamic ? DYNAMIC_ENTRY_USER_SIZE(addr)
2355 7216 : : owner->extended_elem_size;
2356 :
2357 14432 : size_t new_ext_size =
2358 7216 : rmp->mem_pools[crmempool_pool_index_for_size(rmp, size)]
2359 : ->extended_elem_size;
2360 :
2361 7216 : if (held == new_ext_size || held == size) {
2362 : return addr;
2363 : }
2364 : }
2365 :
2366 7212 : void *new_entry = crmempool_alloc_entry(rmp, size);
2367 7206 : if (!new_entry && addr && size <= held) {
2368 : return addr;
2369 : }
2370 7203 : if (new_entry && addr) {
2371 7200 : bool new_is_dynamic = false;
2372 7200 : cmempool *new_owner = rmp_owner_of(rmp, new_entry, &new_is_dynamic);
2373 7205 : size_t old_user_size = held;
2374 14410 : size_t new_user_size =
2375 7205 : new_owner ? entry_user_size(new_owner, new_entry) : 0;
2376 7205 : size_t copy_size =
2377 : old_user_size < new_user_size ? old_user_size : new_user_size;
2378 :
2379 7205 : memcpy(new_entry, addr, copy_size);
2380 7205 : cmempool_free_entry(owner, addr);
2381 : }
2382 :
2383 : return new_entry;
2384 : }
2385 :
2386 : // Gives the used count of the tier that serves size, or 0 for an invalid
2387 : // size.
2388 212 : size_t crmempool_used_count(crmempool *rmp, size_t size) {
2389 212 : if (!rmp) {
2390 0 : ccol__assert(false);
2391 : }
2392 :
2393 212 : if (size == 0 || size > rmp->largest_size) {
2394 : return 0;
2395 : }
2396 :
2397 420 : return cmempool_used_count(
2398 344 : rmp->mem_pools[crmempool_pool_index_for_size(rmp, size)]);
2399 : }
2400 :
2401 : // Gives the bytes of mp's entry block, every slot's stride and status byte
2402 : // with the reserve included, read under the lock. It's what a pool costs,
2403 : // which cmempool_total_capacity() deliberately doesn't report.
2404 7 : size_t cmempool_allocated_bytes(cmempool *mp) {
2405 7 : if (!mp) {
2406 0 : ccol__assert(false);
2407 : }
2408 :
2409 7 : size_t result = 0;
2410 :
2411 7 : if (mp->should_use_locks) {
2412 6 : ccol__mutex_lock(mp->lock);
2413 : }
2414 :
2415 7 : result = mp->total_elem_count * mp->extended_elem_size + mp->total_elem_count;
2416 :
2417 7 : if (mp->should_use_locks) {
2418 6 : ccol__mutex_unlock(mp->lock);
2419 : }
2420 :
2421 7 : return result;
2422 : }
2423 :
2424 : // Gives the sum of every tier's entry block, what a ranged pool costs; the
2425 : // pseudo pool has no block.
2426 1 : size_t crmempool_allocated_bytes(crmempool *rmp) {
2427 1 : if (!rmp) {
2428 0 : ccol__assert(false);
2429 : }
2430 :
2431 : size_t result = 0;
2432 6 : for (size_t i = 0; i < rmp->number_of_mempools; ++i) {
2433 5 : if (rmp->mem_pools[i]) {
2434 5 : result += cmempool_allocated_bytes(rmp->mem_pools[i]);
2435 : }
2436 : }
2437 1 : return result;
2438 : }
2439 :
2440 : // Gives the capacity of the tier that serves size, or 0 for an invalid
2441 : // size.
2442 1090 : size_t crmempool_total_capacity(crmempool *rmp, size_t size) {
2443 1090 : if (!rmp) {
2444 0 : ccol__assert(false);
2445 : }
2446 :
2447 1090 : if (size == 0 || size > rmp->largest_size) {
2448 : return 0;
2449 : }
2450 :
2451 2176 : return cmempool_total_capacity(
2452 2141 : rmp->mem_pools[crmempool_pool_index_for_size(rmp, size)]);
2453 : }
2454 :
2455 : // Gives the live fallback entries for size: The tier's count under
2456 : // crmempool_fallback_at_first_exhaustion, the pseudo pool's count under
2457 : // crmempool_fallback_at_last_exhaustion, and 0 when the fallback is off or the
2458 : // size is invalid.
2459 163 : size_t crmempool_dynamic_allocs_count(crmempool *rmp, size_t size) {
2460 163 : if (!rmp) {
2461 0 : ccol__assert(false);
2462 : }
2463 :
2464 163 : if (size == 0 || size > rmp->largest_size) {
2465 : return 0;
2466 : }
2467 :
2468 161 : if (rmp->fb_policy == crmempool_fallback_disabled) {
2469 : return 0;
2470 : }
2471 :
2472 155 : if (rmp->fb_policy == crmempool_fallback_at_first_exhaustion) {
2473 102 : return cmempool_dynamic_allocs_count(
2474 80 : rmp->mem_pools[crmempool_pool_index_for_size(rmp, size)]);
2475 : }
2476 :
2477 104 : return cmempool_dynamic_allocs_count(&rmp->pseudo_pool);
2478 : }
|