xref: /netbsd-src/common/lib/libc/gen/rb.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /* $NetBSD: rb.c,v 1.6 2010/04/30 13:58:09 joerg 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 #ifndef RBSMALL
476 	const bool was_root = RB_ROOT_P(rbt, self);
477 #endif
478 
479 	KASSERT(rebalance || (RB_ROOT_P(rbt, self) || RB_RED_P(self)));
480 	KASSERT(!rebalance || RB_BLACK_P(self));
481 	KASSERT(RB_CHILDLESS_P(self));
482 	KASSERT(rb_tree_check_node(rbt, self, NULL, false));
483 
484 	/*
485 	 * Since we are childless, we know that self->rb_left is pointing
486 	 * to the sentinel node.
487 	 */
488 	father->rb_nodes[which] = self->rb_left;
489 
490 	/*
491 	 * Remove ourselves from the node list, decrement the count,
492 	 * and update min/max.
493 	 */
494 	RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
495 	RBSTAT_DEC(rbt->rbt_count);
496 #ifndef RBSMALL
497 	if (__predict_false(rbt->rbt_minmax[RB_POSITION(self)] == self)) {
498 		rbt->rbt_minmax[RB_POSITION(self)] = father;
499 		/*
500 		 * When removing the root, rbt->rbt_minmax[RB_DIR_LEFT] is
501 		 * updated automatically, but we also need to update
502 		 * rbt->rbt_minmax[RB_DIR_RIGHT];
503 		 */
504 		if (__predict_false(was_root)) {
505 			rbt->rbt_minmax[RB_DIR_RIGHT] = father;
506 		}
507 	}
508 	RB_SET_FATHER(self, NULL);
509 #endif
510 
511 	/*
512 	 * Rebalance if requested.
513 	 */
514 	if (rebalance)
515 		rb_tree_removal_rebalance(rbt, father, which);
516 	KASSERT(was_root || rb_tree_check_node(rbt, father, NULL, true));
517 }
518 
519 /*
520  * When deleting an interior node
521  */
522 static void
523 rb_tree_swap_prune_and_rebalance(struct rb_tree *rbt, struct rb_node *self,
524 	struct rb_node *standin)
525 {
526 	const unsigned int standin_which = RB_POSITION(standin);
527 	unsigned int standin_other = standin_which ^ RB_DIR_OTHER;
528 	struct rb_node *standin_son;
529 	struct rb_node *standin_father = RB_FATHER(standin);
530 	bool rebalance = RB_BLACK_P(standin);
531 
532 	if (standin_father == self) {
533 		/*
534 		 * As a child of self, any childen would be opposite of
535 		 * our parent.
536 		 */
537 		KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_other]));
538 		standin_son = standin->rb_nodes[standin_which];
539 	} else {
540 		/*
541 		 * Since we aren't a child of self, any childen would be
542 		 * on the same side as our parent.
543 		 */
544 		KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_which]));
545 		standin_son = standin->rb_nodes[standin_other];
546 	}
547 
548 	/*
549 	 * the node we are removing must have two children.
550 	 */
551 	KASSERT(RB_TWOCHILDREN_P(self));
552 	/*
553 	 * If standin has a child, it must be red.
554 	 */
555 	KASSERT(RB_SENTINEL_P(standin_son) || RB_RED_P(standin_son));
556 
557 	/*
558 	 * Verify things are sane.
559 	 */
560 	KASSERT(rb_tree_check_node(rbt, self, NULL, false));
561 	KASSERT(rb_tree_check_node(rbt, standin, NULL, false));
562 
563 	if (__predict_false(RB_RED_P(standin_son))) {
564 		/*
565 		 * We know we have a red child so if we flip it to black
566 		 * we don't have to rebalance.
567 		 */
568 		KASSERT(rb_tree_check_node(rbt, standin_son, NULL, true));
569 		RB_MARK_BLACK(standin_son);
570 		rebalance = false;
571 
572 		if (standin_father == self) {
573 			KASSERT(RB_POSITION(standin_son) == standin_which);
574 		} else {
575 			KASSERT(RB_POSITION(standin_son) == standin_other);
576 			/*
577 			 * Change the son's parentage to point to his grandpa.
578 			 */
579 			RB_SET_FATHER(standin_son, standin_father);
580 			RB_SET_POSITION(standin_son, standin_which);
581 		}
582 	}
583 
584 	if (standin_father == self) {
585 		/*
586 		 * If we are about to delete the standin's father, then when
587 		 * we call rebalance, we need to use ourselves as our father.
588 		 * Otherwise remember our original father.  Also, sincef we are
589 		 * our standin's father we only need to reparent the standin's
590 		 * brother.
591 		 *
592 		 * |    R      -->     S    |
593 		 * |  Q   S    -->   Q   T  |
594 		 * |        t  -->          |
595 		 */
596 		KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_other]));
597 		KASSERT(!RB_SENTINEL_P(self->rb_nodes[standin_other]));
598 		KASSERT(self->rb_nodes[standin_which] == standin);
599 		/*
600 		 * Have our son/standin adopt his brother as his new son.
601 		 */
602 		standin_father = standin;
603 	} else {
604 		/*
605 		 * |    R          -->    S       .  |
606 		 * |   / \  |   T  -->   / \  |  /   |
607 		 * |  ..... | S    -->  ..... | T    |
608 		 *
609 		 * Sever standin's connection to his father.
610 		 */
611 		standin_father->rb_nodes[standin_which] = standin_son;
612 		/*
613 		 * Adopt the far son.
614 		 */
615 		standin->rb_nodes[standin_other] = self->rb_nodes[standin_other];
616 		RB_SET_FATHER(standin->rb_nodes[standin_other], standin);
617 		KASSERT(RB_POSITION(self->rb_nodes[standin_other]) == standin_other);
618 		/*
619 		 * Use standin_other because we need to preserve standin_which
620 		 * for the removal_rebalance.
621 		 */
622 		standin_other = standin_which;
623 	}
624 
625 	/*
626 	 * Move the only remaining son to our standin.  If our standin is our
627 	 * son, this will be the only son needed to be moved.
628 	 */
629 	KASSERT(standin->rb_nodes[standin_other] != self->rb_nodes[standin_other]);
630 	standin->rb_nodes[standin_other] = self->rb_nodes[standin_other];
631 	RB_SET_FATHER(standin->rb_nodes[standin_other], standin);
632 
633 	/*
634 	 * Now copy the result of self to standin and then replace
635 	 * self with standin in the tree.
636 	 */
637 	RB_COPY_PROPERTIES(standin, self);
638 	RB_SET_FATHER(standin, RB_FATHER(self));
639 	RB_FATHER(standin)->rb_nodes[RB_POSITION(standin)] = standin;
640 
641 	/*
642 	 * Remove ourselves from the node list, decrement the count,
643 	 * and update min/max.
644 	 */
645 	RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
646 	RBSTAT_DEC(rbt->rbt_count);
647 #ifndef RBSMALL
648 	if (__predict_false(rbt->rbt_minmax[RB_POSITION(self)] == self))
649 		rbt->rbt_minmax[RB_POSITION(self)] = RB_FATHER(self);
650 	RB_SET_FATHER(self, NULL);
651 #endif
652 
653 	KASSERT(rb_tree_check_node(rbt, standin, NULL, false));
654 	KASSERT(RB_FATHER_SENTINEL_P(standin)
655 		|| rb_tree_check_node(rbt, standin_father, NULL, false));
656 	KASSERT(RB_LEFT_SENTINEL_P(standin)
657 		|| rb_tree_check_node(rbt, standin->rb_left, NULL, false));
658 	KASSERT(RB_RIGHT_SENTINEL_P(standin)
659 		|| rb_tree_check_node(rbt, standin->rb_right, NULL, false));
660 
661 	if (!rebalance)
662 		return;
663 
664 	rb_tree_removal_rebalance(rbt, standin_father, standin_which);
665 	KASSERT(rb_tree_check_node(rbt, standin, NULL, true));
666 }
667 
668 /*
669  * We could do this by doing
670  *	rb_tree_node_swap(rbt, self, which);
671  *	rb_tree_prune_node(rbt, self, false);
672  *
673  * But it's more efficient to just evalate and recolor the child.
674  */
675 static void
676 rb_tree_prune_blackred_branch(struct rb_tree *rbt, struct rb_node *self,
677 	unsigned int which)
678 {
679 	struct rb_node *father = RB_FATHER(self);
680 	struct rb_node *son = self->rb_nodes[which];
681 #ifndef RBSMALL
682 	const bool was_root = RB_ROOT_P(rbt, self);
683 #endif
684 
685 	KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
686 	KASSERT(RB_BLACK_P(self) && RB_RED_P(son));
687 	KASSERT(!RB_TWOCHILDREN_P(son));
688 	KASSERT(RB_CHILDLESS_P(son));
689 	KASSERT(rb_tree_check_node(rbt, self, NULL, false));
690 	KASSERT(rb_tree_check_node(rbt, son, NULL, false));
691 
692 	/*
693 	 * Remove ourselves from the tree and give our former child our
694 	 * properties (position, color, root).
695 	 */
696 	RB_COPY_PROPERTIES(son, self);
697 	father->rb_nodes[RB_POSITION(son)] = son;
698 	RB_SET_FATHER(son, father);
699 
700 	/*
701 	 * Remove ourselves from the node list, decrement the count,
702 	 * and update minmax.
703 	 */
704 	RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
705 	RBSTAT_DEC(rbt->rbt_count);
706 #ifndef RBSMALL
707 	if (__predict_false(was_root)) {
708 		KASSERT(rbt->rbt_minmax[which] == son);
709 		rbt->rbt_minmax[which ^ RB_DIR_OTHER] = son;
710 	} else if (rbt->rbt_minmax[RB_POSITION(self)] == self) {
711 		rbt->rbt_minmax[RB_POSITION(self)] = son;
712 	}
713 	RB_SET_FATHER(self, NULL);
714 #endif
715 
716 	KASSERT(was_root || rb_tree_check_node(rbt, father, NULL, true));
717 	KASSERT(rb_tree_check_node(rbt, son, NULL, true));
718 }
719 /*
720  *
721  */
722 void
723 rb_tree_remove_node(struct rb_tree *rbt, struct rb_node *self)
724 {
725 	struct rb_node *standin;
726 	unsigned int which;
727 
728 	KASSERT(!RB_SENTINEL_P(self));
729 	RBSTAT_INC(rbt->rbt_removals);
730 
731 	/*
732 	 * In the following diagrams, we (the node to be removed) are S.  Red
733 	 * nodes are lowercase.  T could be either red or black.
734 	 *
735 	 * Remember the major axiom of the red-black tree: the number of
736 	 * black nodes from the root to each leaf is constant across all
737 	 * leaves, only the number of red nodes varies.
738 	 *
739 	 * Thus removing a red leaf doesn't require any other changes to a
740 	 * red-black tree.  So if we must remove a node, attempt to rearrange
741 	 * the tree so we can remove a red node.
742 	 *
743 	 * The simpliest case is a childless red node or a childless root node:
744 	 *
745 	 * |    T  -->    T  |    or    |  R  -->  *  |
746 	 * |  s    -->  *    |
747 	 */
748 	if (RB_CHILDLESS_P(self)) {
749 		const bool rebalance = RB_BLACK_P(self) && !RB_ROOT_P(rbt, self);
750 		rb_tree_prune_node(rbt, self, rebalance);
751 		return;
752 	}
753 	KASSERT(!RB_CHILDLESS_P(self));
754 	if (!RB_TWOCHILDREN_P(self)) {
755 		/*
756 		 * The next simpliest case is the node we are deleting is
757 		 * black and has one red child.
758 		 *
759 		 * |      T  -->      T  -->      T  |
760 		 * |    S    -->  R      -->  R      |
761 		 * |  r      -->    s    -->    *    |
762 		 */
763 		which = RB_LEFT_SENTINEL_P(self) ? RB_DIR_RIGHT : RB_DIR_LEFT;
764 		KASSERT(RB_BLACK_P(self));
765 		KASSERT(RB_RED_P(self->rb_nodes[which]));
766 		KASSERT(RB_CHILDLESS_P(self->rb_nodes[which]));
767 		rb_tree_prune_blackred_branch(rbt, self, which);
768 		return;
769 	}
770 	KASSERT(RB_TWOCHILDREN_P(self));
771 
772 	/*
773 	 * We invert these because we prefer to remove from the inside of
774 	 * the tree.
775 	 */
776 	which = RB_POSITION(self) ^ RB_DIR_OTHER;
777 
778 	/*
779 	 * Let's find the node closes to us opposite of our parent
780 	 * Now swap it with ourself, "prune" it, and rebalance, if needed.
781 	 */
782 	standin = rb_tree_iterate(rbt, self, which);
783 	rb_tree_swap_prune_and_rebalance(rbt, self, standin);
784 }
785 
786 static void
787 rb_tree_removal_rebalance(struct rb_tree *rbt, struct rb_node *parent,
788 	unsigned int which)
789 {
790 	KASSERT(!RB_SENTINEL_P(parent));
791 	KASSERT(RB_SENTINEL_P(parent->rb_nodes[which]));
792 	KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
793 	RBSTAT_INC(rbt->rbt_removal_rebalance_calls);
794 
795 	while (RB_BLACK_P(parent->rb_nodes[which])) {
796 		unsigned int other = which ^ RB_DIR_OTHER;
797 		struct rb_node *brother = parent->rb_nodes[other];
798 
799 		RBSTAT_INC(rbt->rbt_removal_rebalance_passes);
800 
801 		KASSERT(!RB_SENTINEL_P(brother));
802 		/*
803 		 * For cases 1, 2a, and 2b, our brother's children must
804 		 * be black and our father must be black
805 		 */
806 		if (RB_BLACK_P(parent)
807 		    && RB_BLACK_P(brother->rb_left)
808 		    && RB_BLACK_P(brother->rb_right)) {
809 			if (RB_RED_P(brother)) {
810 				/*
811 				 * Case 1: Our brother is red, swap its
812 				 * position (and colors) with our parent.
813 				 * This should now be case 2b (unless C or E
814 				 * has a red child which is case 3; thus no
815 				 * explicit branch to case 2b).
816 				 *
817 				 *    B         ->        D
818 				 *  A     d     ->    b     E
819 				 *      C   E   ->  A   C
820 				 */
821 				KASSERT(RB_BLACK_P(parent));
822 				rb_tree_reparent_nodes(rbt, parent, other);
823 				brother = parent->rb_nodes[other];
824 				KASSERT(!RB_SENTINEL_P(brother));
825 				KASSERT(RB_RED_P(parent));
826 				KASSERT(RB_BLACK_P(brother));
827 				KASSERT(rb_tree_check_node(rbt, brother, NULL, false));
828 				KASSERT(rb_tree_check_node(rbt, parent, NULL, false));
829 			} else {
830 				/*
831 				 * Both our parent and brother are black.
832 				 * Change our brother to red, advance up rank
833 				 * and go through the loop again.
834 				 *
835 				 *    B         ->   *B
836 				 * *A     D     ->  A     d
837 				 *      C   E   ->      C   E
838 				 */
839 				RB_MARK_RED(brother);
840 				KASSERT(RB_BLACK_P(brother->rb_left));
841 				KASSERT(RB_BLACK_P(brother->rb_right));
842 				if (RB_ROOT_P(rbt, parent))
843 					return;	/* root == parent == black */
844 				KASSERT(rb_tree_check_node(rbt, brother, NULL, false));
845 				KASSERT(rb_tree_check_node(rbt, parent, NULL, false));
846 				which = RB_POSITION(parent);
847 				parent = RB_FATHER(parent);
848 				continue;
849 			}
850 		}
851 		/*
852 		 * Avoid an else here so that case 2a above can hit either
853 		 * case 2b, 3, or 4.
854 		 */
855 		if (RB_RED_P(parent)
856 		    && RB_BLACK_P(brother)
857 		    && RB_BLACK_P(brother->rb_left)
858 		    && RB_BLACK_P(brother->rb_right)) {
859 			KASSERT(RB_RED_P(parent));
860 			KASSERT(RB_BLACK_P(brother));
861 			KASSERT(RB_BLACK_P(brother->rb_left));
862 			KASSERT(RB_BLACK_P(brother->rb_right));
863 			/*
864 			 * We are black, our father is red, our brother and
865 			 * both nephews are black.  Simply invert/exchange the
866 			 * colors of our father and brother (to black and red
867 			 * respectively).
868 			 *
869 			 *	|    f        -->    F        |
870 			 *	|  *     B    -->  *     b    |
871 			 *	|      N   N  -->      N   N  |
872 			 */
873 			RB_MARK_BLACK(parent);
874 			RB_MARK_RED(brother);
875 			KASSERT(rb_tree_check_node(rbt, brother, NULL, true));
876 			break;		/* We're done! */
877 		} else {
878 			/*
879 			 * Our brother must be black and have at least one
880 			 * red child (it may have two).
881 			 */
882 			KASSERT(RB_BLACK_P(brother));
883 			KASSERT(RB_RED_P(brother->rb_nodes[which]) ||
884 				RB_RED_P(brother->rb_nodes[other]));
885 			if (RB_BLACK_P(brother->rb_nodes[other])) {
886 				/*
887 				 * Case 3: our brother is black, our near
888 				 * nephew is red, and our far nephew is black.
889 				 * Swap our brother with our near nephew.
890 				 * This result in a tree that matches case 4.
891 				 * (Our father could be red or black).
892 				 *
893 				 *	|    F      -->    F      |
894 				 *	|  x     B  -->  x   B    |
895 				 *	|      n    -->        n  |
896 				 */
897 				KASSERT(RB_RED_P(brother->rb_nodes[which]));
898 				rb_tree_reparent_nodes(rbt, brother, which);
899 				KASSERT(RB_FATHER(brother) == parent->rb_nodes[other]);
900 				brother = parent->rb_nodes[other];
901 				KASSERT(RB_RED_P(brother->rb_nodes[other]));
902 			}
903 			/*
904 			 * Case 4: our brother is black and our far nephew
905 			 * is red.  Swap our father and brother locations and
906 			 * change our far nephew to black.  (these can be
907 			 * done in either order so we change the color first).
908 			 * The result is a valid red-black tree and is a
909 			 * terminal case.  (again we don't care about the
910 			 * father's color)
911 			 *
912 			 * If the father is red, we will get a red-black-black
913 			 * tree:
914 			 *	|  f      ->  f      -->    b    |
915 			 *	|    B    ->    B    -->  F   N  |
916 			 *	|      n  ->      N  -->         |
917 			 *
918 			 * If the father is black, we will get an all black
919 			 * tree:
920 			 *	|  F      ->  F      -->    B    |
921 			 *	|    B    ->    B    -->  F   N  |
922 			 *	|      n  ->      N  -->         |
923 			 *
924 			 * If we had two red nephews, then after the swap,
925 			 * our former father would have a red grandson.
926 			 */
927 			KASSERT(RB_BLACK_P(brother));
928 			KASSERT(RB_RED_P(brother->rb_nodes[other]));
929 			RB_MARK_BLACK(brother->rb_nodes[other]);
930 			rb_tree_reparent_nodes(rbt, parent, other);
931 			break;		/* We're done! */
932 		}
933 	}
934 	KASSERT(rb_tree_check_node(rbt, parent, NULL, true));
935 }
936 
937 struct rb_node *
938 rb_tree_iterate(struct rb_tree *rbt, struct rb_node *self,
939 	const unsigned int direction)
940 {
941 	const unsigned int other = direction ^ RB_DIR_OTHER;
942 	KASSERT(direction == RB_DIR_LEFT || direction == RB_DIR_RIGHT);
943 
944 	if (self == NULL) {
945 #ifndef RBSMALL
946 		if (RB_SENTINEL_P(rbt->rbt_root))
947 			return NULL;
948 		return rbt->rbt_minmax[direction];
949 #else
950 		self = rbt->rbt_root;
951 		if (RB_SENTINEL_P(self))
952 			return NULL;
953 		while (!RB_SENTINEL_P(self->rb_nodes[direction]))
954 			self = self->rb_nodes[direction];
955 		return self;
956 #endif /* !RBSMALL */
957 	}
958 	KASSERT(!RB_SENTINEL_P(self));
959 	/*
960 	 * We can't go any further in this direction.  We proceed up in the
961 	 * opposite direction until our parent is in direction we want to go.
962 	 */
963 	if (RB_SENTINEL_P(self->rb_nodes[direction])) {
964 		while (!RB_ROOT_P(rbt, self)) {
965 			if (other == RB_POSITION(self))
966 				return RB_FATHER(self);
967 			self = RB_FATHER(self);
968 		}
969 		return NULL;
970 	}
971 
972 	/*
973 	 * Advance down one in current direction and go down as far as possible
974 	 * in the opposite direction.
975 	 */
976 	self = self->rb_nodes[direction];
977 	KASSERT(!RB_SENTINEL_P(self));
978 	while (!RB_SENTINEL_P(self->rb_nodes[other]))
979 		self = self->rb_nodes[other];
980 	return self;
981 }
982 
983 #ifdef RBDEBUG
984 static const struct rb_node *
985 rb_tree_iterate_const(const struct rb_tree *rbt, const struct rb_node *self,
986 	const unsigned int direction)
987 {
988 	const unsigned int other = direction ^ RB_DIR_OTHER;
989 	KASSERT(direction == RB_DIR_LEFT || direction == RB_DIR_RIGHT);
990 
991 	if (self == NULL) {
992 #ifndef RBSMALL
993 		if (RB_SENTINEL_P(rbt->rbt_root))
994 			return NULL;
995 		return rbt->rbt_minmax[direction];
996 #else
997 		self = rbt->rbt_root;
998 		if (RB_SENTINEL_P(self))
999 			return NULL;
1000 		while (!RB_SENTINEL_P(self->rb_nodes[direction]))
1001 			self = self->rb_nodes[direction];
1002 		return self;
1003 #endif /* !RBSMALL */
1004 	}
1005 	KASSERT(!RB_SENTINEL_P(self));
1006 	/*
1007 	 * We can't go any further in this direction.  We proceed up in the
1008 	 * opposite direction until our parent is in direction we want to go.
1009 	 */
1010 	if (RB_SENTINEL_P(self->rb_nodes[direction])) {
1011 		while (!RB_ROOT_P(rbt, self)) {
1012 			if (other == RB_POSITION(self))
1013 				return RB_FATHER(self);
1014 			self = RB_FATHER(self);
1015 		}
1016 		return NULL;
1017 	}
1018 
1019 	/*
1020 	 * Advance down one in current direction and go down as far as possible
1021 	 * in the opposite direction.
1022 	 */
1023 	self = self->rb_nodes[direction];
1024 	KASSERT(!RB_SENTINEL_P(self));
1025 	while (!RB_SENTINEL_P(self->rb_nodes[other]))
1026 		self = self->rb_nodes[other];
1027 	return self;
1028 }
1029 
1030 static unsigned int
1031 rb_tree_count_black(const struct rb_node *self)
1032 {
1033 	unsigned int left, right;
1034 
1035 	if (RB_SENTINEL_P(self))
1036 		return 0;
1037 
1038 	left = rb_tree_count_black(self->rb_left);
1039 	right = rb_tree_count_black(self->rb_right);
1040 
1041 	KASSERT(left == right);
1042 
1043 	return left + RB_BLACK_P(self);
1044 }
1045 
1046 static bool
1047 rb_tree_check_node(const struct rb_tree *rbt, const struct rb_node *self,
1048 	const struct rb_node *prev, bool red_check)
1049 {
1050 	rbto_compare_nodes_fn compare_nodes = rbt->rbt_ops->rbto_compare_nodes;
1051 
1052 	KASSERT(!RB_SENTINEL_P(self));
1053 	KASSERT(prev == NULL || (*compare_nodes)(prev, self) > 0);
1054 
1055 	/*
1056 	 * Verify our relationship to our parent.
1057 	 */
1058 	if (RB_ROOT_P(rbt, self)) {
1059 		KASSERT(self == rbt->rbt_root);
1060 		KASSERT(RB_POSITION(self) == RB_DIR_LEFT);
1061 		KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_LEFT] == self);
1062 		KASSERT(RB_FATHER(self) == (const struct rb_node *) &rbt->rbt_root);
1063 	} else {
1064 		KASSERT(self != rbt->rbt_root);
1065 		KASSERT(!RB_FATHER_SENTINEL_P(self));
1066 		if (RB_POSITION(self) == RB_DIR_LEFT) {
1067 			KASSERT((*compare_nodes)(self, RB_FATHER(self)) > 0);
1068 			KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_LEFT] == self);
1069 		} else {
1070 			KASSERT((*compare_nodes)(self, RB_FATHER(self)) < 0);
1071 			KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_RIGHT] == self);
1072 		}
1073 	}
1074 
1075 	/*
1076 	 * Verify our position in the linked list against the tree itself.
1077 	 */
1078 	{
1079 		const struct rb_node *prev0 = rb_tree_iterate_const(rbt, self, RB_DIR_LEFT);
1080 		const struct rb_node *next0 = rb_tree_iterate_const(rbt, self, RB_DIR_RIGHT);
1081 		KASSERT(prev0 == TAILQ_PREV(self, rb_node_qh, rb_link));
1082 		KASSERT(next0 == TAILQ_NEXT(self, rb_link));
1083 #ifndef RBSMALL
1084 		KASSERT(prev0 != NULL || self == rbt->rbt_minmax[RB_DIR_LEFT]);
1085 		KASSERT(next0 != NULL || self == rbt->rbt_minmax[RB_DIR_RIGHT]);
1086 #endif
1087 	}
1088 
1089 	/*
1090 	 * The root must be black.
1091 	 * There can never be two adjacent red nodes.
1092 	 */
1093 	if (red_check) {
1094 		KASSERT(!RB_ROOT_P(rbt, self) || RB_BLACK_P(self));
1095 		(void) rb_tree_count_black(self);
1096 		if (RB_RED_P(self)) {
1097 			const struct rb_node *brother;
1098 			KASSERT(!RB_ROOT_P(rbt, self));
1099 			brother = RB_FATHER(self)->rb_nodes[RB_POSITION(self) ^ RB_DIR_OTHER];
1100 			KASSERT(RB_BLACK_P(RB_FATHER(self)));
1101 			/*
1102 			 * I'm red and have no children, then I must either
1103 			 * have no brother or my brother also be red and
1104 			 * also have no children.  (black count == 0)
1105 			 */
1106 			KASSERT(!RB_CHILDLESS_P(self)
1107 				|| RB_SENTINEL_P(brother)
1108 				|| RB_RED_P(brother)
1109 				|| RB_CHILDLESS_P(brother));
1110 			/*
1111 			 * If I'm not childless, I must have two children
1112 			 * and they must be both be black.
1113 			 */
1114 			KASSERT(RB_CHILDLESS_P(self)
1115 				|| (RB_TWOCHILDREN_P(self)
1116 				    && RB_BLACK_P(self->rb_left)
1117 				    && RB_BLACK_P(self->rb_right)));
1118 			/*
1119 			 * If I'm not childless, thus I have black children,
1120 			 * then my brother must either be black or have two
1121 			 * black children.
1122 			 */
1123 			KASSERT(RB_CHILDLESS_P(self)
1124 				|| RB_BLACK_P(brother)
1125 				|| (RB_TWOCHILDREN_P(brother)
1126 				    && RB_BLACK_P(brother->rb_left)
1127 				    && RB_BLACK_P(brother->rb_right)));
1128 		} else {
1129 			/*
1130 			 * If I'm black and have one child, that child must
1131 			 * be red and childless.
1132 			 */
1133 			KASSERT(RB_CHILDLESS_P(self)
1134 				|| RB_TWOCHILDREN_P(self)
1135 				|| (!RB_LEFT_SENTINEL_P(self)
1136 				    && RB_RIGHT_SENTINEL_P(self)
1137 				    && RB_RED_P(self->rb_left)
1138 				    && RB_CHILDLESS_P(self->rb_left))
1139 				|| (!RB_RIGHT_SENTINEL_P(self)
1140 				    && RB_LEFT_SENTINEL_P(self)
1141 				    && RB_RED_P(self->rb_right)
1142 				    && RB_CHILDLESS_P(self->rb_right)));
1143 
1144 			/*
1145 			 * If I'm a childless black node and my parent is
1146 			 * black, my 2nd closet relative away from my parent
1147 			 * is either red or has a red parent or red children.
1148 			 */
1149 			if (!RB_ROOT_P(rbt, self)
1150 			    && RB_CHILDLESS_P(self)
1151 			    && RB_BLACK_P(RB_FATHER(self))) {
1152 				const unsigned int which = RB_POSITION(self);
1153 				const unsigned int other = which ^ RB_DIR_OTHER;
1154 				const struct rb_node *relative0, *relative;
1155 
1156 				relative0 = rb_tree_iterate_const(rbt,
1157 				    self, other);
1158 				KASSERT(relative0 != NULL);
1159 				relative = rb_tree_iterate_const(rbt,
1160 				    relative0, other);
1161 				KASSERT(relative != NULL);
1162 				KASSERT(RB_SENTINEL_P(relative->rb_nodes[which]));
1163 #if 0
1164 				KASSERT(RB_RED_P(relative)
1165 					|| RB_RED_P(relative->rb_left)
1166 					|| RB_RED_P(relative->rb_right)
1167 					|| RB_RED_P(RB_FATHER(relative)));
1168 #endif
1169 			}
1170 		}
1171 		/*
1172 		 * A grandparent's children must be real nodes and not
1173 		 * sentinels.  First check out grandparent.
1174 		 */
1175 		KASSERT(RB_ROOT_P(rbt, self)
1176 			|| RB_ROOT_P(rbt, RB_FATHER(self))
1177 			|| RB_TWOCHILDREN_P(RB_FATHER(RB_FATHER(self))));
1178 		/*
1179 		 * If we are have grandchildren on our left, then
1180 		 * we must have a child on our right.
1181 		 */
1182 		KASSERT(RB_LEFT_SENTINEL_P(self)
1183 			|| RB_CHILDLESS_P(self->rb_left)
1184 			|| !RB_RIGHT_SENTINEL_P(self));
1185 		/*
1186 		 * If we are have grandchildren on our right, then
1187 		 * we must have a child on our left.
1188 		 */
1189 		KASSERT(RB_RIGHT_SENTINEL_P(self)
1190 			|| RB_CHILDLESS_P(self->rb_right)
1191 			|| !RB_LEFT_SENTINEL_P(self));
1192 
1193 		/*
1194 		 * If we have a child on the left and it doesn't have two
1195 		 * children make sure we don't have great-great-grandchildren on
1196 		 * the right.
1197 		 */
1198 		KASSERT(RB_TWOCHILDREN_P(self->rb_left)
1199 			|| RB_CHILDLESS_P(self->rb_right)
1200 			|| RB_CHILDLESS_P(self->rb_right->rb_left)
1201 			|| RB_CHILDLESS_P(self->rb_right->rb_left->rb_left)
1202 			|| RB_CHILDLESS_P(self->rb_right->rb_left->rb_right)
1203 			|| RB_CHILDLESS_P(self->rb_right->rb_right)
1204 			|| RB_CHILDLESS_P(self->rb_right->rb_right->rb_left)
1205 			|| RB_CHILDLESS_P(self->rb_right->rb_right->rb_right));
1206 
1207 		/*
1208 		 * If we have a child on the right and it doesn't have two
1209 		 * children make sure we don't have great-great-grandchildren on
1210 		 * the left.
1211 		 */
1212 		KASSERT(RB_TWOCHILDREN_P(self->rb_right)
1213 			|| RB_CHILDLESS_P(self->rb_left)
1214 			|| RB_CHILDLESS_P(self->rb_left->rb_left)
1215 			|| RB_CHILDLESS_P(self->rb_left->rb_left->rb_left)
1216 			|| RB_CHILDLESS_P(self->rb_left->rb_left->rb_right)
1217 			|| RB_CHILDLESS_P(self->rb_left->rb_right)
1218 			|| RB_CHILDLESS_P(self->rb_left->rb_right->rb_left)
1219 			|| RB_CHILDLESS_P(self->rb_left->rb_right->rb_right));
1220 
1221 		/*
1222 		 * If we are fully interior node, then our predecessors and
1223 		 * successors must have no children in our direction.
1224 		 */
1225 		if (RB_TWOCHILDREN_P(self)) {
1226 			const struct rb_node *prev0;
1227 			const struct rb_node *next0;
1228 
1229 			prev0 = rb_tree_iterate_const(rbt, self, RB_DIR_LEFT);
1230 			KASSERT(prev0 != NULL);
1231 			KASSERT(RB_RIGHT_SENTINEL_P(prev0));
1232 
1233 			next0 = rb_tree_iterate_const(rbt, self, RB_DIR_RIGHT);
1234 			KASSERT(next0 != NULL);
1235 			KASSERT(RB_LEFT_SENTINEL_P(next0));
1236 		}
1237 	}
1238 
1239 	return true;
1240 }
1241 
1242 void
1243 rb_tree_check(const struct rb_tree *rbt, bool red_check)
1244 {
1245 	const struct rb_node *self;
1246 	const struct rb_node *prev;
1247 #ifdef RBSTATS
1248 	unsigned int count = 0;
1249 #endif
1250 
1251 	KASSERT(rbt->rbt_root != NULL);
1252 	KASSERT(RB_LEFT_P(rbt->rbt_root));
1253 
1254 #if defined(RBSTATS) && !defined(RBSMALL)
1255 	KASSERT(rbt->rbt_count > 1
1256 	    || rbt->rbt_minmax[RB_DIR_LEFT] == rbt->rbt_minmax[RB_DIR_RIGHT]);
1257 #endif
1258 
1259 	prev = NULL;
1260 	TAILQ_FOREACH(self, &rbt->rbt_nodes, rb_link) {
1261 		rb_tree_check_node(rbt, self, prev, false);
1262 #ifdef RBSTATS
1263 		count++;
1264 #endif
1265 	}
1266 #ifdef RBSTATS
1267 	KASSERT(rbt->rbt_count == count);
1268 #endif
1269 	if (red_check) {
1270 		KASSERT(RB_BLACK_P(rbt->rbt_root));
1271 		KASSERT(RB_SENTINEL_P(rbt->rbt_root)
1272 			|| rb_tree_count_black(rbt->rbt_root));
1273 
1274 		/*
1275 		 * The root must be black.
1276 		 * There can never be two adjacent red nodes.
1277 		 */
1278 		TAILQ_FOREACH(self, &rbt->rbt_nodes, rb_link) {
1279 			rb_tree_check_node(rbt, self, NULL, true);
1280 		}
1281 	}
1282 }
1283 #endif /* RBDEBUG */
1284 
1285 #ifdef RBSTATS
1286 static void
1287 rb_tree_mark_depth(const struct rb_tree *rbt, const struct rb_node *self,
1288 	size_t *depths, size_t depth)
1289 {
1290 	if (RB_SENTINEL_P(self))
1291 		return;
1292 
1293 	if (RB_TWOCHILDREN_P(self)) {
1294 		rb_tree_mark_depth(rbt, self->rb_left, depths, depth + 1);
1295 		rb_tree_mark_depth(rbt, self->rb_right, depths, depth + 1);
1296 		return;
1297 	}
1298 	depths[depth]++;
1299 	if (!RB_LEFT_SENTINEL_P(self)) {
1300 		rb_tree_mark_depth(rbt, self->rb_left, depths, depth + 1);
1301 	}
1302 	if (!RB_RIGHT_SENTINEL_P(self)) {
1303 		rb_tree_mark_depth(rbt, self->rb_right, depths, depth + 1);
1304 	}
1305 }
1306 
1307 void
1308 rb_tree_depths(const struct rb_tree *rbt, size_t *depths)
1309 {
1310 	rb_tree_mark_depth(rbt, rbt->rbt_root, depths, 1);
1311 }
1312 #endif /* RBSTATS */
1313