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 : #include <chashmap.h>
26 : #include <clrucache.h>
27 : #include <cthreadcomm.h>
28 : #include <cvector.h>
29 : #include <internal/chashkey.h>
30 : #include <internal/cpintable.h>
31 : #include <internal/test_helpers/chashmap.h>
32 : #include <internal/test_helpers/clrucache.h>
33 : #include <stdatomic.h>
34 : #include <string.h>
35 : #ifdef RUNNING_UNIT_TESTS
36 : #include <unistd.h>
37 : #endif
38 :
39 : // One entry of a segment. It sits in the segment's map (key -> entry pointer)
40 : // and, while it has a value, in the segment's LRU list. A placeholder has no
41 : // value and isn't in the list (a fetch or set is in flight), a live entry has a
42 : // value and can be evicted (also while a remote setter runs for it: Eviction
43 : // turns it back into a placeholder that the set fills or removes), and a dead
44 : // entry has left the map and the list (evicted) and lives only while waiters
45 : // hold it.
46 : //
47 : // The segment's mutex guards every field, and cond shares it. Remote getters
48 : // and setters run outside the mutex, so a thread that unlocks while it holds an
49 : // entry pointer increments waiters first and decrements it after locking again;
50 : // whoever brings waiters of a dead entry to 0 frees it. fetch_failed and
51 : // fetch_size_mismatch are set only right before a failed fetch tears the entry
52 : // down, so a waiter that wakes to no value reports the same result as the
53 : // fetching thread.
54 : typedef struct ccache_entry {
55 : void *key;
56 : size_t key_size;
57 :
58 : void *value;
59 : size_t value_size;
60 :
61 : ccol__cond_var cond;
62 :
63 : bool fetch_in_progress;
64 : bool set_in_progress;
65 : bool evicted;
66 :
67 : bool fetch_size_mismatch;
68 :
69 : int waiters;
70 :
71 : struct ccache_entry *prev;
72 : struct ccache_entry *next;
73 : bool in_lru;
74 :
75 : bool fetch_failed;
76 : } ccache_entry;
77 :
78 : // One slot of the handle table. A ccache is (slot index << 32) | generation;
79 : // the generation goes up on every reuse, so a stale handle never names a later
80 : // cache and clrucache__destroy can report a double destroy. ptr is NULL while
81 : // the slot is free.
82 : typedef struct {
83 : struct clrucache *ptr;
84 : uint32_t generation;
85 : bool in_use;
86 : } clrucache_slot;
87 :
88 : // The handle table. Only create, destroy and test helpers take its rwlock; a
89 : // get or set resolves through the lock-free pin table. slots only grows;
90 : // free_indices is a LIFO of released indices. lost_indices counts released
91 : // slots whose index couldn't go back on the free list, which an acquire then
92 : // finds by a scan. release_deferred is set when the exit destructor finds a
93 : // cache still live, so the destroy that frees the last slot frees the table.
94 : // Those two fields are used only under the write lock. The module registers no
95 : // fork handlers, so the table has no fork-time state.
96 : static struct {
97 : ccol__rw_lock rwlock;
98 : ccol__once_flag once;
99 : cvec slots;
100 : cvec free_indices;
101 : size_t lost_indices;
102 : bool release_deferred;
103 : } clrucache_slot_table = {0};
104 :
105 : static bool clrucache_any_slot_live_locked(void);
106 : static void clrucache_release_slot_table_locked(void);
107 : static void clrucache_release_slot_table_if_deferred_locked(void);
108 :
109 : // Creates the handle table; the once of the table runs it on first use, from a
110 : // create, a destroy or a test helper.
111 1 : static void clrucache_slot_table_init_globals(void) {
112 1 : if (ccol__rw_lock_init(clrucache_slot_table.rwlock) != 0)
113 0 : ccol__fatal_err("ccache slot table: failed to initialize rwlock");
114 1 : clrucache_slot_table.slots = cvector_create(sizeof(clrucache_slot), NULL);
115 1 : if (!clrucache_slot_table.slots)
116 0 : ccol__fatal_err("ccache slot table: failed to allocate slots vector");
117 1 : clrucache_slot_table.free_indices = cvector_create(sizeof(uint32_t), NULL);
118 1 : if (!clrucache_slot_table.free_indices)
119 0 : ccol__fatal_err("ccache slot table: failed to allocate free-index vector");
120 1 : }
121 :
122 : // One segment of a cache, with its own map (key -> entry pointer), LRU list and
123 : // lock, so operations on keys of different segments run in parallel. The
124 : // sentinels lru_head (newest end) and lru_tail (oldest end) live in the struct.
125 : // capacity is the segment's share and size counts its live entries. Each
126 : // segment keeps its own copy of the callbacks; the allocator is borrowed from
127 : // the router, which owns the one copy of the caller's procs.
128 : typedef struct ccache_shard {
129 : chmap map;
130 :
131 : ccache_entry lru_head;
132 : ccache_entry lru_tail;
133 :
134 : size_t capacity;
135 : size_t size;
136 :
137 : ccol__mutex mutex;
138 :
139 : ccache_remote_getter_fn remote_getter;
140 : ccache_remote_setter_fn remote_setter;
141 : ccache_eviction_fn eviction_cb;
142 :
143 : ccol_memmgmt_procs *m_procs;
144 : } ccache_shard;
145 :
146 : // The cache itself: The router that picks a segment for each key. key_type and
147 : // key_fixed_width keep the segment choice in agreement with the maps about
148 : // which keys are equal, and let a wrongly sized hand-built key be refused
149 : // before it's read. capacity is the sum of the segment capacities. self_handle
150 : // is written once before the publish. m_procs points at m_procs_copy when the
151 : // caller gave an allocator, so the caller's struct may go away after the
152 : // create; the copy comes last, after every field a lookup reads.
153 : struct clrucache {
154 : ccache_shard **shards;
155 : size_t shard_count;
156 :
157 : ccol_data_type key_type;
158 : size_t key_fixed_width;
159 :
160 : size_t capacity;
161 :
162 : ccol_memmgmt_procs *m_procs;
163 :
164 : ccache self_handle;
165 :
166 : ccol_memmgmt_procs m_procs_copy;
167 : };
168 :
169 : // The hot half of the handle table: Handle to pointer, plus the pin that keeps
170 : // a cache alive during a call. A resolve writes nothing that another thread
171 : // reads, so cache operations from many threads don't contend on it.
172 : static ccol_pintable clrucache_pintable;
173 :
174 : // Resolves h to its cache and pins it, so a concurrent destroy waits until the
175 : // caller is done with it. Every public call on a cache starts here. Gives NULL
176 : // for 0, garbage, a free slot or a reused one. On success the caller must call
177 : // clrucache_resolve_unpin() exactly once. It takes no lock and makes no shared
178 : // write.
179 42041 : static struct clrucache *clrucache_resolve(ccache h) {
180 42041 : return (struct clrucache *)ccol_pintable_pin(&clrucache_pintable, h);
181 : }
182 :
183 : // Drops the pin that clrucache_resolve took, when a public call is done with
184 : // the cache. It touches nothing else: The cache can be freed right after, so
185 : // nothing may read raw once the pin is gone.
186 42036 : static void clrucache_resolve_unpin(struct clrucache *raw) {
187 5 : ccol_pintable_unpin(&clrucache_pintable, raw->self_handle);
188 10701 : }
189 :
190 : #ifdef RUNNING_UNIT_TESTS
191 : // Test only: Makes the next free list push fail like an allocation.
192 : static _Atomic bool g_ccache_fail_next_free_index_push = false;
193 :
194 : // Arms g_ccache_fail_next_free_index_push, so a test reaches the recovery of a
195 : // lost slot index.
196 4 : void clrucache__force_next_free_index_push_failure_for_tests(void) {
197 4 : atomic_store(&g_ccache_fail_next_free_index_push, true);
198 4 : }
199 : #endif
200 :
201 : // Puts idx back on the free list for the next create to reuse; the destroy and
202 : // a failed acquire call it with the write lock held. A failed push is counted
203 : // in lost_indices instead of stranding the slot for good.
204 308 : static void clrucache_free_index_release_locked(uint32_t idx) {
205 : #ifdef RUNNING_UNIT_TESTS
206 308 : if (atomic_exchange(&g_ccache_fail_next_free_index_push, false)) {
207 4 : clrucache_slot_table.lost_indices++;
208 4 : return;
209 : }
210 : #endif
211 304 : if (cvector_push_back(clrucache_slot_table.free_indices, &idx) !=
212 : ccol_success)
213 0 : clrucache_slot_table.lost_indices++;
214 : }
215 :
216 : // Finds a released slot that no free list entry names (ptr NULL and not in_use)
217 : // and puts its index in *out_idx, so a slot lost to a failed push gets reused
218 : // instead of the table growing. The acquire calls it with the write lock held
219 : // after finding the free list empty, which makes that state mean lost rather
220 : // than free; a destroy in progress still has ptr set. A scan that finds nothing
221 : // clears lost_indices.
222 4 : static __attribute__((noinline)) bool clrucache_reclaim_lost_index_locked(
223 : uint32_t *out_idx) {
224 4 : size_t slot_count = cvector_size(clrucache_slot_table.slots);
225 5 : for (size_t i = 0; i < slot_count; i++) {
226 5 : clrucache_slot *slot =
227 5 : (clrucache_slot *)cvector_at(clrucache_slot_table.slots, i);
228 5 : if (slot->ptr == NULL && !slot->in_use) {
229 4 : *out_idx = (uint32_t)i;
230 4 : clrucache_slot_table.lost_indices--;
231 4 : return true;
232 : }
233 : }
234 0 : clrucache_slot_table.lost_indices = 0;
235 0 : return false;
236 : }
237 :
238 : // Gives cache a slot (a free one, a lost one or a new one), publishes it in the
239 : // pin table and gives the handle; it's the last step of clrucache_create_full.
240 : // Gives 0 when the table is full or can't grow, and also when the module
241 : // destructor already released the table, which *released reports. Generation 0
242 : // is skipped because handle 0 is CCACHE_NULL. self_handle is written before the
243 : // publish so a resolver finds it, and cleared again when the publish fails and
244 : // the slot goes back. Takes the write lock.
245 309 : static ccache clrucache_handle_slot_acquire(struct clrucache *cache,
246 : bool *released) {
247 309 : ccol__call_once(clrucache_slot_table.once, clrucache_slot_table_init_globals);
248 309 : ccol__rw_lock_wrlock(clrucache_slot_table.rwlock);
249 309 : *released = clrucache_slot_table.slots == NULL;
250 309 : if (__builtin_expect(*released, 0)) {
251 1 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
252 1 : return 0;
253 : }
254 308 : uint32_t idx;
255 308 : clrucache_slot *slot;
256 308 : if (cvector_size(clrucache_slot_table.free_indices) > 0) {
257 302 : cvector_pop_back(clrucache_slot_table.free_indices, &idx);
258 302 : slot = (clrucache_slot *)cvector_at(clrucache_slot_table.slots, idx);
259 10 : } else if (clrucache_slot_table.lost_indices > 0 &&
260 4 : clrucache_reclaim_lost_index_locked(&idx)) {
261 4 : slot = (clrucache_slot *)cvector_at(clrucache_slot_table.slots, idx);
262 : } else {
263 2 : if (cvector_size(clrucache_slot_table.slots) >= CCOL_PIN_MAX_SLOTS) {
264 0 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
265 0 : return 0;
266 : }
267 2 : clrucache_slot fresh = {0};
268 2 : if (cvector_push_back(clrucache_slot_table.slots, &fresh) != ccol_success) {
269 0 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
270 0 : return 0;
271 : }
272 2 : idx = (uint32_t)cvector_size(clrucache_slot_table.slots) - 1;
273 2 : slot = (clrucache_slot *)cvector_at(clrucache_slot_table.slots, idx);
274 : }
275 308 : slot->generation++;
276 308 : if (slot->generation == 0) slot->generation++;
277 308 : ccache h = ((ccache)idx << 32) | (ccache)slot->generation;
278 :
279 308 : cache->self_handle = h;
280 :
281 308 : if (!ccol_pintable_publish(&clrucache_pintable, idx, slot->generation,
282 : cache)) {
283 8 : cache->self_handle = 0;
284 8 : clrucache_free_index_release_locked(idx);
285 8 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
286 8 : return 0;
287 : }
288 :
289 300 : slot->ptr = cache;
290 300 : slot->in_use = true;
291 300 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
292 300 : return h;
293 : }
294 :
295 : // Links e in as the newest entry of the segment, when it gets a value or is
296 : // used.
297 41591 : static void lru_add_to_front(ccache_shard *cache, ccache_entry *e) {
298 41591 : e->next = cache->lru_head.next;
299 41591 : e->prev = &cache->lru_head;
300 41591 : cache->lru_head.next->prev = e;
301 41591 : cache->lru_head.next = e;
302 41591 : e->in_lru = true;
303 : }
304 :
305 : // Unlinks e from the LRU list, when it's evicted or turned back into a
306 : // placeholder; no-op when it isn't in the list.
307 41591 : static void lru_remove(ccache_entry *e) {
308 41591 : if (!e->in_lru) return;
309 41591 : e->prev->next = e->next;
310 41591 : e->next->prev = e->prev;
311 41591 : e->prev = NULL;
312 41591 : e->next = NULL;
313 40800 : e->in_lru = false;
314 : }
315 :
316 : // Makes e the newest entry of the segment, which a get or set does to the key
317 : // it uses.
318 11304 : static void lru_move_to_front(ccache_shard *cache, ccache_entry *e) {
319 21817 : lru_remove(e);
320 11304 : lru_add_to_front(cache, e);
321 11304 : }
322 :
323 : // Allocates a zeroed entry with an initialized condition variable, or gives
324 : // NULL. A failed init frees the block directly, since entry_free would destroy
325 : // a condition variable that was never initialized.
326 30313 : static ccache_entry *entry_alloc(ccache_shard *cache) {
327 60626 : ccache_entry *e =
328 30313 : (ccache_entry *)ccol__mem_calloc(cache->m_procs, 1, sizeof(ccache_entry));
329 30313 : if (!e) return NULL;
330 30312 : if (ccol__cond_var_init(e->cond) != 0) {
331 0 : ccol__mem_free(cache->m_procs, e);
332 0 : return NULL;
333 : }
334 : return e;
335 : }
336 :
337 : // Frees an entry with its key, value and condition variable, when nobody can
338 : // reach it any more: It was never published, or it is evicted and has no
339 : // waiters. The segment's mutex isn't needed for either case.
340 30312 : static void entry_free(ccache_shard *cache, ccache_entry *e) {
341 30312 : ccol__mem_free(cache->m_procs, e->key);
342 30312 : ccol__mem_free(cache->m_procs, e->value);
343 30312 : ccol__cond_var_destroy(e->cond);
344 30312 : ccol__mem_free(cache->m_procs, e);
345 30312 : }
346 :
347 : // Evicts the oldest live entry of the segment to make room, after calling the
348 : // eviction callback with its key and value; the caller holds the mutex. Gives
349 : // false when the list is empty. The victim is the real oldest entry even when a
350 : // remote setter runs for it, since that set hasn't taken effect yet; such an
351 : // entry stays in the map as a placeholder for the set to fill or remove.
352 : // Otherwise the entry leaves the map, its waiters are woken, and it's freed
353 : // when none hold it.
354 30873 : static bool evict_lru(ccache_shard *cache) {
355 30873 : ccache_entry *victim = cache->lru_tail.prev;
356 30873 : if (victim == &cache->lru_head) return false;
357 :
358 30287 : if (cache->eviction_cb && victim->value) {
359 56 : cmap_pair kp = {.ptr = victim->key, .size = victim->key_size};
360 56 : cmap_pair vp = {.ptr = victim->value, .size = victim->value_size};
361 56 : cache->eviction_cb(&kp, &vp);
362 : }
363 :
364 30287 : lru_remove(victim);
365 30287 : cache->size--;
366 :
367 30287 : if (victim->set_in_progress) {
368 4 : ccol__mem_free(cache->m_procs, victim->value);
369 4 : victim->value = NULL;
370 4 : victim->value_size = 0;
371 4 : return true;
372 : }
373 :
374 30283 : cmap_pair kp = {.ptr = victim->key, .size = victim->key_size};
375 30283 : chashmap_remove_elem(cache->map, &kp);
376 :
377 30283 : victim->evicted = true;
378 30283 : ccol__cond_var_broadcast(victim->cond);
379 :
380 30283 : if (victim->waiters == 0) {
381 30267 : entry_free(cache, victim);
382 : }
383 : return true;
384 : }
385 :
386 : // Evicts until the segment has room for one more live entry; every entry that
387 : // size counts is in the LRU list, so the loop always gets there. The caller
388 : // holds the mutex.
389 3 : static void make_room(ccache_shard *cache) {
390 36636 : while (cache->size >= cache->capacity) {
391 6349 : if (!evict_lru(cache)) break;
392 : }
393 3 : }
394 :
395 : // Gives the entry stored for key_pair in the segment's map, or NULL; the caller
396 : // holds the mutex. The pointer is read with memcpy, as in the other modules
397 : // that store pointers in a chmap.
398 41868 : static ccache_entry *map_lookup(ccache_shard *cache,
399 : const cmap_pair *key_pair) {
400 41868 : cmap_pair found;
401 5 : ccol_retval r = chashmap_get_elem_ref(cache->map, key_pair, &found);
402 41868 : if (r != ccol_success) return NULL;
403 11437 : ccache_entry *e;
404 11437 : memcpy(&e, found.ptr, sizeof(e));
405 0 : return e;
406 : }
407 :
408 : // Stores entry under key_pair in the segment's map (insert or replace); the
409 : // caller holds the mutex. Gives the map's result.
410 30311 : static ccol_retval map_upsert(ccache_shard *cache, const cmap_pair *key_pair,
411 : ccache_entry *entry) {
412 30311 : cmap_pair vp = {.ptr = &entry, .size = sizeof(entry)};
413 3 : return chashmap_insert_elem(cache->map, key_pair, &vp);
414 : }
415 :
416 : // The most segments a cache gets. More segments mean less contention but a
417 : // coarser eviction order, and no realistic thread count needs more.
418 : #define CCACHE_MAX_SHARDS 16u
419 :
420 : // The size a segment must have before a cache is split. Keys spread unevenly,
421 : // so a full split cache evicts from its fuller segments early; with segments of
422 : // this size that loss stays at a few percent, and smaller caches keep one exact
423 : // eviction order.
424 : #define CCACHE_MIN_ENTRIES_PER_SHARD 64u
425 :
426 : // Gives the number of segments for a cache of capacity entries, at least 1 and
427 : // at most CCACHE_MAX_SHARDS; the create sizes the cache with it.
428 329 : static size_t shard_count_for(size_t capacity) {
429 329 : size_t n = capacity / CCACHE_MIN_ENTRIES_PER_SHARD;
430 329 : if (n > CCACHE_MAX_SHARDS) n = CCACHE_MAX_SHARDS;
431 325 : if (n == 0) n = 1;
432 329 : return n;
433 : }
434 :
435 : // Reduces a key hash h to a segment index below shard_count. The modulo reads
436 : // only low bits, and the map's hash is meant to be read from its top bits, so a
437 : // key set with constant low bits (aligned pointers, scaled IDs) would all land
438 : // on one segment. A 64-bit avalanche first makes every bit depend on every
439 : // input bit.
440 40338 : static inline size_t ccache_reduce(uint64_t h, size_t shard_count) {
441 40338 : h ^= h >> 33;
442 40338 : h *= 0xff51afd7ed558ccdULL;
443 40338 : h ^= h >> 33;
444 40338 : h *= 0xc4ceb9fe1a85ec53ULL;
445 40338 : h ^= h >> 33;
446 40338 : return (size_t)(h % (uint64_t)shard_count);
447 : }
448 :
449 : // Gives the segment that key_pair belongs to. It hashes through the map's own
450 : // key hash, so keys the map treats as equal (-0.0 and 0.0, a long double by
451 : // value) always land on the same segment and no padding byte is read. Gives
452 : // NULL when the size of a fixed-width key is wrong, before anything reads the
453 : // key, so a malformed key gives ccol_invalid_args whatever the segment count.
454 41869 : static ccache_shard *shard_for(struct clrucache *router,
455 : const cmap_pair *key_pair) {
456 41869 : if (router->key_fixed_width != 0 &&
457 41125 : key_pair->size != router->key_fixed_width) {
458 : return NULL;
459 : }
460 41863 : if (router->shard_count == 1) return router->shards[0];
461 40338 : uint64_t h =
462 40338 : ccol_chmap_hash_key(key_pair->ptr, key_pair->size, router->key_type);
463 40338 : return router->shards[ccache_reduce(h, router->shard_count)];
464 : }
465 :
466 : // Frees the router and its segment array; the free function is read from the
467 : // router's own procs copy before the router goes away. The last step of a
468 : // destroy or a failed create.
469 329 : static void router_free_self(struct clrucache *router) {
470 329 : ccol_memmgmt_procs *mp = router->m_procs;
471 329 : if (router->shards) ccol__mem_free(mp, router->shards);
472 329 : if (mp) {
473 91 : ccol_free f = mp->free;
474 91 : f(router);
475 : } else {
476 238 : free(router);
477 : }
478 329 : }
479 :
480 : // Builds one segment with its share of the capacity: Its map, its LRU ring and
481 : // its mutex, plus copies of the callbacks; mprocs is the router's procs, which
482 : // the segment borrows. Gives NULL with *err set on failure. A failed mutex init
483 : // is checked, since a lock on it would be undefined.
484 603 : static ccache_shard *shard_create(size_t capacity, ccol_data_type key_type,
485 : ccache_remote_getter_fn getter,
486 : ccache_remote_setter_fn setter,
487 : ccache_eviction_fn eviction_cb,
488 : ccol_memmgmt_procs *mprocs, char **err) {
489 603 : ccache_shard *cache =
490 603 : (ccache_shard *)ccol__mem_calloc(mprocs, 1, sizeof(*cache));
491 603 : if (!cache) {
492 6 : if (err) *err = CCOL__ERR_STR("failed to allocate cache segment");
493 6 : return NULL;
494 : }
495 597 : cache->m_procs = mprocs;
496 :
497 597 : char *map_err = NULL;
498 1194 : cache->map =
499 597 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, key_type,
500 : ccol_pointer, cache->m_procs, NULL, NULL, &map_err);
501 597 : if (!cache->map) {
502 11 : if (err)
503 6 : *err = map_err ? map_err : CCOL__ERR_STR("failed to create internal map");
504 11 : ccol__mem_free(mprocs, cache);
505 11 : return NULL;
506 : }
507 :
508 586 : cache->lru_head.next = &cache->lru_tail;
509 586 : cache->lru_head.prev = NULL;
510 586 : cache->lru_tail.prev = &cache->lru_head;
511 586 : cache->lru_tail.next = NULL;
512 :
513 586 : if (ccol__mutex_init(cache->mutex) != 0) {
514 0 : if (err) *err = CCOL__ERR_STR("failed to initialize cache mutex");
515 0 : chashmap__destroy(cache->map);
516 0 : ccol__mem_free(mprocs, cache);
517 0 : return NULL;
518 : }
519 :
520 586 : cache->capacity = capacity;
521 586 : cache->remote_getter = getter;
522 586 : cache->remote_setter = setter;
523 586 : cache->eviction_cb = eviction_cb;
524 586 : return cache;
525 : }
526 :
527 : // Evicts everything a segment holds, through the eviction callback and under
528 : // its lock as on every other path, and frees the segment. No set can be in
529 : // flight here, since the destroy waited for every pin first.
530 621 : static void shard_destroy(ccache_shard *cache) {
531 621 : if (!cache) return;
532 586 : ccol__mutex_lock(cache->mutex);
533 25110 : while (evict_lru(cache)) {
534 24524 : }
535 586 : ccol__mutex_unlock(cache->mutex);
536 :
537 586 : chashmap__destroy(cache->map);
538 586 : ccol__mutex_destroy(cache->mutex);
539 586 : ccol__mem_free(cache->m_procs, cache);
540 : }
541 :
542 : // Destroys every segment of the router, for a destroy or a failed create.
543 326 : static void router_destroy_shards(struct clrucache *router) {
544 326 : if (!router->shards) return;
545 947 : for (size_t i = 0; i < router->shard_count; i++) {
546 621 : shard_destroy(router->shards[i]);
547 621 : router->shards[i] = NULL;
548 : }
549 : }
550 :
551 : // Creates a cache of capacity entries split into shard_count_for(capacity)
552 : // segments, and gives its handle or CCACHE_NULL with *err set. The segment
553 : // capacities add up to exactly capacity (the first capacity % shard_count
554 : // segments get one more). The procs are copied into the router. The slot is
555 : // acquired last, once everything else is built; the module starts no threads,
556 : // so a failure there only frees what was built. val_type is unused, since the
557 : // maps store pointers.
558 335 : ccache clrucache_create_full(size_t capacity, ccol_data_type key_type,
559 : ccol_data_type val_type,
560 : ccache_remote_getter_fn getter,
561 : ccache_remote_setter_fn setter,
562 : ccache_eviction_fn eviction_cb,
563 : ccol_memmgmt_procs *mprocs, char **err) {
564 335 : (void)val_type;
565 :
566 335 : if (capacity == 0) {
567 2 : if (err) *err = CCOL__ERR_STR("capacity must be > 0");
568 2 : return CCACHE_NULL;
569 : }
570 :
571 333 : if (!ccol__verify_memmgmt_procs(mprocs, err)) return CCACHE_NULL;
572 :
573 332 : struct clrucache *router =
574 94 : (struct clrucache *)(mprocs ? mprocs->calloc(1, sizeof(*router))
575 238 : : calloc(1, sizeof(*router)));
576 332 : if (!router) {
577 3 : if (err) *err = CCOL__ERR_STR("failed to allocate cache struct");
578 3 : return CCACHE_NULL;
579 : }
580 :
581 329 : if (mprocs) {
582 91 : memcpy(&router->m_procs_copy, mprocs, sizeof(router->m_procs_copy));
583 91 : router->m_procs = &router->m_procs_copy;
584 : }
585 :
586 329 : router->capacity = capacity;
587 329 : router->key_type = key_type;
588 329 : router->key_fixed_width = ccol_fixed_width_data_type_size(key_type);
589 329 : router->shard_count = shard_count_for(capacity);
590 329 : router->shards = (ccache_shard **)ccol__mem_calloc(
591 : router->m_procs, router->shard_count, sizeof(*router->shards));
592 329 : if (!router->shards) {
593 3 : if (err) *err = CCOL__ERR_STR("failed to allocate cache segments");
594 3 : router_free_self(router);
595 3 : return CCACHE_NULL;
596 : }
597 :
598 326 : size_t base = capacity / router->shard_count;
599 326 : size_t extra = capacity % router->shard_count;
600 912 : for (size_t i = 0; i < router->shard_count; i++) {
601 603 : size_t cap_i = base + (i < extra ? 1 : 0);
602 603 : router->shards[i] = shard_create(cap_i, key_type, getter, setter,
603 : eviction_cb, router->m_procs, err);
604 603 : if (!router->shards[i]) {
605 17 : router_destroy_shards(router);
606 17 : router_free_self(router);
607 17 : return CCACHE_NULL;
608 : }
609 : }
610 :
611 309 : bool table_released = false;
612 309 : ccache h = clrucache_handle_slot_acquire(router, &table_released);
613 309 : if (h == 0) {
614 9 : if (err)
615 9 : *err = table_released
616 9 : ? CCOL__ERR_STR(
617 : "the ccache handle table is released at the end of "
618 : "the process")
619 9 : : CCOL__ERR_STR("failed to allocate ccache handle slot");
620 9 : router_destroy_shards(router);
621 9 : router_free_self(router);
622 9 : return CCACHE_NULL;
623 : }
624 :
625 : return h;
626 : }
627 :
628 : // Destroys the cache behind a live handle and releases its slot; CCACHE_NULL is
629 : // a no-op and a stale handle is fatal. It looks the handle up and retires it in
630 : // one write lock section, so a second destroy fails the lookup. Then it waits
631 : // for the pins to drain before any teardown: No blocked caller here depends on
632 : // the destroy to wake it (they wait for remote calls of other threads). It
633 : // evicts every entry through the callback, frees the segments and the router,
634 : // and releases the slot last, fetched again by index because a concurrent
635 : // create can move the slots vector, with its generation raised. The destroy
636 : // that frees the last slot also does a release the exit destructor deferred.
637 303 : void clrucache__destroy(ccache cache) {
638 303 : if (!cache) return;
639 :
640 302 : ccol__call_once(clrucache_slot_table.once, clrucache_slot_table_init_globals);
641 302 : uint32_t idx = (uint32_t)(cache >> 32);
642 302 : uint32_t gen = (uint32_t)(cache & 0xFFFFFFFFu);
643 302 : ccol__rw_lock_wrlock(clrucache_slot_table.rwlock);
644 302 : clrucache_slot *slot = NULL;
645 302 : struct clrucache *raw = NULL;
646 604 : if (clrucache_slot_table.slots != NULL &&
647 302 : idx < cvector_size(clrucache_slot_table.slots)) {
648 302 : clrucache_slot *s =
649 302 : (clrucache_slot *)cvector_at(clrucache_slot_table.slots, idx);
650 302 : if (s->in_use && s->generation == gen) {
651 300 : slot = s;
652 300 : raw = s->ptr;
653 : }
654 : }
655 300 : if (!raw) {
656 2 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
657 2 : ccol__fatal_err(
658 : "clrucache_destroy: handle is stale or already destroyed "
659 : "(double-destroy / use-after-destroy of a ccache handle)");
660 : }
661 300 : slot->in_use = false;
662 300 : ccol_pintable_retire(&clrucache_pintable, idx);
663 300 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
664 :
665 : {
666 300 : long delay_ns = 1000;
667 689 : while (ccol_pintable_pins(&clrucache_pintable, idx) > 0) {
668 389 : struct timespec ts = {.tv_sec = 0, .tv_nsec = delay_ns};
669 389 : nanosleep(&ts, NULL);
670 389 : if (delay_ns < 1000000L) delay_ns *= 2;
671 : }
672 : }
673 :
674 300 : router_destroy_shards(raw);
675 300 : router_free_self(raw);
676 :
677 300 : ccol__rw_lock_wrlock(clrucache_slot_table.rwlock);
678 300 : clrucache_slot *slot2 =
679 300 : (clrucache_slot *)cvector_at(clrucache_slot_table.slots, idx);
680 300 : slot2->ptr = NULL;
681 300 : slot2->generation++;
682 300 : clrucache_free_index_release_locked(idx);
683 300 : clrucache_release_slot_table_if_deferred_locked();
684 300 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
685 : }
686 :
687 : #ifdef RUNNING_UNIT_TESTS
688 : // Gives the cache behind h, looked up under the read lock with no pin, so a
689 : // test has no unpin to forget.
690 1 : struct clrucache *clrucache__resolve_for_tests(ccache h) {
691 1 : ccol__call_once(clrucache_slot_table.once, clrucache_slot_table_init_globals);
692 1 : if (h == 0) return NULL;
693 1 : uint32_t idx = (uint32_t)(h >> 32);
694 1 : uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
695 1 : ccol__rw_lock_rdlock(clrucache_slot_table.rwlock);
696 1 : struct clrucache *raw = NULL;
697 2 : if (clrucache_slot_table.slots != NULL &&
698 1 : idx < cvector_size(clrucache_slot_table.slots)) {
699 1 : clrucache_slot *slot =
700 1 : (clrucache_slot *)cvector_at(clrucache_slot_table.slots, idx);
701 1 : if (slot->in_use && slot->generation == gen) raw = slot->ptr;
702 : }
703 1 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
704 1 : return raw;
705 : }
706 :
707 : // Gives the sum of the segment capacities and the segment count, so a test can
708 : // pin how a capacity is split; nothing public shows the remainder.
709 4 : size_t clrucache__segment_capacity_sum_for_tests(ccache cache,
710 : size_t *out_segments) {
711 4 : struct clrucache *raw = clrucache_resolve(cache);
712 4 : if (!raw) {
713 0 : if (out_segments) *out_segments = 0;
714 0 : return 0;
715 : }
716 : size_t total = 0;
717 40 : for (size_t i = 0; i < raw->shard_count; i++)
718 36 : total += raw->shards[i]->capacity;
719 4 : if (out_segments) *out_segments = raw->shard_count;
720 4 : clrucache_resolve_unpin(raw);
721 4 : return total;
722 : }
723 :
724 : // Counts the segments whose map hashes in the keyed mode, each read under its
725 : // mutex, so a test can see a flood switch the maps.
726 2 : size_t clrucache__keyed_segment_maps_for_tests(ccache cache,
727 : size_t *out_segments) {
728 2 : struct clrucache *raw = clrucache_resolve(cache);
729 2 : if (!raw) {
730 0 : if (out_segments) *out_segments = 0;
731 0 : return 0;
732 : }
733 : size_t keyed = 0;
734 34 : for (size_t i = 0; i < raw->shard_count; i++) {
735 32 : ccol__mutex_lock(raw->shards[i]->mutex);
736 32 : if (chashmap_is_keyed_for_tests(raw->shards[i]->map)) keyed++;
737 32 : ccol__mutex_unlock(raw->shards[i]->mutex);
738 : }
739 2 : if (out_segments) *out_segments = raw->shard_count;
740 2 : clrucache_resolve_unpin(raw);
741 2 : return keyed;
742 : }
743 :
744 : // Gives the number of indices on the free list, so a test can see that no slot
745 : // is lost.
746 2 : size_t clrucache__free_index_count_for_tests(void) {
747 2 : ccol__call_once(clrucache_slot_table.once, clrucache_slot_table_init_globals);
748 2 : ccol__rw_lock_rdlock(clrucache_slot_table.rwlock);
749 4 : size_t n = clrucache_slot_table.free_indices
750 2 : ? cvector_size(clrucache_slot_table.free_indices)
751 2 : : 0;
752 2 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
753 2 : return n;
754 : }
755 :
756 : // Gives the waiter references of key_pair's entry (blocked threads and a thread
757 : // running a remote call), or -1 when the key is absent, so a test knows that a
758 : // getter really waits instead of guessing with a sleep.
759 86 : int clrucache__key_waiters_for_tests(ccache cache, const cmap_pair *key_pair) {
760 86 : struct clrucache *raw = clrucache_resolve(cache);
761 86 : if (!raw) return -1;
762 86 : int n = -1;
763 86 : ccache_shard *shard = shard_for(raw, key_pair);
764 86 : if (shard) {
765 86 : ccol__mutex_lock(shard->mutex);
766 86 : ccache_entry *entry = map_lookup(shard, key_pair);
767 86 : if (entry) n = entry->waiters;
768 86 : ccol__mutex_unlock(shard->mutex);
769 : }
770 86 : clrucache_resolve_unpin(raw);
771 86 : return n;
772 : }
773 :
774 : // Gives the number of slots in the table, free ones included, so a test can see
775 : // that a create and destroy loop reuses slots.
776 6 : size_t clrucache__slot_table_capacity_for_tests(void) {
777 6 : ccol__call_once(clrucache_slot_table.once, clrucache_slot_table_init_globals);
778 6 : ccol__rw_lock_rdlock(clrucache_slot_table.rwlock);
779 12 : size_t n =
780 6 : clrucache_slot_table.slots ? cvector_size(clrucache_slot_table.slots) : 0;
781 6 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
782 6 : return n;
783 : }
784 :
785 : // Test hook: A publisher of a fetched or set value holds its segment's mutex
786 : // this much longer before it wakes the waiters, so an unrelated thread (an
787 : // evictor) can queue for the mutex first and the test reaches the path where a
788 : // waiter survives a racing eviction. The flag tells that a publisher is in the
789 : // delay. The test resets the delay to 0 itself.
790 : static _Atomic unsigned int ccache_test_post_publish_delay_us = 0;
791 : static _Atomic bool ccache_test_post_publish_delay_entered_flag = false;
792 :
793 : // Sets the publish delay and clears the entered flag, for a test that races an
794 : // eviction against a waiter.
795 60 : void ccache_test_set_post_publish_delay_us(unsigned int delay_us) {
796 60 : atomic_store(&ccache_test_post_publish_delay_entered_flag, false);
797 60 : atomic_store(&ccache_test_post_publish_delay_us, delay_us);
798 60 : }
799 :
800 : // Tells whether a publisher is in its delay and so holds the mutex right now,
801 : // so the test's evictor can lock it at the earliest moment.
802 86 : bool ccache_test_post_publish_delay_entered(void) {
803 86 : return atomic_load(&ccache_test_post_publish_delay_entered_flag);
804 : }
805 :
806 : // Sleeps for the armed publish delay and sets the entered flag; publishers call
807 : // it with the segment's mutex held, right before they wake the waiters.
808 31093 : static void ccache_test_maybe_delay_post_publish(void) {
809 31093 : unsigned int us = atomic_load(&ccache_test_post_publish_delay_us);
810 31093 : if (!us) return;
811 60 : atomic_store(&ccache_test_post_publish_delay_entered_flag, true);
812 60 : usleep(us);
813 : }
814 : #endif
815 :
816 : // Tells whether any slot names a cache, so the table is never freed while a
817 : // cache or its destroy may still use it; the caller holds the write lock. It
818 : // reads ptr, not in_use: A destroy clears in_use first but still uses the table
819 : // until its last step.
820 2 : static bool clrucache_any_slot_live_locked(void) {
821 2 : size_t slot_count = cvector_size(clrucache_slot_table.slots);
822 6 : for (size_t i = 0; i < slot_count; i++) {
823 4 : clrucache_slot *slot =
824 4 : (clrucache_slot *)cvector_at(clrucache_slot_table.slots, i);
825 4 : if (slot->ptr != NULL) return true;
826 : }
827 : return false;
828 : }
829 :
830 : // Frees the table when the exit destructor deferred that and no slot is live
831 : // any more; the caller holds the write lock. Out of line so the destroy path
832 : // keeps its shape.
833 : static __attribute__((noinline)) void
834 300 : clrucache_release_slot_table_if_deferred_locked(void) {
835 300 : if (clrucache_slot_table.release_deferred &&
836 0 : !clrucache_any_slot_live_locked()) {
837 0 : clrucache_release_slot_table_locked();
838 : }
839 300 : }
840 :
841 : // Frees the table vectors and the pin table; the caller holds the write lock
842 : // and found no live slot. Each vector becomes NULL, so a later call sees the
843 : // release. The rwlock isn't destroyed, since the caller holds it.
844 2 : static void clrucache_release_slot_table_locked(void) {
845 2 : cvector_destroy(clrucache_slot_table.slots);
846 2 : cvector_destroy(clrucache_slot_table.free_indices);
847 2 : ccol_pintable_dispose(&clrucache_pintable);
848 2 : clrucache_slot_table.release_deferred = false;
849 2 : }
850 :
851 : // Frees the table at process exit or unload so a leak checker doesn't report
852 : // it, or sets release_deferred when a cache is still live, so the destroy that
853 : // frees the last slot does it. The call_once is needed because a process may
854 : // never have created a cache. The static rwlock is never destroyed.
855 2 : __attribute__((destructor)) static void cleanup_ccache_slot_table(void) {
856 2 : ccol__call_once(clrucache_slot_table.once, clrucache_slot_table_init_globals);
857 2 : if (!clrucache_slot_table.slots) return;
858 2 : ccol__rw_lock_wrlock(clrucache_slot_table.rwlock);
859 2 : if (clrucache_any_slot_live_locked()) {
860 0 : clrucache_slot_table.release_deferred = true;
861 0 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
862 0 : return;
863 : }
864 2 : clrucache_release_slot_table_locked();
865 2 : ccol__rw_lock_unlock(clrucache_slot_table.rwlock);
866 : }
867 :
868 : static ccol_retval clrucache_get_full_retry(struct clrucache *raw,
869 : ccache_shard *shard,
870 : const cmap_pair *key_pair,
871 : cmap_pair *val_out);
872 :
873 : // The body of clrucache_get_full(), entered with the segment's mutex held;
874 : // every path that returns releases the mutex and the pin. On a miss it inserts
875 : // a placeholder, runs the remote getter outside the mutex with a waiter
876 : // reference held (so other getters of the key join this fetch) and stores the
877 : // value; a failed fetch removes the placeholder with fetch_failed set. On a hit
878 : // it waits for a fetch or set in flight. A waiter that finds a failed set looks
879 : // the key up again, since nobody asked the getter: With again == NULL (the hot
880 : // instantiation) through clrucache_get_full_retry, otherwise by setting *again.
881 : // A waiter that finds a value keeps it even when an eviction removed the entry
882 : // meanwhile; its waiter reference keeps the entry alive. Gives a heap copy in
883 : // *val_out.
884 : static inline __attribute__((always_inline)) ccol_retval
885 77 : clrucache_get_full_locked(struct clrucache *raw, ccache_shard *shard,
886 : const cmap_pair *key_pair, cmap_pair *val_out,
887 : bool *again) {
888 154 : ccache_entry *entry = map_lookup(shard, key_pair);
889 :
890 77 : if (!entry) {
891 18 : if (!shard->remote_getter) {
892 5 : ccol__mutex_unlock(shard->mutex);
893 5 : clrucache_resolve_unpin(raw);
894 5 : return ccol_key_not_found;
895 : }
896 :
897 13 : entry = entry_alloc(shard);
898 13 : if (!entry) {
899 0 : ccol__mutex_unlock(shard->mutex);
900 0 : clrucache_resolve_unpin(raw);
901 0 : return ccol_not_enough_memory;
902 : }
903 :
904 13 : entry->key = ccol__mem_alloc(shard->m_procs, key_pair->size);
905 13 : if (!entry->key) {
906 0 : ccol__mutex_unlock(shard->mutex);
907 0 : entry_free(shard, entry);
908 0 : clrucache_resolve_unpin(raw);
909 0 : return ccol_not_enough_memory;
910 : }
911 13 : memcpy(entry->key, key_pair->ptr, key_pair->size);
912 13 : entry->key_size = key_pair->size;
913 13 : entry->fetch_in_progress = true;
914 :
915 13 : ccol_retval ins = map_upsert(shard, key_pair, entry);
916 13 : if (ins != ccol_success && ins != ccol_key_already_present) {
917 0 : ccol__mutex_unlock(shard->mutex);
918 0 : entry_free(shard, entry);
919 0 : clrucache_resolve_unpin(raw);
920 0 : return ins;
921 : }
922 :
923 13 : entry->waiters++;
924 13 : ccol__mutex_unlock(shard->mutex);
925 :
926 13 : cmap_pair fetched = {};
927 13 : bool fetch_ok = shard->remote_getter(key_pair, &fetched);
928 :
929 13 : ccol__mutex_lock(shard->mutex);
930 13 : entry->waiters--;
931 13 : entry->fetch_in_progress = false;
932 :
933 13 : if (fetch_ok && fetched.ptr && fetched.size > 0) {
934 1 : make_room(shard);
935 5 : entry->value = fetched.ptr;
936 5 : entry->value_size = fetched.size;
937 5 : lru_add_to_front(shard, entry);
938 5 : shard->size++;
939 :
940 5 : void *copy = ccol__mem_alloc(shard->m_procs, fetched.size);
941 5 : if (!copy) {
942 0 : ccol__cond_var_broadcast(entry->cond);
943 0 : ccol__mutex_unlock(shard->mutex);
944 0 : clrucache_resolve_unpin(raw);
945 0 : return ccol_not_enough_memory;
946 : }
947 5 : memcpy(copy, fetched.ptr, fetched.size);
948 5 : val_out->ptr = copy;
949 5 : val_out->size = fetched.size;
950 :
951 : #ifdef RUNNING_UNIT_TESTS
952 5 : ccache_test_maybe_delay_post_publish();
953 : #endif
954 5 : ccol__cond_var_broadcast(entry->cond);
955 5 : ccol__mutex_unlock(shard->mutex);
956 5 : clrucache_resolve_unpin(raw);
957 5 : return ccol_success;
958 : } else {
959 8 : if (fetched.ptr) ccol__mem_free(shard->m_procs, fetched.ptr);
960 8 : cmap_pair kp = {.ptr = entry->key, .size = entry->key_size};
961 8 : chashmap_remove_elem(shard->map, &kp);
962 8 : entry->evicted = true;
963 8 : entry->fetch_failed = true;
964 8 : ccol__cond_var_broadcast(entry->cond);
965 8 : bool should_free = (entry->waiters == 0);
966 8 : ccol__mutex_unlock(shard->mutex);
967 8 : if (should_free) entry_free(shard, entry);
968 8 : clrucache_resolve_unpin(raw);
969 8 : return ccol_key_not_found;
970 : }
971 : }
972 :
973 59 : if (__builtin_expect(entry->fetch_in_progress || entry->set_in_progress, 0)) {
974 27 : entry->waiters++;
975 54 : while (entry->fetch_in_progress || entry->set_in_progress) {
976 27 : ccol__cond_var_wait(entry->cond, shard->mutex);
977 : }
978 27 : entry->waiters--;
979 :
980 27 : if (!entry->value) {
981 7 : if (!entry->fetch_failed) {
982 1 : if (entry->evicted && entry->waiters == 0) {
983 1 : ccol__mutex_unlock(shard->mutex);
984 1 : entry_free(shard, entry);
985 1 : ccol__mutex_lock(shard->mutex);
986 : }
987 1 : if (again) {
988 : *again = true;
989 : return ccol_success;
990 : }
991 1 : return clrucache_get_full_retry(raw, shard, key_pair, val_out);
992 : }
993 12 : ccol_retval fail_r = entry->fetch_size_mismatch ? ccol_unexpected_failure
994 6 : : ccol_key_not_found;
995 6 : bool should_free = (entry->evicted && entry->waiters == 0);
996 6 : ccol__mutex_unlock(shard->mutex);
997 6 : if (should_free) entry_free(shard, entry);
998 6 : clrucache_resolve_unpin(raw);
999 6 : return fail_r;
1000 : }
1001 : }
1002 :
1003 52 : ccol__assert(entry->value != NULL);
1004 52 : ccol__assert(entry->evicted || entry->in_lru);
1005 :
1006 52 : void *copy = ccol__mem_alloc(shard->m_procs, entry->value_size);
1007 52 : if (!copy) {
1008 1 : bool should_free = (entry->evicted && entry->waiters == 0);
1009 1 : ccol__mutex_unlock(shard->mutex);
1010 1 : if (should_free) entry_free(shard, entry);
1011 1 : clrucache_resolve_unpin(raw);
1012 1 : return ccol_not_enough_memory;
1013 : }
1014 95 : if (!entry->evicted) lru_move_to_front(shard, entry);
1015 51 : memcpy(copy, entry->value, entry->value_size);
1016 51 : val_out->ptr = copy;
1017 51 : val_out->size = entry->value_size;
1018 :
1019 51 : bool should_free = (entry->evicted && entry->waiters == 0);
1020 51 : ccol__mutex_unlock(shard->mutex);
1021 51 : if (should_free) entry_free(shard, entry);
1022 51 : clrucache_resolve_unpin(raw);
1023 51 : return ccol_success;
1024 : }
1025 :
1026 : // The cold instantiation of clrucache_get_full_locked(): Repeats the lookup as
1027 : // long as a waiter keeps finding a failed set. Keeping the loop here spares the
1028 : // hit path a register spill.
1029 : static __attribute__((noinline)) ccol_retval
1030 1 : clrucache_get_full_retry(struct clrucache *raw, ccache_shard *shard,
1031 : const cmap_pair *key_pair, cmap_pair *val_out) {
1032 1 : for (;;) {
1033 1 : bool retry = false;
1034 1 : ccol_retval r =
1035 1 : clrucache_get_full_locked(raw, shard, key_pair, val_out, &retry);
1036 1 : if (!retry) return r;
1037 : }
1038 : }
1039 :
1040 : // Looks key_pair up and gives a heap copy of its value; the raw get. It
1041 : // resolves the handle, checks the arguments, picks the key's segment (NULL
1042 : // means a wrongly sized fixed-width key) and runs clrucache_get_full_locked
1043 : // under that segment's mutex.
1044 83 : ccol_retval clrucache_get_full(ccache cache, const cmap_pair *key_pair,
1045 : cmap_pair *val_out) {
1046 83 : struct clrucache *raw = clrucache_resolve(cache);
1047 83 : if (!raw) return ccol_invalid_args;
1048 82 : if (!key_pair || !key_pair->ptr || !key_pair->size || !val_out) {
1049 4 : clrucache_resolve_unpin(raw);
1050 4 : return ccol_invalid_args;
1051 : }
1052 :
1053 78 : ccache_shard *shard = shard_for(raw, key_pair);
1054 78 : if (!shard) {
1055 2 : clrucache_resolve_unpin(raw);
1056 2 : return ccol_invalid_args;
1057 : }
1058 :
1059 76 : ccol__mutex_lock(shard->mutex);
1060 76 : return clrucache_get_full_locked(raw, shard, key_pair, val_out, NULL);
1061 : }
1062 :
1063 : // Allocates a placeholder entry for key_pair and inserts it into the segment's
1064 : // map, for a set of an absent key. Gives the entry, or NULL with the real
1065 : // failure code in *err_out. Called and returns with the mutex held; it unlocks
1066 : // only around its own entry_free calls, so the free doesn't block other
1067 : // callers.
1068 30249 : static ccache_entry *create_and_insert_placeholder(ccache_shard *cache,
1069 : const cmap_pair *key_pair,
1070 : ccol_retval *err_out) {
1071 30249 : ccache_entry *e = entry_alloc(cache);
1072 30249 : if (!e) {
1073 1 : *err_out = ccol_not_enough_memory;
1074 1 : return NULL;
1075 : }
1076 :
1077 30248 : e->key = ccol__mem_alloc(cache->m_procs, key_pair->size);
1078 30248 : if (!e->key) {
1079 1 : ccol__mutex_unlock(cache->mutex);
1080 1 : entry_free(cache, e);
1081 1 : ccol__mutex_lock(cache->mutex);
1082 1 : *err_out = ccol_not_enough_memory;
1083 1 : return NULL;
1084 : }
1085 30247 : memcpy(e->key, key_pair->ptr, key_pair->size);
1086 30247 : e->key_size = key_pair->size;
1087 :
1088 30247 : ccol_retval ins = map_upsert(cache, key_pair, e);
1089 30247 : if (ins != ccol_success && ins != ccol_key_already_present) {
1090 0 : ccol__mutex_unlock(cache->mutex);
1091 0 : entry_free(cache, e);
1092 0 : ccol__mutex_lock(cache->mutex);
1093 0 : *err_out = ins;
1094 0 : return NULL;
1095 : }
1096 : return e;
1097 : }
1098 :
1099 : // Installs a value copy that the set already allocated and makes the entry live
1100 : // and newest, evicting first when the entry is new to the list. It allocates
1101 : // nothing and can't fail, which is what lets a set never fail after its remote
1102 : // setter succeeded. Gives the old value, which the caller frees after
1103 : // unlocking. The caller holds the mutex.
1104 31033 : static void *entry_store_value(ccache_shard *cache, ccache_entry *entry,
1105 : void *new_val, size_t new_size) {
1106 31033 : void *old_val = entry->value;
1107 31033 : entry->value = new_val;
1108 31033 : entry->value_size = new_size;
1109 :
1110 31033 : if (!entry->in_lru) {
1111 : make_room(cache);
1112 30242 : lru_add_to_front(cache, entry);
1113 30242 : cache->size++;
1114 : } else {
1115 791 : lru_move_to_front(cache, entry);
1116 : }
1117 31033 : return old_val;
1118 : }
1119 :
1120 : // Stores val_pair under key_pair after the remote setter succeeded; the raw
1121 : // set. The value copy is made first, outside the mutex, so every allocation
1122 : // fails before any side effect. It loops until this thread owns the key's set
1123 : // slot, waiting on any fetch or set in flight, because several setters woken
1124 : // together must find each other's placeholder. Without a remote setter the
1125 : // update runs under the mutex in one go. With one, the setter runs outside the
1126 : // mutex with a waiter reference held while the key stays an ordinary entry; a
1127 : // failed setter frees the copy and removes a placeholder that an eviction left,
1128 : // a successful one installs the copy. Waiters are woken and freed memory is
1129 : // released after the unlock.
1130 31063 : ccol_retval clrucache_set_full(ccache cache, const cmap_pair *key_pair,
1131 : const cmap_pair *val_pair) {
1132 31063 : struct clrucache *raw = clrucache_resolve(cache);
1133 31063 : if (!raw) return ccol_invalid_args;
1134 31062 : if (!key_pair || !key_pair->ptr || !key_pair->size || !val_pair ||
1135 31057 : !val_pair->ptr || val_pair->size == 0) {
1136 8 : clrucache_resolve_unpin(raw);
1137 8 : return ccol_invalid_args;
1138 : }
1139 :
1140 31054 : ccache_shard *shard = shard_for(raw, key_pair);
1141 31054 : if (!shard) {
1142 2 : clrucache_resolve_unpin(raw);
1143 2 : return ccol_invalid_args;
1144 : }
1145 :
1146 31052 : void *new_val = ccol__mem_alloc(shard->m_procs, val_pair->size);
1147 31052 : if (!new_val) {
1148 2 : clrucache_resolve_unpin(raw);
1149 2 : return ccol_not_enough_memory;
1150 : }
1151 31050 : memcpy(new_val, val_pair->ptr, val_pair->size);
1152 :
1153 31050 : ccol__mutex_lock(shard->mutex);
1154 :
1155 31052 : ccache_entry *entry;
1156 :
1157 31052 : for (;;) {
1158 31052 : entry = map_lookup(shard, key_pair);
1159 31052 : if (!entry) {
1160 30249 : ccol_retval create_err = ccol_not_enough_memory;
1161 30249 : entry = create_and_insert_placeholder(shard, key_pair, &create_err);
1162 30249 : if (!entry) {
1163 2 : ccol__mutex_unlock(shard->mutex);
1164 2 : ccol__mem_free(shard->m_procs, new_val);
1165 2 : clrucache_resolve_unpin(raw);
1166 2 : return create_err;
1167 : }
1168 30247 : break;
1169 : }
1170 803 : if (!entry->fetch_in_progress && !entry->set_in_progress) {
1171 : break;
1172 : }
1173 7 : entry->waiters++;
1174 17 : while (entry->fetch_in_progress || entry->set_in_progress) {
1175 10 : ccol__cond_var_wait(entry->cond, shard->mutex);
1176 : }
1177 7 : entry->waiters--;
1178 7 : if (!entry->evicted) {
1179 : break;
1180 : }
1181 2 : bool should_free = (entry->waiters == 0);
1182 2 : if (should_free) {
1183 1 : ccol__mutex_unlock(shard->mutex);
1184 1 : entry_free(shard, entry);
1185 1 : ccol__mutex_lock(shard->mutex);
1186 : }
1187 : }
1188 :
1189 31048 : entry->set_in_progress = true;
1190 :
1191 31048 : bool remote_ok = true;
1192 :
1193 31048 : if (shard->remote_setter) {
1194 104 : entry->waiters++;
1195 104 : ccol__mutex_unlock(shard->mutex);
1196 :
1197 104 : remote_ok = shard->remote_setter(key_pair, val_pair);
1198 :
1199 104 : ccol__mutex_lock(shard->mutex);
1200 104 : entry->waiters--;
1201 : }
1202 :
1203 104 : ccol_retval retval = remote_ok ? ccol_success : ccol_unexpected_failure;
1204 :
1205 31033 : void *val_to_free;
1206 31033 : if (remote_ok) {
1207 31033 : val_to_free = entry_store_value(shard, entry, new_val, val_pair->size);
1208 : } else {
1209 : val_to_free = new_val;
1210 : }
1211 31048 : if (!remote_ok && !entry->in_lru) {
1212 9 : cmap_pair kp = {.ptr = entry->key, .size = entry->key_size};
1213 9 : chashmap_remove_elem(shard->map, &kp);
1214 9 : entry->evicted = true;
1215 : }
1216 :
1217 31048 : entry->set_in_progress = false;
1218 : #ifdef RUNNING_UNIT_TESTS
1219 31048 : ccache_test_maybe_delay_post_publish();
1220 : #endif
1221 31048 : ccol__cond_var_broadcast(entry->cond);
1222 :
1223 31048 : bool should_free = (entry->evicted && entry->waiters == 0);
1224 31048 : ccol__mutex_unlock(shard->mutex);
1225 31048 : if (val_to_free) ccol__mem_free(shard->m_procs, val_to_free);
1226 31048 : if (should_free) entry_free(shard, entry);
1227 :
1228 31048 : clrucache_resolve_unpin(raw);
1229 31048 : return retval;
1230 : }
1231 :
1232 : static ccol_retval clrucache_get_into_retry(struct clrucache *raw,
1233 : ccache_shard *shard,
1234 : const cmap_pair *key_pair,
1235 : void *buf, size_t buf_size);
1236 :
1237 : // The body of clrucache__get_into(), entered with the segment's mutex held;
1238 : // every path that returns releases the mutex and the pin. It follows
1239 : // clrucache_get_full_locked, but copies into buf. A fetched or stored value
1240 : // whose size isn't exactly buf_size gives ccol_unexpected_failure: A larger one
1241 : // would overflow buf and a smaller one leave part of it stale. A fetched value
1242 : // of the wrong size is a failed fetch (fetch_size_mismatch, nothing cached) so
1243 : // every waiter gets the same answer, and a stored one is refused before the
1244 : // entry moves in the eviction order.
1245 : static inline __attribute__((always_inline)) ccol_retval
1246 10653 : clrucache_get_into_locked(struct clrucache *raw, ccache_shard *shard,
1247 : const cmap_pair *key_pair, void *buf, size_t buf_size,
1248 : bool *again) {
1249 21306 : ccache_entry *entry = map_lookup(shard, key_pair);
1250 :
1251 10653 : if (!entry) {
1252 162 : if (!shard->remote_getter) {
1253 111 : ccol__mutex_unlock(shard->mutex);
1254 111 : clrucache_resolve_unpin(raw);
1255 111 : return ccol_key_not_found;
1256 : }
1257 :
1258 51 : entry = entry_alloc(shard);
1259 51 : if (!entry) {
1260 0 : ccol__mutex_unlock(shard->mutex);
1261 0 : clrucache_resolve_unpin(raw);
1262 0 : return ccol_not_enough_memory;
1263 : }
1264 :
1265 51 : entry->key = ccol__mem_alloc(shard->m_procs, key_pair->size);
1266 51 : if (!entry->key) {
1267 0 : ccol__mutex_unlock(shard->mutex);
1268 0 : entry_free(shard, entry);
1269 0 : clrucache_resolve_unpin(raw);
1270 0 : return ccol_not_enough_memory;
1271 : }
1272 51 : memcpy(entry->key, key_pair->ptr, key_pair->size);
1273 51 : entry->key_size = key_pair->size;
1274 51 : entry->fetch_in_progress = true;
1275 :
1276 51 : ccol_retval ins = map_upsert(shard, key_pair, entry);
1277 51 : if (ins != ccol_success && ins != ccol_key_already_present) {
1278 0 : ccol__mutex_unlock(shard->mutex);
1279 0 : entry_free(shard, entry);
1280 0 : clrucache_resolve_unpin(raw);
1281 0 : return ins;
1282 : }
1283 :
1284 51 : entry->waiters++;
1285 51 : ccol__mutex_unlock(shard->mutex);
1286 :
1287 51 : cmap_pair fetched = {};
1288 51 : bool fetch_ok = shard->remote_getter(key_pair, &fetched);
1289 :
1290 51 : ccol__mutex_lock(shard->mutex);
1291 51 : entry->waiters--;
1292 51 : entry->fetch_in_progress = false;
1293 :
1294 51 : if (fetch_ok && fetched.ptr && fetched.size > 0) {
1295 43 : if (fetched.size != buf_size) {
1296 3 : ccol__mem_free(shard->m_procs, fetched.ptr);
1297 3 : cmap_pair kp = {.ptr = entry->key, .size = entry->key_size};
1298 3 : chashmap_remove_elem(shard->map, &kp);
1299 3 : entry->evicted = true;
1300 3 : entry->fetch_size_mismatch = true;
1301 3 : entry->fetch_failed = true;
1302 3 : ccol__cond_var_broadcast(entry->cond);
1303 3 : bool should_free = (entry->waiters == 0);
1304 3 : ccol__mutex_unlock(shard->mutex);
1305 3 : if (should_free) entry_free(shard, entry);
1306 3 : clrucache_resolve_unpin(raw);
1307 3 : return ccol_unexpected_failure;
1308 : }
1309 :
1310 2 : make_room(shard);
1311 40 : entry->value = fetched.ptr;
1312 40 : entry->value_size = fetched.size;
1313 40 : lru_add_to_front(shard, entry);
1314 40 : shard->size++;
1315 :
1316 40 : memcpy(buf, fetched.ptr, fetched.size);
1317 :
1318 : #ifdef RUNNING_UNIT_TESTS
1319 40 : ccache_test_maybe_delay_post_publish();
1320 : #endif
1321 40 : ccol__cond_var_broadcast(entry->cond);
1322 40 : ccol__mutex_unlock(shard->mutex);
1323 40 : clrucache_resolve_unpin(raw);
1324 40 : return ccol_success;
1325 : } else {
1326 8 : if (fetched.ptr) ccol__mem_free(shard->m_procs, fetched.ptr);
1327 8 : cmap_pair kp = {.ptr = entry->key, .size = entry->key_size};
1328 8 : chashmap_remove_elem(shard->map, &kp);
1329 8 : entry->evicted = true;
1330 8 : entry->fetch_failed = true;
1331 8 : ccol__cond_var_broadcast(entry->cond);
1332 8 : bool should_free = (entry->waiters == 0);
1333 8 : ccol__mutex_unlock(shard->mutex);
1334 8 : if (should_free) entry_free(shard, entry);
1335 8 : clrucache_resolve_unpin(raw);
1336 8 : return ccol_key_not_found;
1337 : }
1338 : }
1339 :
1340 10491 : if (entry->fetch_in_progress || entry->set_in_progress) {
1341 41 : entry->waiters++;
1342 82 : while (entry->fetch_in_progress || entry->set_in_progress) {
1343 41 : ccol__cond_var_wait(entry->cond, shard->mutex);
1344 : }
1345 41 : entry->waiters--;
1346 :
1347 41 : if (!entry->value) {
1348 10 : if (!entry->fetch_failed) {
1349 4 : if (entry->evicted && entry->waiters == 0) {
1350 4 : ccol__mutex_unlock(shard->mutex);
1351 4 : entry_free(shard, entry);
1352 4 : ccol__mutex_lock(shard->mutex);
1353 : }
1354 4 : if (again) {
1355 : *again = true;
1356 : return ccol_success;
1357 : }
1358 4 : return clrucache_get_into_retry(raw, shard, key_pair, buf, buf_size);
1359 : }
1360 12 : ccol_retval fail_r = entry->fetch_size_mismatch ? ccol_unexpected_failure
1361 6 : : ccol_key_not_found;
1362 6 : bool should_free = (entry->evicted && entry->waiters == 0);
1363 6 : ccol__mutex_unlock(shard->mutex);
1364 6 : if (should_free) entry_free(shard, entry);
1365 6 : clrucache_resolve_unpin(raw);
1366 6 : return fail_r;
1367 : }
1368 : }
1369 :
1370 10481 : ccol__assert(entry->value != NULL);
1371 10481 : ccol__assert(entry->evicted || entry->in_lru);
1372 :
1373 10481 : if (entry->value_size != buf_size) {
1374 3 : bool should_free = (entry->evicted && entry->waiters == 0);
1375 3 : ccol__mutex_unlock(shard->mutex);
1376 3 : if (should_free) entry_free(shard, entry);
1377 3 : clrucache_resolve_unpin(raw);
1378 3 : return ccol_unexpected_failure;
1379 : }
1380 20947 : if (!entry->evicted) lru_move_to_front(shard, entry);
1381 10478 : memcpy(buf, entry->value, entry->value_size);
1382 :
1383 10478 : bool should_free = (entry->evicted && entry->waiters == 0);
1384 10478 : ccol__mutex_unlock(shard->mutex);
1385 10478 : if (should_free) entry_free(shard, entry);
1386 10478 : clrucache_resolve_unpin(raw);
1387 10478 : return ccol_success;
1388 : }
1389 :
1390 : // The cold instantiation of clrucache_get_into_locked(): Repeats the lookup as
1391 : // long as a waiter keeps finding a failed set.
1392 4 : static __attribute__((noinline)) ccol_retval clrucache_get_into_retry(
1393 : struct clrucache *raw, ccache_shard *shard, const cmap_pair *key_pair,
1394 : void *buf, size_t buf_size) {
1395 4 : for (;;) {
1396 4 : bool retry = false;
1397 4 : ccol_retval r =
1398 4 : clrucache_get_into_locked(raw, shard, key_pair, buf, buf_size, &retry);
1399 4 : if (!retry) return r;
1400 : }
1401 : }
1402 :
1403 : // Copies the value of key_pair into buf; the get behind ccache_get() for every
1404 : // value type but char *. It resolves the handle, checks the arguments, picks
1405 : // the key's segment and runs clrucache_get_into_locked under its mutex.
1406 10652 : ccol_retval clrucache__get_into(ccache cache, const cmap_pair *key_pair,
1407 : void *buf, size_t buf_size) {
1408 10652 : struct clrucache *raw = clrucache_resolve(cache);
1409 10652 : if (!raw) return ccol_invalid_args;
1410 10652 : if (!key_pair || !key_pair->ptr || !key_pair->size || !buf || buf_size == 0) {
1411 1 : clrucache_resolve_unpin(raw);
1412 1 : return ccol_invalid_args;
1413 : }
1414 :
1415 10651 : ccache_shard *shard = shard_for(raw, key_pair);
1416 10651 : if (!shard) {
1417 2 : clrucache_resolve_unpin(raw);
1418 2 : return ccol_invalid_args;
1419 : }
1420 :
1421 10649 : ccol__mutex_lock(shard->mutex);
1422 10649 : return clrucache_get_into_locked(raw, shard, key_pair, buf, buf_size, NULL);
1423 : }
1424 :
1425 : // Gives the number of live entries, for monitoring. It adds up the segment
1426 : // sizes, each under its own lock, so the total is a snapshot.
1427 111 : size_t clrucache_size(ccache cache) {
1428 111 : struct clrucache *raw = clrucache_resolve(cache);
1429 111 : if (!raw) return 0;
1430 : size_t total = 0;
1431 389 : for (size_t i = 0; i < raw->shard_count; i++) {
1432 280 : ccache_shard *sh = raw->shards[i];
1433 280 : ccol__mutex_lock(sh->mutex);
1434 280 : total += sh->size;
1435 280 : ccol__mutex_unlock(sh->mutex);
1436 : }
1437 109 : clrucache_resolve_unpin(raw);
1438 109 : return total;
1439 : }
1440 :
1441 : // Gives the capacity the cache was created with. It never changes after the
1442 : // create, so no lock is needed.
1443 40 : size_t clrucache_capacity(ccache cache) {
1444 40 : struct clrucache *raw = clrucache_resolve(cache);
1445 40 : if (!raw) return 0;
1446 39 : size_t c = raw->capacity;
1447 39 : clrucache_resolve_unpin(raw);
1448 39 : return c;
1449 : }
|