subr_thmap.c revision 1.5.6.2 1 /* $NetBSD: subr_thmap.c,v 1.5.6.2 2023/10/18 15:07:06 martin Exp $ */
2
3 /*-
4 * Copyright (c) 2018 Mindaugas Rasiukevicius <rmind at noxt eu>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 * Upstream: https://github.com/rmind/thmap/
29 */
30
31 /*
32 * Concurrent trie-hash map.
33 *
34 * The data structure is conceptually a radix trie on hashed keys.
35 * Keys are hashed using a 32-bit function. The root level is a special
36 * case: it is managed using the compare-and-swap (CAS) atomic operation
37 * and has a fanout of 64. The subsequent levels are constructed using
38 * intermediate nodes with a fanout of 16 (using 4 bits). As more levels
39 * are created, more blocks of the 32-bit hash value might be generated
40 * by incrementing the seed parameter of the hash function.
41 *
42 * Concurrency
43 *
44 * - READERS: Descending is simply walking through the slot values of
45 * the intermediate nodes. It is lock-free as there is no intermediate
46 * state: the slot is either empty or has a pointer to the child node.
47 * The main assumptions here are the following:
48 *
49 * i) modifications must preserve consistency with the respect to the
50 * readers i.e. the readers can only see the valid node values;
51 *
52 * ii) any invalid view must "fail" the reads, e.g. by making them
53 * re-try from the root; this is a case for deletions and is achieved
54 * using the NODE_DELETED flag.
55 *
56 * iii) the node destruction must be synchronized with the readers,
57 * e.g. by using the Epoch-based reclamation or other techniques.
58 *
59 * - WRITERS AND LOCKING: Each intermediate node has a spin-lock (which
60 * is implemented using the NODE_LOCKED bit) -- it provides mutual
61 * exclusion amongst concurrent writers. The lock order for the nodes
62 * is "bottom-up" i.e. they are locked as we ascend the trie. A key
63 * constraint here is that parent pointer never changes.
64 *
65 * - DELETES: In addition to writer's locking, the deletion keeps the
66 * intermediate nodes in a valid state and sets the NODE_DELETED flag,
67 * to indicate that the readers must re-start the walk from the root.
68 * As the levels are collapsed, NODE_DELETED gets propagated up-tree.
69 * The leaf nodes just stay as-is until they are reclaimed.
70 *
71 * - ROOT LEVEL: The root level is a special case, as it is implemented
72 * as an array (rather than intermediate node). The root-level slot can
73 * only be set using CAS and it can only be set to a valid intermediate
74 * node. The root-level slot can only be cleared when the node it points
75 * at becomes empty, is locked and marked as NODE_DELETED (this causes
76 * the insert/delete operations to re-try until the slot is set to NULL).
77 *
78 * References:
79 *
80 * W. Litwin, 1981, Trie Hashing.
81 * Proceedings of the 1981 ACM SIGMOD, p. 19-29
82 * https://dl.acm.org/citation.cfm?id=582322
83 *
84 * P. L. Lehman and S. B. Yao.
85 * Efficient locking for concurrent operations on B-trees.
86 * ACM TODS, 6(4):650-670, 1981
87 * https://www.csd.uoc.gr/~hy460/pdf/p650-lehman.pdf
88 */
89
90 #ifdef _KERNEL
91 #include <sys/cdefs.h>
92 #include <sys/param.h>
93 #include <sys/types.h>
94 #include <sys/thmap.h>
95 #include <sys/kmem.h>
96 #include <sys/lock.h>
97 #include <sys/atomic.h>
98 #include <sys/hash.h>
99 #define THMAP_RCSID(a) __KERNEL_RCSID(0, a)
100 #else
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <stdbool.h>
104 #include <stddef.h>
105 #include <inttypes.h>
106 #include <string.h>
107 #include <limits.h>
108 #define THMAP_RCSID(a) __RCSID(a)
109
110 #include "thmap.h"
111 #include "utils.h"
112 #endif
113
114 THMAP_RCSID("$NetBSD: subr_thmap.c,v 1.5.6.2 2023/10/18 15:07:06 martin Exp $");
115
116 /*
117 * NetBSD kernel wrappers
118 */
119 #ifdef _KERNEL
120 #define ASSERT KASSERT
121 #define atomic_thread_fence(x) membar_sync()
122 #define atomic_compare_exchange_weak_explicit_32(p, e, n, m1, m2) \
123 (atomic_cas_32((p), *(e), (n)) == *(e))
124 #define atomic_compare_exchange_weak_explicit_ptr(p, e, n, m1, m2) \
125 (atomic_cas_ptr((p), *(void **)(e), (void *)(n)) == *(void **)(e))
126 #define atomic_exchange_explicit(o, n, m1) atomic_swap_ptr((o), (n))
127 #define murmurhash3 murmurhash2
128 #endif
129
130 /*
131 * The root level fanout is 64 (indexed by the last 6 bits of the hash
132 * value XORed with the length). Each subsequent level, represented by
133 * intermediate nodes, has a fanout of 16 (using 4 bits).
134 *
135 * The hash function produces 32-bit values.
136 */
137
138 #define HASHVAL_BITS (32)
139 #define HASHVAL_MOD (HASHVAL_BITS - 1)
140 #define HASHVAL_SHIFT (5)
141
142 #define ROOT_BITS (6)
143 #define ROOT_SIZE (1 << ROOT_BITS)
144 #define ROOT_MASK (ROOT_SIZE - 1)
145 #define ROOT_MSBITS (HASHVAL_BITS - ROOT_BITS)
146
147 #define LEVEL_BITS (4)
148 #define LEVEL_SIZE (1 << LEVEL_BITS)
149 #define LEVEL_MASK (LEVEL_SIZE - 1)
150
151 /*
152 * Instead of raw pointers, we use offsets from the base address.
153 * This accommodates the use of this data structure in shared memory,
154 * where mappings can be in different address spaces.
155 *
156 * The pointers must be aligned, since pointer tagging is used to
157 * differentiate the intermediate nodes from leaves. We reserve the
158 * least significant bit.
159 */
160 typedef uintptr_t thmap_ptr_t;
161 typedef uintptr_t atomic_thmap_ptr_t; // C11 _Atomic
162
163 #define THMAP_NULL ((thmap_ptr_t)0)
164
165 #define THMAP_LEAF_BIT (0x1)
166
167 #define THMAP_ALIGNED_P(p) (((uintptr_t)(p) & 3) == 0)
168 #define THMAP_ALIGN(p) ((uintptr_t)(p) & ~(uintptr_t)3)
169 #define THMAP_INODE_P(p) (((uintptr_t)(p) & THMAP_LEAF_BIT) == 0)
170
171 #define THMAP_GETPTR(th, p) ((void *)((th)->baseptr + (uintptr_t)(p)))
172 #define THMAP_GETOFF(th, p) ((thmap_ptr_t)((uintptr_t)(p) - (th)->baseptr))
173 #define THMAP_NODE(th, p) THMAP_GETPTR(th, THMAP_ALIGN(p))
174
175 /*
176 * State field.
177 */
178
179 #define NODE_LOCKED (1U << 31) // lock (writers)
180 #define NODE_DELETED (1U << 30) // node deleted
181 #define NODE_COUNT(s) ((s) & 0x3fffffff) // slot count mask
182
183 /*
184 * There are two types of nodes:
185 * - Intermediate nodes -- arrays pointing to another level or a leaf;
186 * - Leaves, which store a key-value pair.
187 */
188
189 typedef struct {
190 uint32_t state; // C11 _Atomic
191 thmap_ptr_t parent;
192 atomic_thmap_ptr_t slots[LEVEL_SIZE];
193 } thmap_inode_t;
194
195 #define THMAP_INODE_LEN sizeof(thmap_inode_t)
196
197 typedef struct {
198 thmap_ptr_t key;
199 size_t len;
200 void * val;
201 } thmap_leaf_t;
202
203 typedef struct {
204 unsigned rslot; // root-level slot index
205 unsigned level; // current level in the tree
206 unsigned hashidx; // current hash index (block of bits)
207 uint32_t hashval; // current hash value
208 } thmap_query_t;
209
210 union thmap_align {
211 void * p;
212 uint64_t v;
213 };
214
215 typedef struct thmap_gc thmap_gc_t;
216 struct thmap_gc {
217 size_t len;
218 thmap_gc_t * next;
219 char data[] __aligned(sizeof(union thmap_align));
220 };
221
222 #define THMAP_ROOT_LEN (sizeof(thmap_ptr_t) * ROOT_SIZE)
223
224 struct thmap {
225 uintptr_t baseptr;
226 atomic_thmap_ptr_t * root;
227 unsigned flags;
228 const thmap_ops_t * ops;
229 thmap_gc_t * gc_list; // C11 _Atomic
230 };
231
232 static void stage_mem_gc(thmap_t *, uintptr_t, size_t);
233
234 /*
235 * A few low-level helper routines.
236 */
237
238 static uintptr_t
239 alloc_wrapper(size_t len)
240 {
241 return (uintptr_t)kmem_intr_alloc(len, KM_NOSLEEP);
242 }
243
244 static void
245 free_wrapper(uintptr_t addr, size_t len)
246 {
247 kmem_intr_free((void *)addr, len);
248 }
249
250 static const thmap_ops_t thmap_default_ops = {
251 .alloc = alloc_wrapper,
252 .free = free_wrapper
253 };
254
255 static uintptr_t
256 gc_alloc(const thmap_t *thmap, size_t len)
257 {
258 const size_t alloclen = offsetof(struct thmap_gc, data[len]);
259 const uintptr_t gcaddr = thmap->ops->alloc(alloclen);
260
261 if (!gcaddr)
262 return 0;
263
264 thmap_gc_t *const gc = THMAP_GETPTR(thmap, gcaddr);
265 gc->len = len;
266 return THMAP_GETOFF(thmap, &gc->data[0]);
267 }
268
269 static void
270 gc_free(const thmap_t *thmap, uintptr_t addr, size_t len)
271 {
272 const size_t alloclen = offsetof(struct thmap_gc, data[len]);
273 char *const ptr = THMAP_GETPTR(thmap, addr);
274 thmap_gc_t *const gc = container_of(ptr, struct thmap_gc, data[0]);
275 const uintptr_t gcaddr = THMAP_GETOFF(thmap, gc);
276
277 KASSERTMSG(gc->len == len, "thmap=%p ops=%p addr=%p len=%zu"
278 " gc=%p gc->len=%zu",
279 thmap, thmap->ops, (void *)addr, len, gc, gc->len);
280 thmap->ops->free(gcaddr, alloclen);
281 }
282
283 /*
284 * NODE LOCKING.
285 */
286
287 #ifdef DIAGNOSTIC
288 static inline bool
289 node_locked_p(thmap_inode_t *node)
290 {
291 return (atomic_load_relaxed(&node->state) & NODE_LOCKED) != 0;
292 }
293 #endif
294
295 static void
296 lock_node(thmap_inode_t *node)
297 {
298 unsigned bcount = SPINLOCK_BACKOFF_MIN;
299 uint32_t s;
300 again:
301 s = atomic_load_relaxed(&node->state);
302 if (s & NODE_LOCKED) {
303 SPINLOCK_BACKOFF(bcount);
304 goto again;
305 }
306 /* Acquire from prior release in unlock_node.() */
307 if (!atomic_compare_exchange_weak_explicit_32(&node->state,
308 &s, s | NODE_LOCKED, memory_order_acquire, memory_order_relaxed)) {
309 bcount = SPINLOCK_BACKOFF_MIN;
310 goto again;
311 }
312 }
313
314 static void
315 unlock_node(thmap_inode_t *node)
316 {
317 uint32_t s = atomic_load_relaxed(&node->state) & ~NODE_LOCKED;
318
319 ASSERT(node_locked_p(node));
320 /* Release to subsequent acquire in lock_node(). */
321 atomic_store_release(&node->state, s);
322 }
323
324 /*
325 * HASH VALUE AND KEY OPERATIONS.
326 */
327
328 static inline void
329 hashval_init(thmap_query_t *query, const void * restrict key, size_t len)
330 {
331 const uint32_t hashval = murmurhash3(key, len, 0);
332
333 query->rslot = ((hashval >> ROOT_MSBITS) ^ len) & ROOT_MASK;
334 query->level = 0;
335 query->hashval = hashval;
336 query->hashidx = 0;
337 }
338
339 /*
340 * hashval_getslot: given the key, compute the hash (if not already cached)
341 * and return the offset for the current level.
342 */
343 static unsigned
344 hashval_getslot(thmap_query_t *query, const void * restrict key, size_t len)
345 {
346 const unsigned offset = query->level * LEVEL_BITS;
347 const unsigned shift = offset & HASHVAL_MOD;
348 const unsigned i = offset >> HASHVAL_SHIFT;
349
350 if (query->hashidx != i) {
351 /* Generate a hash value for a required range. */
352 query->hashval = murmurhash3(key, len, i);
353 query->hashidx = i;
354 }
355 return (query->hashval >> shift) & LEVEL_MASK;
356 }
357
358 static unsigned
359 hashval_getleafslot(const thmap_t *thmap,
360 const thmap_leaf_t *leaf, unsigned level)
361 {
362 const void *key = THMAP_GETPTR(thmap, leaf->key);
363 const unsigned offset = level * LEVEL_BITS;
364 const unsigned shift = offset & HASHVAL_MOD;
365 const unsigned i = offset >> HASHVAL_SHIFT;
366
367 return (murmurhash3(key, leaf->len, i) >> shift) & LEVEL_MASK;
368 }
369
370 static inline unsigned
371 hashval_getl0slot(const thmap_t *thmap, const thmap_query_t *query,
372 const thmap_leaf_t *leaf)
373 {
374 if (__predict_true(query->hashidx == 0)) {
375 return query->hashval & LEVEL_MASK;
376 }
377 return hashval_getleafslot(thmap, leaf, 0);
378 }
379
380 static bool
381 key_cmp_p(const thmap_t *thmap, const thmap_leaf_t *leaf,
382 const void * restrict key, size_t len)
383 {
384 const void *leafkey = THMAP_GETPTR(thmap, leaf->key);
385 return len == leaf->len && memcmp(key, leafkey, len) == 0;
386 }
387
388 /*
389 * INTER-NODE OPERATIONS.
390 */
391
392 static thmap_inode_t *
393 node_create(thmap_t *thmap, thmap_inode_t *parent)
394 {
395 thmap_inode_t *node;
396 uintptr_t p;
397
398 p = gc_alloc(thmap, THMAP_INODE_LEN);
399 if (!p) {
400 return NULL;
401 }
402 node = THMAP_GETPTR(thmap, p);
403 ASSERT(THMAP_ALIGNED_P(node));
404
405 memset(node, 0, THMAP_INODE_LEN);
406 if (parent) {
407 /* Not yet published, no need for ordering. */
408 atomic_store_relaxed(&node->state, NODE_LOCKED);
409 node->parent = THMAP_GETOFF(thmap, parent);
410 }
411 return node;
412 }
413
414 static void
415 node_insert(thmap_inode_t *node, unsigned slot, thmap_ptr_t child)
416 {
417 ASSERT(node_locked_p(node) || node->parent == THMAP_NULL);
418 ASSERT((atomic_load_relaxed(&node->state) & NODE_DELETED) == 0);
419 ASSERT(atomic_load_relaxed(&node->slots[slot]) == THMAP_NULL);
420
421 ASSERT(NODE_COUNT(atomic_load_relaxed(&node->state)) < LEVEL_SIZE);
422
423 /*
424 * If node is public already, caller is responsible for issuing
425 * release fence; if node is not public, no ordering is needed.
426 * Hence relaxed ordering.
427 */
428 atomic_store_relaxed(&node->slots[slot], child);
429 atomic_store_relaxed(&node->state,
430 atomic_load_relaxed(&node->state) + 1);
431 }
432
433 static void
434 node_remove(thmap_inode_t *node, unsigned slot)
435 {
436 ASSERT(node_locked_p(node));
437 ASSERT((atomic_load_relaxed(&node->state) & NODE_DELETED) == 0);
438 ASSERT(atomic_load_relaxed(&node->slots[slot]) != THMAP_NULL);
439
440 ASSERT(NODE_COUNT(atomic_load_relaxed(&node->state)) > 0);
441 ASSERT(NODE_COUNT(atomic_load_relaxed(&node->state)) <= LEVEL_SIZE);
442
443 /* Element will be GC-ed later; no need for ordering here. */
444 atomic_store_relaxed(&node->slots[slot], THMAP_NULL);
445 atomic_store_relaxed(&node->state,
446 atomic_load_relaxed(&node->state) - 1);
447 }
448
449 /*
450 * LEAF OPERATIONS.
451 */
452
453 static thmap_leaf_t *
454 leaf_create(const thmap_t *thmap, const void *key, size_t len, void *val)
455 {
456 thmap_leaf_t *leaf;
457 uintptr_t leaf_off, key_off;
458
459 leaf_off = gc_alloc(thmap, sizeof(thmap_leaf_t));
460 if (!leaf_off) {
461 return NULL;
462 }
463 leaf = THMAP_GETPTR(thmap, leaf_off);
464 ASSERT(THMAP_ALIGNED_P(leaf));
465
466 if ((thmap->flags & THMAP_NOCOPY) == 0) {
467 /*
468 * Copy the key.
469 */
470 key_off = gc_alloc(thmap, len);
471 if (!key_off) {
472 gc_free(thmap, leaf_off, sizeof(thmap_leaf_t));
473 return NULL;
474 }
475 memcpy(THMAP_GETPTR(thmap, key_off), key, len);
476 leaf->key = key_off;
477 } else {
478 /* Otherwise, we use a reference. */
479 leaf->key = (uintptr_t)key;
480 }
481 leaf->len = len;
482 leaf->val = val;
483 return leaf;
484 }
485
486 static void
487 leaf_free(const thmap_t *thmap, thmap_leaf_t *leaf)
488 {
489 if ((thmap->flags & THMAP_NOCOPY) == 0) {
490 gc_free(thmap, leaf->key, leaf->len);
491 }
492 gc_free(thmap, THMAP_GETOFF(thmap, leaf), sizeof(thmap_leaf_t));
493 }
494
495 static thmap_leaf_t *
496 get_leaf(const thmap_t *thmap, thmap_inode_t *parent, unsigned slot)
497 {
498 thmap_ptr_t node;
499
500 /* Consume from prior release in thmap_put(). */
501 node = atomic_load_consume(&parent->slots[slot]);
502 if (THMAP_INODE_P(node)) {
503 return NULL;
504 }
505 return THMAP_NODE(thmap, node);
506 }
507
508 /*
509 * ROOT OPERATIONS.
510 */
511
512 /*
513 * root_try_put: Try to set a root pointer at query->rslot.
514 *
515 * => Implies release operation on success.
516 * => Implies no ordering on failure.
517 */
518 static inline bool
519 root_try_put(thmap_t *thmap, const thmap_query_t *query, thmap_leaf_t *leaf)
520 {
521 thmap_ptr_t expected;
522 const unsigned i = query->rslot;
523 thmap_inode_t *node;
524 thmap_ptr_t nptr;
525 unsigned slot;
526
527 /*
528 * Must pre-check first. No ordering required because we will
529 * check again before taking any actions, and start over if
530 * this changes from null.
531 */
532 if (atomic_load_relaxed(&thmap->root[i])) {
533 return false;
534 }
535
536 /*
537 * Create an intermediate node. Since there is no parent set,
538 * it will be created unlocked and the CAS operation will
539 * release it to readers.
540 */
541 node = node_create(thmap, NULL);
542 slot = hashval_getl0slot(thmap, query, leaf);
543 node_insert(node, slot, THMAP_GETOFF(thmap, leaf) | THMAP_LEAF_BIT);
544 nptr = THMAP_GETOFF(thmap, node);
545 again:
546 if (atomic_load_relaxed(&thmap->root[i])) {
547 gc_free(thmap, nptr, THMAP_INODE_LEN);
548 return false;
549 }
550 /* Release to subsequent consume in find_edge_node(). */
551 expected = THMAP_NULL;
552 if (!atomic_compare_exchange_weak_explicit_ptr(&thmap->root[i], &expected,
553 nptr, memory_order_release, memory_order_relaxed)) {
554 goto again;
555 }
556 return true;
557 }
558
559 /*
560 * find_edge_node: given the hash, traverse the tree to find the edge node.
561 *
562 * => Returns an aligned (clean) pointer to the parent node.
563 * => Returns the slot number and sets current level.
564 */
565 static thmap_inode_t *
566 find_edge_node(const thmap_t *thmap, thmap_query_t *query,
567 const void * restrict key, size_t len, unsigned *slot)
568 {
569 thmap_ptr_t root_slot;
570 thmap_inode_t *parent;
571 thmap_ptr_t node;
572 unsigned off;
573
574 ASSERT(query->level == 0);
575
576 /* Consume from prior release in root_try_put(). */
577 root_slot = atomic_load_consume(&thmap->root[query->rslot]);
578 parent = THMAP_NODE(thmap, root_slot);
579 if (!parent) {
580 return NULL;
581 }
582 descend:
583 off = hashval_getslot(query, key, len);
584 /* Consume from prior release in thmap_put(). */
585 node = atomic_load_consume(&parent->slots[off]);
586
587 /* Descend the tree until we find a leaf or empty slot. */
588 if (node && THMAP_INODE_P(node)) {
589 parent = THMAP_NODE(thmap, node);
590 query->level++;
591 goto descend;
592 }
593 /*
594 * NODE_DELETED does not become stale until GC runs, which
595 * cannot happen while we are in the middle of an operation,
596 * hence relaxed ordering.
597 */
598 if (atomic_load_relaxed(&parent->state) & NODE_DELETED) {
599 return NULL;
600 }
601 *slot = off;
602 return parent;
603 }
604
605 /*
606 * find_edge_node_locked: traverse the tree, like find_edge_node(),
607 * but attempt to lock the edge node.
608 *
609 * => Returns NULL if the deleted node is found. This indicates that
610 * the caller must re-try from the root, as the root slot might have
611 * changed too.
612 */
613 static thmap_inode_t *
614 find_edge_node_locked(const thmap_t *thmap, thmap_query_t *query,
615 const void * restrict key, size_t len, unsigned *slot)
616 {
617 thmap_inode_t *node;
618 thmap_ptr_t target;
619 retry:
620 /*
621 * Find the edge node and lock it! Re-check the state since
622 * the tree might change by the time we acquire the lock.
623 */
624 node = find_edge_node(thmap, query, key, len, slot);
625 if (!node) {
626 /* The root slot is empty -- let the caller decide. */
627 query->level = 0;
628 return NULL;
629 }
630 lock_node(node);
631 if (__predict_false(atomic_load_relaxed(&node->state) & NODE_DELETED)) {
632 /*
633 * The node has been deleted. The tree might have a new
634 * shape now, therefore we must re-start from the root.
635 */
636 unlock_node(node);
637 query->level = 0;
638 return NULL;
639 }
640 target = atomic_load_relaxed(&node->slots[*slot]);
641 if (__predict_false(target && THMAP_INODE_P(target))) {
642 /*
643 * The target slot has been changed and it is now an
644 * intermediate node. Re-start from the top internode.
645 */
646 unlock_node(node);
647 query->level = 0;
648 goto retry;
649 }
650 return node;
651 }
652
653 /*
654 * thmap_get: lookup a value given the key.
655 */
656 void *
657 thmap_get(thmap_t *thmap, const void *key, size_t len)
658 {
659 thmap_query_t query;
660 thmap_inode_t *parent;
661 thmap_leaf_t *leaf;
662 unsigned slot;
663
664 hashval_init(&query, key, len);
665 parent = find_edge_node(thmap, &query, key, len, &slot);
666 if (!parent) {
667 return NULL;
668 }
669 leaf = get_leaf(thmap, parent, slot);
670 if (!leaf) {
671 return NULL;
672 }
673 if (!key_cmp_p(thmap, leaf, key, len)) {
674 return NULL;
675 }
676 return leaf->val;
677 }
678
679 /*
680 * thmap_put: insert a value given the key.
681 *
682 * => If the key is already present, return the associated value.
683 * => Otherwise, on successful insert, return the given value.
684 */
685 void *
686 thmap_put(thmap_t *thmap, const void *key, size_t len, void *val)
687 {
688 thmap_query_t query;
689 thmap_leaf_t *leaf, *other;
690 thmap_inode_t *parent, *child;
691 unsigned slot, other_slot;
692 thmap_ptr_t target;
693
694 /*
695 * First, pre-allocate and initialize the leaf node.
696 */
697 leaf = leaf_create(thmap, key, len, val);
698 if (__predict_false(!leaf)) {
699 return NULL;
700 }
701 hashval_init(&query, key, len);
702 retry:
703 /*
704 * Try to insert into the root first, if its slot is empty.
705 */
706 if (root_try_put(thmap, &query, leaf)) {
707 /* Success: the leaf was inserted; no locking involved. */
708 return val;
709 }
710
711 /*
712 * Release node via store in node_insert (*) to subsequent
713 * consume in get_leaf() or find_edge_node().
714 */
715 atomic_thread_fence(memory_order_release);
716
717 /*
718 * Find the edge node and the target slot.
719 */
720 parent = find_edge_node_locked(thmap, &query, key, len, &slot);
721 if (!parent) {
722 goto retry;
723 }
724 target = atomic_load_relaxed(&parent->slots[slot]); // tagged offset
725 if (THMAP_INODE_P(target)) {
726 /*
727 * Empty slot: simply insert the new leaf. The release
728 * fence is already issued for us.
729 */
730 target = THMAP_GETOFF(thmap, leaf) | THMAP_LEAF_BIT;
731 node_insert(parent, slot, target); /* (*) */
732 goto out;
733 }
734
735 /*
736 * Collision or duplicate.
737 */
738 other = THMAP_NODE(thmap, target);
739 if (key_cmp_p(thmap, other, key, len)) {
740 /*
741 * Duplicate. Free the pre-allocated leaf and
742 * return the present value.
743 */
744 leaf_free(thmap, leaf);
745 val = other->val;
746 goto out;
747 }
748 descend:
749 /*
750 * Collision -- expand the tree. Create an intermediate node
751 * which will be locked (NODE_LOCKED) for us. At this point,
752 * we advance to the next level.
753 */
754 child = node_create(thmap, parent);
755 if (__predict_false(!child)) {
756 leaf_free(thmap, leaf);
757 val = NULL;
758 goto out;
759 }
760 query.level++;
761
762 /*
763 * Insert the other (colliding) leaf first. The new child is
764 * not yet published, so memory order is relaxed.
765 */
766 other_slot = hashval_getleafslot(thmap, other, query.level);
767 target = THMAP_GETOFF(thmap, other) | THMAP_LEAF_BIT;
768 node_insert(child, other_slot, target);
769
770 /*
771 * Insert the intermediate node into the parent node.
772 * It becomes the new parent for the our new leaf.
773 *
774 * Ensure that stores to the child (and leaf) reach global
775 * visibility before it gets inserted to the parent, as
776 * consumed by get_leaf() or find_edge_node().
777 */
778 atomic_store_release(&parent->slots[slot], THMAP_GETOFF(thmap, child));
779
780 unlock_node(parent);
781 ASSERT(node_locked_p(child));
782 parent = child;
783
784 /*
785 * Get the new slot and check for another collision
786 * at the next level.
787 */
788 slot = hashval_getslot(&query, key, len);
789 if (slot == other_slot) {
790 /* Another collision -- descend and expand again. */
791 goto descend;
792 }
793
794 /*
795 * Insert our new leaf once we expanded enough. The release
796 * fence is already issued for us.
797 */
798 target = THMAP_GETOFF(thmap, leaf) | THMAP_LEAF_BIT;
799 node_insert(parent, slot, target); /* (*) */
800 out:
801 unlock_node(parent);
802 return val;
803 }
804
805 /*
806 * thmap_del: remove the entry given the key.
807 */
808 void *
809 thmap_del(thmap_t *thmap, const void *key, size_t len)
810 {
811 thmap_query_t query;
812 thmap_leaf_t *leaf;
813 thmap_inode_t *parent;
814 unsigned slot;
815 void *val;
816
817 hashval_init(&query, key, len);
818 parent = find_edge_node_locked(thmap, &query, key, len, &slot);
819 if (!parent) {
820 /* Root slot empty: not found. */
821 return NULL;
822 }
823 leaf = get_leaf(thmap, parent, slot);
824 if (!leaf || !key_cmp_p(thmap, leaf, key, len)) {
825 /* Not found. */
826 unlock_node(parent);
827 return NULL;
828 }
829
830 /* Remove the leaf. */
831 ASSERT(THMAP_NODE(thmap, atomic_load_relaxed(&parent->slots[slot]))
832 == leaf);
833 node_remove(parent, slot);
834
835 /*
836 * Collapse the levels if removing the last item.
837 */
838 while (query.level &&
839 NODE_COUNT(atomic_load_relaxed(&parent->state)) == 0) {
840 thmap_inode_t *node = parent;
841
842 ASSERT(atomic_load_relaxed(&node->state) == NODE_LOCKED);
843
844 /*
845 * Ascend one level up.
846 * => Mark our current parent as deleted.
847 * => Lock the parent one level up.
848 */
849 query.level--;
850 slot = hashval_getslot(&query, key, len);
851 parent = THMAP_NODE(thmap, node->parent);
852 ASSERT(parent != NULL);
853
854 lock_node(parent);
855 ASSERT((atomic_load_relaxed(&parent->state) & NODE_DELETED)
856 == 0);
857
858 /*
859 * Lock is exclusive, so nobody else can be writing at
860 * the same time, and no need for atomic R/M/W, but
861 * readers may read without the lock and so need atomic
862 * load/store. No ordering here needed because the
863 * entry itself stays valid until GC.
864 */
865 atomic_store_relaxed(&node->state,
866 atomic_load_relaxed(&node->state) | NODE_DELETED);
867 unlock_node(node); // memory_order_release
868
869 ASSERT(THMAP_NODE(thmap,
870 atomic_load_relaxed(&parent->slots[slot])) == node);
871 node_remove(parent, slot);
872
873 /* Stage the removed node for G/C. */
874 stage_mem_gc(thmap, THMAP_GETOFF(thmap, node), THMAP_INODE_LEN);
875 }
876
877 /*
878 * If the top node is empty, then we need to remove it from the
879 * root level. Mark the node as deleted and clear the slot.
880 *
881 * Note: acquiring the lock on the top node effectively prevents
882 * the root slot from changing.
883 */
884 if (NODE_COUNT(atomic_load_relaxed(&parent->state)) == 0) {
885 const unsigned rslot = query.rslot;
886 const thmap_ptr_t nptr =
887 atomic_load_relaxed(&thmap->root[rslot]);
888
889 ASSERT(query.level == 0);
890 ASSERT(parent->parent == THMAP_NULL);
891 ASSERT(THMAP_GETOFF(thmap, parent) == nptr);
892
893 /* Mark as deleted and remove from the root-level slot. */
894 atomic_store_relaxed(&parent->state,
895 atomic_load_relaxed(&parent->state) | NODE_DELETED);
896 atomic_store_relaxed(&thmap->root[rslot], THMAP_NULL);
897
898 stage_mem_gc(thmap, nptr, THMAP_INODE_LEN);
899 }
900 unlock_node(parent);
901
902 /*
903 * Save the value and stage the leaf for G/C.
904 */
905 val = leaf->val;
906 if ((thmap->flags & THMAP_NOCOPY) == 0) {
907 stage_mem_gc(thmap, leaf->key, leaf->len);
908 }
909 stage_mem_gc(thmap, THMAP_GETOFF(thmap, leaf), sizeof(thmap_leaf_t));
910 return val;
911 }
912
913 /*
914 * G/C routines.
915 */
916
917 static void
918 stage_mem_gc(thmap_t *thmap, uintptr_t addr, size_t len)
919 {
920 char *const ptr = THMAP_GETPTR(thmap, addr);
921 thmap_gc_t *head, *gc;
922
923 gc = container_of(ptr, struct thmap_gc, data[0]);
924 KASSERTMSG(gc->len == len,
925 "thmap=%p ops=%p ptr=%p len=%zu gc=%p gc->len=%zu",
926 thmap, thmap->ops, (char *)addr, len, gc, gc->len);
927 retry:
928 head = atomic_load_relaxed(&thmap->gc_list);
929 gc->next = head; // not yet published
930
931 /* Release to subsequent acquire in thmap_stage_gc(). */
932 if (!atomic_compare_exchange_weak_explicit_ptr(&thmap->gc_list, &head, gc,
933 memory_order_release, memory_order_relaxed)) {
934 goto retry;
935 }
936 }
937
938 void *
939 thmap_stage_gc(thmap_t *thmap)
940 {
941 /* Acquire from prior release in stage_mem_gc(). */
942 return atomic_exchange_explicit(&thmap->gc_list, NULL,
943 memory_order_acquire);
944 }
945
946 void
947 thmap_gc(thmap_t *thmap, void *ref)
948 {
949 thmap_gc_t *gc = ref;
950
951 while (gc) {
952 thmap_gc_t *next = gc->next;
953 gc_free(thmap, THMAP_GETOFF(thmap, &gc->data[0]), gc->len);
954 gc = next;
955 }
956 }
957
958 /*
959 * thmap_create: construct a new trie-hash map object.
960 */
961 thmap_t *
962 thmap_create(uintptr_t baseptr, const thmap_ops_t *ops, unsigned flags)
963 {
964 thmap_t *thmap;
965 uintptr_t root;
966
967 /*
968 * Setup the map object.
969 */
970 if (!THMAP_ALIGNED_P(baseptr)) {
971 return NULL;
972 }
973 thmap = kmem_zalloc(sizeof(thmap_t), KM_SLEEP);
974 if (!thmap) {
975 return NULL;
976 }
977 thmap->baseptr = baseptr;
978 thmap->ops = ops ? ops : &thmap_default_ops;
979 thmap->flags = flags;
980
981 if ((thmap->flags & THMAP_SETROOT) == 0) {
982 /* Allocate the root level. */
983 root = gc_alloc(thmap, THMAP_ROOT_LEN);
984 if (!root) {
985 kmem_free(thmap, sizeof(thmap_t));
986 return NULL;
987 }
988 thmap->root = THMAP_GETPTR(thmap, root);
989 memset(thmap->root, 0, THMAP_ROOT_LEN);
990 atomic_thread_fence(memory_order_release); /* XXX */
991 }
992 return thmap;
993 }
994
995 int
996 thmap_setroot(thmap_t *thmap, uintptr_t root_off)
997 {
998 if (thmap->root) {
999 return -1;
1000 }
1001 thmap->root = THMAP_GETPTR(thmap, root_off);
1002 atomic_thread_fence(memory_order_release); /* XXX */
1003 return 0;
1004 }
1005
1006 uintptr_t
1007 thmap_getroot(const thmap_t *thmap)
1008 {
1009 return THMAP_GETOFF(thmap, thmap->root);
1010 }
1011
1012 void
1013 thmap_destroy(thmap_t *thmap)
1014 {
1015 uintptr_t root = THMAP_GETOFF(thmap, thmap->root);
1016 void *ref;
1017
1018 ref = thmap_stage_gc(thmap);
1019 thmap_gc(thmap, ref);
1020
1021 if ((thmap->flags & THMAP_SETROOT) == 0) {
1022 gc_free(thmap, root, THMAP_ROOT_LEN);
1023 }
1024 kmem_free(thmap, sizeof(thmap_t));
1025 }
1026