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