Home | History | Annotate | Line # | Download | only in gen
rb.c revision 1.14
      1 /*	$NetBSD: rb.c,v 1.14 2019/03/08 09:14:54 roy Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Matt Thomas <matt (at) 3am-software.com>.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #if !defined(_KERNEL) && !defined(_STANDALONE)
     33 #include <sys/types.h>
     34 #include <stddef.h>
     35 #include <assert.h>
     36 #include <stdbool.h>
     37 #ifdef RBDEBUG
     38 #define	KASSERT(s)	assert(s)
     39 #define	__rbt_unused
     40 #else
     41 #define KASSERT(s)	do { } while (/*CONSTCOND*/ 0)
     42 #define	__rbt_unused	__unused
     43 #endif
     44 __RCSID("$NetBSD: rb.c,v 1.14 2019/03/08 09:14:54 roy Exp $");
     45 #else
     46 #include <lib/libkern/libkern.h>
     47 __KERNEL_RCSID(0, "$NetBSD: rb.c,v 1.14 2019/03/08 09:14:54 roy Exp $");
     48 #ifndef DIAGNOSTIC
     49 #define	__rbt_unused	__unused
     50 #else
     51 #define	__rbt_unused
     52 #endif
     53 #endif
     54 
     55 #ifdef _LIBC
     56 __weak_alias(rb_tree_init, _rb_tree_init)
     57 __weak_alias(rb_tree_find_node, _rb_tree_find_node)
     58 __weak_alias(rb_tree_find_node_geq, _rb_tree_find_node_geq)
     59 __weak_alias(rb_tree_find_node_leq, _rb_tree_find_node_leq)
     60 __weak_alias(rb_tree_insert_node, _rb_tree_insert_node)
     61 __weak_alias(rb_tree_remove_node, _rb_tree_remove_node)
     62 __weak_alias(rb_tree_iterate, _rb_tree_iterate)
     63 #ifdef RBDEBUG
     64 __weak_alias(rb_tree_check, _rb_tree_check)
     65 __weak_alias(rb_tree_depths, _rb_tree_depths)
     66 #endif
     67 
     68 #include "namespace.h"
     69 #endif
     70 
     71 #ifdef RBTEST
     72 #include "rbtree.h"
     73 #else
     74 #include <sys/rbtree.h>
     75 #endif
     76 
     77 static void rb_tree_insert_rebalance(struct rb_tree *, struct rb_node *);
     78 static void rb_tree_removal_rebalance(struct rb_tree *, struct rb_node *,
     79 	unsigned int);
     80 #ifdef RBDEBUG
     81 static const struct rb_node *rb_tree_iterate_const(const struct rb_tree *,
     82 	const struct rb_node *, const unsigned int);
     83 static bool rb_tree_check_node(const struct rb_tree *, const struct rb_node *,
     84 	const struct rb_node *, bool);
     85 #else
     86 #define	rb_tree_check_node(a, b, c, d)	true
     87 #endif
     88 
     89 #define	RB_NODETOITEM(rbto, rbn)	\
     90     ((void *)((uintptr_t)(rbn) - (rbto)->rbto_node_offset))
     91 #define	RB_ITEMTONODE(rbto, rbn)	\
     92     ((rb_node_t *)((uintptr_t)(rbn) + (rbto)->rbto_node_offset))
     93 
     94 #define	RB_SENTINEL_NODE	NULL
     95 
     96 void
     97 rb_tree_init(struct rb_tree *rbt, const rb_tree_ops_t *ops)
     98 {
     99 
    100 	rbt->rbt_ops = ops;
    101 	rbt->rbt_root = RB_SENTINEL_NODE;
    102 	RB_TAILQ_INIT(&rbt->rbt_nodes);
    103 #ifndef RBSMALL
    104 	rbt->rbt_minmax[RB_DIR_LEFT] = rbt->rbt_root;	/* minimum node */
    105 	rbt->rbt_minmax[RB_DIR_RIGHT] = rbt->rbt_root;	/* maximum node */
    106 #endif
    107 #ifdef RBSTATS
    108 	rbt->rbt_count = 0;
    109 	rbt->rbt_insertions = 0;
    110 	rbt->rbt_removals = 0;
    111 	rbt->rbt_insertion_rebalance_calls = 0;
    112 	rbt->rbt_insertion_rebalance_passes = 0;
    113 	rbt->rbt_removal_rebalance_calls = 0;
    114 	rbt->rbt_removal_rebalance_passes = 0;
    115 #endif
    116 }
    117 
    118 void *
    119 rb_tree_find_node(struct rb_tree *rbt, const void *key)
    120 {
    121 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
    122 	rbto_compare_key_fn compare_key = rbto->rbto_compare_key;
    123 	struct rb_node *parent = rbt->rbt_root;
    124 
    125 	while (!RB_SENTINEL_P(parent)) {
    126 		void *pobj = RB_NODETOITEM(rbto, parent);
    127 		const signed int diff = (*compare_key)(rbto->rbto_context,
    128 		    pobj, key);
    129 		if (diff == 0)
    130 			return pobj;
    131 		parent = parent->rb_nodes[diff < 0];
    132 	}
    133 
    134 	return NULL;
    135 }
    136 
    137 void *
    138 rb_tree_find_node_geq(struct rb_tree *rbt, const void *key)
    139 {
    140 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
    141 	rbto_compare_key_fn compare_key = rbto->rbto_compare_key;
    142 	struct rb_node *parent = rbt->rbt_root, *last = NULL;
    143 
    144 	while (!RB_SENTINEL_P(parent)) {
    145 		void *pobj = RB_NODETOITEM(rbto, parent);
    146 		const signed int diff = (*compare_key)(rbto->rbto_context,
    147 		    pobj, key);
    148 		if (diff == 0)
    149 			return pobj;
    150 		if (diff > 0)
    151 			last = parent;
    152 		parent = parent->rb_nodes[diff < 0];
    153 	}
    154 
    155 	return last == NULL ? NULL : RB_NODETOITEM(rbto, last);
    156 }
    157 
    158 void *
    159 rb_tree_find_node_leq(struct rb_tree *rbt, const void *key)
    160 {
    161 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
    162 	rbto_compare_key_fn compare_key = rbto->rbto_compare_key;
    163 	struct rb_node *parent = rbt->rbt_root, *last = NULL;
    164 
    165 	while (!RB_SENTINEL_P(parent)) {
    166 		void *pobj = RB_NODETOITEM(rbto, parent);
    167 		const signed int diff = (*compare_key)(rbto->rbto_context,
    168 		    pobj, key);
    169 		if (diff == 0)
    170 			return pobj;
    171 		if (diff < 0)
    172 			last = parent;
    173 		parent = parent->rb_nodes[diff < 0];
    174 	}
    175 
    176 	return last == NULL ? NULL : RB_NODETOITEM(rbto, last);
    177 }
    178 
    179 void *
    180 rb_tree_insert_node(struct rb_tree *rbt, void *object)
    181 {
    182 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
    183 	rbto_compare_nodes_fn compare_nodes = rbto->rbto_compare_nodes;
    184 	struct rb_node *parent, *tmp, *self = RB_ITEMTONODE(rbto, object);
    185 	unsigned int position;
    186 	bool rebalance;
    187 
    188 	RBSTAT_INC(rbt->rbt_insertions);
    189 
    190 	tmp = rbt->rbt_root;
    191 	/*
    192 	 * This is a hack.  Because rbt->rbt_root is just a struct rb_node *,
    193 	 * just like rb_node->rb_nodes[RB_DIR_LEFT], we can use this fact to
    194 	 * avoid a lot of tests for root and know that even at root,
    195 	 * updating RB_FATHER(rb_node)->rb_nodes[RB_POSITION(rb_node)] will
    196 	 * update rbt->rbt_root.
    197 	 */
    198 	parent = (struct rb_node *)(void *)&rbt->rbt_root;
    199 	position = RB_DIR_LEFT;
    200 
    201 	/*
    202 	 * Find out where to place this new leaf.
    203 	 */
    204 	while (!RB_SENTINEL_P(tmp)) {
    205 		void *tobj = RB_NODETOITEM(rbto, tmp);
    206 		const signed int diff = (*compare_nodes)(rbto->rbto_context,
    207 		    tobj, object);
    208 		if (__predict_false(diff == 0)) {
    209 			/*
    210 			 * Node already exists; return it.
    211 			 */
    212 			return tobj;
    213 		}
    214 		parent = tmp;
    215 		position = (diff < 0);
    216 		tmp = parent->rb_nodes[position];
    217 	}
    218 
    219 #ifdef RBDEBUG
    220 	{
    221 		struct rb_node *prev = NULL, *next = NULL;
    222 
    223 		if (position == RB_DIR_RIGHT)
    224 			prev = parent;
    225 		else if (tmp != rbt->rbt_root)
    226 			next = parent;
    227 
    228 		/*
    229 		 * Verify our sequential position
    230 		 */
    231 		KASSERT(prev == NULL || !RB_SENTINEL_P(prev));
    232 		KASSERT(next == NULL || !RB_SENTINEL_P(next));
    233 		if (prev != NULL && next == NULL)
    234 			next = TAILQ_NEXT(prev, rb_link);
    235 		if (prev == NULL && next != NULL)
    236 			prev = TAILQ_PREV(next, rb_node_qh, rb_link);
    237 		KASSERT(prev == NULL || !RB_SENTINEL_P(prev));
    238 		KASSERT(next == NULL || !RB_SENTINEL_P(next));
    239 		KASSERT(prev == NULL || (*compare_nodes)(rbto->rbto_context,
    240 		    RB_NODETOITEM(rbto, prev), RB_NODETOITEM(rbto, self)) < 0);
    241 		KASSERT(next == NULL || (*compare_nodes)(rbto->rbto_context,
    242 		    RB_NODETOITEM(rbto, self), RB_NODETOITEM(rbto, next)) < 0);
    243 	}
    244 #endif
    245 
    246 	/*
    247 	 * Initialize the node and insert as a leaf into the tree.
    248 	 */
    249 	RB_SET_FATHER(self, parent);
    250 	RB_SET_POSITION(self, position);
    251 	if (__predict_false(parent == (struct rb_node *)(void *)&rbt->rbt_root)) {
    252 		RB_MARK_BLACK(self);		/* root is always black */
    253 #ifndef RBSMALL
    254 		rbt->rbt_minmax[RB_DIR_LEFT] = self;
    255 		rbt->rbt_minmax[RB_DIR_RIGHT] = self;
    256 #endif
    257 		rebalance = false;
    258 	} else {
    259 		KASSERT(position == RB_DIR_LEFT || position == RB_DIR_RIGHT);
    260 #ifndef RBSMALL
    261 		/*
    262 		 * Keep track of the minimum and maximum nodes.  If our
    263 		 * parent is a minmax node and we on their min/max side,
    264 		 * we must be the new min/max node.
    265 		 */
    266 		if (parent == rbt->rbt_minmax[position])
    267 			rbt->rbt_minmax[position] = self;
    268 #endif /* !RBSMALL */
    269 		/*
    270 		 * All new nodes are colored red.  We only need to rebalance
    271 		 * if our parent is also red.
    272 		 */
    273 		RB_MARK_RED(self);
    274 		rebalance = RB_RED_P(parent);
    275 	}
    276 	KASSERT(RB_SENTINEL_P(parent->rb_nodes[position]));
    277 	self->rb_left = parent->rb_nodes[position];
    278 	self->rb_right = parent->rb_nodes[position];
    279 	parent->rb_nodes[position] = self;
    280 	KASSERT(RB_CHILDLESS_P(self));
    281 
    282 	/*
    283 	 * Insert the new node into a sorted list for easy sequential access
    284 	 */
    285 	RBSTAT_INC(rbt->rbt_count);
    286 #ifdef RBDEBUG
    287 	if (RB_ROOT_P(rbt, self)) {
    288 		RB_TAILQ_INSERT_HEAD(&rbt->rbt_nodes, self, rb_link);
    289 	} else if (position == RB_DIR_LEFT) {
    290 		KASSERT((*compare_nodes)(rbto->rbto_context,
    291 		    RB_NODETOITEM(rbto, self),
    292 		    RB_NODETOITEM(rbto, RB_FATHER(self))) < 0);
    293 		RB_TAILQ_INSERT_BEFORE(RB_FATHER(self), self, rb_link);
    294 	} else {
    295 		KASSERT((*compare_nodes)(rbto->rbto_context,
    296 		    RB_NODETOITEM(rbto, RB_FATHER(self)),
    297 		    RB_NODETOITEM(rbto, self)) < 0);
    298 		RB_TAILQ_INSERT_AFTER(&rbt->rbt_nodes, RB_FATHER(self),
    299 		    self, rb_link);
    300 	}
    301 #endif
    302 	KASSERT(rb_tree_check_node(rbt, self, NULL, !rebalance));
    303 
    304 	/*
    305 	 * Rebalance tree after insertion
    306 	 */
    307 	if (rebalance) {
    308 		rb_tree_insert_rebalance(rbt, self);
    309 		KASSERT(rb_tree_check_node(rbt, self, NULL, true));
    310 	}
    311 
    312 	/* Succesfully inserted, return our node pointer. */
    313 	return object;
    314 }
    315 
    316 /*
    317  * Swap the location and colors of 'self' and its child @ which.  The child
    318  * can not be a sentinel node.  This is our rotation function.  However,
    319  * since it preserves coloring, it great simplifies both insertion and
    320  * removal since rotation almost always involves the exchanging of colors
    321  * as a separate step.
    322  */
    323 static void
    324 rb_tree_reparent_nodes(__rbt_unused struct rb_tree *rbt,
    325 	struct rb_node *old_father, const unsigned int which)
    326 {
    327 	const unsigned int other = which ^ RB_DIR_OTHER;
    328 	struct rb_node * const grandpa = RB_FATHER(old_father);
    329 	struct rb_node * const old_child = old_father->rb_nodes[which];
    330 	struct rb_node * const new_father = old_child;
    331 	struct rb_node * const new_child = old_father;
    332 
    333 	KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
    334 
    335 	KASSERT(!RB_SENTINEL_P(old_child));
    336 	KASSERT(RB_FATHER(old_child) == old_father);
    337 
    338 	KASSERT(rb_tree_check_node(rbt, old_father, NULL, false));
    339 	KASSERT(rb_tree_check_node(rbt, old_child, NULL, false));
    340 	KASSERT(RB_ROOT_P(rbt, old_father) ||
    341 	    rb_tree_check_node(rbt, grandpa, NULL, false));
    342 
    343 	/*
    344 	 * Exchange descendant linkages.
    345 	 */
    346 	grandpa->rb_nodes[RB_POSITION(old_father)] = new_father;
    347 	new_child->rb_nodes[which] = old_child->rb_nodes[other];
    348 	new_father->rb_nodes[other] = new_child;
    349 
    350 	/*
    351 	 * Update ancestor linkages
    352 	 */
    353 	RB_SET_FATHER(new_father, grandpa);
    354 	RB_SET_FATHER(new_child, new_father);
    355 
    356 	/*
    357 	 * Exchange properties between new_father and new_child.  The only
    358 	 * change is that new_child's position is now on the other side.
    359 	 */
    360 #if 0
    361 	{
    362 		struct rb_node tmp;
    363 		tmp.rb_info = 0;
    364 		RB_COPY_PROPERTIES(&tmp, old_child);
    365 		RB_COPY_PROPERTIES(new_father, old_father);
    366 		RB_COPY_PROPERTIES(new_child, &tmp);
    367 	}
    368 #else
    369 	RB_SWAP_PROPERTIES(new_father, new_child);
    370 #endif
    371 	RB_SET_POSITION(new_child, other);
    372 
    373 	/*
    374 	 * Make sure to reparent the new child to ourself.
    375 	 */
    376 	if (!RB_SENTINEL_P(new_child->rb_nodes[which])) {
    377 		RB_SET_FATHER(new_child->rb_nodes[which], new_child);
    378 		RB_SET_POSITION(new_child->rb_nodes[which], which);
    379 	}
    380 
    381 	KASSERT(rb_tree_check_node(rbt, new_father, NULL, false));
    382 	KASSERT(rb_tree_check_node(rbt, new_child, NULL, false));
    383 	KASSERT(RB_ROOT_P(rbt, new_father) ||
    384 	    rb_tree_check_node(rbt, grandpa, NULL, false));
    385 }
    386 
    387 static void
    388 rb_tree_insert_rebalance(struct rb_tree *rbt, struct rb_node *self)
    389 {
    390 	struct rb_node * father = RB_FATHER(self);
    391 	struct rb_node * grandpa = RB_FATHER(father);
    392 	struct rb_node * uncle;
    393 	unsigned int which;
    394 	unsigned int other;
    395 
    396 	KASSERT(!RB_ROOT_P(rbt, self));
    397 	KASSERT(RB_RED_P(self));
    398 	KASSERT(RB_RED_P(father));
    399 	RBSTAT_INC(rbt->rbt_insertion_rebalance_calls);
    400 
    401 	for (;;) {
    402 		KASSERT(!RB_SENTINEL_P(self));
    403 
    404 		KASSERT(RB_RED_P(self));
    405 		KASSERT(RB_RED_P(father));
    406 		/*
    407 		 * We are red and our parent is red, therefore we must have a
    408 		 * grandfather and he must be black.
    409 		 */
    410 		grandpa = RB_FATHER(father);
    411 		KASSERT(RB_BLACK_P(grandpa));
    412 		KASSERT(RB_DIR_RIGHT == 1 && RB_DIR_LEFT == 0);
    413 		which = (father == grandpa->rb_right);
    414 		other = which ^ RB_DIR_OTHER;
    415 		uncle = grandpa->rb_nodes[other];
    416 
    417 		if (RB_BLACK_P(uncle))
    418 			break;
    419 
    420 		RBSTAT_INC(rbt->rbt_insertion_rebalance_passes);
    421 		/*
    422 		 * Case 1: our uncle is red
    423 		 *   Simply invert the colors of our parent and
    424 		 *   uncle and make our grandparent red.  And
    425 		 *   then solve the problem up at his level.
    426 		 */
    427 		RB_MARK_BLACK(uncle);
    428 		RB_MARK_BLACK(father);
    429 		if (__predict_false(RB_ROOT_P(rbt, grandpa))) {
    430 			/*
    431 			 * If our grandpa is root, don't bother
    432 			 * setting him to red, just return.
    433 			 */
    434 			KASSERT(RB_BLACK_P(grandpa));
    435 			return;
    436 		}
    437 		RB_MARK_RED(grandpa);
    438 		self = grandpa;
    439 		father = RB_FATHER(self);
    440 		KASSERT(RB_RED_P(self));
    441 		if (RB_BLACK_P(father)) {
    442 			/*
    443 			 * If our greatgrandpa is black, we're done.
    444 			 */
    445 			KASSERT(RB_BLACK_P(rbt->rbt_root));
    446 			return;
    447 		}
    448 	}
    449 
    450 	KASSERT(!RB_ROOT_P(rbt, self));
    451 	KASSERT(RB_RED_P(self));
    452 	KASSERT(RB_RED_P(father));
    453 	KASSERT(RB_BLACK_P(uncle));
    454 	KASSERT(RB_BLACK_P(grandpa));
    455 	/*
    456 	 * Case 2&3: our uncle is black.
    457 	 */
    458 	if (self == father->rb_nodes[other]) {
    459 		/*
    460 		 * Case 2: we are on the same side as our uncle
    461 		 *   Swap ourselves with our parent so this case
    462 		 *   becomes case 3.  Basically our parent becomes our
    463 		 *   child.
    464 		 */
    465 		rb_tree_reparent_nodes(rbt, father, other);
    466 		KASSERT(RB_FATHER(father) == self);
    467 		KASSERT(self->rb_nodes[which] == father);
    468 		KASSERT(RB_FATHER(self) == grandpa);
    469 		self = father;
    470 		father = RB_FATHER(self);
    471 	}
    472 	KASSERT(RB_RED_P(self) && RB_RED_P(father));
    473 	KASSERT(grandpa->rb_nodes[which] == father);
    474 	/*
    475 	 * Case 3: we are opposite a child of a black uncle.
    476 	 *   Swap our parent and grandparent.  Since our grandfather
    477 	 *   is black, our father will become black and our new sibling
    478 	 *   (former grandparent) will become red.
    479 	 */
    480 	rb_tree_reparent_nodes(rbt, grandpa, which);
    481 	KASSERT(RB_FATHER(self) == father);
    482 	KASSERT(RB_FATHER(self)->rb_nodes[RB_POSITION(self) ^ RB_DIR_OTHER] == grandpa);
    483 	KASSERT(RB_RED_P(self));
    484 	KASSERT(RB_BLACK_P(father));
    485 	KASSERT(RB_RED_P(grandpa));
    486 
    487 	/*
    488 	 * Final step: Set the root to black.
    489 	 */
    490 	RB_MARK_BLACK(rbt->rbt_root);
    491 }
    492 
    493 static void
    494 rb_tree_prune_node(struct rb_tree *rbt, struct rb_node *self, bool rebalance)
    495 {
    496 	const unsigned int which = RB_POSITION(self);
    497 	struct rb_node *father = RB_FATHER(self);
    498 #ifndef RBSMALL
    499 	const bool was_root = RB_ROOT_P(rbt, self);
    500 #endif
    501 
    502 	KASSERT(rebalance || (RB_ROOT_P(rbt, self) || RB_RED_P(self)));
    503 	KASSERT(!rebalance || RB_BLACK_P(self));
    504 	KASSERT(RB_CHILDLESS_P(self));
    505 	KASSERT(rb_tree_check_node(rbt, self, NULL, false));
    506 
    507 	/*
    508 	 * Since we are childless, we know that self->rb_left is pointing
    509 	 * to the sentinel node.
    510 	 */
    511 	father->rb_nodes[which] = self->rb_left;
    512 
    513 	/*
    514 	 * Remove ourselves from the node list, decrement the count,
    515 	 * and update min/max.
    516 	 */
    517 	RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
    518 	RBSTAT_DEC(rbt->rbt_count);
    519 #ifndef RBSMALL
    520 	if (__predict_false(rbt->rbt_minmax[RB_POSITION(self)] == self)) {
    521 		rbt->rbt_minmax[RB_POSITION(self)] = father;
    522 		/*
    523 		 * When removing the root, rbt->rbt_minmax[RB_DIR_LEFT] is
    524 		 * updated automatically, but we also need to update
    525 		 * rbt->rbt_minmax[RB_DIR_RIGHT];
    526 		 */
    527 		if (__predict_false(was_root)) {
    528 			rbt->rbt_minmax[RB_DIR_RIGHT] = father;
    529 		}
    530 	}
    531 	RB_SET_FATHER(self, NULL);
    532 #endif
    533 
    534 	/*
    535 	 * Rebalance if requested.
    536 	 */
    537 	if (rebalance)
    538 		rb_tree_removal_rebalance(rbt, father, which);
    539 	KASSERT(was_root || rb_tree_check_node(rbt, father, NULL, true));
    540 }
    541 
    542 /*
    543  * When deleting an interior node
    544  */
    545 static void
    546 rb_tree_swap_prune_and_rebalance(struct rb_tree *rbt, struct rb_node *self,
    547 	struct rb_node *standin)
    548 {
    549 	const unsigned int standin_which = RB_POSITION(standin);
    550 	unsigned int standin_other = standin_which ^ RB_DIR_OTHER;
    551 	struct rb_node *standin_son;
    552 	struct rb_node *standin_father = RB_FATHER(standin);
    553 	bool rebalance = RB_BLACK_P(standin);
    554 
    555 	if (standin_father == self) {
    556 		/*
    557 		 * As a child of self, any childen would be opposite of
    558 		 * our parent.
    559 		 */
    560 		KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_other]));
    561 		standin_son = standin->rb_nodes[standin_which];
    562 	} else {
    563 		/*
    564 		 * Since we aren't a child of self, any childen would be
    565 		 * on the same side as our parent.
    566 		 */
    567 		KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_which]));
    568 		standin_son = standin->rb_nodes[standin_other];
    569 	}
    570 
    571 	/*
    572 	 * the node we are removing must have two children.
    573 	 */
    574 	KASSERT(RB_TWOCHILDREN_P(self));
    575 	/*
    576 	 * If standin has a child, it must be red.
    577 	 */
    578 	KASSERT(RB_SENTINEL_P(standin_son) || RB_RED_P(standin_son));
    579 
    580 	/*
    581 	 * Verify things are sane.
    582 	 */
    583 	KASSERT(rb_tree_check_node(rbt, self, NULL, false));
    584 	KASSERT(rb_tree_check_node(rbt, standin, NULL, false));
    585 
    586 	if (__predict_false(RB_RED_P(standin_son))) {
    587 		/*
    588 		 * We know we have a red child so if we flip it to black
    589 		 * we don't have to rebalance.
    590 		 */
    591 		KASSERT(rb_tree_check_node(rbt, standin_son, NULL, true));
    592 		RB_MARK_BLACK(standin_son);
    593 		rebalance = false;
    594 
    595 		if (standin_father == self) {
    596 			KASSERT(RB_POSITION(standin_son) == standin_which);
    597 		} else {
    598 			KASSERT(RB_POSITION(standin_son) == standin_other);
    599 			/*
    600 			 * Change the son's parentage to point to his grandpa.
    601 			 */
    602 			RB_SET_FATHER(standin_son, standin_father);
    603 			RB_SET_POSITION(standin_son, standin_which);
    604 		}
    605 	}
    606 
    607 	if (standin_father == self) {
    608 		/*
    609 		 * If we are about to delete the standin's father, then when
    610 		 * we call rebalance, we need to use ourselves as our father.
    611 		 * Otherwise remember our original father.  Also, sincef we are
    612 		 * our standin's father we only need to reparent the standin's
    613 		 * brother.
    614 		 *
    615 		 * |    R      -->     S    |
    616 		 * |  Q   S    -->   Q   T  |
    617 		 * |        t  -->          |
    618 		 */
    619 		KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_other]));
    620 		KASSERT(!RB_SENTINEL_P(self->rb_nodes[standin_other]));
    621 		KASSERT(self->rb_nodes[standin_which] == standin);
    622 		/*
    623 		 * Have our son/standin adopt his brother as his new son.
    624 		 */
    625 		standin_father = standin;
    626 	} else {
    627 		/*
    628 		 * |    R          -->    S       .  |
    629 		 * |   / \  |   T  -->   / \  |  /   |
    630 		 * |  ..... | S    -->  ..... | T    |
    631 		 *
    632 		 * Sever standin's connection to his father.
    633 		 */
    634 		standin_father->rb_nodes[standin_which] = standin_son;
    635 		/*
    636 		 * Adopt the far son.
    637 		 */
    638 		standin->rb_nodes[standin_other] = self->rb_nodes[standin_other];
    639 		RB_SET_FATHER(standin->rb_nodes[standin_other], standin);
    640 		KASSERT(RB_POSITION(self->rb_nodes[standin_other]) == standin_other);
    641 		/*
    642 		 * Use standin_other because we need to preserve standin_which
    643 		 * for the removal_rebalance.
    644 		 */
    645 		standin_other = standin_which;
    646 	}
    647 
    648 	/*
    649 	 * Move the only remaining son to our standin.  If our standin is our
    650 	 * son, this will be the only son needed to be moved.
    651 	 */
    652 	KASSERT(standin->rb_nodes[standin_other] != self->rb_nodes[standin_other]);
    653 	standin->rb_nodes[standin_other] = self->rb_nodes[standin_other];
    654 	RB_SET_FATHER(standin->rb_nodes[standin_other], standin);
    655 
    656 	/*
    657 	 * Now copy the result of self to standin and then replace
    658 	 * self with standin in the tree.
    659 	 */
    660 	RB_COPY_PROPERTIES(standin, self);
    661 	RB_SET_FATHER(standin, RB_FATHER(self));
    662 	RB_FATHER(standin)->rb_nodes[RB_POSITION(standin)] = standin;
    663 
    664 	/*
    665 	 * Remove ourselves from the node list, decrement the count,
    666 	 * and update min/max.
    667 	 */
    668 	RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
    669 	RBSTAT_DEC(rbt->rbt_count);
    670 #ifndef RBSMALL
    671 	if (__predict_false(rbt->rbt_minmax[RB_POSITION(self)] == self))
    672 		rbt->rbt_minmax[RB_POSITION(self)] = RB_FATHER(self);
    673 	RB_SET_FATHER(self, NULL);
    674 #endif
    675 
    676 	KASSERT(rb_tree_check_node(rbt, standin, NULL, false));
    677 	KASSERT(RB_FATHER_SENTINEL_P(standin)
    678 		|| rb_tree_check_node(rbt, standin_father, NULL, false));
    679 	KASSERT(RB_LEFT_SENTINEL_P(standin)
    680 		|| rb_tree_check_node(rbt, standin->rb_left, NULL, false));
    681 	KASSERT(RB_RIGHT_SENTINEL_P(standin)
    682 		|| rb_tree_check_node(rbt, standin->rb_right, NULL, false));
    683 
    684 	if (!rebalance)
    685 		return;
    686 
    687 	rb_tree_removal_rebalance(rbt, standin_father, standin_which);
    688 	KASSERT(rb_tree_check_node(rbt, standin, NULL, true));
    689 }
    690 
    691 /*
    692  * We could do this by doing
    693  *	rb_tree_node_swap(rbt, self, which);
    694  *	rb_tree_prune_node(rbt, self, false);
    695  *
    696  * But it's more efficient to just evalate and recolor the child.
    697  */
    698 static void
    699 rb_tree_prune_blackred_branch(struct rb_tree *rbt, struct rb_node *self,
    700 	unsigned int which)
    701 {
    702 	struct rb_node *father = RB_FATHER(self);
    703 	struct rb_node *son = self->rb_nodes[which];
    704 #ifndef RBSMALL
    705 	const bool was_root = RB_ROOT_P(rbt, self);
    706 #endif
    707 
    708 	KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
    709 	KASSERT(RB_BLACK_P(self) && RB_RED_P(son));
    710 	KASSERT(!RB_TWOCHILDREN_P(son));
    711 	KASSERT(RB_CHILDLESS_P(son));
    712 	KASSERT(rb_tree_check_node(rbt, self, NULL, false));
    713 	KASSERT(rb_tree_check_node(rbt, son, NULL, false));
    714 
    715 	/*
    716 	 * Remove ourselves from the tree and give our former child our
    717 	 * properties (position, color, root).
    718 	 */
    719 	RB_COPY_PROPERTIES(son, self);
    720 	father->rb_nodes[RB_POSITION(son)] = son;
    721 	RB_SET_FATHER(son, father);
    722 
    723 	/*
    724 	 * Remove ourselves from the node list, decrement the count,
    725 	 * and update minmax.
    726 	 */
    727 	RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
    728 	RBSTAT_DEC(rbt->rbt_count);
    729 #ifndef RBSMALL
    730 	if (__predict_false(was_root)) {
    731 		KASSERT(rbt->rbt_minmax[which] == son);
    732 		rbt->rbt_minmax[which ^ RB_DIR_OTHER] = son;
    733 	} else if (rbt->rbt_minmax[RB_POSITION(self)] == self) {
    734 		rbt->rbt_minmax[RB_POSITION(self)] = son;
    735 	}
    736 	RB_SET_FATHER(self, NULL);
    737 #endif
    738 
    739 	KASSERT(was_root || rb_tree_check_node(rbt, father, NULL, true));
    740 	KASSERT(rb_tree_check_node(rbt, son, NULL, true));
    741 }
    742 
    743 void
    744 rb_tree_remove_node(struct rb_tree *rbt, void *object)
    745 {
    746 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
    747 	struct rb_node *standin, *self = RB_ITEMTONODE(rbto, object);
    748 	unsigned int which;
    749 
    750 	KASSERT(!RB_SENTINEL_P(self));
    751 	RBSTAT_INC(rbt->rbt_removals);
    752 
    753 	/*
    754 	 * In the following diagrams, we (the node to be removed) are S.  Red
    755 	 * nodes are lowercase.  T could be either red or black.
    756 	 *
    757 	 * Remember the major axiom of the red-black tree: the number of
    758 	 * black nodes from the root to each leaf is constant across all
    759 	 * leaves, only the number of red nodes varies.
    760 	 *
    761 	 * Thus removing a red leaf doesn't require any other changes to a
    762 	 * red-black tree.  So if we must remove a node, attempt to rearrange
    763 	 * the tree so we can remove a red node.
    764 	 *
    765 	 * The simpliest case is a childless red node or a childless root node:
    766 	 *
    767 	 * |    T  -->    T  |    or    |  R  -->  *  |
    768 	 * |  s    -->  *    |
    769 	 */
    770 	if (RB_CHILDLESS_P(self)) {
    771 		const bool rebalance = RB_BLACK_P(self) && !RB_ROOT_P(rbt, self);
    772 		rb_tree_prune_node(rbt, self, rebalance);
    773 		return;
    774 	}
    775 	KASSERT(!RB_CHILDLESS_P(self));
    776 	if (!RB_TWOCHILDREN_P(self)) {
    777 		/*
    778 		 * The next simpliest case is the node we are deleting is
    779 		 * black and has one red child.
    780 		 *
    781 		 * |      T  -->      T  -->      T  |
    782 		 * |    S    -->  R      -->  R      |
    783 		 * |  r      -->    s    -->    *    |
    784 		 */
    785 		which = RB_LEFT_SENTINEL_P(self) ? RB_DIR_RIGHT : RB_DIR_LEFT;
    786 		KASSERT(RB_BLACK_P(self));
    787 		KASSERT(RB_RED_P(self->rb_nodes[which]));
    788 		KASSERT(RB_CHILDLESS_P(self->rb_nodes[which]));
    789 		rb_tree_prune_blackred_branch(rbt, self, which);
    790 		return;
    791 	}
    792 	KASSERT(RB_TWOCHILDREN_P(self));
    793 
    794 	/*
    795 	 * We invert these because we prefer to remove from the inside of
    796 	 * the tree.
    797 	 */
    798 	which = RB_POSITION(self) ^ RB_DIR_OTHER;
    799 
    800 	/*
    801 	 * Let's find the node closes to us opposite of our parent
    802 	 * Now swap it with ourself, "prune" it, and rebalance, if needed.
    803 	 */
    804 	standin = RB_ITEMTONODE(rbto, rb_tree_iterate(rbt, object, which));
    805 	rb_tree_swap_prune_and_rebalance(rbt, self, standin);
    806 }
    807 
    808 static void
    809 rb_tree_removal_rebalance(struct rb_tree *rbt, struct rb_node *parent,
    810 	unsigned int which)
    811 {
    812 	KASSERT(!RB_SENTINEL_P(parent));
    813 	KASSERT(RB_SENTINEL_P(parent->rb_nodes[which]));
    814 	KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
    815 	RBSTAT_INC(rbt->rbt_removal_rebalance_calls);
    816 
    817 	while (RB_BLACK_P(parent->rb_nodes[which])) {
    818 		unsigned int other = which ^ RB_DIR_OTHER;
    819 		struct rb_node *brother = parent->rb_nodes[other];
    820 
    821 		RBSTAT_INC(rbt->rbt_removal_rebalance_passes);
    822 
    823 		KASSERT(!RB_SENTINEL_P(brother));
    824 		/*
    825 		 * For cases 1, 2a, and 2b, our brother's children must
    826 		 * be black and our father must be black
    827 		 */
    828 		if (RB_BLACK_P(parent)
    829 		    && RB_BLACK_P(brother->rb_left)
    830 		    && RB_BLACK_P(brother->rb_right)) {
    831 			if (RB_RED_P(brother)) {
    832 				/*
    833 				 * Case 1: Our brother is red, swap its
    834 				 * position (and colors) with our parent.
    835 				 * This should now be case 2b (unless C or E
    836 				 * has a red child which is case 3; thus no
    837 				 * explicit branch to case 2b).
    838 				 *
    839 				 *    B         ->        D
    840 				 *  A     d     ->    b     E
    841 				 *      C   E   ->  A   C
    842 				 */
    843 				KASSERT(RB_BLACK_P(parent));
    844 				rb_tree_reparent_nodes(rbt, parent, other);
    845 				brother = parent->rb_nodes[other];
    846 				KASSERT(!RB_SENTINEL_P(brother));
    847 				KASSERT(RB_RED_P(parent));
    848 				KASSERT(RB_BLACK_P(brother));
    849 				KASSERT(rb_tree_check_node(rbt, brother, NULL, false));
    850 				KASSERT(rb_tree_check_node(rbt, parent, NULL, false));
    851 			} else {
    852 				/*
    853 				 * Both our parent and brother are black.
    854 				 * Change our brother to red, advance up rank
    855 				 * and go through the loop again.
    856 				 *
    857 				 *    B         ->   *B
    858 				 * *A     D     ->  A     d
    859 				 *      C   E   ->      C   E
    860 				 */
    861 				RB_MARK_RED(brother);
    862 				KASSERT(RB_BLACK_P(brother->rb_left));
    863 				KASSERT(RB_BLACK_P(brother->rb_right));
    864 				if (RB_ROOT_P(rbt, parent))
    865 					return;	/* root == parent == black */
    866 				KASSERT(rb_tree_check_node(rbt, brother, NULL, false));
    867 				KASSERT(rb_tree_check_node(rbt, parent, NULL, false));
    868 				which = RB_POSITION(parent);
    869 				parent = RB_FATHER(parent);
    870 				continue;
    871 			}
    872 		}
    873 		/*
    874 		 * Avoid an else here so that case 2a above can hit either
    875 		 * case 2b, 3, or 4.
    876 		 */
    877 		if (RB_RED_P(parent)
    878 		    && RB_BLACK_P(brother)
    879 		    && RB_BLACK_P(brother->rb_left)
    880 		    && RB_BLACK_P(brother->rb_right)) {
    881 			KASSERT(RB_RED_P(parent));
    882 			KASSERT(RB_BLACK_P(brother));
    883 			KASSERT(RB_BLACK_P(brother->rb_left));
    884 			KASSERT(RB_BLACK_P(brother->rb_right));
    885 			/*
    886 			 * We are black, our father is red, our brother and
    887 			 * both nephews are black.  Simply invert/exchange the
    888 			 * colors of our father and brother (to black and red
    889 			 * respectively).
    890 			 *
    891 			 *	|    f        -->    F        |
    892 			 *	|  *     B    -->  *     b    |
    893 			 *	|      N   N  -->      N   N  |
    894 			 */
    895 			RB_MARK_BLACK(parent);
    896 			RB_MARK_RED(brother);
    897 			KASSERT(rb_tree_check_node(rbt, brother, NULL, true));
    898 			break;		/* We're done! */
    899 		} else {
    900 			/*
    901 			 * Our brother must be black and have at least one
    902 			 * red child (it may have two).
    903 			 */
    904 			KASSERT(RB_BLACK_P(brother));
    905 			KASSERT(RB_RED_P(brother->rb_nodes[which]) ||
    906 				RB_RED_P(brother->rb_nodes[other]));
    907 			if (RB_BLACK_P(brother->rb_nodes[other])) {
    908 				/*
    909 				 * Case 3: our brother is black, our near
    910 				 * nephew is red, and our far nephew is black.
    911 				 * Swap our brother with our near nephew.
    912 				 * This result in a tree that matches case 4.
    913 				 * (Our father could be red or black).
    914 				 *
    915 				 *	|    F      -->    F      |
    916 				 *	|  x     B  -->  x   B    |
    917 				 *	|      n    -->        n  |
    918 				 */
    919 				KASSERT(RB_RED_P(brother->rb_nodes[which]));
    920 				rb_tree_reparent_nodes(rbt, brother, which);
    921 				KASSERT(RB_FATHER(brother) == parent->rb_nodes[other]);
    922 				brother = parent->rb_nodes[other];
    923 				KASSERT(RB_RED_P(brother->rb_nodes[other]));
    924 			}
    925 			/*
    926 			 * Case 4: our brother is black and our far nephew
    927 			 * is red.  Swap our father and brother locations and
    928 			 * change our far nephew to black.  (these can be
    929 			 * done in either order so we change the color first).
    930 			 * The result is a valid red-black tree and is a
    931 			 * terminal case.  (again we don't care about the
    932 			 * father's color)
    933 			 *
    934 			 * If the father is red, we will get a red-black-black
    935 			 * tree:
    936 			 *	|  f      ->  f      -->    b    |
    937 			 *	|    B    ->    B    -->  F   N  |
    938 			 *	|      n  ->      N  -->         |
    939 			 *
    940 			 * If the father is black, we will get an all black
    941 			 * tree:
    942 			 *	|  F      ->  F      -->    B    |
    943 			 *	|    B    ->    B    -->  F   N  |
    944 			 *	|      n  ->      N  -->         |
    945 			 *
    946 			 * If we had two red nephews, then after the swap,
    947 			 * our former father would have a red grandson.
    948 			 */
    949 			KASSERT(RB_BLACK_P(brother));
    950 			KASSERT(RB_RED_P(brother->rb_nodes[other]));
    951 			RB_MARK_BLACK(brother->rb_nodes[other]);
    952 			rb_tree_reparent_nodes(rbt, parent, other);
    953 			break;		/* We're done! */
    954 		}
    955 	}
    956 	KASSERT(rb_tree_check_node(rbt, parent, NULL, true));
    957 }
    958 
    959 void *
    960 rb_tree_iterate(struct rb_tree *rbt, void *object, const unsigned int direction)
    961 {
    962 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
    963 	const unsigned int other = direction ^ RB_DIR_OTHER;
    964 	struct rb_node *self;
    965 
    966 	KASSERT(direction == RB_DIR_LEFT || direction == RB_DIR_RIGHT);
    967 
    968 	if (object == NULL) {
    969 #ifndef RBSMALL
    970 		if (RB_SENTINEL_P(rbt->rbt_root))
    971 			return NULL;
    972 		return RB_NODETOITEM(rbto, rbt->rbt_minmax[direction]);
    973 #else
    974 		self = rbt->rbt_root;
    975 		if (RB_SENTINEL_P(self))
    976 			return NULL;
    977 		while (!RB_SENTINEL_P(self->rb_nodes[direction]))
    978 			self = self->rb_nodes[direction];
    979 		return RB_NODETOITEM(rbto, self);
    980 #endif /* !RBSMALL */
    981 	}
    982 	self = RB_ITEMTONODE(rbto, object);
    983 	KASSERT(!RB_SENTINEL_P(self));
    984 	/*
    985 	 * We can't go any further in this direction.  We proceed up in the
    986 	 * opposite direction until our parent is in direction we want to go.
    987 	 */
    988 	if (RB_SENTINEL_P(self->rb_nodes[direction])) {
    989 		while (!RB_ROOT_P(rbt, self)) {
    990 			if (other == RB_POSITION(self))
    991 				return RB_NODETOITEM(rbto, RB_FATHER(self));
    992 			self = RB_FATHER(self);
    993 		}
    994 		return NULL;
    995 	}
    996 
    997 	/*
    998 	 * Advance down one in current direction and go down as far as possible
    999 	 * in the opposite direction.
   1000 	 */
   1001 	self = self->rb_nodes[direction];
   1002 	KASSERT(!RB_SENTINEL_P(self));
   1003 	while (!RB_SENTINEL_P(self->rb_nodes[other]))
   1004 		self = self->rb_nodes[other];
   1005 	return RB_NODETOITEM(rbto, self);
   1006 }
   1007 
   1008 #ifdef RBDEBUG
   1009 static const struct rb_node *
   1010 rb_tree_iterate_const(const struct rb_tree *rbt, const struct rb_node *self,
   1011 	const unsigned int direction)
   1012 {
   1013 	const unsigned int other = direction ^ RB_DIR_OTHER;
   1014 	KASSERT(direction == RB_DIR_LEFT || direction == RB_DIR_RIGHT);
   1015 
   1016 	if (self == NULL) {
   1017 #ifndef RBSMALL
   1018 		if (RB_SENTINEL_P(rbt->rbt_root))
   1019 			return NULL;
   1020 		return rbt->rbt_minmax[direction];
   1021 #else
   1022 		self = rbt->rbt_root;
   1023 		if (RB_SENTINEL_P(self))
   1024 			return NULL;
   1025 		while (!RB_SENTINEL_P(self->rb_nodes[direction]))
   1026 			self = self->rb_nodes[direction];
   1027 		return self;
   1028 #endif /* !RBSMALL */
   1029 	}
   1030 	KASSERT(!RB_SENTINEL_P(self));
   1031 	/*
   1032 	 * We can't go any further in this direction.  We proceed up in the
   1033 	 * opposite direction until our parent is in direction we want to go.
   1034 	 */
   1035 	if (RB_SENTINEL_P(self->rb_nodes[direction])) {
   1036 		while (!RB_ROOT_P(rbt, self)) {
   1037 			if (other == RB_POSITION(self))
   1038 				return RB_FATHER(self);
   1039 			self = RB_FATHER(self);
   1040 		}
   1041 		return NULL;
   1042 	}
   1043 
   1044 	/*
   1045 	 * Advance down one in current direction and go down as far as possible
   1046 	 * in the opposite direction.
   1047 	 */
   1048 	self = self->rb_nodes[direction];
   1049 	KASSERT(!RB_SENTINEL_P(self));
   1050 	while (!RB_SENTINEL_P(self->rb_nodes[other]))
   1051 		self = self->rb_nodes[other];
   1052 	return self;
   1053 }
   1054 
   1055 static unsigned int
   1056 rb_tree_count_black(const struct rb_node *self)
   1057 {
   1058 	unsigned int left, right;
   1059 
   1060 	if (RB_SENTINEL_P(self))
   1061 		return 0;
   1062 
   1063 	left = rb_tree_count_black(self->rb_left);
   1064 	right = rb_tree_count_black(self->rb_right);
   1065 
   1066 	KASSERT(left == right);
   1067 
   1068 	return left + RB_BLACK_P(self);
   1069 }
   1070 
   1071 static bool
   1072 rb_tree_check_node(const struct rb_tree *rbt, const struct rb_node *self,
   1073 	const struct rb_node *prev, bool red_check)
   1074 {
   1075 	const rb_tree_ops_t *rbto = rbt->rbt_ops;
   1076 	rbto_compare_nodes_fn compare_nodes = rbto->rbto_compare_nodes;
   1077 
   1078 	KASSERT(!RB_SENTINEL_P(self));
   1079 	KASSERT(prev == NULL || (*compare_nodes)(rbto->rbto_context,
   1080 	    RB_NODETOITEM(rbto, prev), RB_NODETOITEM(rbto, self)) < 0);
   1081 
   1082 	/*
   1083 	 * Verify our relationship to our parent.
   1084 	 */
   1085 	if (RB_ROOT_P(rbt, self)) {
   1086 		KASSERT(self == rbt->rbt_root);
   1087 		KASSERT(RB_POSITION(self) == RB_DIR_LEFT);
   1088 		KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_LEFT] == self);
   1089 		KASSERT(RB_FATHER(self) == (const struct rb_node *) &rbt->rbt_root);
   1090 	} else {
   1091 		int diff = (*compare_nodes)(rbto->rbto_context,
   1092 		    RB_NODETOITEM(rbto, self),
   1093 		    RB_NODETOITEM(rbto, RB_FATHER(self)));
   1094 
   1095 		KASSERT(self != rbt->rbt_root);
   1096 		KASSERT(!RB_FATHER_SENTINEL_P(self));
   1097 		if (RB_POSITION(self) == RB_DIR_LEFT) {
   1098 			KASSERT(diff < 0);
   1099 			KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_LEFT] == self);
   1100 		} else {
   1101 			KASSERT(diff > 0);
   1102 			KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_RIGHT] == self);
   1103 		}
   1104 	}
   1105 
   1106 	/*
   1107 	 * Verify our position in the linked list against the tree itself.
   1108 	 */
   1109 	{
   1110 		const struct rb_node *prev0 = rb_tree_iterate_const(rbt, self, RB_DIR_LEFT);
   1111 		const struct rb_node *next0 = rb_tree_iterate_const(rbt, self, RB_DIR_RIGHT);
   1112 		KASSERT(prev0 == TAILQ_PREV(self, rb_node_qh, rb_link));
   1113 		KASSERT(next0 == TAILQ_NEXT(self, rb_link));
   1114 #ifndef RBSMALL
   1115 		KASSERT(prev0 != NULL || self == rbt->rbt_minmax[RB_DIR_LEFT]);
   1116 		KASSERT(next0 != NULL || self == rbt->rbt_minmax[RB_DIR_RIGHT]);
   1117 #endif
   1118 	}
   1119 
   1120 	/*
   1121 	 * The root must be black.
   1122 	 * There can never be two adjacent red nodes.
   1123 	 */
   1124 	if (red_check) {
   1125 		KASSERT(!RB_ROOT_P(rbt, self) || RB_BLACK_P(self));
   1126 		(void) rb_tree_count_black(self);
   1127 		if (RB_RED_P(self)) {
   1128 			const struct rb_node *brother;
   1129 			KASSERT(!RB_ROOT_P(rbt, self));
   1130 			brother = RB_FATHER(self)->rb_nodes[RB_POSITION(self) ^ RB_DIR_OTHER];
   1131 			KASSERT(RB_BLACK_P(RB_FATHER(self)));
   1132 			/*
   1133 			 * I'm red and have no children, then I must either
   1134 			 * have no brother or my brother also be red and
   1135 			 * also have no children.  (black count == 0)
   1136 			 */
   1137 			KASSERT(!RB_CHILDLESS_P(self)
   1138 				|| RB_SENTINEL_P(brother)
   1139 				|| RB_RED_P(brother)
   1140 				|| RB_CHILDLESS_P(brother));
   1141 			/*
   1142 			 * If I'm not childless, I must have two children
   1143 			 * and they must be both be black.
   1144 			 */
   1145 			KASSERT(RB_CHILDLESS_P(self)
   1146 				|| (RB_TWOCHILDREN_P(self)
   1147 				    && RB_BLACK_P(self->rb_left)
   1148 				    && RB_BLACK_P(self->rb_right)));
   1149 			/*
   1150 			 * If I'm not childless, thus I have black children,
   1151 			 * then my brother must either be black or have two
   1152 			 * black children.
   1153 			 */
   1154 			KASSERT(RB_CHILDLESS_P(self)
   1155 				|| RB_BLACK_P(brother)
   1156 				|| (RB_TWOCHILDREN_P(brother)
   1157 				    && RB_BLACK_P(brother->rb_left)
   1158 				    && RB_BLACK_P(brother->rb_right)));
   1159 		} else {
   1160 			/*
   1161 			 * If I'm black and have one child, that child must
   1162 			 * be red and childless.
   1163 			 */
   1164 			KASSERT(RB_CHILDLESS_P(self)
   1165 				|| RB_TWOCHILDREN_P(self)
   1166 				|| (!RB_LEFT_SENTINEL_P(self)
   1167 				    && RB_RIGHT_SENTINEL_P(self)
   1168 				    && RB_RED_P(self->rb_left)
   1169 				    && RB_CHILDLESS_P(self->rb_left))
   1170 				|| (!RB_RIGHT_SENTINEL_P(self)
   1171 				    && RB_LEFT_SENTINEL_P(self)
   1172 				    && RB_RED_P(self->rb_right)
   1173 				    && RB_CHILDLESS_P(self->rb_right)));
   1174 
   1175 			/*
   1176 			 * If I'm a childless black node and my parent is
   1177 			 * black, my 2nd closet relative away from my parent
   1178 			 * is either red or has a red parent or red children.
   1179 			 */
   1180 			if (!RB_ROOT_P(rbt, self)
   1181 			    && RB_CHILDLESS_P(self)
   1182 			    && RB_BLACK_P(RB_FATHER(self))) {
   1183 				const unsigned int which = RB_POSITION(self);
   1184 				const unsigned int other = which ^ RB_DIR_OTHER;
   1185 				const struct rb_node *relative0, *relative;
   1186 
   1187 				relative0 = rb_tree_iterate_const(rbt,
   1188 				    self, other);
   1189 				KASSERT(relative0 != NULL);
   1190 				relative = rb_tree_iterate_const(rbt,
   1191 				    relative0, other);
   1192 				KASSERT(relative != NULL);
   1193 				KASSERT(RB_SENTINEL_P(relative->rb_nodes[which]));
   1194 #if 0
   1195 				KASSERT(RB_RED_P(relative)
   1196 					|| RB_RED_P(relative->rb_left)
   1197 					|| RB_RED_P(relative->rb_right)
   1198 					|| RB_RED_P(RB_FATHER(relative)));
   1199 #endif
   1200 			}
   1201 		}
   1202 		/*
   1203 		 * A grandparent's children must be real nodes and not
   1204 		 * sentinels.  First check out grandparent.
   1205 		 */
   1206 		KASSERT(RB_ROOT_P(rbt, self)
   1207 			|| RB_ROOT_P(rbt, RB_FATHER(self))
   1208 			|| RB_TWOCHILDREN_P(RB_FATHER(RB_FATHER(self))));
   1209 		/*
   1210 		 * If we are have grandchildren on our left, then
   1211 		 * we must have a child on our right.
   1212 		 */
   1213 		KASSERT(RB_LEFT_SENTINEL_P(self)
   1214 			|| RB_CHILDLESS_P(self->rb_left)
   1215 			|| !RB_RIGHT_SENTINEL_P(self));
   1216 		/*
   1217 		 * If we are have grandchildren on our right, then
   1218 		 * we must have a child on our left.
   1219 		 */
   1220 		KASSERT(RB_RIGHT_SENTINEL_P(self)
   1221 			|| RB_CHILDLESS_P(self->rb_right)
   1222 			|| !RB_LEFT_SENTINEL_P(self));
   1223 
   1224 		/*
   1225 		 * If we have a child on the left and it doesn't have two
   1226 		 * children make sure we don't have great-great-grandchildren on
   1227 		 * the right.
   1228 		 */
   1229 		KASSERT(RB_TWOCHILDREN_P(self->rb_left)
   1230 			|| RB_CHILDLESS_P(self->rb_right)
   1231 			|| RB_CHILDLESS_P(self->rb_right->rb_left)
   1232 			|| RB_CHILDLESS_P(self->rb_right->rb_left->rb_left)
   1233 			|| RB_CHILDLESS_P(self->rb_right->rb_left->rb_right)
   1234 			|| RB_CHILDLESS_P(self->rb_right->rb_right)
   1235 			|| RB_CHILDLESS_P(self->rb_right->rb_right->rb_left)
   1236 			|| RB_CHILDLESS_P(self->rb_right->rb_right->rb_right));
   1237 
   1238 		/*
   1239 		 * If we have a child on the right and it doesn't have two
   1240 		 * children make sure we don't have great-great-grandchildren on
   1241 		 * the left.
   1242 		 */
   1243 		KASSERT(RB_TWOCHILDREN_P(self->rb_right)
   1244 			|| RB_CHILDLESS_P(self->rb_left)
   1245 			|| RB_CHILDLESS_P(self->rb_left->rb_left)
   1246 			|| RB_CHILDLESS_P(self->rb_left->rb_left->rb_left)
   1247 			|| RB_CHILDLESS_P(self->rb_left->rb_left->rb_right)
   1248 			|| RB_CHILDLESS_P(self->rb_left->rb_right)
   1249 			|| RB_CHILDLESS_P(self->rb_left->rb_right->rb_left)
   1250 			|| RB_CHILDLESS_P(self->rb_left->rb_right->rb_right));
   1251 
   1252 		/*
   1253 		 * If we are fully interior node, then our predecessors and
   1254 		 * successors must have no children in our direction.
   1255 		 */
   1256 		if (RB_TWOCHILDREN_P(self)) {
   1257 			const struct rb_node *prev0;
   1258 			const struct rb_node *next0;
   1259 
   1260 			prev0 = rb_tree_iterate_const(rbt, self, RB_DIR_LEFT);
   1261 			KASSERT(prev0 != NULL);
   1262 			KASSERT(RB_RIGHT_SENTINEL_P(prev0));
   1263 
   1264 			next0 = rb_tree_iterate_const(rbt, self, RB_DIR_RIGHT);
   1265 			KASSERT(next0 != NULL);
   1266 			KASSERT(RB_LEFT_SENTINEL_P(next0));
   1267 		}
   1268 	}
   1269 
   1270 	return true;
   1271 }
   1272 
   1273 void
   1274 rb_tree_check(const struct rb_tree *rbt, bool red_check)
   1275 {
   1276 	const struct rb_node *self;
   1277 	const struct rb_node *prev;
   1278 #ifdef RBSTATS
   1279 	unsigned int count = 0;
   1280 #endif
   1281 
   1282 	KASSERT(rbt->rbt_root != NULL);
   1283 	KASSERT(RB_LEFT_P(rbt->rbt_root));
   1284 
   1285 #if defined(RBSTATS) && !defined(RBSMALL)
   1286 	KASSERT(rbt->rbt_count > 1
   1287 	    || rbt->rbt_minmax[RB_DIR_LEFT] == rbt->rbt_minmax[RB_DIR_RIGHT]);
   1288 #endif
   1289 
   1290 	prev = NULL;
   1291 	TAILQ_FOREACH(self, &rbt->rbt_nodes, rb_link) {
   1292 		rb_tree_check_node(rbt, self, prev, false);
   1293 #ifdef RBSTATS
   1294 		count++;
   1295 #endif
   1296 	}
   1297 #ifdef RBSTATS
   1298 	KASSERT(rbt->rbt_count == count);
   1299 #endif
   1300 	if (red_check) {
   1301 		KASSERT(RB_BLACK_P(rbt->rbt_root));
   1302 		KASSERT(RB_SENTINEL_P(rbt->rbt_root)
   1303 			|| rb_tree_count_black(rbt->rbt_root));
   1304 
   1305 		/*
   1306 		 * The root must be black.
   1307 		 * There can never be two adjacent red nodes.
   1308 		 */
   1309 		TAILQ_FOREACH(self, &rbt->rbt_nodes, rb_link) {
   1310 			rb_tree_check_node(rbt, self, NULL, true);
   1311 		}
   1312 	}
   1313 }
   1314 #endif /* RBDEBUG */
   1315 
   1316 #ifdef RBSTATS
   1317 static void
   1318 rb_tree_mark_depth(const struct rb_tree *rbt, const struct rb_node *self,
   1319 	size_t *depths, size_t depth)
   1320 {
   1321 	if (RB_SENTINEL_P(self))
   1322 		return;
   1323 
   1324 	if (RB_TWOCHILDREN_P(self)) {
   1325 		rb_tree_mark_depth(rbt, self->rb_left, depths, depth + 1);
   1326 		rb_tree_mark_depth(rbt, self->rb_right, depths, depth + 1);
   1327 		return;
   1328 	}
   1329 	depths[depth]++;
   1330 	if (!RB_LEFT_SENTINEL_P(self)) {
   1331 		rb_tree_mark_depth(rbt, self->rb_left, depths, depth + 1);
   1332 	}
   1333 	if (!RB_RIGHT_SENTINEL_P(self)) {
   1334 		rb_tree_mark_depth(rbt, self->rb_right, depths, depth + 1);
   1335 	}
   1336 }
   1337 
   1338 void
   1339 rb_tree_depths(const struct rb_tree *rbt, size_t *depths)
   1340 {
   1341 	rb_tree_mark_depth(rbt, rbt->rbt_root, depths, 1);
   1342 }
   1343 #endif /* RBSTATS */
   1344