FreeBSD: Parameterize ZFS_ENTER/ZFS_VERIFY_VP with an error code
[zfs.git] / module / avl / avl.c
blob3891a2d628804581c80ea29e14321795d681a183
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
22 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
27 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
28 * Copyright (c) 2015 by Delphix. All rights reserved.
32 * AVL - generic AVL tree implementation for kernel use
34 * A complete description of AVL trees can be found in many CS textbooks.
36 * Here is a very brief overview. An AVL tree is a binary search tree that is
37 * almost perfectly balanced. By "almost" perfectly balanced, we mean that at
38 * any given node, the left and right subtrees are allowed to differ in height
39 * by at most 1 level.
41 * This relaxation from a perfectly balanced binary tree allows doing
42 * insertion and deletion relatively efficiently. Searching the tree is
43 * still a fast operation, roughly O(log(N)).
45 * The key to insertion and deletion is a set of tree manipulations called
46 * rotations, which bring unbalanced subtrees back into the semi-balanced state.
48 * This implementation of AVL trees has the following peculiarities:
50 * - The AVL specific data structures are physically embedded as fields
51 * in the "using" data structures. To maintain generality the code
52 * must constantly translate between "avl_node_t *" and containing
53 * data structure "void *"s by adding/subtracting the avl_offset.
55 * - Since the AVL data is always embedded in other structures, there is
56 * no locking or memory allocation in the AVL routines. This must be
57 * provided for by the enclosing data structure's semantics. Typically,
58 * avl_insert()/_add()/_remove()/avl_insert_here() require some kind of
59 * exclusive write lock. Other operations require a read lock.
61 * - The implementation uses iteration instead of explicit recursion,
62 * since it is intended to run on limited size kernel stacks. Since
63 * there is no recursion stack present to move "up" in the tree,
64 * there is an explicit "parent" link in the avl_node_t.
66 * - The left/right children pointers of a node are in an array.
67 * In the code, variables (instead of constants) are used to represent
68 * left and right indices. The implementation is written as if it only
69 * dealt with left handed manipulations. By changing the value assigned
70 * to "left", the code also works for right handed trees. The
71 * following variables/terms are frequently used:
73 * int left; // 0 when dealing with left children,
74 * // 1 for dealing with right children
76 * int left_heavy; // -1 when left subtree is taller at some node,
77 * // +1 when right subtree is taller
79 * int right; // will be the opposite of left (0 or 1)
80 * int right_heavy;// will be the opposite of left_heavy (-1 or 1)
82 * int direction; // 0 for "<" (ie. left child); 1 for ">" (right)
84 * Though it is a little more confusing to read the code, the approach
85 * allows using half as much code (and hence cache footprint) for tree
86 * manipulations and eliminates many conditional branches.
88 * - The avl_index_t is an opaque "cookie" used to find nodes at or
89 * adjacent to where a new value would be inserted in the tree. The value
90 * is a modified "avl_node_t *". The bottom bit (normally 0 for a
91 * pointer) is set to indicate if that the new node has a value greater
92 * than the value of the indicated "avl_node_t *".
94 * Note - in addition to userland (e.g. libavl and libutil) and the kernel
95 * (e.g. genunix), avl.c is compiled into ld.so and kmdb's genunix module,
96 * which each have their own compilation environments and subsequent
97 * requirements. Each of these environments must be considered when adding
98 * dependencies from avl.c.
100 * Link to Illumos.org for more information on avl function:
101 * [1] https://illumos.org/man/9f/avl
104 #include <sys/types.h>
105 #include <sys/param.h>
106 #include <sys/debug.h>
107 #include <sys/avl.h>
108 #include <sys/cmn_err.h>
109 #include <sys/mod.h>
112 * Small arrays to translate between balance (or diff) values and child indices.
114 * Code that deals with binary tree data structures will randomly use
115 * left and right children when examining a tree. C "if()" statements
116 * which evaluate randomly suffer from very poor hardware branch prediction.
117 * In this code we avoid some of the branch mispredictions by using the
118 * following translation arrays. They replace random branches with an
119 * additional memory reference. Since the translation arrays are both very
120 * small the data should remain efficiently in cache.
122 static const int avl_child2balance[] = {-1, 1};
123 static const int avl_balance2child[] = {0, 0, 1};
127 * Walk from one node to the previous valued node (ie. an infix walk
128 * towards the left). At any given node we do one of 2 things:
130 * - If there is a left child, go to it, then to it's rightmost descendant.
132 * - otherwise we return through parent nodes until we've come from a right
133 * child.
135 * Return Value:
136 * NULL - if at the end of the nodes
137 * otherwise next node
139 void *
140 avl_walk(avl_tree_t *tree, void *oldnode, int left)
142 size_t off = tree->avl_offset;
143 avl_node_t *node = AVL_DATA2NODE(oldnode, off);
144 int right = 1 - left;
145 int was_child;
149 * nowhere to walk to if tree is empty
151 if (node == NULL)
152 return (NULL);
155 * Visit the previous valued node. There are two possibilities:
157 * If this node has a left child, go down one left, then all
158 * the way right.
160 if (node->avl_child[left] != NULL) {
161 for (node = node->avl_child[left];
162 node->avl_child[right] != NULL;
163 node = node->avl_child[right])
166 * Otherwise, return through left children as far as we can.
168 } else {
169 for (;;) {
170 was_child = AVL_XCHILD(node);
171 node = AVL_XPARENT(node);
172 if (node == NULL)
173 return (NULL);
174 if (was_child == right)
175 break;
179 return (AVL_NODE2DATA(node, off));
183 * Return the lowest valued node in a tree or NULL.
184 * (leftmost child from root of tree)
186 void *
187 avl_first(avl_tree_t *tree)
189 avl_node_t *node;
190 avl_node_t *prev = NULL;
191 size_t off = tree->avl_offset;
193 for (node = tree->avl_root; node != NULL; node = node->avl_child[0])
194 prev = node;
196 if (prev != NULL)
197 return (AVL_NODE2DATA(prev, off));
198 return (NULL);
202 * Return the highest valued node in a tree or NULL.
203 * (rightmost child from root of tree)
205 void *
206 avl_last(avl_tree_t *tree)
208 avl_node_t *node;
209 avl_node_t *prev = NULL;
210 size_t off = tree->avl_offset;
212 for (node = tree->avl_root; node != NULL; node = node->avl_child[1])
213 prev = node;
215 if (prev != NULL)
216 return (AVL_NODE2DATA(prev, off));
217 return (NULL);
221 * Access the node immediately before or after an insertion point.
223 * "avl_index_t" is a (avl_node_t *) with the bottom bit indicating a child
225 * Return value:
226 * NULL: no node in the given direction
227 * "void *" of the found tree node
229 void *
230 avl_nearest(avl_tree_t *tree, avl_index_t where, int direction)
232 int child = AVL_INDEX2CHILD(where);
233 avl_node_t *node = AVL_INDEX2NODE(where);
234 void *data;
235 size_t off = tree->avl_offset;
237 if (node == NULL) {
238 ASSERT(tree->avl_root == NULL);
239 return (NULL);
241 data = AVL_NODE2DATA(node, off);
242 if (child != direction)
243 return (data);
245 return (avl_walk(tree, data, direction));
250 * Search for the node which contains "value". The algorithm is a
251 * simple binary tree search.
253 * return value:
254 * NULL: the value is not in the AVL tree
255 * *where (if not NULL) is set to indicate the insertion point
256 * "void *" of the found tree node
258 void *
259 avl_find(avl_tree_t *tree, const void *value, avl_index_t *where)
261 avl_node_t *node;
262 avl_node_t *prev = NULL;
263 int child = 0;
264 int diff;
265 size_t off = tree->avl_offset;
267 for (node = tree->avl_root; node != NULL;
268 node = node->avl_child[child]) {
270 prev = node;
272 diff = tree->avl_compar(value, AVL_NODE2DATA(node, off));
273 ASSERT(-1 <= diff && diff <= 1);
274 if (diff == 0) {
275 #ifdef ZFS_DEBUG
276 if (where != NULL)
277 *where = 0;
278 #endif
279 return (AVL_NODE2DATA(node, off));
281 child = avl_balance2child[1 + diff];
285 if (where != NULL)
286 *where = AVL_MKINDEX(prev, child);
288 return (NULL);
293 * Perform a rotation to restore balance at the subtree given by depth.
295 * This routine is used by both insertion and deletion. The return value
296 * indicates:
297 * 0 : subtree did not change height
298 * !0 : subtree was reduced in height
300 * The code is written as if handling left rotations, right rotations are
301 * symmetric and handled by swapping values of variables right/left[_heavy]
303 * On input balance is the "new" balance at "node". This value is either
304 * -2 or +2.
306 static int
307 avl_rotation(avl_tree_t *tree, avl_node_t *node, int balance)
309 int left = !(balance < 0); /* when balance = -2, left will be 0 */
310 int right = 1 - left;
311 int left_heavy = balance >> 1;
312 int right_heavy = -left_heavy;
313 avl_node_t *parent = AVL_XPARENT(node);
314 avl_node_t *child = node->avl_child[left];
315 avl_node_t *cright;
316 avl_node_t *gchild;
317 avl_node_t *gright;
318 avl_node_t *gleft;
319 int which_child = AVL_XCHILD(node);
320 int child_bal = AVL_XBALANCE(child);
323 * case 1 : node is overly left heavy, the left child is balanced or
324 * also left heavy. This requires the following rotation.
326 * (node bal:-2)
327 * / \
328 * / \
329 * (child bal:0 or -1)
330 * / \
331 * / \
332 * cright
334 * becomes:
336 * (child bal:1 or 0)
337 * / \
338 * / \
339 * (node bal:-1 or 0)
340 * / \
341 * / \
342 * cright
344 * we detect this situation by noting that child's balance is not
345 * right_heavy.
347 if (child_bal != right_heavy) {
350 * compute new balance of nodes
352 * If child used to be left heavy (now balanced) we reduced
353 * the height of this sub-tree -- used in "return...;" below
355 child_bal += right_heavy; /* adjust towards right */
358 * move "cright" to be node's left child
360 cright = child->avl_child[right];
361 node->avl_child[left] = cright;
362 if (cright != NULL) {
363 AVL_SETPARENT(cright, node);
364 AVL_SETCHILD(cright, left);
368 * move node to be child's right child
370 child->avl_child[right] = node;
371 AVL_SETBALANCE(node, -child_bal);
372 AVL_SETCHILD(node, right);
373 AVL_SETPARENT(node, child);
376 * update the pointer into this subtree
378 AVL_SETBALANCE(child, child_bal);
379 AVL_SETCHILD(child, which_child);
380 AVL_SETPARENT(child, parent);
381 if (parent != NULL)
382 parent->avl_child[which_child] = child;
383 else
384 tree->avl_root = child;
386 return (child_bal == 0);
390 * case 2 : When node is left heavy, but child is right heavy we use
391 * a different rotation.
393 * (node b:-2)
394 * / \
395 * / \
396 * / \
397 * (child b:+1)
398 * / \
399 * / \
400 * (gchild b: != 0)
401 * / \
402 * / \
403 * gleft gright
405 * becomes:
407 * (gchild b:0)
408 * / \
409 * / \
410 * / \
411 * (child b:?) (node b:?)
412 * / \ / \
413 * / \ / \
414 * gleft gright
416 * computing the new balances is more complicated. As an example:
417 * if gchild was right_heavy, then child is now left heavy
418 * else it is balanced
420 gchild = child->avl_child[right];
421 gleft = gchild->avl_child[left];
422 gright = gchild->avl_child[right];
425 * move gright to left child of node and
427 * move gleft to right child of node
429 node->avl_child[left] = gright;
430 if (gright != NULL) {
431 AVL_SETPARENT(gright, node);
432 AVL_SETCHILD(gright, left);
435 child->avl_child[right] = gleft;
436 if (gleft != NULL) {
437 AVL_SETPARENT(gleft, child);
438 AVL_SETCHILD(gleft, right);
442 * move child to left child of gchild and
444 * move node to right child of gchild and
446 * fixup parent of all this to point to gchild
448 balance = AVL_XBALANCE(gchild);
449 gchild->avl_child[left] = child;
450 AVL_SETBALANCE(child, (balance == right_heavy ? left_heavy : 0));
451 AVL_SETPARENT(child, gchild);
452 AVL_SETCHILD(child, left);
454 gchild->avl_child[right] = node;
455 AVL_SETBALANCE(node, (balance == left_heavy ? right_heavy : 0));
456 AVL_SETPARENT(node, gchild);
457 AVL_SETCHILD(node, right);
459 AVL_SETBALANCE(gchild, 0);
460 AVL_SETPARENT(gchild, parent);
461 AVL_SETCHILD(gchild, which_child);
462 if (parent != NULL)
463 parent->avl_child[which_child] = gchild;
464 else
465 tree->avl_root = gchild;
467 return (1); /* the new tree is always shorter */
472 * Insert a new node into an AVL tree at the specified (from avl_find()) place.
474 * Newly inserted nodes are always leaf nodes in the tree, since avl_find()
475 * searches out to the leaf positions. The avl_index_t indicates the node
476 * which will be the parent of the new node.
478 * After the node is inserted, a single rotation further up the tree may
479 * be necessary to maintain an acceptable AVL balance.
481 void
482 avl_insert(avl_tree_t *tree, void *new_data, avl_index_t where)
484 avl_node_t *node;
485 avl_node_t *parent = AVL_INDEX2NODE(where);
486 int old_balance;
487 int new_balance;
488 int which_child = AVL_INDEX2CHILD(where);
489 size_t off = tree->avl_offset;
491 #ifdef _LP64
492 ASSERT(((uintptr_t)new_data & 0x7) == 0);
493 #endif
495 node = AVL_DATA2NODE(new_data, off);
498 * First, add the node to the tree at the indicated position.
500 ++tree->avl_numnodes;
502 node->avl_child[0] = NULL;
503 node->avl_child[1] = NULL;
505 AVL_SETCHILD(node, which_child);
506 AVL_SETBALANCE(node, 0);
507 AVL_SETPARENT(node, parent);
508 if (parent != NULL) {
509 ASSERT(parent->avl_child[which_child] == NULL);
510 parent->avl_child[which_child] = node;
511 } else {
512 ASSERT(tree->avl_root == NULL);
513 tree->avl_root = node;
516 * Now, back up the tree modifying the balance of all nodes above the
517 * insertion point. If we get to a highly unbalanced ancestor, we
518 * need to do a rotation. If we back out of the tree we are done.
519 * If we brought any subtree into perfect balance (0), we are also done.
521 for (;;) {
522 node = parent;
523 if (node == NULL)
524 return;
527 * Compute the new balance
529 old_balance = AVL_XBALANCE(node);
530 new_balance = old_balance + avl_child2balance[which_child];
533 * If we introduced equal balance, then we are done immediately
535 if (new_balance == 0) {
536 AVL_SETBALANCE(node, 0);
537 return;
541 * If both old and new are not zero we went
542 * from -1 to -2 balance, do a rotation.
544 if (old_balance != 0)
545 break;
547 AVL_SETBALANCE(node, new_balance);
548 parent = AVL_XPARENT(node);
549 which_child = AVL_XCHILD(node);
553 * perform a rotation to fix the tree and return
555 (void) avl_rotation(tree, node, new_balance);
559 * Insert "new_data" in "tree" in the given "direction" either after or
560 * before (AVL_AFTER, AVL_BEFORE) the data "here".
562 * Insertions can only be done at empty leaf points in the tree, therefore
563 * if the given child of the node is already present we move to either
564 * the AVL_PREV or AVL_NEXT and reverse the insertion direction. Since
565 * every other node in the tree is a leaf, this always works.
567 * To help developers using this interface, we assert that the new node
568 * is correctly ordered at every step of the way in DEBUG kernels.
570 void
571 avl_insert_here(
572 avl_tree_t *tree,
573 void *new_data,
574 void *here,
575 int direction)
577 avl_node_t *node;
578 int child = direction; /* rely on AVL_BEFORE == 0, AVL_AFTER == 1 */
579 #ifdef ZFS_DEBUG
580 int diff;
581 #endif
583 ASSERT(tree != NULL);
584 ASSERT(new_data != NULL);
585 ASSERT(here != NULL);
586 ASSERT(direction == AVL_BEFORE || direction == AVL_AFTER);
589 * If corresponding child of node is not NULL, go to the neighboring
590 * node and reverse the insertion direction.
592 node = AVL_DATA2NODE(here, tree->avl_offset);
594 #ifdef ZFS_DEBUG
595 diff = tree->avl_compar(new_data, here);
596 ASSERT(-1 <= diff && diff <= 1);
597 ASSERT(diff != 0);
598 ASSERT(diff > 0 ? child == 1 : child == 0);
599 #endif
601 if (node->avl_child[child] != NULL) {
602 node = node->avl_child[child];
603 child = 1 - child;
604 while (node->avl_child[child] != NULL) {
605 #ifdef ZFS_DEBUG
606 diff = tree->avl_compar(new_data,
607 AVL_NODE2DATA(node, tree->avl_offset));
608 ASSERT(-1 <= diff && diff <= 1);
609 ASSERT(diff != 0);
610 ASSERT(diff > 0 ? child == 1 : child == 0);
611 #endif
612 node = node->avl_child[child];
614 #ifdef ZFS_DEBUG
615 diff = tree->avl_compar(new_data,
616 AVL_NODE2DATA(node, tree->avl_offset));
617 ASSERT(-1 <= diff && diff <= 1);
618 ASSERT(diff != 0);
619 ASSERT(diff > 0 ? child == 1 : child == 0);
620 #endif
622 ASSERT(node->avl_child[child] == NULL);
624 avl_insert(tree, new_data, AVL_MKINDEX(node, child));
628 * Add a new node to an AVL tree. Strictly enforce that no duplicates can
629 * be added to the tree with a VERIFY which is enabled for non-DEBUG builds.
631 void
632 avl_add(avl_tree_t *tree, void *new_node)
634 avl_index_t where = 0;
636 VERIFY(avl_find(tree, new_node, &where) == NULL);
638 avl_insert(tree, new_node, where);
642 * Delete a node from the AVL tree. Deletion is similar to insertion, but
643 * with 2 complications.
645 * First, we may be deleting an interior node. Consider the following subtree:
647 * d c c
648 * / \ / \ / \
649 * b e b e b e
650 * / \ / \ /
651 * a c a a
653 * When we are deleting node (d), we find and bring up an adjacent valued leaf
654 * node, say (c), to take the interior node's place. In the code this is
655 * handled by temporarily swapping (d) and (c) in the tree and then using
656 * common code to delete (d) from the leaf position.
658 * Secondly, an interior deletion from a deep tree may require more than one
659 * rotation to fix the balance. This is handled by moving up the tree through
660 * parents and applying rotations as needed. The return value from
661 * avl_rotation() is used to detect when a subtree did not change overall
662 * height due to a rotation.
664 void
665 avl_remove(avl_tree_t *tree, void *data)
667 avl_node_t *delete;
668 avl_node_t *parent;
669 avl_node_t *node;
670 avl_node_t tmp;
671 int old_balance;
672 int new_balance;
673 int left;
674 int right;
675 int which_child;
676 size_t off = tree->avl_offset;
678 delete = AVL_DATA2NODE(data, off);
681 * Deletion is easiest with a node that has at most 1 child.
682 * We swap a node with 2 children with a sequentially valued
683 * neighbor node. That node will have at most 1 child. Note this
684 * has no effect on the ordering of the remaining nodes.
686 * As an optimization, we choose the greater neighbor if the tree
687 * is right heavy, otherwise the left neighbor. This reduces the
688 * number of rotations needed.
690 if (delete->avl_child[0] != NULL && delete->avl_child[1] != NULL) {
693 * choose node to swap from whichever side is taller
695 old_balance = AVL_XBALANCE(delete);
696 left = avl_balance2child[old_balance + 1];
697 right = 1 - left;
700 * get to the previous value'd node
701 * (down 1 left, as far as possible right)
703 for (node = delete->avl_child[left];
704 node->avl_child[right] != NULL;
705 node = node->avl_child[right])
709 * create a temp placeholder for 'node'
710 * move 'node' to delete's spot in the tree
712 tmp = *node;
714 *node = *delete;
715 if (node->avl_child[left] == node)
716 node->avl_child[left] = &tmp;
718 parent = AVL_XPARENT(node);
719 if (parent != NULL)
720 parent->avl_child[AVL_XCHILD(node)] = node;
721 else
722 tree->avl_root = node;
723 AVL_SETPARENT(node->avl_child[left], node);
724 AVL_SETPARENT(node->avl_child[right], node);
727 * Put tmp where node used to be (just temporary).
728 * It always has a parent and at most 1 child.
730 delete = &tmp;
731 parent = AVL_XPARENT(delete);
732 parent->avl_child[AVL_XCHILD(delete)] = delete;
733 which_child = (delete->avl_child[1] != 0);
734 if (delete->avl_child[which_child] != NULL)
735 AVL_SETPARENT(delete->avl_child[which_child], delete);
740 * Here we know "delete" is at least partially a leaf node. It can
741 * be easily removed from the tree.
743 ASSERT(tree->avl_numnodes > 0);
744 --tree->avl_numnodes;
745 parent = AVL_XPARENT(delete);
746 which_child = AVL_XCHILD(delete);
747 if (delete->avl_child[0] != NULL)
748 node = delete->avl_child[0];
749 else
750 node = delete->avl_child[1];
753 * Connect parent directly to node (leaving out delete).
755 if (node != NULL) {
756 AVL_SETPARENT(node, parent);
757 AVL_SETCHILD(node, which_child);
759 if (parent == NULL) {
760 tree->avl_root = node;
761 return;
763 parent->avl_child[which_child] = node;
767 * Since the subtree is now shorter, begin adjusting parent balances
768 * and performing any needed rotations.
770 do {
773 * Move up the tree and adjust the balance
775 * Capture the parent and which_child values for the next
776 * iteration before any rotations occur.
778 node = parent;
779 old_balance = AVL_XBALANCE(node);
780 new_balance = old_balance - avl_child2balance[which_child];
781 parent = AVL_XPARENT(node);
782 which_child = AVL_XCHILD(node);
785 * If a node was in perfect balance but isn't anymore then
786 * we can stop, since the height didn't change above this point
787 * due to a deletion.
789 if (old_balance == 0) {
790 AVL_SETBALANCE(node, new_balance);
791 break;
795 * If the new balance is zero, we don't need to rotate
796 * else
797 * need a rotation to fix the balance.
798 * If the rotation doesn't change the height
799 * of the sub-tree we have finished adjusting.
801 if (new_balance == 0)
802 AVL_SETBALANCE(node, new_balance);
803 else if (!avl_rotation(tree, node, new_balance))
804 break;
805 } while (parent != NULL);
808 #define AVL_REINSERT(tree, obj) \
809 avl_remove((tree), (obj)); \
810 avl_add((tree), (obj))
812 boolean_t
813 avl_update_lt(avl_tree_t *t, void *obj)
815 void *neighbor;
817 ASSERT(((neighbor = AVL_NEXT(t, obj)) == NULL) ||
818 (t->avl_compar(obj, neighbor) <= 0));
820 neighbor = AVL_PREV(t, obj);
821 if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) < 0)) {
822 AVL_REINSERT(t, obj);
823 return (B_TRUE);
826 return (B_FALSE);
829 boolean_t
830 avl_update_gt(avl_tree_t *t, void *obj)
832 void *neighbor;
834 ASSERT(((neighbor = AVL_PREV(t, obj)) == NULL) ||
835 (t->avl_compar(obj, neighbor) >= 0));
837 neighbor = AVL_NEXT(t, obj);
838 if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) > 0)) {
839 AVL_REINSERT(t, obj);
840 return (B_TRUE);
843 return (B_FALSE);
846 boolean_t
847 avl_update(avl_tree_t *t, void *obj)
849 void *neighbor;
851 neighbor = AVL_PREV(t, obj);
852 if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) < 0)) {
853 AVL_REINSERT(t, obj);
854 return (B_TRUE);
857 neighbor = AVL_NEXT(t, obj);
858 if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) > 0)) {
859 AVL_REINSERT(t, obj);
860 return (B_TRUE);
863 return (B_FALSE);
866 void
867 avl_swap(avl_tree_t *tree1, avl_tree_t *tree2)
869 avl_node_t *temp_node;
870 ulong_t temp_numnodes;
872 ASSERT3P(tree1->avl_compar, ==, tree2->avl_compar);
873 ASSERT3U(tree1->avl_offset, ==, tree2->avl_offset);
875 temp_node = tree1->avl_root;
876 temp_numnodes = tree1->avl_numnodes;
877 tree1->avl_root = tree2->avl_root;
878 tree1->avl_numnodes = tree2->avl_numnodes;
879 tree2->avl_root = temp_node;
880 tree2->avl_numnodes = temp_numnodes;
884 * initialize a new AVL tree
886 void
887 avl_create(avl_tree_t *tree, int (*compar) (const void *, const void *),
888 size_t size, size_t offset)
890 ASSERT(tree);
891 ASSERT(compar);
892 ASSERT(size > 0);
893 ASSERT(size >= offset + sizeof (avl_node_t));
894 #ifdef _LP64
895 ASSERT((offset & 0x7) == 0);
896 #endif
898 tree->avl_compar = compar;
899 tree->avl_root = NULL;
900 tree->avl_numnodes = 0;
901 tree->avl_offset = offset;
905 * Delete a tree.
907 void
908 avl_destroy(avl_tree_t *tree)
910 ASSERT(tree);
911 ASSERT(tree->avl_numnodes == 0);
912 ASSERT(tree->avl_root == NULL);
917 * Return the number of nodes in an AVL tree.
919 ulong_t
920 avl_numnodes(avl_tree_t *tree)
922 ASSERT(tree);
923 return (tree->avl_numnodes);
926 boolean_t
927 avl_is_empty(avl_tree_t *tree)
929 ASSERT(tree);
930 return (tree->avl_numnodes == 0);
933 #define CHILDBIT (1L)
936 * Post-order tree walk used to visit all tree nodes and destroy the tree
937 * in post order. This is used for removing all the nodes from a tree without
938 * paying any cost for rebalancing it.
940 * example:
942 * void *cookie = NULL;
943 * my_data_t *node;
945 * while ((node = avl_destroy_nodes(tree, &cookie)) != NULL)
946 * free(node);
947 * avl_destroy(tree);
949 * The cookie is really an avl_node_t to the current node's parent and
950 * an indication of which child you looked at last.
952 * On input, a cookie value of CHILDBIT indicates the tree is done.
954 void *
955 avl_destroy_nodes(avl_tree_t *tree, void **cookie)
957 avl_node_t *node;
958 avl_node_t *parent;
959 int child;
960 void *first;
961 size_t off = tree->avl_offset;
964 * Initial calls go to the first node or it's right descendant.
966 if (*cookie == NULL) {
967 first = avl_first(tree);
970 * deal with an empty tree
972 if (first == NULL) {
973 *cookie = (void *)CHILDBIT;
974 return (NULL);
977 node = AVL_DATA2NODE(first, off);
978 parent = AVL_XPARENT(node);
979 goto check_right_side;
983 * If there is no parent to return to we are done.
985 parent = (avl_node_t *)((uintptr_t)(*cookie) & ~CHILDBIT);
986 if (parent == NULL) {
987 if (tree->avl_root != NULL) {
988 ASSERT(tree->avl_numnodes == 1);
989 tree->avl_root = NULL;
990 tree->avl_numnodes = 0;
992 return (NULL);
996 * Remove the child pointer we just visited from the parent and tree.
998 child = (uintptr_t)(*cookie) & CHILDBIT;
999 parent->avl_child[child] = NULL;
1000 ASSERT(tree->avl_numnodes > 1);
1001 --tree->avl_numnodes;
1004 * If we just removed a right child or there isn't one, go up to parent.
1006 if (child == 1 || parent->avl_child[1] == NULL) {
1007 node = parent;
1008 parent = AVL_XPARENT(parent);
1009 goto done;
1013 * Do parent's right child, then leftmost descendent.
1015 node = parent->avl_child[1];
1016 while (node->avl_child[0] != NULL) {
1017 parent = node;
1018 node = node->avl_child[0];
1022 * If here, we moved to a left child. It may have one
1023 * child on the right (when balance == +1).
1025 check_right_side:
1026 if (node->avl_child[1] != NULL) {
1027 ASSERT(AVL_XBALANCE(node) == 1);
1028 parent = node;
1029 node = node->avl_child[1];
1030 ASSERT(node->avl_child[0] == NULL &&
1031 node->avl_child[1] == NULL);
1032 } else {
1033 ASSERT(AVL_XBALANCE(node) <= 0);
1036 done:
1037 if (parent == NULL) {
1038 *cookie = (void *)CHILDBIT;
1039 ASSERT(node == tree->avl_root);
1040 } else {
1041 *cookie = (void *)((uintptr_t)parent | AVL_XCHILD(node));
1044 return (AVL_NODE2DATA(node, off));
1047 #if defined(_KERNEL)
1049 static int __init
1050 avl_init(void)
1052 return (0);
1055 static void __exit
1056 avl_fini(void)
1060 module_init(avl_init);
1061 module_exit(avl_fini);
1062 #endif
1064 ZFS_MODULE_DESCRIPTION("Generic AVL tree implementation");
1065 ZFS_MODULE_AUTHOR(ZFS_META_AUTHOR);
1066 ZFS_MODULE_LICENSE(ZFS_META_LICENSE);
1067 ZFS_MODULE_VERSION(ZFS_META_VERSION "-" ZFS_META_RELEASE);
1069 EXPORT_SYMBOL(avl_create);
1070 EXPORT_SYMBOL(avl_find);
1071 EXPORT_SYMBOL(avl_insert);
1072 EXPORT_SYMBOL(avl_insert_here);
1073 EXPORT_SYMBOL(avl_walk);
1074 EXPORT_SYMBOL(avl_first);
1075 EXPORT_SYMBOL(avl_last);
1076 EXPORT_SYMBOL(avl_nearest);
1077 EXPORT_SYMBOL(avl_add);
1078 EXPORT_SYMBOL(avl_swap);
1079 EXPORT_SYMBOL(avl_is_empty);
1080 EXPORT_SYMBOL(avl_remove);
1081 EXPORT_SYMBOL(avl_numnodes);
1082 EXPORT_SYMBOL(avl_destroy_nodes);
1083 EXPORT_SYMBOL(avl_destroy);
1084 EXPORT_SYMBOL(avl_update_lt);
1085 EXPORT_SYMBOL(avl_update_gt);
1086 EXPORT_SYMBOL(avl_update);