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 : #pragma once
26 :
27 : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
28 : #include <stdbool.h>
29 : #endif
30 : #include <string.h>
31 :
32 : #include "common.h"
33 :
34 : // Everything from here to the matching pop is the public ABI and the shared
35 : // library exports it. The library builds with -fvisibility=hidden, so anything
36 : // outside these blocks stays internal.
37 : #pragma GCC visibility push(default)
38 :
39 : // The remote getter type. It's called for a missing key when a remote source
40 : // exists. On success it allocates the value with the cache's allocator (the
41 : // custom procs or malloc), stores it in val and returns true; the cache owns
42 : // the value from then on. On failure it leaves val->ptr NULL and returns false.
43 : // No cache lock is held during the call, so it may use the cache for other
44 : // keys, but not for the key it serves and not to destroy the cache, which would
45 : // deadlock.
46 : typedef bool (*ccache_remote_getter_fn)(const cmap_pair *key, cmap_pair *val);
47 :
48 : // The remote setter type: Writes key and val to the remote source and returns
49 : // true on success. No cache lock is held during the call; the rules of the
50 : // getter about the same key and the destroy apply.
51 : typedef bool (*ccache_remote_setter_fn)(const cmap_pair *key,
52 : const cmap_pair *val);
53 :
54 : // The eviction callback type: Gets the key and value of an entry evicted to
55 : // make room. It runs with the owning segment's lock held, so it must not call
56 : // back into the cache, and evictions in two segments can run it at the same
57 : // time.
58 : typedef void (*ccache_eviction_fn)(const cmap_pair *key, const cmap_pair *val);
59 :
60 : // The opaque cache: A thread-safe least recently used cache with an optional
61 : // remote source. A hash map gives O(1) lookup and a linked list O(1) eviction.
62 : // From a capacity of 128 on, the cache is split into segments with their own
63 : // locks, each key belongs to one segment by its hash, and each segment evicts
64 : // its own least recently used entry; below 128 there is one segment and one
65 : // exact order.
66 : //
67 : // Getters of the same missing key join one remote fetch and all get its
68 : // result. A getter waits while a set of its key runs; when the set fails it
69 : // starts over as an ordinary miss. Setters of one key are serialized. The
70 : // remote setter always runs before the cache changes, and every allocation of a
71 : // set happens before it, so ccol_not_enough_memory or ccol_container_full means
72 : // the setter never ran. A failed set changes nothing (value and place in the
73 : // eviction order stay); after a successful setter the cache update can't fail.
74 : // While the setter runs the key stays an ordinary entry that an insert may
75 : // evict; a successful set then inserts it again as the newest entry.
76 : //
77 : // The eviction callback runs with its segment's lock held and must not call
78 : // back into the cache; two segments can run it at the same time. A key of a
79 : // type the cache doesn't know (a struct) is compared by all its bytes, padding
80 : // included: Zero such a key with memset() before using the raw functions.
81 : // ccache_get() and ccache_set() clear the padding of their own copy with GCC 11
82 : // or later; with other compilers use the raw functions for padded keys.
83 : typedef struct clrucache clrucache;
84 :
85 : // The handle is an opaque value (slot index plus generation), never a pointer.
86 : // Compare it with CCACHE_NULL, which is 0, so `if (!cache)` works. Every use
87 : // goes through the library's slot table, so a freed or reused slot is always
88 : // detected.
89 : typedef uint64_t ccache;
90 :
91 : // "No cache": The failure value of a create and what a destroy leaves in the
92 : // handle, so a handle can be tested for validity.
93 : #define CCACHE_NULL ((ccache)0)
94 :
95 : // Creates a thread-safe least recently used cache that holds up to capacity
96 : // live entries (0 is refused); a set into a full cache evicts the least
97 : // recently used entry. key_type and val_type describe the key and the value
98 : // (ccol_determine_ccol_data_type() gives them for a C type). getter fetches a
99 : // missing key from a remote source, setter writes each set to it before the
100 : // cache changes, and eviction_cb hears about every evicted entry; each may be
101 : // NULL. mprocs is your allocator table or NULL for the default; the cache
102 : // keeps a copy of the struct, but its functions must stay callable until the
103 : // destroy. Returns the handle, or CCACHE_NULL with *err set (also for a create
104 : // after the library's destructor released the handle table). Destroy it with
105 : // clrucache_destroy().
106 : //
107 : // From a capacity of 128 the capacity is divided across segments that evict on
108 : // their own, so a full cache holds a few percent less than capacity;
109 : // clrucache_capacity() reports capacity itself.
110 : ccache clrucache_create_full(size_t capacity, ccol_data_type key_type,
111 : ccol_data_type val_type,
112 : ccache_remote_getter_fn getter,
113 : ccache_remote_setter_fn setter,
114 : ccache_eviction_fn eviction_cb,
115 : ccol_memmgmt_procs *mprocs, char **err);
116 :
117 : // Internal: Destroys a cache. It's the body of ccache_destroy(); use the macro,
118 : // which also clears the handle. CCACHE_NULL is a no-op; any other handle that
119 : // isn't live (already destroyed, being destroyed, garbage) is a fatal error.
120 : // It waits for every call that resolved the handle, evicts the remaining
121 : // entries through the eviction callback and frees everything.
122 : void clrucache__destroy(ccache cache);
123 :
124 : // Internal: Copies the value of key_pair into buf without a heap allocation.
125 : // ccache_get() uses it for every value type other than char *, so a get
126 : // allocates nothing. buf_size must equal the stored size (ccache_get passes
127 : // sizeof(ValT)); any other size gives ccol_unexpected_failure and leaves buf
128 : // untouched.
129 : ccol_retval clrucache__get_into(ccache cache, const cmap_pair *key_pair,
130 : void *buf, size_t buf_size);
131 :
132 : // Looks key_pair up and gives a heap copy of its value in *val_out; you own
133 : // val_out->ptr and free it with the cache's allocator (free() for the
134 : // default). A hit makes the key the most recently used. It's the raw get, for
135 : // callers that don't use the typed macros. On a miss the remote getter runs
136 : // once and every other getter of that key waits for its result; a getter also
137 : // waits while a set of the key runs. A fixed-width key must have the width of
138 : // its type, or the call gives ccol_invalid_args without reading it. Returns
139 : // ccol_success, ccol_key_not_found (missing and no getter, or the getter
140 : // failed), ccol_invalid_args (also for CCACHE_NULL or a destroyed handle),
141 : // ccol_not_enough_memory, ccol_unexpected_failure (a joined fetch stored a
142 : // value of the wrong size) or ccol_container_full (the internal records are
143 : // full).
144 : ccol_retval clrucache_get_full(ccache cache, const cmap_pair *key_pair,
145 : cmap_pair *val_out);
146 :
147 : // Copies val_pair into the cache under key_pair, after the remote setter (if
148 : // any) succeeded; it's the raw set. The key becomes its segment's newest entry,
149 : // and a full cache evicts its least recently used entry to make room. A failed
150 : // setter gives ccol_unexpected_failure and changes nothing in the cache. Every
151 : // allocation happens before the setter runs, so ccol_not_enough_memory means
152 : // the setter never ran. Setters of one key are serialized, and a getter of the
153 : // key waits for the set. Returns ccol_success, ccol_invalid_args (also for
154 : // CCACHE_NULL, a destroyed handle or a value of size 0),
155 : // ccol_not_enough_memory, ccol_unexpected_failure or ccol_container_full.
156 : ccol_retval clrucache_set_full(ccache cache, const cmap_pair *key_pair,
157 : const cmap_pair *val_pair);
158 :
159 : // Internal: Destroys *cp and clears it. The _scoped macros attach it with
160 : // ccol__destructor; a CCACHE_NULL handle is a no-op, a stale one is fatal.
161 2 : static inline __attribute__((always_inline)) void clrucache__destroy_cleanup(
162 : ccache *cp) {
163 2 : if (cp && *cp) {
164 1 : clrucache__destroy(*cp);
165 2 : *cp = CCACHE_NULL;
166 : }
167 : }
168 :
169 : // Destroys a cache and sets the handle to CCACHE_NULL, so the variable can't be
170 : // used again by mistake. It waits for every call in flight on the handle,
171 : // passes each remaining entry to the eviction callback and frees everything.
172 : // CCACHE_NULL does nothing; a handle that was already destroyed, or a
173 : // concurrent second destroy, is a fatal error. name must be a modifiable
174 : // lvalue and is evaluated once.
175 : #define clrucache_destroy(name) \
176 : ccol__clrucache_destroy_impl( \
177 : name, ccol__uniq(ccol__clrucache_destroy_slot, __COUNTER__))
178 :
179 : // Internal: The body of clrucache_destroy(). slot comes from ccol__uniq(), so
180 : // destroy macros can nest without -Wshadow warnings.
181 : #define ccol__clrucache_destroy_impl(name, slot) \
182 : do { \
183 : __typeof__(name) *slot = &(name); \
184 : clrucache__destroy(*slot); \
185 : *slot = CCACHE_NULL; \
186 : } while (0)
187 :
188 : // Destroys a cache and sets the handle to CCACHE_NULL, so the variable can't be
189 : // used again by mistake. It waits for every call in flight on the handle,
190 : // passes each remaining entry to the eviction callback and frees everything.
191 : // CCACHE_NULL does nothing; a handle that was already destroyed, or a
192 : // concurrent second destroy, is a fatal error. name must be a modifiable
193 : // lvalue and is evaluated once.
194 : #define ccache_destroy(name) clrucache_destroy(name)
195 :
196 : // Declares a cache handle called name for key type KeyT and value type ValT,
197 : // without creating a cache; the handle is left uninitialized. Create the cache
198 : // with ccache_init() before any other ccache_* macro, and destroy it with
199 : // ccache_destroy(). An array key or value type is refused at compile time;
200 : // wrap it in a struct.
201 : #define ccache_declare(name, KeyT, ValT) \
202 : ccol__refuse_array_types("clru", KeyT, ValT); \
203 : __typeof__(KeyT) *name##__ccache_key_type_var __attribute__((unused)); \
204 : __typeof__(ValT) *name##__ccache_val_type_var __attribute__((unused)); \
205 : ccache name
206 :
207 : // Declares a cache handle called name for key type KeyT and value type ValT,
208 : // set to CCACHE_NULL, without creating a cache; create it with ccache_init().
209 : // The cache is destroyed by itself when name goes out of scope, so no exit
210 : // path can leak it; ccache_destroy() before that is allowed. An array key or
211 : // value type is refused at compile time; wrap it in a struct.
212 : #define ccache_declare_scoped(name, KeyT, ValT) \
213 : ccol__refuse_array_types("clru", KeyT, ValT); \
214 : __typeof__(KeyT) *name##__ccache_key_type_var __attribute__((unused)) = \
215 : NULL; \
216 : __typeof__(ValT) *name##__ccache_val_type_var __attribute__((unused)) = \
217 : NULL; \
218 : ccache name ccol__destructor(clrucache__destroy_cleanup) = CCACHE_NULL
219 :
220 : // Creates the cache for a handle that ccache_declare() or
221 : // ccache_declare_scoped() declared, with room for capacity entries (0 is
222 : // refused) and the default allocator; the key and value types come from that
223 : // declaration. getter fetches a missing key from a remote source, setter
224 : // writes each set to it first, and evict_cb hears about every evicted entry;
225 : // each may be NULL. Ends the program with a fatal error when the cache can't
226 : // be created.
227 : #define ccache_init(name, capacity, getter, setter, evict_cb) \
228 : do { \
229 : char *ccache__err = NULL; \
230 : (name) = clrucache_create_full( \
231 : (capacity), \
232 : ccol_determine_ccol_data_type(*name##__ccache_key_type_var), \
233 : ccol_determine_ccol_data_type(*name##__ccache_val_type_var), (getter), \
234 : (setter), (evict_cb), NULL, &ccache__err); \
235 : if (!(name)) { \
236 : ccol__fatal_err("ccache_init('%s'): %s", #name, \
237 : ccache__err ? ccache__err : "unknown error"); \
238 : } \
239 : } while (0)
240 :
241 : // Declares a cache handle called name for key type KeyT and value type ValT and
242 : // creates a thread-safe least recently used cache with room for capacity
243 : // entries (0 is refused) and the default allocator; the usual way to make one.
244 : // getter fetches a missing key from a remote source, setter writes each set to
245 : // it first, and evict_cb hears about every evicted entry; each may be NULL.
246 : // Ends the program with a fatal error when the cache can't be created. Destroy
247 : // it with ccache_destroy(). An array key or value type is refused at compile
248 : // time.
249 : //
250 : // ccache_construct(my_cache, int, double, 128, NULL, NULL, NULL);
251 : // ccache_set(my_cache, 42, 3.14);
252 : // double out;
253 : // ccache_get(my_cache, 42, &out);
254 : // ccache_destroy(my_cache);
255 : #define ccache_construct(name, KeyT, ValT, capacity, getter, setter, evict_cb) \
256 : ccol__refuse_array_types("clru", KeyT, ValT); \
257 : __typeof__(KeyT) *name##__ccache_key_type_var __attribute__((unused)) = \
258 : NULL; \
259 : __typeof__(ValT) *name##__ccache_val_type_var __attribute__((unused)) = \
260 : NULL; \
261 : ccache name = CCACHE_NULL; \
262 : do { \
263 : char *ccache__err = NULL; \
264 : (name) = clrucache_create_full( \
265 : (capacity), \
266 : ccol_determine_ccol_data_type(*name##__ccache_key_type_var), \
267 : ccol_determine_ccol_data_type(*name##__ccache_val_type_var), (getter), \
268 : (setter), (evict_cb), NULL, &ccache__err); \
269 : if (!(name)) { \
270 : ccol__fatal_err("ccache_construct('%s'): %s", #name, \
271 : ccache__err ? ccache__err : "unknown error"); \
272 : } \
273 : } while (0)
274 :
275 : // Declares a cache handle called name for key type KeyT and value type ValT and
276 : // creates a thread-safe least recently used cache with room for capacity
277 : // entries (0 is refused) and the default allocator. The cache is destroyed by
278 : // itself when name goes out of scope. getter fetches a missing key from a
279 : // remote source, setter writes each set to it first, and evict_cb hears about
280 : // every evicted entry; each may be NULL. Ends the program with a fatal error
281 : // when the cache can't be created.
282 : #define ccache_construct_scoped(name, KeyT, ValT, capacity, getter, setter, \
283 : evict_cb) \
284 : ccol__refuse_array_types("clru", KeyT, ValT); \
285 : __typeof__(KeyT) *name##__ccache_key_type_var __attribute__((unused)) = \
286 : NULL; \
287 : __typeof__(ValT) *name##__ccache_val_type_var __attribute__((unused)) = \
288 : NULL; \
289 : ccache name ccol__destructor(clrucache__destroy_cleanup) = CCACHE_NULL; \
290 : do { \
291 : char *ccache__err = NULL; \
292 : (name) = clrucache_create_full( \
293 : (capacity), \
294 : ccol_determine_ccol_data_type(*name##__ccache_key_type_var), \
295 : ccol_determine_ccol_data_type(*name##__ccache_val_type_var), (getter), \
296 : (setter), (evict_cb), NULL, &ccache__err); \
297 : if (!(name)) { \
298 : ccol__fatal_err("ccache_construct_scoped('%s'): %s", #name, \
299 : ccache__err ? ccache__err : "unknown error"); \
300 : } \
301 : } while (0)
302 :
303 : // Makes the typed ccache_* macros usable on a cache handle that came from
304 : // another scope, such as a function parameter or a struct field. It declares
305 : // only the key and value type information those macros read; it creates and
306 : // destroys nothing. KeyT and ValT must be the types the cache was created
307 : // with. An array type is refused at compile time.
308 : //
309 : // void use_cache(ccache c) {
310 : // ccache_redeclare(c, int, double);
311 : // double out;
312 : // ccache_get(c, 42, &out);
313 : // }
314 : #define ccache_redeclare(name, KeyT, ValT) \
315 : ccol__refuse_array_types("clru", KeyT, ValT); \
316 : __typeof__(KeyT) *name##__ccache_key_type_var __attribute__((unused)) = \
317 : NULL; \
318 : __typeof__(ValT) *name##__ccache_val_type_var __attribute__((unused)) = NULL
319 :
320 : // Looks key up in the typed cache name and stores the value in *val_ptr; a hit
321 : // makes the key the most recently used, and a miss asks the remote getter, if
322 : // there is one. Evaluates to ccol_success, ccol_key_not_found (missing and no
323 : // getter, or the getter failed), ccol_invalid_args (CCACHE_NULL, a destroyed
324 : // handle or a NULL char * key), ccol_not_enough_memory, or
325 : // ccol_unexpected_failure (the getter gave a value of the wrong size). key is
326 : // converted to the declared KeyT as by assignment (a char * key type keeps the
327 : // caller's pointer type). A value of another type is converted into *val_ptr
328 : // as by assignment and no heap memory is left; for a char * value type you get
329 : // a new heap string on each call and free it with the cache's allocator
330 : // (free() for the default). On failure *val_ptr is left untouched. A cache
331 : // from another scope needs ccache_redeclare() first.
332 : #define ccache_get(name, key, val_ptr) \
333 : ccol__ccache_get_impl(name, (key), (val_ptr), \
334 : ccol__uniq(ccol__ccache_get_k, __COUNTER__), \
335 : ccol__uniq(ccol__ccache_get_kp, __COUNTER__), \
336 : ccol__uniq(ccol__ccache_get_r, __COUNTER__), \
337 : ccol__uniq(ccol__ccache_get_vtmp, __COUNTER__), \
338 : ccol__uniq(ccol__ccache_get_vout, __COUNTER__))
339 :
340 : // The value type of cache name without top-level qualifiers, so ccache_get()
341 : // can write a temporary of it when the value type is const.
342 : #define ccache__unqual_val_type(name) \
343 : ccol__unqual_type(*(name##__ccache_val_type_var))
344 :
345 : // Internal: The body of ccache_get(), with temporaries named by ccol__uniq() so
346 : // it nests inside any public macro. The key copy has the declared key type and
347 : // its padding cleared, since the segment choice and the map read every byte.
348 : // Both arms are compiled for every ValT, so the shared ValT temporary sizes
349 : // each copy by the declared type; without it the dead char * arm would be a
350 : // _FORTIFY_SOURCE error for a narrow ValT.
351 : #define ccol__ccache_get_impl(name, key, val_ptr, ccache__k, ccache__kp, \
352 : ccache__r, ccache__vtmp, ccache__vout) \
353 : ({ \
354 : ccol__declared_or_own_type(name##__ccache_key_type_var, (key)) ccache__k = \
355 : (key); \
356 : ccol__clear_padding(&ccache__k); \
357 : cmap_pair ccache__kp = {}; \
358 : ccol__populate_cmap_pair(&ccache__kp, ccache__k); \
359 : ccol_retval ccache__r; \
360 : ccache__unqual_val_type(name) ccache__vtmp; \
361 : if (ccol__is_char_ptr(*(name##__ccache_val_type_var))) { \
362 : cmap_pair ccache__vout = {}; \
363 : ccache__r = clrucache_get_full((name), &ccache__kp, &ccache__vout); \
364 : if (ccache__r == ccol_success && ccache__vout.ptr) { \
365 : memcpy(&ccache__vtmp, &ccache__vout.ptr, sizeof(ccache__vtmp)); \
366 : *(val_ptr) = ccache__vtmp; \
367 : } \
368 : } else { \
369 : ccache__r = clrucache__get_into((name), &ccache__kp, &ccache__vtmp, \
370 : sizeof(ccache__vtmp)); \
371 : if (ccache__r == ccol_success) *(val_ptr) = ccache__vtmp; \
372 : } \
373 : ccache__r; \
374 : })
375 :
376 : // Stores a copy of val under key in the typed cache name and makes the key the
377 : // most recently used; a full cache evicts its least recently used entry. When
378 : // the cache has a remote setter it runs first, and a failed setter gives
379 : // ccol_unexpected_failure and changes nothing. Evaluates to ccol_success,
380 : // ccol_unexpected_failure, ccol_invalid_args (CCACHE_NULL, a destroyed handle,
381 : // or a NULL char * key or value), ccol_not_enough_memory or
382 : // ccol_container_full. key and val are converted to the declared KeyT and
383 : // ValT as by assignment (a char * type keeps the caller's pointer type). name
384 : // must be a plain variable with its companion variables; a cache from another
385 : // scope needs ccache_redeclare().
386 : #define ccache_set(name, key, val) \
387 : ccol__ccache_set_impl(name, (key), (val), \
388 : ccol__uniq(ccol__ccache_set_k, __COUNTER__), \
389 : ccol__uniq(ccol__ccache_set_v, __COUNTER__), \
390 : ccol__uniq(ccol__ccache_set_kp, __COUNTER__), \
391 : ccol__uniq(ccol__ccache_set_vp, __COUNTER__))
392 :
393 : // Internal: The body of ccache_set(), with ccol__uniq() temporaries; the key
394 : // and value copies follow the rules of ccache_get().
395 : #define ccol__ccache_set_impl(name, key, val, ccache__k, ccache__v, \
396 : ccache__kp, ccache__vp) \
397 : ({ \
398 : ccol__declared_or_own_type(name##__ccache_key_type_var, (key)) ccache__k = \
399 : (key); \
400 : ccol__clear_padding(&ccache__k); \
401 : ccol__declared_or_own_type(name##__ccache_val_type_var, (val)) ccache__v = \
402 : (val); \
403 : cmap_pair ccache__kp = {}; \
404 : cmap_pair ccache__vp = {}; \
405 : ccol__populate_cmap_pair(&ccache__kp, ccache__k); \
406 : ccol__populate_cmap_pair(&ccache__vp, ccache__v); \
407 : clrucache_set_full((name), &ccache__kp, &ccache__vp); \
408 : })
409 :
410 : // Returns the number of live entries in the cache, for monitoring. Each
411 : // segment is counted in turn, so under concurrent use the total is a snapshot.
412 : // Returns 0 for CCACHE_NULL or a destroyed handle.
413 : size_t clrucache_size(ccache cache);
414 :
415 : // Returns the capacity the cache was created with, or 0 for CCACHE_NULL or a
416 : // destroyed handle.
417 : size_t clrucache_capacity(ccache cache);
418 :
419 : // Evaluates to the number of live entries in the cache, as a size_t, for
420 : // monitoring; under concurrent use the total is a snapshot. Gives 0 for
421 : // CCACHE_NULL or a destroyed handle.
422 : #define ccache_size(name) clrucache_size((name))
423 :
424 : // Evaluates to the capacity the cache was created with, as a size_t, or 0 for
425 : // CCACHE_NULL or a destroyed handle.
426 : #define ccache_capacity(name) clrucache_capacity((name))
427 :
428 : #pragma GCC visibility pop
|