xref: /netbsd-src/sys/kern/subr_thmap.c (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
1 /*	$NetBSD: subr_thmap.c,v 1.5 2019/02/04 08:00:27 mrg 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 synchronised 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 
91 #ifdef _KERNEL
92 #include <sys/cdefs.h>
93 #include <sys/param.h>
94 #include <sys/types.h>
95 #include <sys/thmap.h>
96 #include <sys/kmem.h>
97 #include <sys/lock.h>
98 #include <sys/atomic.h>
99 #include <sys/hash.h>
100 #define THMAP_RCSID(a) __KERNEL_RCSID(0, a)
101 #else
102 #include <stdio.h>
103 #include <stdlib.h>
104 #include <stdbool.h>
105 #include <stddef.h>
106 #include <inttypes.h>
107 #include <string.h>
108 #include <limits.h>
109 #define THMAP_RCSID(a) __RCSID(a)
110 
111 #include "thmap.h"
112 #include "utils.h"
113 #endif
114 
115 THMAP_RCSID("$NetBSD: subr_thmap.c,v 1.5 2019/02/04 08:00:27 mrg Exp $");
116 
117 /*
118  * NetBSD kernel wrappers
119  */
120 #ifdef _KERNEL
121 #define	ASSERT KASSERT
122 #define	atomic_thread_fence(x) x
123 #define	memory_order_stores membar_producer()
124 #define	memory_order_loads membar_consumer()
125 #define	atomic_cas_32_p(p, e, n) (atomic_cas_32((p), (e), (n)) == (e))
126 #define	atomic_cas_ptr_p(p, e, n) \
127     (atomic_cas_ptr((p), (void *)(e), (void *)(n)) == (e))
128 #define	atomic_exchange atomic_swap_ptr
129 #define	murmurhash3 murmurhash2
130 #endif
131 
132 /*
133  * The root level fanout is 64 (indexed by the last 6 bits of the hash
134  * value XORed with the length).  Each subsequent level, represented by
135  * intermediate nodes, has a fanout of 16 (using 4 bits).
136  *
137  * The hash function produces 32-bit values.
138  */
139 
140 #define	HASHVAL_BITS	(32)
141 #define	HASHVAL_MOD	(HASHVAL_BITS - 1)
142 #define	HASHVAL_SHIFT	(5)
143 
144 #define	ROOT_BITS	(6)
145 #define	ROOT_SIZE	(1 << ROOT_BITS)
146 #define	ROOT_MASK	(ROOT_SIZE - 1)
147 #define	ROOT_MSBITS	(HASHVAL_BITS - ROOT_BITS)
148 
149 #define	LEVEL_BITS	(4)
150 #define	LEVEL_SIZE	(1 << LEVEL_BITS)
151 #define	LEVEL_MASK	(LEVEL_SIZE - 1)
152 
153 /*
154  * Instead of raw pointers, we use offsets from the base address.
155  * This accommodates the use of this data structure in shared memory,
156  * where mappings can be in different address spaces.
157  *
158  * The pointers must be aligned, since pointer tagging is used to
159  * differentiate the intermediate nodes from leaves.  We reserve the
160  * least significant bit.
161  */
162 typedef uintptr_t thmap_ptr_t;
163 
164 #define	THMAP_NULL		((thmap_ptr_t)0)
165 
166 #define	THMAP_LEAF_BIT		(0x1)
167 
168 #define	THMAP_ALIGNED_P(p)	(((uintptr_t)(p) & 3) == 0)
169 #define	THMAP_ALIGN(p)		((uintptr_t)(p) & ~(uintptr_t)3)
170 #define	THMAP_INODE_P(p)	(((uintptr_t)(p) & THMAP_LEAF_BIT) == 0)
171 
172 #define	THMAP_GETPTR(th, p)	((void *)((th)->baseptr + (uintptr_t)(p)))
173 #define	THMAP_GETOFF(th, p)	((thmap_ptr_t)((uintptr_t)(p) - (th)->baseptr))
174 #define	THMAP_NODE(th, p)	THMAP_GETPTR(th, THMAP_ALIGN(p))
175 
176 /*
177  * State field.
178  */
179 
180 #define	NODE_LOCKED		(1U << 31)		// lock (writers)
181 #define	NODE_DELETED		(1U << 30)		// node deleted
182 #define	NODE_COUNT(s)		((s) & 0x3fffffff)	// slot count mask
183 
184 /*
185  * There are two types of nodes:
186  * - Intermediate nodes -- arrays pointing to another level or a leaf;
187  * - Leaves, which store a key-value pair.
188  */
189 
190 typedef struct {
191 	uint32_t	state;
192 	thmap_ptr_t	parent;
193 	thmap_ptr_t	slots[LEVEL_SIZE];
194 } thmap_inode_t;
195 
196 #define	THMAP_INODE_LEN	sizeof(thmap_inode_t)
197 
198 typedef struct {
199 	thmap_ptr_t	key;
200 	size_t		len;
201 	void *		val;
202 } thmap_leaf_t;
203 
204 typedef struct {
205 	unsigned	rslot;		// root-level slot index
206 	unsigned	level;		// current level in the tree
207 	unsigned	hashidx;	// current hash index (block of bits)
208 	uint32_t	hashval;	// current hash value
209 } thmap_query_t;
210 
211 typedef struct {
212 	uintptr_t	addr;
213 	size_t		len;
214 	void *		next;
215 } thmap_gc_t;
216 
217 #define	THMAP_ROOT_LEN	(sizeof(thmap_ptr_t) * ROOT_SIZE)
218 
219 struct thmap {
220 	uintptr_t	baseptr;
221 	thmap_ptr_t *	root;
222 	unsigned	flags;
223 	const thmap_ops_t *ops;
224 	thmap_gc_t *	gc_list;
225 };
226 
227 static void	stage_mem_gc(thmap_t *, uintptr_t, size_t);
228 
229 /*
230  * A few low-level helper routines.
231  */
232 
233 static uintptr_t
234 alloc_wrapper(size_t len)
235 {
236 	return (uintptr_t)kmem_intr_alloc(len, KM_NOSLEEP);
237 }
238 
239 static void
240 free_wrapper(uintptr_t addr, size_t len)
241 {
242 	kmem_intr_free((void *)addr, len);
243 }
244 
245 static const thmap_ops_t thmap_default_ops = {
246 	.alloc = alloc_wrapper,
247 	.free = free_wrapper
248 };
249 
250 /*
251  * NODE LOCKING.
252  */
253 
254 #ifdef DIAGNOSTIC
255 static inline bool
256 node_locked_p(const thmap_inode_t *node)
257 {
258 	return (node->state & NODE_LOCKED) != 0;
259 }
260 #endif
261 
262 static void
263 lock_node(thmap_inode_t *node)
264 {
265 	unsigned bcount = SPINLOCK_BACKOFF_MIN;
266 	uint32_t s;
267 again:
268 	s = node->state;
269 	if (s & NODE_LOCKED) {
270 		SPINLOCK_BACKOFF(bcount);
271 		goto again;
272 	}
273 	/*
274 	 * CAS will issue a full memory fence for us.
275 	 *
276 	 * WARNING: for optimisations purposes, callers rely on us
277 	 * issuing load and store fence
278 	 */
279 	if (!atomic_cas_32_p(&node->state, s, s | NODE_LOCKED)) {
280 		bcount = SPINLOCK_BACKOFF_MIN;
281 		goto again;
282 	}
283 }
284 
285 static void
286 unlock_node(thmap_inode_t *node)
287 {
288 	uint32_t s = node->state & ~NODE_LOCKED;
289 
290 	ASSERT(node_locked_p(node));
291 	atomic_thread_fence(memory_order_stores);
292 	node->state = s; // atomic store
293 }
294 
295 /*
296  * HASH VALUE AND KEY OPERATIONS.
297  */
298 
299 static inline void
300 hashval_init(thmap_query_t *query, const void * restrict key, size_t len)
301 {
302 	const uint32_t hashval = murmurhash3(key, len, 0);
303 
304 	query->rslot = ((hashval >> ROOT_MSBITS) ^ len) & ROOT_MASK;
305 	query->level = 0;
306 	query->hashval = hashval;
307 	query->hashidx = 0;
308 }
309 
310 /*
311  * hashval_getslot: given the key, compute the hash (if not already cached)
312  * and return the offset for the current level.
313  */
314 static unsigned
315 hashval_getslot(thmap_query_t *query, const void * restrict key, size_t len)
316 {
317 	const unsigned offset = query->level * LEVEL_BITS;
318 	const unsigned shift = offset & HASHVAL_MOD;
319 	const unsigned i = offset >> HASHVAL_SHIFT;
320 
321 	if (query->hashidx != i) {
322 		/* Generate a hash value for a required range. */
323 		query->hashval = murmurhash3(key, len, i);
324 		query->hashidx = i;
325 	}
326 	return (query->hashval >> shift) & LEVEL_MASK;
327 }
328 
329 static unsigned
330 hashval_getleafslot(const thmap_t *thmap,
331     const thmap_leaf_t *leaf, unsigned level)
332 {
333 	const void *key = THMAP_GETPTR(thmap, leaf->key);
334 	const unsigned offset = level * LEVEL_BITS;
335 	const unsigned shift = offset & HASHVAL_MOD;
336 	const unsigned i = offset >> HASHVAL_SHIFT;
337 
338 	return (murmurhash3(key, leaf->len, i) >> shift) & LEVEL_MASK;
339 }
340 
341 static inline unsigned
342 hashval_getl0slot(const thmap_t *thmap, const thmap_query_t *query,
343     const thmap_leaf_t *leaf)
344 {
345 	if (__predict_true(query->hashidx == 0)) {
346 		return query->hashval & LEVEL_MASK;
347 	}
348 	return hashval_getleafslot(thmap, leaf, 0);
349 }
350 
351 static bool
352 key_cmp_p(const thmap_t *thmap, const thmap_leaf_t *leaf,
353     const void * restrict key, size_t len)
354 {
355 	const void *leafkey = THMAP_GETPTR(thmap, leaf->key);
356 	return len == leaf->len && memcmp(key, leafkey, len) == 0;
357 }
358 
359 /*
360  * INTER-NODE OPERATIONS.
361  */
362 
363 static thmap_inode_t *
364 node_create(thmap_t *thmap, thmap_inode_t *parent)
365 {
366 	thmap_inode_t *node;
367 	uintptr_t p;
368 
369 	p = thmap->ops->alloc(THMAP_INODE_LEN);
370 	if (!p) {
371 		return NULL;
372 	}
373 	node = THMAP_GETPTR(thmap, p);
374 	ASSERT(THMAP_ALIGNED_P(node));
375 
376 	memset(node, 0, THMAP_INODE_LEN);
377 	if (parent) {
378 		node->state = NODE_LOCKED;
379 		node->parent = THMAP_GETOFF(thmap, parent);
380 	}
381 	return node;
382 }
383 
384 static void
385 node_insert(thmap_inode_t *node, unsigned slot, thmap_ptr_t child)
386 {
387 	ASSERT(node_locked_p(node) || node->parent == THMAP_NULL);
388 	ASSERT((node->state & NODE_DELETED) == 0);
389 	ASSERT(node->slots[slot] == THMAP_NULL);
390 
391 	ASSERT(NODE_COUNT(node->state) < LEVEL_SIZE);
392 
393 	node->slots[slot] = child;
394 	node->state++;
395 }
396 
397 static void
398 node_remove(thmap_inode_t *node, unsigned slot)
399 {
400 	ASSERT(node_locked_p(node));
401 	ASSERT((node->state & NODE_DELETED) == 0);
402 	ASSERT(node->slots[slot] != THMAP_NULL);
403 
404 	ASSERT(NODE_COUNT(node->state) > 0);
405 	ASSERT(NODE_COUNT(node->state) <= LEVEL_SIZE);
406 
407 	node->slots[slot] = THMAP_NULL;
408 	node->state--;
409 }
410 
411 /*
412  * LEAF OPERATIONS.
413  */
414 
415 static thmap_leaf_t *
416 leaf_create(const thmap_t *thmap, const void *key, size_t len, void *val)
417 {
418 	thmap_leaf_t *leaf;
419 	uintptr_t leaf_off, key_off;
420 
421 	leaf_off = thmap->ops->alloc(sizeof(thmap_leaf_t));
422 	if (!leaf_off) {
423 		return NULL;
424 	}
425 	leaf = THMAP_GETPTR(thmap, leaf_off);
426 	ASSERT(THMAP_ALIGNED_P(leaf));
427 
428 	if ((thmap->flags & THMAP_NOCOPY) == 0) {
429 		/*
430 		 * Copy the key.
431 		 */
432 		key_off = thmap->ops->alloc(len);
433 		if (!key_off) {
434 			thmap->ops->free(leaf_off, sizeof(thmap_leaf_t));
435 			return NULL;
436 		}
437 		memcpy(THMAP_GETPTR(thmap, key_off), key, len);
438 		leaf->key = key_off;
439 	} else {
440 		/* Otherwise, we use a reference. */
441 		leaf->key = (uintptr_t)key;
442 	}
443 	leaf->len = len;
444 	leaf->val = val;
445 	return leaf;
446 }
447 
448 static void
449 leaf_free(const thmap_t *thmap, thmap_leaf_t *leaf)
450 {
451 	if ((thmap->flags & THMAP_NOCOPY) == 0) {
452 		thmap->ops->free(leaf->key, leaf->len);
453 	}
454 	thmap->ops->free(THMAP_GETOFF(thmap, leaf), sizeof(thmap_leaf_t));
455 }
456 
457 static thmap_leaf_t *
458 get_leaf(const thmap_t *thmap, thmap_inode_t *parent, unsigned slot)
459 {
460 	thmap_ptr_t node;
461 
462 	node = parent->slots[slot];
463 	if (THMAP_INODE_P(node)) {
464 		return NULL;
465 	}
466 	return THMAP_NODE(thmap, node);
467 }
468 
469 /*
470  * ROOT OPERATIONS.
471  */
472 
473 static inline bool
474 root_try_put(thmap_t *thmap, const thmap_query_t *query, thmap_leaf_t *leaf)
475 {
476 	const unsigned i = query->rslot;
477 	thmap_inode_t *node;
478 	thmap_ptr_t nptr;
479 	unsigned slot;
480 
481 	/*
482 	 * Must pre-check first.
483 	 */
484 	if (thmap->root[i]) {
485 		return false;
486 	}
487 
488 	/*
489 	 * Create an intermediate node.  Since there is no parent set,
490 	 * it will be created unlocked and the CAS operation will issue
491 	 * the store memory fence for us.
492 	 */
493 	node = node_create(thmap, NULL);
494 	slot = hashval_getl0slot(thmap, query, leaf);
495 	node_insert(node, slot, THMAP_GETOFF(thmap, leaf) | THMAP_LEAF_BIT);
496 	nptr = THMAP_GETOFF(thmap, node);
497 again:
498 	if (thmap->root[i]) {
499 		thmap->ops->free(nptr, THMAP_INODE_LEN);
500 		return false;
501 	}
502 	if (!atomic_cas_ptr_p(&thmap->root[i], NULL, nptr)) {
503 		goto again;
504 	}
505 	return true;
506 }
507 
508 /*
509  * find_edge_node: given the hash, traverse the tree to find the edge node.
510  *
511  * => Returns an aligned (clean) pointer to the parent node.
512  * => Returns the slot number and sets current level.
513  */
514 static thmap_inode_t *
515 find_edge_node(const thmap_t *thmap, thmap_query_t *query,
516     const void * restrict key, size_t len, unsigned *slot)
517 {
518 	thmap_ptr_t root_slot = thmap->root[query->rslot];
519 	thmap_inode_t *parent;
520 	thmap_ptr_t node;
521 	unsigned off;
522 
523 	ASSERT(query->level == 0);
524 
525 	parent = THMAP_NODE(thmap, root_slot);
526 	if (!parent) {
527 		return NULL;
528 	}
529 descend:
530 	off = hashval_getslot(query, key, len);
531 	node = parent->slots[off];
532 
533 	/* Ensure the parent load happens before the child load. */
534 	atomic_thread_fence(memory_order_loads);
535 
536 	/* Descend the tree until we find a leaf or empty slot. */
537 	if (node && THMAP_INODE_P(node)) {
538 		parent = THMAP_NODE(thmap, node);
539 		query->level++;
540 		goto descend;
541 	}
542 	if (parent->state & NODE_DELETED) {
543 		return NULL;
544 	}
545 	*slot = off;
546 	return parent;
547 }
548 
549 /*
550  * find_edge_node_locked: traverse the tree, like find_edge_node(),
551  * but attempt to lock the edge node.
552  *
553  * => Returns NULL if the deleted node is found.  This indicates that
554  *    the caller must re-try from the root, as the root slot might have
555  *    changed too.
556  */
557 static thmap_inode_t *
558 find_edge_node_locked(const thmap_t *thmap, thmap_query_t *query,
559     const void * restrict key, size_t len, unsigned *slot)
560 {
561 	thmap_inode_t *node;
562 	thmap_ptr_t target;
563 retry:
564 	/*
565 	 * Find the edge node and lock it!  Re-check the state since
566 	 * the tree might change by the time we acquire the lock.
567 	 */
568 	node = find_edge_node(thmap, query, key, len, slot);
569 	if (!node) {
570 		/* The root slot is empty -- let the caller decide. */
571 		query->level = 0;
572 		return NULL;
573 	}
574 	lock_node(node);
575 	if (__predict_false(node->state & NODE_DELETED)) {
576 		/*
577 		 * The node has been deleted.  The tree might have a new
578 		 * shape now, therefore we must re-start from the root.
579 		 */
580 		unlock_node(node);
581 		query->level = 0;
582 		return NULL;
583 	}
584 	target = node->slots[*slot];
585 	if (__predict_false(target && THMAP_INODE_P(target))) {
586 		/*
587 		 * The target slot has been changed and it is now an
588 		 * intermediate node.  Re-start from the top internode.
589 		 */
590 		unlock_node(node);
591 		query->level = 0;
592 		goto retry;
593 	}
594 	return node;
595 }
596 
597 /*
598  * thmap_get: lookup a value given the key.
599  */
600 void *
601 thmap_get(thmap_t *thmap, const void *key, size_t len)
602 {
603 	thmap_query_t query;
604 	thmap_inode_t *parent;
605 	thmap_leaf_t *leaf;
606 	unsigned slot;
607 
608 	hashval_init(&query, key, len);
609 	parent = find_edge_node(thmap, &query, key, len, &slot);
610 	if (!parent) {
611 		return NULL;
612 	}
613 	leaf = get_leaf(thmap, parent, slot);
614 	if (!leaf) {
615 		return NULL;
616 	}
617 	if (!key_cmp_p(thmap, leaf, key, len)) {
618 		return NULL;
619 	}
620 	return leaf->val;
621 }
622 
623 /*
624  * thmap_put: insert a value given the key.
625  *
626  * => If the key is already present, return the associated value.
627  * => Otherwise, on successful insert, return the given value.
628  */
629 void *
630 thmap_put(thmap_t *thmap, const void *key, size_t len, void *val)
631 {
632 	thmap_query_t query;
633 	thmap_leaf_t *leaf, *other;
634 	thmap_inode_t *parent, *child;
635 	unsigned slot, other_slot;
636 	thmap_ptr_t target;
637 
638 	/*
639 	 * First, pre-allocate and initialise the leaf node.
640 	 *
641 	 * NOTE: locking of the edge node below will issue the
642 	 * store fence for us.
643 	 */
644 	leaf = leaf_create(thmap, key, len, val);
645 	if (__predict_false(!leaf)) {
646 		return NULL;
647 	}
648 	hashval_init(&query, key, len);
649 retry:
650 	/*
651 	 * Try to insert into the root first, if its slot is empty.
652 	 */
653 	if (root_try_put(thmap, &query, leaf)) {
654 		/* Success: the leaf was inserted; no locking involved. */
655 		return val;
656 	}
657 
658 	/*
659 	 * Find the edge node and the target slot.
660 	 */
661 	parent = find_edge_node_locked(thmap, &query, key, len, &slot);
662 	if (!parent) {
663 		goto retry;
664 	}
665 	target = parent->slots[slot]; // tagged offset
666 	if (THMAP_INODE_P(target)) {
667 		/*
668 		 * Empty slot: simply insert the new leaf.  The store
669 		 * fence is already issued for us.
670 		 */
671 		target = THMAP_GETOFF(thmap, leaf) | THMAP_LEAF_BIT;
672 		node_insert(parent, slot, target);
673 		goto out;
674 	}
675 
676 	/*
677 	 * Collision or duplicate.
678 	 */
679 	other = THMAP_NODE(thmap, target);
680 	if (key_cmp_p(thmap, other, key, len)) {
681 		/*
682 		 * Duplicate.  Free the pre-allocated leaf and
683 		 * return the present value.
684 		 */
685 		leaf_free(thmap, leaf);
686 		val = other->val;
687 		goto out;
688 	}
689 descend:
690 	/*
691 	 * Collision -- expand the tree.  Create an intermediate node
692 	 * which will be locked (NODE_LOCKED) for us.  At this point,
693 	 * we advance to the next level.
694 	 */
695 	child = node_create(thmap, parent);
696 	if (__predict_false(!child)) {
697 		leaf_free(thmap, leaf);
698 		val = NULL;
699 		goto out;
700 	}
701 	query.level++;
702 
703 	/*
704 	 * Insert the other (colliding) leaf first.
705 	 */
706 	other_slot = hashval_getleafslot(thmap, other, query.level);
707 	target = THMAP_GETOFF(thmap, other) | THMAP_LEAF_BIT;
708 	node_insert(child, other_slot, target);
709 
710 	/*
711 	 * Insert the intermediate node into the parent node.
712 	 * It becomes the new parent for the our new leaf.
713 	 *
714 	 * Ensure that stores to the child (and leaf) reach the
715 	 * global visibility before it gets inserted to the parent.
716 	 */
717 	atomic_thread_fence(memory_order_stores);
718 	parent->slots[slot] = THMAP_GETOFF(thmap, child);
719 
720 	unlock_node(parent);
721 	ASSERT(node_locked_p(child));
722 	parent = child;
723 
724 	/*
725 	 * Get the new slot and check for another collision
726 	 * at the next level.
727 	 */
728 	slot = hashval_getslot(&query, key, len);
729 	if (slot == other_slot) {
730 		/* Another collision -- descend and expand again. */
731 		goto descend;
732 	}
733 
734 	/* Insert our new leaf once we expanded enough. */
735 	target = THMAP_GETOFF(thmap, leaf) | THMAP_LEAF_BIT;
736 	node_insert(parent, slot, target);
737 out:
738 	unlock_node(parent);
739 	return val;
740 }
741 
742 /*
743  * thmap_del: remove the entry given the key.
744  */
745 void *
746 thmap_del(thmap_t *thmap, const void *key, size_t len)
747 {
748 	thmap_query_t query;
749 	thmap_leaf_t *leaf;
750 	thmap_inode_t *parent;
751 	unsigned slot;
752 	void *val;
753 
754 	hashval_init(&query, key, len);
755 	parent = find_edge_node_locked(thmap, &query, key, len, &slot);
756 	if (!parent) {
757 		/* Root slot empty: not found. */
758 		return NULL;
759 	}
760 	leaf = get_leaf(thmap, parent, slot);
761 	if (!leaf || !key_cmp_p(thmap, leaf, key, len)) {
762 		/* Not found. */
763 		unlock_node(parent);
764 		return NULL;
765 	}
766 
767 	/* Remove the leaf. */
768 	ASSERT(THMAP_NODE(thmap, parent->slots[slot]) == leaf);
769 	node_remove(parent, slot);
770 
771 	/*
772 	 * Collapse the levels if removing the last item.
773 	 */
774 	while (query.level && NODE_COUNT(parent->state) == 0) {
775 		thmap_inode_t *node = parent;
776 
777 		ASSERT(node->state == NODE_LOCKED);
778 
779 		/*
780 		 * Ascend one level up.
781 		 * => Mark our current parent as deleted.
782 		 * => Lock the parent one level up.
783 		 */
784 		query.level--;
785 		slot = hashval_getslot(&query, key, len);
786 		parent = THMAP_NODE(thmap, node->parent);
787 		ASSERT(parent != NULL);
788 
789 		lock_node(parent);
790 		ASSERT((parent->state & NODE_DELETED) == 0);
791 
792 		node->state |= NODE_DELETED;
793 		unlock_node(node); // memory_order_stores
794 
795 		ASSERT(THMAP_NODE(thmap, parent->slots[slot]) == node);
796 		node_remove(parent, slot);
797 
798 		/* Stage the removed node for G/C. */
799 		stage_mem_gc(thmap, THMAP_GETOFF(thmap, node), THMAP_INODE_LEN);
800 	}
801 
802 	/*
803 	 * If the top node is empty, then we need to remove it from the
804 	 * root level.  Mark the node as deleted and clear the slot.
805 	 *
806 	 * Note: acquiring the lock on the top node effectively prevents
807 	 * the root slot from changing.
808 	 */
809 	if (NODE_COUNT(parent->state) == 0) {
810 		const unsigned rslot = query.rslot;
811 		const thmap_ptr_t nptr = thmap->root[rslot];
812 
813 		ASSERT(query.level == 0);
814 		ASSERT(parent->parent == THMAP_NULL);
815 		ASSERT(THMAP_GETOFF(thmap, parent) == nptr);
816 
817 		/* Mark as deleted and remove from the root-level slot. */
818 		parent->state |= NODE_DELETED;
819 		atomic_thread_fence(memory_order_stores);
820 		thmap->root[rslot] = THMAP_NULL;
821 
822 		stage_mem_gc(thmap, nptr, THMAP_INODE_LEN);
823 	}
824 	unlock_node(parent);
825 
826 	/*
827 	 * Save the value and stage the leaf for G/C.
828 	 */
829 	val = leaf->val;
830 	if ((thmap->flags & THMAP_NOCOPY) == 0) {
831 		stage_mem_gc(thmap, leaf->key, leaf->len);
832 	}
833 	stage_mem_gc(thmap, THMAP_GETOFF(thmap, leaf), sizeof(thmap_leaf_t));
834 	return val;
835 }
836 
837 /*
838  * G/C routines.
839  */
840 
841 static void
842 stage_mem_gc(thmap_t *thmap, uintptr_t addr, size_t len)
843 {
844 	thmap_gc_t *head, *gc;
845 
846 	gc = kmem_intr_alloc(sizeof(thmap_gc_t), KM_NOSLEEP);
847 	gc->addr = addr;
848 	gc->len = len;
849 retry:
850 	gc->next = head = thmap->gc_list;
851 	if (!atomic_cas_ptr_p(&thmap->gc_list, head, gc)) {
852 		goto retry;
853 	}
854 }
855 
856 void *
857 thmap_stage_gc(thmap_t *thmap)
858 {
859 	return atomic_exchange(&thmap->gc_list, NULL);
860 }
861 
862 void
863 thmap_gc(thmap_t *thmap, void *ref)
864 {
865 	thmap_gc_t *gc = ref;
866 
867 	while (gc) {
868 		thmap_gc_t *next = gc->next;
869 		thmap->ops->free(gc->addr, gc->len);
870 		kmem_intr_free(gc, sizeof(thmap_gc_t));
871 		gc = next;
872 	}
873 }
874 
875 /*
876  * thmap_create: construct a new trie-hash map object.
877  */
878 thmap_t *
879 thmap_create(uintptr_t baseptr, const thmap_ops_t *ops, unsigned flags)
880 {
881 	thmap_t *thmap;
882 	uintptr_t root;
883 
884 	/*
885 	 * Setup the map object.
886 	 */
887 	if (!THMAP_ALIGNED_P(baseptr)) {
888 		return NULL;
889 	}
890 	thmap = kmem_zalloc(sizeof(thmap_t), KM_SLEEP);
891 	if (!thmap) {
892 		return NULL;
893 	}
894 	thmap->baseptr = baseptr;
895 	thmap->ops = ops ? ops : &thmap_default_ops;
896 	thmap->flags = flags;
897 
898 	if ((thmap->flags & THMAP_SETROOT) == 0) {
899 		/* Allocate the root level. */
900 		root = thmap->ops->alloc(THMAP_ROOT_LEN);
901 		thmap->root = THMAP_GETPTR(thmap, root);
902 		if (!thmap->root) {
903 			kmem_free(thmap, sizeof(thmap_t));
904 			return NULL;
905 		}
906 		memset(thmap->root, 0, THMAP_ROOT_LEN);
907 	}
908 	return thmap;
909 }
910 
911 int
912 thmap_setroot(thmap_t *thmap, uintptr_t root_off)
913 {
914 	if (thmap->root) {
915 		return -1;
916 	}
917 	thmap->root = THMAP_GETPTR(thmap, root_off);
918 	return 0;
919 }
920 
921 uintptr_t
922 thmap_getroot(const thmap_t *thmap)
923 {
924 	return THMAP_GETOFF(thmap, thmap->root);
925 }
926 
927 void
928 thmap_destroy(thmap_t *thmap)
929 {
930 	uintptr_t root = THMAP_GETOFF(thmap, thmap->root);
931 	void *ref;
932 
933 	ref = thmap_stage_gc(thmap);
934 	thmap_gc(thmap, ref);
935 
936 	if ((thmap->flags & THMAP_SETROOT) == 0) {
937 		thmap->ops->free(root, THMAP_ROOT_LEN);
938 	}
939 	kmem_free(thmap, sizeof(thmap_t));
940 }
941