Home | History | Annotate | Line # | Download | only in gen
radixtree.c revision 1.17.2.5
      1 /*	$NetBSD: radixtree.c,v 1.17.2.5 2014/03/25 16:21:08 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c)2011,2012,2013 YAMAMOTO Takashi,
      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 
     29 /*
     30  * radixtree.c
     31  *
     32  * Overview:
     33  *
     34  * This is an implementation of radix tree, whose keys are uint64_t and leafs
     35  * are user provided pointers.
     36  *
     37  * Leaf nodes are just void * and this implementation doesn't care about
     38  * what they actually point to.  However, this implementation has an assumption
     39  * about their alignment.  Specifically, this implementation assumes that their
     40  * 2 LSBs are always zero and uses them for internal accounting.
     41  *
     42  * Intermediate nodes and memory allocation:
     43  *
     44  * Intermediate nodes are automatically allocated and freed internally and
     45  * basically users don't need to care about them.  The allocation is done via
     46  * pool_cache_get(9) for _KERNEL, malloc(3) for userland, and alloc() for
     47  * _STANDALONE environment.  Only radix_tree_insert_node function can allocate
     48  * memory for intermediate nodes and thus can fail for ENOMEM.
     49  *
     50  * Memory Efficiency:
     51  *
     52  * It's designed to work efficiently with dense index distribution.
     53  * The memory consumption (number of necessary intermediate nodes) heavily
     54  * depends on the index distribution.  Basically, more dense index distribution
     55  * consumes less nodes per item.  Approximately,
     56  *
     57  *  - the best case: about RADIX_TREE_PTR_PER_NODE items per intermediate node.
     58  *    it would look like the following.
     59  *
     60  *     root (t_height=1)
     61  *      |
     62  *      v
     63  *      [ | | | ]   (intermediate node.  RADIX_TREE_PTR_PER_NODE=4 in this fig)
     64  *       | | | |
     65  *       v v v v
     66  *       p p p p    (items)
     67  *
     68  *  - the worst case: RADIX_TREE_MAX_HEIGHT intermediate nodes per item.
     69  *    it would look like the following if RADIX_TREE_MAX_HEIGHT=3.
     70  *
     71  *     root (t_height=3)
     72  *      |
     73  *      v
     74  *      [ | | | ]
     75  *           |
     76  *           v
     77  *           [ | | | ]
     78  *                |
     79  *                v
     80  *                [ | | | ]
     81  *                   |
     82  *                   v
     83  *                   p
     84  *
     85  * The height of tree (t_height) is dynamic.  It's smaller if only small
     86  * index values are used.  As an extreme case, if only index 0 is used,
     87  * the corresponding value is directly stored in the root of the tree
     88  * (struct radix_tree) without allocating any intermediate nodes.  In that
     89  * case, t_height=0.
     90  *
     91  * Gang lookup:
     92  *
     93  * This implementation provides a way to scan many nodes quickly via
     94  * radix_tree_gang_lookup_node function and its varients.
     95  *
     96  * Tags:
     97  *
     98  * This implementation provides tagging functionality, which allows quick
     99  * scanning of a subset of leaf nodes.  Leaf nodes are untagged when inserted
    100  * into the tree and can be tagged by radix_tree_set_tag function.
    101  * radix_tree_gang_lookup_tagged_node function and its variants returns only
    102  * leaf nodes with the given tag.  To reduce amount of nodes to visit for
    103  * these functions, this implementation keeps tagging information in internal
    104  * intermediate nodes and quickly skips uninterested parts of a tree.
    105  *
    106  * A tree has RADIX_TREE_TAG_ID_MAX independent tag spaces, each of which are
    107  * identified by an zero-origin numbers, tagid.  For the current implementation,
    108  * RADIX_TREE_TAG_ID_MAX is 2.  A set of tags is described as a bitmask tagmask,
    109  * which is a bitwise OR of (1 << tagid).
    110  */
    111 
    112 #include <sys/cdefs.h>
    113 
    114 #if defined(_KERNEL) || defined(_STANDALONE)
    115 __KERNEL_RCSID(0, "$NetBSD: radixtree.c,v 1.17.2.5 2014/03/25 16:21:08 yamt Exp $");
    116 #include <sys/param.h>
    117 #include <sys/errno.h>
    118 #include <sys/pool.h>
    119 #include <sys/radixtree.h>
    120 #include <lib/libkern/libkern.h>
    121 #if defined(_STANDALONE)
    122 #include <lib/libsa/stand.h>
    123 #endif /* defined(_STANDALONE) */
    124 #else /* defined(_KERNEL) || defined(_STANDALONE) */
    125 __RCSID("$NetBSD: radixtree.c,v 1.17.2.5 2014/03/25 16:21:08 yamt Exp $");
    126 #include <assert.h>
    127 #include <errno.h>
    128 #include <stdbool.h>
    129 #include <stdlib.h>
    130 #include <string.h>
    131 #if 1
    132 #define KASSERT assert
    133 #else
    134 #define KASSERT(a)	/* nothing */
    135 #endif
    136 #endif /* defined(_KERNEL) || defined(_STANDALONE) */
    137 
    138 #include <sys/radixtree.h>
    139 
    140 #define	RADIX_TREE_BITS_PER_HEIGHT	4	/* XXX tune */
    141 #define	RADIX_TREE_PTR_PER_NODE		(1 << RADIX_TREE_BITS_PER_HEIGHT)
    142 #define	RADIX_TREE_MAX_HEIGHT		(64 / RADIX_TREE_BITS_PER_HEIGHT)
    143 #define	RADIX_TREE_INVALID_HEIGHT	(RADIX_TREE_MAX_HEIGHT + 1)
    144 __CTASSERT((64 % RADIX_TREE_BITS_PER_HEIGHT) == 0);
    145 
    146 __CTASSERT(((1 << RADIX_TREE_TAG_ID_MAX) & (sizeof(int) - 1)) == 0);
    147 #define	RADIX_TREE_TAG_MASK	((1 << RADIX_TREE_TAG_ID_MAX) - 1)
    148 
    149 static inline void *
    150 entry_ptr(void *p)
    151 {
    152 
    153 	return (void *)((uintptr_t)p & ~RADIX_TREE_TAG_MASK);
    154 }
    155 
    156 static inline unsigned int
    157 entry_tagmask(void *p)
    158 {
    159 
    160 	return (uintptr_t)p & RADIX_TREE_TAG_MASK;
    161 }
    162 
    163 static inline void *
    164 entry_compose(void *p, unsigned int tagmask)
    165 {
    166 
    167 	return (void *)((uintptr_t)p | tagmask);
    168 }
    169 
    170 static inline bool
    171 entry_match_p(void *p, unsigned int tagmask)
    172 {
    173 
    174 	KASSERT(entry_ptr(p) != NULL || entry_tagmask(p) == 0);
    175 	if (p == NULL) {
    176 		return false;
    177 	}
    178 	if (tagmask == 0) {
    179 		return true;
    180 	}
    181 	return (entry_tagmask(p) & tagmask) != 0;
    182 }
    183 
    184 /*
    185  * radix_tree_node: an intermediate node
    186  *
    187  * we don't care the type of leaf nodes.  they are just void *.
    188  */
    189 
    190 struct radix_tree_node {
    191 	void *n_ptrs[RADIX_TREE_PTR_PER_NODE];
    192 	unsigned int n_nptrs;	/* # of non-NULL pointers in n_ptrs */
    193 };
    194 
    195 /*
    196  * any_children_tagmask:
    197  *
    198  * return OR'ed tagmask of the given node's children.
    199  */
    200 
    201 static unsigned int
    202 any_children_tagmask(const struct radix_tree_node *n)
    203 {
    204 	unsigned int mask;
    205 	int i;
    206 
    207 	mask = 0;
    208 	for (i = 0; i < RADIX_TREE_PTR_PER_NODE; i++) {
    209 		mask |= (unsigned int)(uintptr_t)n->n_ptrs[i];
    210 	}
    211 	return mask & RADIX_TREE_TAG_MASK;
    212 }
    213 
    214 /*
    215  * p_refs[0].pptr == &t->t_root
    216  *	:
    217  * p_refs[n].pptr == &(*p_refs[n-1])->n_ptrs[x]
    218  *	:
    219  *	:
    220  * p_refs[t->t_height].pptr == &leaf_pointer
    221  */
    222 
    223 struct radix_tree_path {
    224 	struct radix_tree_node_ref {
    225 		void **pptr;
    226 	} p_refs[RADIX_TREE_MAX_HEIGHT + 1]; /* +1 for the root ptr */
    227 	/*
    228 	 * p_lastidx is either the index of the last valid element of p_refs[]
    229 	 * or RADIX_TREE_INVALID_HEIGHT.
    230 	 * RADIX_TREE_INVALID_HEIGHT means that radix_tree_lookup_ptr found
    231 	 * that the height of the tree is not enough to cover the given index.
    232 	 */
    233 	unsigned int p_lastidx;
    234 };
    235 
    236 static inline void **
    237 path_pptr(const struct radix_tree *t, const struct radix_tree_path *p,
    238     unsigned int height)
    239 {
    240 
    241 	KASSERT(height <= t->t_height);
    242 	return p->p_refs[height].pptr;
    243 }
    244 
    245 static inline struct radix_tree_node *
    246 path_node(const struct radix_tree * t, const struct radix_tree_path *p,
    247     unsigned int height)
    248 {
    249 
    250 	KASSERT(height <= t->t_height);
    251 	return entry_ptr(*path_pptr(t, p, height));
    252 }
    253 
    254 /*
    255  * radix_tree_init_tree:
    256  *
    257  * Initialize a tree.
    258  */
    259 
    260 void
    261 radix_tree_init_tree(struct radix_tree *t)
    262 {
    263 
    264 	t->t_height = 0;
    265 	t->t_root = NULL;
    266 }
    267 
    268 /*
    269  * radix_tree_fini_tree:
    270  *
    271  * Finish using a tree.
    272  */
    273 
    274 void
    275 radix_tree_fini_tree(struct radix_tree *t)
    276 {
    277 
    278 	KASSERT(t->t_root == NULL);
    279 	KASSERT(t->t_height == 0);
    280 }
    281 
    282 /*
    283  * radix_tree_empty_tree_p:
    284  *
    285  * Return if the tree is empty.
    286  */
    287 
    288 bool
    289 radix_tree_empty_tree_p(struct radix_tree *t)
    290 {
    291 
    292 	return t->t_root == NULL;
    293 }
    294 
    295 /*
    296  * radix_tree_empty_tree_p:
    297  *
    298  * Return true if the tree has any nodes with the given tag.  Otherwise
    299  * return false.
    300  *
    301  * It's illegal to call this function with tagmask 0.
    302  */
    303 
    304 bool
    305 radix_tree_empty_tagged_tree_p(struct radix_tree *t, unsigned int tagmask)
    306 {
    307 
    308 	KASSERT(tagmask != 0);
    309 	return (entry_tagmask(t->t_root) & tagmask) == 0;
    310 }
    311 
    312 static void
    313 radix_tree_node_init(struct radix_tree_node *n)
    314 {
    315 
    316 	memset(n, 0, sizeof(*n));
    317 }
    318 
    319 #if defined(_KERNEL)
    320 pool_cache_t radix_tree_node_cache __read_mostly;
    321 
    322 static int
    323 radix_tree_node_ctor(void *dummy, void *item, int flags)
    324 {
    325 	struct radix_tree_node *n = item;
    326 
    327 	KASSERT(dummy == NULL);
    328 	radix_tree_node_init(n);
    329 	return 0;
    330 }
    331 
    332 /*
    333  * radix_tree_init:
    334  *
    335  * initialize the subsystem.
    336  */
    337 
    338 void
    339 radix_tree_init(void)
    340 {
    341 
    342 	radix_tree_node_cache = pool_cache_init(sizeof(struct radix_tree_node),
    343 	    0, 0, 0, "radix_tree_node", NULL, IPL_NONE, radix_tree_node_ctor,
    344 	    NULL, NULL);
    345 	KASSERT(radix_tree_node_cache != NULL);
    346 }
    347 #endif /* defined(_KERNEL) */
    348 
    349 static bool __unused
    350 radix_tree_node_clean_p(const struct radix_tree_node *n)
    351 {
    352 	unsigned int i;
    353 
    354 	if (n->n_nptrs != 0) {
    355 		return false;
    356 	}
    357 	for (i = 0; i < RADIX_TREE_PTR_PER_NODE; i++) {
    358 		if (n->n_ptrs[i] != NULL) {
    359 			return false;
    360 		}
    361 	}
    362 	return true;
    363 }
    364 
    365 static struct radix_tree_node *
    366 radix_tree_alloc_node(void)
    367 {
    368 	struct radix_tree_node *n;
    369 
    370 #if defined(_KERNEL)
    371 	/*
    372 	 * note that pool_cache_get can block.
    373 	 */
    374 	n = pool_cache_get(radix_tree_node_cache, PR_NOWAIT);
    375 #else /* defined(_KERNEL) */
    376 #if defined(_STANDALONE)
    377 	n = alloc(sizeof(*n));
    378 #else /* defined(_STANDALONE) */
    379 	n = malloc(sizeof(*n));
    380 #endif /* defined(_STANDALONE) */
    381 	if (n != NULL) {
    382 		radix_tree_node_init(n);
    383 	}
    384 #endif /* defined(_KERNEL) */
    385 	KASSERT(n == NULL || radix_tree_node_clean_p(n));
    386 	return n;
    387 }
    388 
    389 static void
    390 radix_tree_free_node(struct radix_tree_node *n)
    391 {
    392 
    393 	KASSERT(radix_tree_node_clean_p(n));
    394 #if defined(_KERNEL)
    395 	pool_cache_put(radix_tree_node_cache, n);
    396 #elif defined(_STANDALONE)
    397 	dealloc(n, sizeof(*n));
    398 #else
    399 	free(n);
    400 #endif
    401 }
    402 
    403 static int
    404 radix_tree_grow(struct radix_tree *t, unsigned int newheight)
    405 {
    406 	const unsigned int tagmask = entry_tagmask(t->t_root);
    407 
    408 	KASSERT(newheight <= 64 / RADIX_TREE_BITS_PER_HEIGHT);
    409 	if (t->t_root == NULL) {
    410 		t->t_height = newheight;
    411 		return 0;
    412 	}
    413 	while (t->t_height < newheight) {
    414 		struct radix_tree_node *n;
    415 
    416 		n = radix_tree_alloc_node();
    417 		if (n == NULL) {
    418 			/*
    419 			 * don't bother to revert our changes.
    420 			 * the caller will likely retry.
    421 			 */
    422 			return ENOMEM;
    423 		}
    424 		n->n_nptrs = 1;
    425 		n->n_ptrs[0] = t->t_root;
    426 		t->t_root = entry_compose(n, tagmask);
    427 		t->t_height++;
    428 	}
    429 	return 0;
    430 }
    431 
    432 /*
    433  * radix_tree_lookup_ptr:
    434  *
    435  * an internal helper function used for various exported functions.
    436  *
    437  * return the pointer to store the node for the given index.
    438  *
    439  * if alloc is true, try to allocate the storage.  (note for _KERNEL:
    440  * in that case, this function can block.)  if the allocation failed or
    441  * alloc is false, return NULL.
    442  *
    443  * if path is not NULL, fill it for the caller's investigation.
    444  *
    445  * if tagmask is not zero, search only for nodes with the tag set.
    446  * note that, however, this function doesn't check the tagmask for the leaf
    447  * pointer.  it's a caller's responsibility to investigate the value which
    448  * is pointed by the returned pointer if necessary.
    449  *
    450  * while this function is a bit large, as it's called with some constant
    451  * arguments, inlining might have benefits.  anyway, a compiler will decide.
    452  */
    453 
    454 static inline void **
    455 radix_tree_lookup_ptr(struct radix_tree *t, uint64_t idx,
    456     struct radix_tree_path *path, bool alloc, const unsigned int tagmask)
    457 {
    458 	struct radix_tree_node *n;
    459 	int hshift = RADIX_TREE_BITS_PER_HEIGHT * t->t_height;
    460 	int shift;
    461 	void **vpp;
    462 	const uint64_t mask = (UINT64_C(1) << RADIX_TREE_BITS_PER_HEIGHT) - 1;
    463 	struct radix_tree_node_ref *refs = NULL;
    464 
    465 	/*
    466 	 * check unsupported combinations
    467 	 */
    468 	KASSERT(tagmask == 0 || !alloc);
    469 	KASSERT(path == NULL || !alloc);
    470 	vpp = &t->t_root;
    471 	if (path != NULL) {
    472 		refs = path->p_refs;
    473 		refs->pptr = vpp;
    474 	}
    475 	n = NULL;
    476 	for (shift = 64 - RADIX_TREE_BITS_PER_HEIGHT; shift >= 0;) {
    477 		struct radix_tree_node *c;
    478 		void *entry;
    479 		const uint64_t i = (idx >> shift) & mask;
    480 
    481 		if (shift >= hshift) {
    482 			unsigned int newheight;
    483 
    484 			KASSERT(vpp == &t->t_root);
    485 			if (i == 0) {
    486 				shift -= RADIX_TREE_BITS_PER_HEIGHT;
    487 				continue;
    488 			}
    489 			if (!alloc) {
    490 				if (path != NULL) {
    491 					KASSERT((refs - path->p_refs) == 0);
    492 					path->p_lastidx =
    493 					    RADIX_TREE_INVALID_HEIGHT;
    494 				}
    495 				return NULL;
    496 			}
    497 			newheight = shift / RADIX_TREE_BITS_PER_HEIGHT + 1;
    498 			if (radix_tree_grow(t, newheight)) {
    499 				return NULL;
    500 			}
    501 			hshift = RADIX_TREE_BITS_PER_HEIGHT * t->t_height;
    502 		}
    503 		entry = *vpp;
    504 		c = entry_ptr(entry);
    505 		if (c == NULL ||
    506 		    (tagmask != 0 &&
    507 		    (entry_tagmask(entry) & tagmask) == 0)) {
    508 			if (!alloc) {
    509 				if (path != NULL) {
    510 					path->p_lastidx = refs - path->p_refs;
    511 				}
    512 				return NULL;
    513 			}
    514 			c = radix_tree_alloc_node();
    515 			if (c == NULL) {
    516 				return NULL;
    517 			}
    518 			*vpp = c;
    519 			if (n != NULL) {
    520 				KASSERT(n->n_nptrs < RADIX_TREE_PTR_PER_NODE);
    521 				n->n_nptrs++;
    522 			}
    523 		}
    524 		n = c;
    525 		vpp = &n->n_ptrs[i];
    526 		if (path != NULL) {
    527 			refs++;
    528 			refs->pptr = vpp;
    529 		}
    530 		shift -= RADIX_TREE_BITS_PER_HEIGHT;
    531 	}
    532 	if (alloc) {
    533 		KASSERT(*vpp == NULL);
    534 		if (n != NULL) {
    535 			KASSERT(n->n_nptrs < RADIX_TREE_PTR_PER_NODE);
    536 			n->n_nptrs++;
    537 		}
    538 	}
    539 	if (path != NULL) {
    540 		path->p_lastidx = refs - path->p_refs;
    541 	}
    542 	return vpp;
    543 }
    544 
    545 /*
    546  * radix_tree_insert_node:
    547  *
    548  * Insert the node at the given index.
    549  *
    550  * It's illegal to insert NULL.  It's illegal to insert a non-aligned pointer.
    551  *
    552  * This function returns ENOMEM if necessary memory allocation failed.
    553  * Otherwise, this function returns 0.
    554  *
    555  * Note that inserting a node can involves memory allocation for intermediate
    556  * nodes.  If _KERNEL, it's done with no-sleep IPL_NONE memory allocation.
    557  *
    558  * For the newly inserted node, all tags are cleared.
    559  */
    560 
    561 int
    562 radix_tree_insert_node(struct radix_tree *t, uint64_t idx, void *p)
    563 {
    564 	void **vpp;
    565 
    566 	KASSERT(p != NULL);
    567 	KASSERT(entry_tagmask(entry_compose(p, 0)) == 0);
    568 	vpp = radix_tree_lookup_ptr(t, idx, NULL, true, 0);
    569 	if (vpp == NULL) {
    570 		return ENOMEM;
    571 	}
    572 	KASSERT(*vpp == NULL);
    573 	*vpp = p;
    574 	return 0;
    575 }
    576 
    577 /*
    578  * radix_tree_replace_node:
    579  *
    580  * Replace a node at the given index with the given node and return the
    581  * replaced one.
    582  *
    583  * It's illegal to try to replace a node which has not been inserted.
    584  *
    585  * This function keeps tags intact.
    586  */
    587 
    588 void *
    589 radix_tree_replace_node(struct radix_tree *t, uint64_t idx, void *p)
    590 {
    591 	void **vpp;
    592 	void *oldp;
    593 
    594 	KASSERT(p != NULL);
    595 	KASSERT(entry_tagmask(entry_compose(p, 0)) == 0);
    596 	vpp = radix_tree_lookup_ptr(t, idx, NULL, false, 0);
    597 	KASSERT(vpp != NULL);
    598 	oldp = *vpp;
    599 	KASSERT(oldp != NULL);
    600 	*vpp = entry_compose(p, entry_tagmask(*vpp));
    601 	return entry_ptr(oldp);
    602 }
    603 
    604 /*
    605  * radix_tree_remove_node:
    606  *
    607  * Remove the node at the given index.
    608  *
    609  * It's illegal to try to remove a node which has not been inserted.
    610  */
    611 
    612 void *
    613 radix_tree_remove_node(struct radix_tree *t, uint64_t idx)
    614 {
    615 	struct radix_tree_path path;
    616 	void **vpp;
    617 	void *oldp;
    618 	int i;
    619 
    620 	vpp = radix_tree_lookup_ptr(t, idx, &path, false, 0);
    621 	KASSERT(vpp != NULL);
    622 	oldp = *vpp;
    623 	KASSERT(oldp != NULL);
    624 	KASSERT(path.p_lastidx == t->t_height);
    625 	KASSERT(vpp == path_pptr(t, &path, path.p_lastidx));
    626 	*vpp = NULL;
    627 	for (i = t->t_height - 1; i >= 0; i--) {
    628 		void *entry;
    629 		struct radix_tree_node ** const pptr =
    630 		    (struct radix_tree_node **)path_pptr(t, &path, i);
    631 		struct radix_tree_node *n;
    632 
    633 		KASSERT(pptr != NULL);
    634 		entry = *pptr;
    635 		n = entry_ptr(entry);
    636 		KASSERT(n != NULL);
    637 		KASSERT(n->n_nptrs > 0);
    638 		n->n_nptrs--;
    639 		if (n->n_nptrs > 0) {
    640 			break;
    641 		}
    642 		radix_tree_free_node(n);
    643 		*pptr = NULL;
    644 	}
    645 	/*
    646 	 * fix up height
    647 	 */
    648 	if (i < 0) {
    649 		KASSERT(t->t_root == NULL);
    650 		t->t_height = 0;
    651 	}
    652 	/*
    653 	 * update tags
    654 	 */
    655 	for (; i >= 0; i--) {
    656 		void *entry;
    657 		struct radix_tree_node ** const pptr =
    658 		    (struct radix_tree_node **)path_pptr(t, &path, i);
    659 		struct radix_tree_node *n;
    660 		unsigned int newmask;
    661 
    662 		KASSERT(pptr != NULL);
    663 		entry = *pptr;
    664 		n = entry_ptr(entry);
    665 		KASSERT(n != NULL);
    666 		KASSERT(n->n_nptrs > 0);
    667 		newmask = any_children_tagmask(n);
    668 		if (newmask == entry_tagmask(entry)) {
    669 			break;
    670 		}
    671 		*pptr = entry_compose(n, newmask);
    672 	}
    673 	/*
    674 	 * XXX is it worth to try to reduce height?
    675 	 * if we do that, make radix_tree_grow rollback its change as well.
    676 	 */
    677 	return entry_ptr(oldp);
    678 }
    679 
    680 /*
    681  * radix_tree_lookup_node:
    682  *
    683  * Returns the node at the given index.
    684  * Returns NULL if nothing is found at the given index.
    685  */
    686 
    687 void *
    688 radix_tree_lookup_node(struct radix_tree *t, uint64_t idx)
    689 {
    690 	void **vpp;
    691 
    692 	vpp = radix_tree_lookup_ptr(t, idx, NULL, false, 0);
    693 	if (vpp == NULL) {
    694 		return NULL;
    695 	}
    696 	return entry_ptr(*vpp);
    697 }
    698 
    699 static inline void
    700 gang_lookup_init(struct radix_tree *t, uint64_t idx,
    701     struct radix_tree_path *path, const unsigned int tagmask)
    702 {
    703 	void **vpp;
    704 
    705 	vpp = radix_tree_lookup_ptr(t, idx, path, false, tagmask);
    706 	KASSERT(vpp == NULL ||
    707 	    vpp == path_pptr(t, path, path->p_lastidx));
    708 	KASSERT(&t->t_root == path_pptr(t, path, 0));
    709 	KASSERT(path->p_lastidx == RADIX_TREE_INVALID_HEIGHT ||
    710 	   path->p_lastidx == t->t_height ||
    711 	   !entry_match_p(*path_pptr(t, path, path->p_lastidx), tagmask));
    712 }
    713 
    714 /*
    715  * gang_lookup_scan:
    716  *
    717  * a helper routine for radix_tree_gang_lookup_node and its variants.
    718  */
    719 
    720 static inline unsigned int
    721 __attribute__((__always_inline__))
    722 gang_lookup_scan(struct radix_tree *t, struct radix_tree_path *path,
    723     void **results, const unsigned int maxresults, const unsigned int tagmask,
    724     const bool reverse, const bool dense)
    725 {
    726 
    727 	/*
    728 	 * we keep the path updated only for lastidx-1.
    729 	 * vpp is what path_pptr(t, path, lastidx) would be.
    730 	 */
    731 	void **vpp;
    732 	unsigned int nfound;
    733 	unsigned int lastidx;
    734 	/*
    735 	 * set up scan direction dependant constants so that we can iterate
    736 	 * n_ptrs as the following.
    737 	 *
    738 	 *	for (i = first; i != guard; i += step)
    739 	 *		visit n->n_ptrs[i];
    740 	 */
    741 	const int step = reverse ? -1 : 1;
    742 	const unsigned int first = reverse ? RADIX_TREE_PTR_PER_NODE - 1 : 0;
    743 	const unsigned int last = reverse ? 0 : RADIX_TREE_PTR_PER_NODE - 1;
    744 	const unsigned int guard = last + step;
    745 
    746 	KASSERT(maxresults > 0);
    747 	KASSERT(&t->t_root == path_pptr(t, path, 0));
    748 	lastidx = path->p_lastidx;
    749 	KASSERT(lastidx == RADIX_TREE_INVALID_HEIGHT ||
    750 	   lastidx == t->t_height ||
    751 	   !entry_match_p(*path_pptr(t, path, lastidx), tagmask));
    752 	nfound = 0;
    753 	if (lastidx == RADIX_TREE_INVALID_HEIGHT) {
    754 		/*
    755 		 * requested idx is beyond the right-most node.
    756 		 */
    757 		if (reverse && !dense) {
    758 			lastidx = 0;
    759 			vpp = path_pptr(t, path, lastidx);
    760 			goto descend;
    761 		}
    762 		return 0;
    763 	}
    764 	vpp = path_pptr(t, path, lastidx);
    765 	while (/*CONSTCOND*/true) {
    766 		struct radix_tree_node *n;
    767 		unsigned int i;
    768 
    769 		if (entry_match_p(*vpp, tagmask)) {
    770 			KASSERT(lastidx == t->t_height);
    771 			/*
    772 			 * record the matching non-NULL leaf.
    773 			 */
    774 			results[nfound] = entry_ptr(*vpp);
    775 			nfound++;
    776 			if (nfound == maxresults) {
    777 				return nfound;
    778 			}
    779 		} else if (dense) {
    780 			return nfound;
    781 		}
    782 scan_siblings:
    783 		/*
    784 		 * try to find the next matching non-NULL sibling.
    785 		 */
    786 		if (lastidx == 0) {
    787 			/*
    788 			 * the root has no siblings.
    789 			 * we've done.
    790 			 */
    791 			KASSERT(vpp == &t->t_root);
    792 			break;
    793 		}
    794 		n = path_node(t, path, lastidx - 1);
    795 		if (*vpp != NULL && n->n_nptrs == 1) {
    796 			/*
    797 			 * optimization; if the node has only a single pointer
    798 			 * and we've already visited it, there's no point to
    799 			 * keep scanning in this node.
    800 			 */
    801 			goto no_siblings;
    802 		}
    803 		for (i = vpp - n->n_ptrs + step; i != guard; i += step) {
    804 			KASSERT(i < RADIX_TREE_PTR_PER_NODE);
    805 			if (entry_match_p(n->n_ptrs[i], tagmask)) {
    806 				vpp = &n->n_ptrs[i];
    807 				break;
    808 			}
    809 		}
    810 		if (i == guard) {
    811 no_siblings:
    812 			/*
    813 			 * not found.  go to parent.
    814 			 */
    815 			lastidx--;
    816 			vpp = path_pptr(t, path, lastidx);
    817 			goto scan_siblings;
    818 		}
    819 descend:
    820 		/*
    821 		 * following the left-most (or right-most in the case of
    822 		 * reverse scan) child node, decend until reaching the leaf or
    823 		 * an non-matching entry.
    824 		 */
    825 		while (entry_match_p(*vpp, tagmask) && lastidx < t->t_height) {
    826 			/*
    827 			 * save vpp in the path so that we can come back to this
    828 			 * node after finishing visiting children.
    829 			 */
    830 			path->p_refs[lastidx].pptr = vpp;
    831 			n = entry_ptr(*vpp);
    832 			vpp = &n->n_ptrs[first];
    833 			lastidx++;
    834 		}
    835 	}
    836 	return nfound;
    837 }
    838 
    839 /*
    840  * radix_tree_gang_lookup_node:
    841  *
    842  * Scan the tree starting from the given index in the ascending order and
    843  * return found nodes.
    844  *
    845  * results should be an array large enough to hold maxresults pointers.
    846  * This function returns the number of nodes found, up to maxresults.
    847  * Returning less than maxresults means there are no more nodes in the tree.
    848  *
    849  * If dense == true, this function stops scanning when it founds a hole of
    850  * indexes.  I.e. an index for which radix_tree_lookup_node would returns NULL.
    851  * If dense == false, this function skips holes and continue scanning until
    852  * maxresults nodes are found or it reaches the limit of the index range.
    853  *
    854  * The result of this function is semantically equivalent to what could be
    855  * obtained by repeated calls of radix_tree_lookup_node with increasing index.
    856  * but this function is expected to be computationally cheaper when looking up
    857  * multiple nodes at once.  Especially, it's expected to be much cheaper when
    858  * node indexes are distributed sparsely.
    859  *
    860  * Note that this function doesn't return index values of found nodes.
    861  * Thus, in the case of dense == false, if index values are important for
    862  * a caller, it's the caller's responsibility to check them, typically
    863  * by examinining the returned nodes using some caller-specific knowledge
    864  * about them.
    865  * In the case of dense == true, a node returned via results[N] is always for
    866  * the index (idx + N).
    867  */
    868 
    869 unsigned int
    870 radix_tree_gang_lookup_node(struct radix_tree *t, uint64_t idx,
    871     void **results, unsigned int maxresults, bool dense)
    872 {
    873 	struct radix_tree_path path;
    874 
    875 	gang_lookup_init(t, idx, &path, 0);
    876 	return gang_lookup_scan(t, &path, results, maxresults, 0, false, dense);
    877 }
    878 
    879 /*
    880  * radix_tree_gang_lookup_node_reverse:
    881  *
    882  * Same as radix_tree_gang_lookup_node except that this one scans the
    883  * tree in the reverse order.  I.e. descending index values.
    884  */
    885 
    886 unsigned int
    887 radix_tree_gang_lookup_node_reverse(struct radix_tree *t, uint64_t idx,
    888     void **results, unsigned int maxresults, bool dense)
    889 {
    890 	struct radix_tree_path path;
    891 
    892 	gang_lookup_init(t, idx, &path, 0);
    893 	return gang_lookup_scan(t, &path, results, maxresults, 0, true, dense);
    894 }
    895 
    896 /*
    897  * radix_tree_gang_lookup_tagged_node:
    898  *
    899  * Same as radix_tree_gang_lookup_node except that this one only returns
    900  * nodes tagged with tagid.
    901  *
    902  * It's illegal to call this function with tagmask 0.
    903  */
    904 
    905 unsigned int
    906 radix_tree_gang_lookup_tagged_node(struct radix_tree *t, uint64_t idx,
    907     void **results, unsigned int maxresults, bool dense, unsigned int tagmask)
    908 {
    909 	struct radix_tree_path path;
    910 
    911 	KASSERT(tagmask != 0);
    912 	gang_lookup_init(t, idx, &path, tagmask);
    913 	return gang_lookup_scan(t, &path, results, maxresults, tagmask, false,
    914 	    dense);
    915 }
    916 
    917 /*
    918  * radix_tree_gang_lookup_tagged_node_reverse:
    919  *
    920  * Same as radix_tree_gang_lookup_tagged_node except that this one scans the
    921  * tree in the reverse order.  I.e. descending index values.
    922  */
    923 
    924 unsigned int
    925 radix_tree_gang_lookup_tagged_node_reverse(struct radix_tree *t, uint64_t idx,
    926     void **results, unsigned int maxresults, bool dense, unsigned int tagmask)
    927 {
    928 	struct radix_tree_path path;
    929 
    930 	KASSERT(tagmask != 0);
    931 	gang_lookup_init(t, idx, &path, tagmask);
    932 	return gang_lookup_scan(t, &path, results, maxresults, tagmask, true,
    933 	    dense);
    934 }
    935 
    936 /*
    937  * radix_tree_get_tag:
    938  *
    939  * Return the tagmask for the node at the given index.
    940  *
    941  * It's illegal to call this function for a node which has not been inserted.
    942  */
    943 
    944 unsigned int
    945 radix_tree_get_tag(struct radix_tree *t, uint64_t idx, unsigned int tagmask)
    946 {
    947 	/*
    948 	 * the following two implementations should behave same.
    949 	 * the former one was chosen because it seems faster.
    950 	 */
    951 #if 1
    952 	void **vpp;
    953 
    954 	vpp = radix_tree_lookup_ptr(t, idx, NULL, false, tagmask);
    955 	if (vpp == NULL) {
    956 		return false;
    957 	}
    958 	KASSERT(*vpp != NULL);
    959 	return (entry_tagmask(*vpp) & tagmask);
    960 #else
    961 	void **vpp;
    962 
    963 	vpp = radix_tree_lookup_ptr(t, idx, NULL, false, 0);
    964 	KASSERT(vpp != NULL);
    965 	return (entry_tagmask(*vpp) & tagmask);
    966 #endif
    967 }
    968 
    969 /*
    970  * radix_tree_set_tag:
    971  *
    972  * Set the tag for the node at the given index.
    973  *
    974  * It's illegal to call this function for a node which has not been inserted.
    975  * It's illegal to call this function with tagmask 0.
    976  */
    977 
    978 void
    979 radix_tree_set_tag(struct radix_tree *t, uint64_t idx, unsigned int tagmask)
    980 {
    981 	struct radix_tree_path path;
    982 	void **vpp;
    983 	int i;
    984 
    985 	KASSERT(tagmask != 0);
    986 	vpp = radix_tree_lookup_ptr(t, idx, &path, false, 0);
    987 	KASSERT(vpp != NULL);
    988 	KASSERT(*vpp != NULL);
    989 	KASSERT(path.p_lastidx == t->t_height);
    990 	KASSERT(vpp == path_pptr(t, &path, path.p_lastidx));
    991 	for (i = t->t_height; i >= 0; i--) {
    992 		void ** const pptr = (void **)path_pptr(t, &path, i);
    993 		void *entry;
    994 
    995 		KASSERT(pptr != NULL);
    996 		entry = *pptr;
    997 		if ((entry_tagmask(entry) & tagmask) != 0) {
    998 			break;
    999 		}
   1000 		*pptr = (void *)((uintptr_t)entry | tagmask);
   1001 	}
   1002 }
   1003 
   1004 /*
   1005  * radix_tree_clear_tag:
   1006  *
   1007  * Clear the tag for the node at the given index.
   1008  *
   1009  * It's illegal to call this function for a node which has not been inserted.
   1010  * It's illegal to call this function with tagmask 0.
   1011  */
   1012 
   1013 void
   1014 radix_tree_clear_tag(struct radix_tree *t, uint64_t idx, unsigned int tagmask)
   1015 {
   1016 	struct radix_tree_path path;
   1017 	void **vpp;
   1018 	int i;
   1019 
   1020 	KASSERT(tagmask != 0);
   1021 	vpp = radix_tree_lookup_ptr(t, idx, &path, false, 0);
   1022 	KASSERT(vpp != NULL);
   1023 	KASSERT(*vpp != NULL);
   1024 	KASSERT(path.p_lastidx == t->t_height);
   1025 	KASSERT(vpp == path_pptr(t, &path, path.p_lastidx));
   1026 	/*
   1027 	 * if already cleared, nothing to do
   1028 	 */
   1029 	if ((entry_tagmask(*vpp) & tagmask) == 0) {
   1030 		return;
   1031 	}
   1032 	/*
   1033 	 * clear the tag only if no children have the tag.
   1034 	 */
   1035 	for (i = t->t_height; i >= 0; i--) {
   1036 		void ** const pptr = (void **)path_pptr(t, &path, i);
   1037 		void *entry;
   1038 
   1039 		KASSERT(pptr != NULL);
   1040 		entry = *pptr;
   1041 		KASSERT((entry_tagmask(entry) & tagmask) != 0);
   1042 		*pptr = entry_compose(entry_ptr(entry),
   1043 		    entry_tagmask(entry) & ~tagmask);
   1044 		/*
   1045 		 * check if we should proceed to process the next level.
   1046 		 */
   1047 		if (0 < i) {
   1048 			struct radix_tree_node *n = path_node(t, &path, i - 1);
   1049 
   1050 			if ((any_children_tagmask(n) & tagmask) != 0) {
   1051 				break;
   1052 			}
   1053 		}
   1054 	}
   1055 }
   1056 
   1057 #if defined(UNITTEST)
   1058 
   1059 #include <inttypes.h>
   1060 #include <stdio.h>
   1061 
   1062 static void
   1063 radix_tree_dump_node(const struct radix_tree *t, void *vp,
   1064     uint64_t offset, unsigned int height)
   1065 {
   1066 	struct radix_tree_node *n;
   1067 	unsigned int i;
   1068 
   1069 	for (i = 0; i < t->t_height - height; i++) {
   1070 		printf(" ");
   1071 	}
   1072 	if (entry_tagmask(vp) == 0) {
   1073 		printf("[%" PRIu64 "] %p", offset, entry_ptr(vp));
   1074 	} else {
   1075 		printf("[%" PRIu64 "] %p (tagmask=0x%x)", offset, entry_ptr(vp),
   1076 		    entry_tagmask(vp));
   1077 	}
   1078 	if (height == 0) {
   1079 		printf(" (leaf)\n");
   1080 		return;
   1081 	}
   1082 	n = entry_ptr(vp);
   1083 	assert(any_children_tagmask(n) == entry_tagmask(vp));
   1084 	printf(" (%u children)\n", n->n_nptrs);
   1085 	for (i = 0; i < __arraycount(n->n_ptrs); i++) {
   1086 		void *c;
   1087 
   1088 		c = n->n_ptrs[i];
   1089 		if (c == NULL) {
   1090 			continue;
   1091 		}
   1092 		radix_tree_dump_node(t, c,
   1093 		    offset + i * (UINT64_C(1) <<
   1094 		    (RADIX_TREE_BITS_PER_HEIGHT * (height - 1))), height - 1);
   1095 	}
   1096 }
   1097 
   1098 void radix_tree_dump(const struct radix_tree *);
   1099 
   1100 void
   1101 radix_tree_dump(const struct radix_tree *t)
   1102 {
   1103 
   1104 	printf("tree %p height=%u\n", t, t->t_height);
   1105 	radix_tree_dump_node(t, t->t_root, 0, t->t_height);
   1106 }
   1107 
   1108 static void
   1109 test1(void)
   1110 {
   1111 	struct radix_tree s;
   1112 	struct radix_tree *t = &s;
   1113 	void *results[3];
   1114 
   1115 	radix_tree_init_tree(t);
   1116 	radix_tree_dump(t);
   1117 	assert(radix_tree_lookup_node(t, 0) == NULL);
   1118 	assert(radix_tree_lookup_node(t, 1000) == NULL);
   1119 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, false) == 0);
   1120 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, true) == 0);
   1121 	assert(radix_tree_gang_lookup_node(t, 1000, results, 3, false) == 0);
   1122 	assert(radix_tree_gang_lookup_node(t, 1000, results, 3, true) == 0);
   1123 	assert(radix_tree_gang_lookup_node_reverse(t, 0, results, 3, false) ==
   1124 	    0);
   1125 	assert(radix_tree_gang_lookup_node_reverse(t, 0, results, 3, true) ==
   1126 	    0);
   1127 	assert(radix_tree_gang_lookup_node_reverse(t, 1000, results, 3, false)
   1128 	    == 0);
   1129 	assert(radix_tree_gang_lookup_node_reverse(t, 1000, results, 3, true)
   1130 	    == 0);
   1131 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 3, false, 1)
   1132 	    == 0);
   1133 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 3, true, 1)
   1134 	    == 0);
   1135 	assert(radix_tree_gang_lookup_tagged_node(t, 1000, results, 3, false, 1)
   1136 	    == 0);
   1137 	assert(radix_tree_gang_lookup_tagged_node(t, 1000, results, 3, true, 1)
   1138 	    == 0);
   1139 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 0, results, 3,
   1140 	    false, 1) == 0);
   1141 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 0, results, 3,
   1142 	    true, 1) == 0);
   1143 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 1000, results, 3,
   1144 	    false, 1) == 0);
   1145 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 1000, results, 3,
   1146 	    true, 1) == 0);
   1147 	assert(radix_tree_empty_tree_p(t));
   1148 	assert(radix_tree_empty_tagged_tree_p(t, 1));
   1149 	assert(radix_tree_empty_tagged_tree_p(t, 2));
   1150 	assert(radix_tree_insert_node(t, 0, (void *)0xdeadbea0) == 0);
   1151 	assert(!radix_tree_empty_tree_p(t));
   1152 	assert(radix_tree_empty_tagged_tree_p(t, 1));
   1153 	assert(radix_tree_empty_tagged_tree_p(t, 2));
   1154 	assert(radix_tree_lookup_node(t, 0) == (void *)0xdeadbea0);
   1155 	assert(radix_tree_lookup_node(t, 1000) == NULL);
   1156 	memset(results, 0, sizeof(results));
   1157 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, false) == 1);
   1158 	assert(results[0] == (void *)0xdeadbea0);
   1159 	memset(results, 0, sizeof(results));
   1160 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, true) == 1);
   1161 	assert(results[0] == (void *)0xdeadbea0);
   1162 	assert(radix_tree_gang_lookup_node(t, 1000, results, 3, false) == 0);
   1163 	assert(radix_tree_gang_lookup_node(t, 1000, results, 3, true) == 0);
   1164 	memset(results, 0, sizeof(results));
   1165 	assert(radix_tree_gang_lookup_node_reverse(t, 0, results, 3, false) ==
   1166 	    1);
   1167 	assert(results[0] == (void *)0xdeadbea0);
   1168 	memset(results, 0, sizeof(results));
   1169 	assert(radix_tree_gang_lookup_node_reverse(t, 0, results, 3, true) ==
   1170 	    1);
   1171 	assert(results[0] == (void *)0xdeadbea0);
   1172 	memset(results, 0, sizeof(results));
   1173 	assert(radix_tree_gang_lookup_node_reverse(t, 1000, results, 3, false)
   1174 	    == 1);
   1175 	assert(results[0] == (void *)0xdeadbea0);
   1176 	assert(radix_tree_gang_lookup_node_reverse(t, 1000, results, 3, true)
   1177 	    == 0);
   1178 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 3, false, 1)
   1179 	    == 0);
   1180 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 3, true, 1)
   1181 	    == 0);
   1182 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 0, results, 3,
   1183 	    false, 1) == 0);
   1184 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 0, results, 3,
   1185 	    true, 1) == 0);
   1186 	assert(radix_tree_insert_node(t, 1000, (void *)0xdeadbea0) == 0);
   1187 	assert(radix_tree_remove_node(t, 0) == (void *)0xdeadbea0);
   1188 	assert(!radix_tree_empty_tree_p(t));
   1189 	radix_tree_dump(t);
   1190 	assert(radix_tree_lookup_node(t, 0) == NULL);
   1191 	assert(radix_tree_lookup_node(t, 1000) == (void *)0xdeadbea0);
   1192 	memset(results, 0, sizeof(results));
   1193 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, false) == 1);
   1194 	assert(results[0] == (void *)0xdeadbea0);
   1195 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, true) == 0);
   1196 	memset(results, 0, sizeof(results));
   1197 	assert(radix_tree_gang_lookup_node(t, 1000, results, 3, false) == 1);
   1198 	assert(results[0] == (void *)0xdeadbea0);
   1199 	memset(results, 0, sizeof(results));
   1200 	assert(radix_tree_gang_lookup_node(t, 1000, results, 3, true) == 1);
   1201 	assert(results[0] == (void *)0xdeadbea0);
   1202 	assert(radix_tree_gang_lookup_node_reverse(t, 0, results, 3, false)
   1203 	    == 0);
   1204 	assert(radix_tree_gang_lookup_node_reverse(t, 0, results, 3, true)
   1205 	    == 0);
   1206 	memset(results, 0, sizeof(results));
   1207 	assert(radix_tree_gang_lookup_node_reverse(t, 1000, results, 3, false)
   1208 	    == 1);
   1209 	memset(results, 0, sizeof(results));
   1210 	assert(radix_tree_gang_lookup_node_reverse(t, 1000, results, 3, true)
   1211 	    == 1);
   1212 	assert(results[0] == (void *)0xdeadbea0);
   1213 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 3, false, 1)
   1214 	    == 0);
   1215 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 3, true, 1)
   1216 	    == 0);
   1217 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 0, results, 3,
   1218 	    false, 1) == 0);
   1219 	assert(radix_tree_gang_lookup_tagged_node_reverse(t, 0, results, 3,
   1220 	    true, 1) == 0);
   1221 	assert(!radix_tree_get_tag(t, 1000, 1));
   1222 	assert(!radix_tree_get_tag(t, 1000, 2));
   1223 	assert(radix_tree_get_tag(t, 1000, 2 | 1) == 0);
   1224 	assert(radix_tree_empty_tagged_tree_p(t, 1));
   1225 	assert(radix_tree_empty_tagged_tree_p(t, 2));
   1226 	radix_tree_set_tag(t, 1000, 2);
   1227 	assert(!radix_tree_get_tag(t, 1000, 1));
   1228 	assert(radix_tree_get_tag(t, 1000, 2));
   1229 	assert(radix_tree_get_tag(t, 1000, 2 | 1) == 2);
   1230 	assert(radix_tree_empty_tagged_tree_p(t, 1));
   1231 	assert(!radix_tree_empty_tagged_tree_p(t, 2));
   1232 	radix_tree_dump(t);
   1233 	assert(radix_tree_lookup_node(t, 1000) == (void *)0xdeadbea0);
   1234 	assert(radix_tree_insert_node(t, 0, (void *)0xbea0) == 0);
   1235 	radix_tree_dump(t);
   1236 	assert(radix_tree_lookup_node(t, 0) == (void *)0xbea0);
   1237 	assert(radix_tree_lookup_node(t, 1000) == (void *)0xdeadbea0);
   1238 	assert(radix_tree_insert_node(t, UINT64_C(10000000000), (void *)0xdea0)
   1239 	    == 0);
   1240 	radix_tree_dump(t);
   1241 	assert(radix_tree_lookup_node(t, 0) == (void *)0xbea0);
   1242 	assert(radix_tree_lookup_node(t, 1000) == (void *)0xdeadbea0);
   1243 	assert(radix_tree_lookup_node(t, UINT64_C(10000000000)) ==
   1244 	    (void *)0xdea0);
   1245 	radix_tree_dump(t);
   1246 	assert(!radix_tree_get_tag(t, 0, 2));
   1247 	assert(radix_tree_get_tag(t, 1000, 2));
   1248 	assert(!radix_tree_get_tag(t, UINT64_C(10000000000), 1));
   1249 	radix_tree_set_tag(t, 0, 2);;
   1250 	radix_tree_set_tag(t, UINT64_C(10000000000), 2);
   1251 	radix_tree_dump(t);
   1252 	assert(radix_tree_get_tag(t, 0, 2));
   1253 	assert(radix_tree_get_tag(t, 1000, 2));
   1254 	assert(radix_tree_get_tag(t, UINT64_C(10000000000), 2));
   1255 	radix_tree_clear_tag(t, 0, 2);;
   1256 	radix_tree_clear_tag(t, UINT64_C(10000000000), 2);
   1257 	radix_tree_dump(t);
   1258 	assert(!radix_tree_get_tag(t, 0, 2));
   1259 	assert(radix_tree_get_tag(t, 1000, 2));
   1260 	assert(!radix_tree_get_tag(t, UINT64_C(10000000000), 2));
   1261 	radix_tree_dump(t);
   1262 	assert(radix_tree_replace_node(t, 1000, (void *)0x12345678) ==
   1263 	    (void *)0xdeadbea0);
   1264 	assert(!radix_tree_get_tag(t, 1000, 1));
   1265 	assert(radix_tree_get_tag(t, 1000, 2));
   1266 	assert(radix_tree_get_tag(t, 1000, 2 | 1) == 2);
   1267 	memset(results, 0, sizeof(results));
   1268 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, false) == 3);
   1269 	assert(results[0] == (void *)0xbea0);
   1270 	assert(results[1] == (void *)0x12345678);
   1271 	assert(results[2] == (void *)0xdea0);
   1272 	memset(results, 0, sizeof(results));
   1273 	assert(radix_tree_gang_lookup_node(t, 0, results, 3, true) == 1);
   1274 	assert(results[0] == (void *)0xbea0);
   1275 	memset(results, 0, sizeof(results));
   1276 	assert(radix_tree_gang_lookup_node(t, 1, results, 3, false) == 2);
   1277 	assert(results[0] == (void *)0x12345678);
   1278 	assert(results[1] == (void *)0xdea0);
   1279 	assert(radix_tree_gang_lookup_node(t, 1, results, 3, true) == 0);
   1280 	memset(results, 0, sizeof(results));
   1281 	assert(radix_tree_gang_lookup_node(t, 1001, results, 3, false) == 1);
   1282 	assert(results[0] == (void *)0xdea0);
   1283 	assert(radix_tree_gang_lookup_node(t, 1001, results, 3, true) == 0);
   1284 	assert(radix_tree_gang_lookup_node(t, UINT64_C(10000000001), results, 3,
   1285 	    false) == 0);
   1286 	assert(radix_tree_gang_lookup_node(t, UINT64_C(10000000001), results, 3,
   1287 	    true) == 0);
   1288 	assert(radix_tree_gang_lookup_node(t, UINT64_C(1000000000000), results,
   1289 	    3, false) == 0);
   1290 	assert(radix_tree_gang_lookup_node(t, UINT64_C(1000000000000), results,
   1291 	    3, true) == 0);
   1292 	memset(results, 0, sizeof(results));
   1293 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 100, false, 2)
   1294 	    == 1);
   1295 	assert(results[0] == (void *)0x12345678);
   1296 	assert(radix_tree_gang_lookup_tagged_node(t, 0, results, 100, true, 2)
   1297 	    == 0);
   1298 	assert(entry_tagmask(t->t_root) != 0);
   1299 	assert(radix_tree_remove_node(t, 1000) == (void *)0x12345678);
   1300 	assert(entry_tagmask(t->t_root) == 0);
   1301 	radix_tree_dump(t);
   1302 	assert(radix_tree_insert_node(t, UINT64_C(10000000001), (void *)0xfff0)
   1303 	    == 0);
   1304 	memset(results, 0, sizeof(results));
   1305 	assert(radix_tree_gang_lookup_node(t, UINT64_C(10000000000), results, 3,
   1306 	    false) == 2);
   1307 	assert(results[0] == (void *)0xdea0);
   1308 	assert(results[1] == (void *)0xfff0);
   1309 	memset(results, 0, sizeof(results));
   1310 	assert(radix_tree_gang_lookup_node(t, UINT64_C(10000000000), results, 3,
   1311 	    true) == 2);
   1312 	assert(results[0] == (void *)0xdea0);
   1313 	assert(results[1] == (void *)0xfff0);
   1314 	memset(results, 0, sizeof(results));
   1315 	assert(radix_tree_gang_lookup_node_reverse(t, UINT64_C(10000000001),
   1316 	    results, 3, false) == 3);
   1317 	assert(results[0] == (void *)0xfff0);
   1318 	assert(results[1] == (void *)0xdea0);
   1319 	assert(results[2] == (void *)0xbea0);
   1320 	memset(results, 0, sizeof(results));
   1321 	assert(radix_tree_gang_lookup_node_reverse(t, UINT64_C(10000000001),
   1322 	    results, 3, true) == 2);
   1323 	assert(results[0] == (void *)0xfff0);
   1324 	assert(results[1] == (void *)0xdea0);
   1325 	assert(radix_tree_remove_node(t, UINT64_C(10000000000)) ==
   1326 	    (void *)0xdea0);
   1327 	assert(radix_tree_remove_node(t, UINT64_C(10000000001)) ==
   1328 	    (void *)0xfff0);
   1329 	radix_tree_dump(t);
   1330 	assert(radix_tree_remove_node(t, 0) == (void *)0xbea0);
   1331 	radix_tree_dump(t);
   1332 	radix_tree_fini_tree(t);
   1333 }
   1334 
   1335 #include <sys/time.h>
   1336 
   1337 struct testnode {
   1338 	uint64_t idx;
   1339 	bool tagged[RADIX_TREE_TAG_ID_MAX];
   1340 };
   1341 
   1342 static void
   1343 printops(const char *title, const char *name, int tag, unsigned int n,
   1344     const struct timeval *stv, const struct timeval *etv)
   1345 {
   1346 	uint64_t s = stv->tv_sec * 1000000 + stv->tv_usec;
   1347 	uint64_t e = etv->tv_sec * 1000000 + etv->tv_usec;
   1348 
   1349 	printf("RESULT %s %s %d %lf op/s\n", title, name, tag,
   1350 	    (double)n / (e - s) * 1000000);
   1351 }
   1352 
   1353 #define	TEST2_GANG_LOOKUP_NODES	16
   1354 
   1355 static bool
   1356 test2_should_tag(unsigned int i, unsigned int tagid)
   1357 {
   1358 
   1359 	if (tagid == 0) {
   1360 		return (i % 4) == 0;	/* 25% */
   1361 	} else {
   1362 		return (i % 7) == 0;	/* 14% */
   1363 	}
   1364 	return 1;
   1365 }
   1366 
   1367 static void
   1368 check_tag_count(const unsigned int *ntagged, unsigned int tagmask,
   1369     unsigned int count)
   1370 {
   1371 	unsigned int tag;
   1372 
   1373 	for (tag = 0; tag < RADIX_TREE_TAG_ID_MAX; tag++) {
   1374 		if ((tagmask & (1 << tag)) == 0) {
   1375 			continue;
   1376 		}
   1377 		if (((tagmask - 1) & tagmask) == 0) {
   1378 			assert(count == ntagged[tag]);
   1379 		} else {
   1380 			assert(count >= ntagged[tag]);
   1381 		}
   1382 	}
   1383 }
   1384 
   1385 static void
   1386 test2(const char *title, bool dense)
   1387 {
   1388 	struct radix_tree s;
   1389 	struct radix_tree *t = &s;
   1390 	struct testnode *n;
   1391 	unsigned int i;
   1392 	unsigned int nnodes = 100000;
   1393 	unsigned int removed;
   1394 	unsigned int tag;
   1395 	unsigned int tagmask;
   1396 	unsigned int ntagged[RADIX_TREE_TAG_ID_MAX];
   1397 	struct testnode *nodes;
   1398 	struct timeval stv;
   1399 	struct timeval etv;
   1400 
   1401 	nodes = malloc(nnodes * sizeof(*nodes));
   1402 	for (tag = 0; tag < RADIX_TREE_TAG_ID_MAX; tag++) {
   1403 		ntagged[tag] = 0;
   1404 	}
   1405 	radix_tree_init_tree(t);
   1406 	for (i = 0; i < nnodes; i++) {
   1407 		n = &nodes[i];
   1408 		n->idx = random();
   1409 		if (sizeof(long) == 4) {
   1410 			n->idx <<= 32;
   1411 			n->idx |= (uint32_t)random();
   1412 		}
   1413 		if (dense) {
   1414 			n->idx %= nnodes * 2;
   1415 		}
   1416 		while (radix_tree_lookup_node(t, n->idx) != NULL) {
   1417 			n->idx++;
   1418 		}
   1419 		radix_tree_insert_node(t, n->idx, n);
   1420 		for (tag = 0; tag < RADIX_TREE_TAG_ID_MAX; tag++) {
   1421 			tagmask = 1 << tag;
   1422 
   1423 			n->tagged[tag] = test2_should_tag(i, tag);
   1424 			if (n->tagged[tag]) {
   1425 				radix_tree_set_tag(t, n->idx, tagmask);
   1426 				ntagged[tag]++;
   1427 			}
   1428 			assert((n->tagged[tag] ? tagmask : 0) ==
   1429 			    radix_tree_get_tag(t, n->idx, tagmask));
   1430 		}
   1431 	}
   1432 
   1433 	gettimeofday(&stv, NULL);
   1434 	for (i = 0; i < nnodes; i++) {
   1435 		n = &nodes[i];
   1436 		assert(radix_tree_lookup_node(t, n->idx) == n);
   1437 	}
   1438 	gettimeofday(&etv, NULL);
   1439 	printops(title, "lookup", 0, nnodes, &stv, &etv);
   1440 
   1441 	for (tagmask = 1; tagmask <= RADIX_TREE_TAG_MASK; tagmask ++) {
   1442 		unsigned int count = 0;
   1443 
   1444 		gettimeofday(&stv, NULL);
   1445 		for (i = 0; i < nnodes; i++) {
   1446 			unsigned int tagged;
   1447 
   1448 			n = &nodes[i];
   1449 			tagged = radix_tree_get_tag(t, n->idx, tagmask);
   1450 			assert((tagged & ~tagmask) == 0);
   1451 			for (tag = 0; tag < RADIX_TREE_TAG_ID_MAX; tag++) {
   1452 				assert((tagmask & (1 << tag)) == 0 ||
   1453 				    n->tagged[tag] == !!(tagged & (1 << tag)));
   1454 			}
   1455 			if (tagged) {
   1456 				count++;
   1457 			}
   1458 		}
   1459 		gettimeofday(&etv, NULL);
   1460 		check_tag_count(ntagged, tagmask, count);
   1461 		printops(title, "get_tag", tagmask, nnodes, &stv, &etv);
   1462 	}
   1463 
   1464 	gettimeofday(&stv, NULL);
   1465 	for (i = 0; i < nnodes; i++) {
   1466 		n = &nodes[i];
   1467 		radix_tree_remove_node(t, n->idx);
   1468 	}
   1469 	gettimeofday(&etv, NULL);
   1470 	printops(title, "remove", 0, nnodes, &stv, &etv);
   1471 
   1472 	gettimeofday(&stv, NULL);
   1473 	for (i = 0; i < nnodes; i++) {
   1474 		n = &nodes[i];
   1475 		radix_tree_insert_node(t, n->idx, n);
   1476 	}
   1477 	gettimeofday(&etv, NULL);
   1478 	printops(title, "insert", 0, nnodes, &stv, &etv);
   1479 
   1480 	for (tag = 0; tag < RADIX_TREE_TAG_ID_MAX; tag++) {
   1481 		tagmask = 1 << tag;
   1482 
   1483 		ntagged[tag] = 0;
   1484 		gettimeofday(&stv, NULL);
   1485 		for (i = 0; i < nnodes; i++) {
   1486 			n = &nodes[i];
   1487 			if (n->tagged[tag]) {
   1488 				radix_tree_set_tag(t, n->idx, tagmask);
   1489 				ntagged[tag]++;
   1490 			}
   1491 		}
   1492 		gettimeofday(&etv, NULL);
   1493 		printops(title, "set_tag", tag, ntagged[tag], &stv, &etv);
   1494 	}
   1495 
   1496 	gettimeofday(&stv, NULL);
   1497 	{
   1498 		struct testnode *results[TEST2_GANG_LOOKUP_NODES];
   1499 		uint64_t nextidx;
   1500 		unsigned int nfound;
   1501 		unsigned int total;
   1502 
   1503 		nextidx = 0;
   1504 		total = 0;
   1505 		while ((nfound = radix_tree_gang_lookup_node(t, nextidx,
   1506 		    (void *)results, __arraycount(results), false)) > 0) {
   1507 			nextidx = results[nfound - 1]->idx + 1;
   1508 			total += nfound;
   1509 			if (nextidx == 0) {
   1510 				break;
   1511 			}
   1512 		}
   1513 		assert(total == nnodes);
   1514 	}
   1515 	gettimeofday(&etv, NULL);
   1516 	printops(title, "ganglookup", 0, nnodes, &stv, &etv);
   1517 
   1518 	gettimeofday(&stv, NULL);
   1519 	{
   1520 		struct testnode *results[TEST2_GANG_LOOKUP_NODES];
   1521 		uint64_t nextidx;
   1522 		unsigned int nfound;
   1523 		unsigned int total;
   1524 
   1525 		nextidx = UINT64_MAX;
   1526 		total = 0;
   1527 		while ((nfound = radix_tree_gang_lookup_node_reverse(t, nextidx,
   1528 		    (void *)results, __arraycount(results), false)) > 0) {
   1529 			nextidx = results[nfound - 1]->idx - 1;
   1530 			total += nfound;
   1531 			if (nextidx == UINT64_MAX) {
   1532 				break;
   1533 			}
   1534 		}
   1535 		assert(total == nnodes);
   1536 	}
   1537 	gettimeofday(&etv, NULL);
   1538 	printops(title, "ganglookup_reverse", 0, nnodes, &stv, &etv);
   1539 
   1540 	for (tagmask = 1; tagmask <= RADIX_TREE_TAG_MASK; tagmask ++) {
   1541 		unsigned int total = 0;
   1542 
   1543 		gettimeofday(&stv, NULL);
   1544 		{
   1545 			struct testnode *results[TEST2_GANG_LOOKUP_NODES];
   1546 			uint64_t nextidx;
   1547 			unsigned int nfound;
   1548 
   1549 			nextidx = 0;
   1550 			while ((nfound = radix_tree_gang_lookup_tagged_node(t,
   1551 			    nextidx, (void *)results, __arraycount(results),
   1552 			    false, tagmask)) > 0) {
   1553 				nextidx = results[nfound - 1]->idx + 1;
   1554 				total += nfound;
   1555 			}
   1556 		}
   1557 		gettimeofday(&etv, NULL);
   1558 		check_tag_count(ntagged, tagmask, total);
   1559 		assert(tagmask != 0 || total == 0);
   1560 		printops(title, "ganglookup_tag", tagmask, total, &stv, &etv);
   1561 	}
   1562 
   1563 	for (tagmask = 1; tagmask <= RADIX_TREE_TAG_MASK; tagmask ++) {
   1564 		unsigned int total = 0;
   1565 
   1566 		gettimeofday(&stv, NULL);
   1567 		{
   1568 			struct testnode *results[TEST2_GANG_LOOKUP_NODES];
   1569 			uint64_t nextidx;
   1570 			unsigned int nfound;
   1571 
   1572 			nextidx = UINT64_MAX;
   1573 			while ((nfound =
   1574 			    radix_tree_gang_lookup_tagged_node_reverse(t,
   1575 			    nextidx, (void *)results, __arraycount(results),
   1576 			    false, tagmask)) > 0) {
   1577 				nextidx = results[nfound - 1]->idx - 1;
   1578 				total += nfound;
   1579 				if (nextidx == UINT64_MAX) {
   1580 					break;
   1581 				}
   1582 			}
   1583 		}
   1584 		gettimeofday(&etv, NULL);
   1585 		check_tag_count(ntagged, tagmask, total);
   1586 		assert(tagmask != 0 || total == 0);
   1587 		printops(title, "ganglookup_tag_reverse", tagmask, total,
   1588 		    &stv, &etv);
   1589 	}
   1590 
   1591 	removed = 0;
   1592 	for (tag = 0; tag < RADIX_TREE_TAG_ID_MAX; tag++) {
   1593 		unsigned int total;
   1594 
   1595 		total = 0;
   1596 		tagmask = 1 << tag;
   1597 		gettimeofday(&stv, NULL);
   1598 		{
   1599 			struct testnode *results[TEST2_GANG_LOOKUP_NODES];
   1600 			uint64_t nextidx;
   1601 			unsigned int nfound;
   1602 
   1603 			nextidx = 0;
   1604 			while ((nfound = radix_tree_gang_lookup_tagged_node(t,
   1605 			    nextidx, (void *)results, __arraycount(results),
   1606 			    false, tagmask)) > 0) {
   1607 				for (i = 0; i < nfound; i++) {
   1608 					radix_tree_remove_node(t,
   1609 					    results[i]->idx);
   1610 				}
   1611 				nextidx = results[nfound - 1]->idx + 1;
   1612 				total += nfound;
   1613 				if (nextidx == 0) {
   1614 					break;
   1615 				}
   1616 			}
   1617 		}
   1618 		gettimeofday(&etv, NULL);
   1619 		if (tag == 0) {
   1620 			check_tag_count(ntagged, tagmask, total);
   1621 		} else {
   1622 			assert(total <= ntagged[tag]);
   1623 		}
   1624 		printops(title, "ganglookup_tag+remove", tagmask, total, &stv,
   1625 		    &etv);
   1626 		removed += total;
   1627 	}
   1628 
   1629 	gettimeofday(&stv, NULL);
   1630 	{
   1631 		struct testnode *results[TEST2_GANG_LOOKUP_NODES];
   1632 		uint64_t nextidx;
   1633 		unsigned int nfound;
   1634 		unsigned int total;
   1635 
   1636 		nextidx = 0;
   1637 		total = 0;
   1638 		while ((nfound = radix_tree_gang_lookup_node(t, nextidx,
   1639 		    (void *)results, __arraycount(results), false)) > 0) {
   1640 			for (i = 0; i < nfound; i++) {
   1641 				assert(results[i] == radix_tree_remove_node(t,
   1642 				    results[i]->idx));
   1643 			}
   1644 			nextidx = results[nfound - 1]->idx + 1;
   1645 			total += nfound;
   1646 			if (nextidx == 0) {
   1647 				break;
   1648 			}
   1649 		}
   1650 		assert(total == nnodes - removed);
   1651 	}
   1652 	gettimeofday(&etv, NULL);
   1653 	printops(title, "ganglookup+remove", 0, nnodes - removed, &stv, &etv);
   1654 
   1655 	assert(radix_tree_empty_tree_p(t));
   1656 	for (tagmask = 1; tagmask <= RADIX_TREE_TAG_MASK; tagmask ++) {
   1657 		assert(radix_tree_empty_tagged_tree_p(t, tagmask));
   1658 	}
   1659 	radix_tree_fini_tree(t);
   1660 	free(nodes);
   1661 }
   1662 
   1663 int
   1664 main(int argc, char *argv[])
   1665 {
   1666 
   1667 	test1();
   1668 	test2("dense", true);
   1669 	test2("sparse", false);
   1670 	return 0;
   1671 }
   1672 
   1673 #endif /* defined(UNITTEST) */
   1674