2 * Copyright (c) 2007 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * $DragonFly: src/sys/vfs/hammer/hammer_btree.c,v 1.30 2008/02/10 09:51:01 dillon Exp $
40 * HAMMER implements a modified B+Tree. In documentation this will
41 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
42 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
43 * of the tree), but adds two additional boundary elements which describe
44 * the left-most and right-most element a node is able to represent. In
45 * otherwords, we have boundary elements at the two ends of a B-Tree node
46 * instead of sub-tree pointers.
48 * A B-Tree internal node looks like this:
50 * B N N N N N N B <-- boundary and internal elements
51 * S S S S S S S <-- subtree pointers
53 * A B-Tree leaf node basically looks like this:
55 * L L L L L L L L <-- leaf elemenets
57 * The radix for an internal node is 1 less then a leaf but we get a
58 * number of significant benefits for our troubles.
60 * The big benefit to using a B-Tree containing boundary information
61 * is that it is possible to cache pointers into the middle of the tree
62 * and not have to start searches, insertions, OR deletions at the root
63 * node. In particular, searches are able to progress in a definitive
64 * direction from any point in the tree without revisting nodes. This
65 * greatly improves the efficiency of many operations, most especially
68 * B-Trees also make the stacking of trees fairly straightforward.
70 * INSERTIONS: A search performed with the intention of doing
71 * an insert will guarantee that the terminal leaf node is not full by
72 * splitting full nodes. Splits occur top-down during the dive down the
75 * DELETIONS: A deletion makes no attempt to proactively balance the
76 * tree and will recursively remove nodes that become empty. Empty
77 * nodes are not allowed and a deletion may recurse upwards from the leaf.
78 * Rather then allow a deadlock a deletion may terminate early by setting
79 * an internal node's element's subtree_offset to 0. The deletion will
80 * then be resumed the next time a search encounters the element.
86 static int btree_search(hammer_cursor_t cursor, int flags);
87 static int btree_split_internal(hammer_cursor_t cursor);
88 static int btree_split_leaf(hammer_cursor_t cursor);
89 static int btree_remove(hammer_cursor_t cursor);
90 static int btree_remove_deleted_element(hammer_cursor_t cursor);
91 static int btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm);
92 static int btree_node_is_full(hammer_node_ondisk_t node);
93 static void hammer_make_separator(hammer_base_elm_t key1,
94 hammer_base_elm_t key2, hammer_base_elm_t dest);
97 * Iterate records after a search. The cursor is iterated forwards past
98 * the current record until a record matching the key-range requirements
99 * is found. ENOENT is returned if the iteration goes past the ending
102 * The iteration is inclusive of key_beg and can be inclusive or exclusive
103 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
105 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
106 * may be modified by B-Tree functions.
108 * cursor->key_beg may or may not be modified by this function during
109 * the iteration. XXX future - in case of an inverted lock we may have
110 * to reinitiate the lookup and set key_beg to properly pick up where we
113 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
116 hammer_btree_iterate(hammer_cursor_t cursor)
118 hammer_node_ondisk_t node;
119 hammer_btree_elm_t elm;
125 * Skip past the current record
127 node = cursor->node->ondisk;
130 if (cursor->index < node->count &&
131 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
136 * Loop until an element is found or we are done.
140 * We iterate up the tree and then index over one element
141 * while we are at the last element in the current node.
143 * If we are at the root of the filesystem, cursor_up
146 * XXX this could be optimized by storing the information in
147 * the parent reference.
149 * XXX we can lose the node lock temporarily, this could mess
152 if (cursor->index == node->count) {
153 error = hammer_cursor_up(cursor);
156 /* reload stale pointer */
157 node = cursor->node->ondisk;
158 KKASSERT(cursor->index != node->count);
164 * Check internal or leaf element. Determine if the record
165 * at the cursor has gone beyond the end of our range.
167 * We recurse down through internal nodes.
169 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
170 elm = &node->elms[cursor->index];
171 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
172 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
173 if (hammer_debug_btree) {
174 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
175 cursor->node->node_offset,
177 elm[0].internal.base.obj_id,
178 elm[0].internal.base.rec_type,
179 elm[0].internal.base.key,
182 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
183 cursor->node->node_offset,
185 elm[1].internal.base.obj_id,
186 elm[1].internal.base.rec_type,
187 elm[1].internal.base.key,
196 if (r == 0 && (cursor->flags &
197 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
204 * When iterating try to clean up any deleted
205 * internal elements left over from btree_remove()
206 * deadlocks, but it is ok if we can't.
208 if (elm->internal.subtree_offset == 0) {
209 btree_remove_deleted_element(cursor);
210 /* note: elm also invalid */
211 } else if (elm->internal.subtree_offset != 0) {
212 error = hammer_cursor_down(cursor);
215 KKASSERT(cursor->index == 0);
217 /* reload stale pointer */
218 node = cursor->node->ondisk;
221 elm = &node->elms[cursor->index];
222 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
223 if (hammer_debug_btree) {
224 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
225 cursor->node->node_offset,
227 (elm[0].leaf.base.btype ?
228 elm[0].leaf.base.btype : '?'),
229 elm[0].leaf.base.obj_id,
230 elm[0].leaf.base.rec_type,
231 elm[0].leaf.base.key,
241 * We support both end-inclusive and
242 * end-exclusive searches.
245 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
250 switch(elm->leaf.base.btype) {
251 case HAMMER_BTREE_TYPE_RECORD:
252 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
253 hammer_btree_chkts(cursor->asof, &elm->base)) {
266 * node pointer invalid after loop
272 if (hammer_debug_btree) {
273 int i = cursor->index;
274 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
275 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
277 elm->internal.base.obj_id,
278 elm->internal.base.rec_type,
279 elm->internal.base.key
288 * Iterate in the reverse direction. This is used by the pruning code to
289 * avoid overlapping records.
292 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
294 hammer_node_ondisk_t node;
295 hammer_btree_elm_t elm;
301 * Skip past the current record. For various reasons the cursor
302 * may end up set to -1 or set to point at the end of the current
303 * node. These cases must be addressed.
305 node = cursor->node->ondisk;
308 if (cursor->index != -1 &&
309 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
312 if (cursor->index == cursor->node->ondisk->count)
316 * Loop until an element is found or we are done.
320 * We iterate up the tree and then index over one element
321 * while we are at the last element in the current node.
323 if (cursor->index == -1) {
324 error = hammer_cursor_up(cursor);
326 cursor->index = 0; /* sanity */
329 /* reload stale pointer */
330 node = cursor->node->ondisk;
331 KKASSERT(cursor->index != node->count);
337 * Check internal or leaf element. Determine if the record
338 * at the cursor has gone beyond the end of our range.
340 * We recurse down through internal nodes.
342 KKASSERT(cursor->index != node->count);
343 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
344 elm = &node->elms[cursor->index];
345 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
346 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
347 if (hammer_debug_btree) {
348 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
349 cursor->node->node_offset,
351 elm[0].internal.base.obj_id,
352 elm[0].internal.base.rec_type,
353 elm[0].internal.base.key,
356 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
357 cursor->node->node_offset,
359 elm[1].internal.base.obj_id,
360 elm[1].internal.base.rec_type,
361 elm[1].internal.base.key,
373 * When iterating try to clean up any deleted
374 * internal elements left over from btree_remove()
375 * deadlocks, but it is ok if we can't.
377 if (elm->internal.subtree_offset == 0) {
378 btree_remove_deleted_element(cursor);
379 /* note: elm also invalid */
380 } else if (elm->internal.subtree_offset != 0) {
381 error = hammer_cursor_down(cursor);
384 KKASSERT(cursor->index == 0);
385 cursor->index = cursor->node->ondisk->count - 1;
387 /* reload stale pointer */
388 node = cursor->node->ondisk;
391 elm = &node->elms[cursor->index];
392 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
393 if (hammer_debug_btree) {
394 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
395 cursor->node->node_offset,
397 (elm[0].leaf.base.btype ?
398 elm[0].leaf.base.btype : '?'),
399 elm[0].leaf.base.obj_id,
400 elm[0].leaf.base.rec_type,
401 elm[0].leaf.base.key,
410 switch(elm->leaf.base.btype) {
411 case HAMMER_BTREE_TYPE_RECORD:
412 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
413 hammer_btree_chkts(cursor->asof, &elm->base)) {
426 * node pointer invalid after loop
432 if (hammer_debug_btree) {
433 int i = cursor->index;
434 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
435 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
437 elm->internal.base.obj_id,
438 elm->internal.base.rec_type,
439 elm->internal.base.key
448 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
449 * could not be found, EDEADLK if inserting and a retry is needed, and a
450 * fatal error otherwise. When retrying, the caller must terminate the
451 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
453 * The cursor is suitably positioned for a deletion on success, and suitably
454 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
457 * The cursor may begin anywhere, the search will traverse the tree in
458 * either direction to locate the requested element.
460 * Most of the logic implementing historical searches is handled here. We
461 * do an initial lookup with create_tid set to the asof TID. Due to the
462 * way records are laid out, a backwards iteration may be required if
463 * ENOENT is returned to locate the historical record. Here's the
466 * create_tid: 10 15 20
470 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
471 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
472 * not visible and thus causes ENOENT to be returned. We really need
473 * to check record 11 in LEAF1. If it also fails then the search fails
474 * (e.g. it might represent the range 11-16 and thus still not match our
475 * AS-OF timestamp of 17).
477 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
478 * and the cursor->create_check TID if an iteration might be needed.
479 * In the above example create_check would be set to 14.
482 hammer_btree_lookup(hammer_cursor_t cursor)
486 if (cursor->flags & HAMMER_CURSOR_ASOF) {
487 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
488 cursor->key_beg.create_tid = cursor->asof;
490 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
491 error = btree_search(cursor, 0);
492 if (error != ENOENT ||
493 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
496 * Stop if error other then ENOENT.
497 * Stop if ENOENT and not special case.
501 if (hammer_debug_btree) {
502 kprintf("CREATE_CHECK %016llx\n",
503 cursor->create_check);
505 cursor->key_beg.create_tid = cursor->create_check;
509 error = btree_search(cursor, 0);
511 if (error == 0 && cursor->flags)
512 error = hammer_btree_extract(cursor, cursor->flags);
517 * Execute the logic required to start an iteration. The first record
518 * located within the specified range is returned and iteration control
519 * flags are adjusted for successive hammer_btree_iterate() calls.
522 hammer_btree_first(hammer_cursor_t cursor)
526 error = hammer_btree_lookup(cursor);
527 if (error == ENOENT) {
528 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
529 error = hammer_btree_iterate(cursor);
531 cursor->flags |= HAMMER_CURSOR_ATEDISK;
536 * Similarly but for an iteration in the reverse direction.
539 hammer_btree_last(hammer_cursor_t cursor)
541 struct hammer_base_elm save;
544 save = cursor->key_beg;
545 cursor->key_beg = cursor->key_end;
546 error = hammer_btree_lookup(cursor);
547 cursor->key_beg = save;
548 if (error == ENOENT ||
549 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
550 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
551 error = hammer_btree_iterate_reverse(cursor);
553 cursor->flags |= HAMMER_CURSOR_ATEDISK;
558 * Extract the record and/or data associated with the cursor's current
559 * position. Any prior record or data stored in the cursor is replaced.
560 * The cursor must be positioned at a leaf node.
562 * NOTE: All extractions occur at the leaf of the B-Tree.
565 hammer_btree_extract(hammer_cursor_t cursor, int flags)
568 hammer_node_ondisk_t node;
569 hammer_btree_elm_t elm;
570 hammer_off_t rec_off;
571 hammer_off_t data_off;
575 * The case where the data reference resolves to the same buffer
576 * as the record reference must be handled.
578 node = cursor->node->ondisk;
579 elm = &node->elms[cursor->index];
581 hmp = cursor->node->hmp;
582 flags |= cursor->flags & HAMMER_CURSOR_DATAEXTOK;
585 * There is nothing to extract for an internal element.
587 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
591 * Only record types have data.
593 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
594 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
595 flags &= ~HAMMER_CURSOR_GET_DATA;
596 data_off = elm->leaf.data_offset;
598 flags &= ~HAMMER_CURSOR_GET_DATA;
599 rec_off = elm->leaf.rec_offset;
602 * Extract the record if the record was requested or the data
603 * resides in the record buf.
605 if ((flags & HAMMER_CURSOR_GET_RECORD) ||
606 ((flags & HAMMER_CURSOR_GET_DATA) &&
607 ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) == 0)) {
608 cursor->record = hammer_bread(hmp, rec_off, &error,
609 &cursor->record_buffer);
614 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
615 if ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) {
617 * Data and record are in different buffers.
619 cursor->data = hammer_bread(hmp, data_off, &error,
620 &cursor->data_buffer);
623 * Data resides in same buffer as record.
625 cursor->data = (void *)
626 ((char *)cursor->record_buffer->ondisk +
627 ((int32_t)data_off & HAMMER_BUFMASK));
635 * Insert a leaf element into the B-Tree at the current cursor position.
636 * The cursor is positioned such that the element at and beyond the cursor
637 * are shifted to make room for the new record.
639 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
640 * flag set and that call must return ENOENT before this function can be
643 * ENOSPC is returned if there is no room to insert a new record.
646 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
648 hammer_node_ondisk_t node;
652 if ((error = hammer_cursor_upgrade(cursor)) != 0)
656 * Insert the element at the leaf node and update the count in the
657 * parent. It is possible for parent to be NULL, indicating that
658 * the filesystem's ROOT B-Tree node is a leaf itself, which is
659 * possible. The root inode can never be deleted so the leaf should
662 * Remember that the right-hand boundary is not included in the
665 hammer_modify_node(cursor->node);
666 node = cursor->node->ondisk;
668 KKASSERT(elm->base.btype != 0);
669 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
670 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
671 if (i != node->count) {
672 bcopy(&node->elms[i], &node->elms[i+1],
673 (node->count - i) * sizeof(*elm));
675 node->elms[i] = *elm;
679 * Debugging sanity checks.
681 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
682 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
684 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->leaf.base) < 0);
686 if (i != node->count - 1)
687 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->leaf.base) > 0);
693 * Delete a record from the B-Tree at the current cursor position.
694 * The cursor is positioned such that the current element is the one
697 * On return the cursor will be positioned after the deleted element and
698 * MAY point to an internal node. It will be suitable for the continuation
699 * of an iteration but not for an insertion or deletion.
701 * Deletions will attempt to partially rebalance the B-Tree in an upward
702 * direction, but will terminate rather then deadlock. Empty leaves are
703 * not allowed. An early termination will leave an internal node with an
704 * element whos subtree_offset is 0, a case detected and handled by
707 * This function can return EDEADLK, requiring the caller to retry the
708 * operation after clearing the deadlock.
711 hammer_btree_delete(hammer_cursor_t cursor)
713 hammer_node_ondisk_t ondisk;
715 hammer_node_t parent;
719 if ((error = hammer_cursor_upgrade(cursor)) != 0)
723 * Delete the element from the leaf node.
725 * Remember that leaf nodes do not have boundaries.
728 ondisk = node->ondisk;
731 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
732 KKASSERT(i >= 0 && i < ondisk->count);
733 hammer_modify_node(node);
734 if (i + 1 != ondisk->count) {
735 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
736 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
741 * Validate local parent
743 if (ondisk->parent) {
744 parent = cursor->parent;
746 KKASSERT(parent != NULL);
747 KKASSERT(parent->node_offset == ondisk->parent);
751 * If the leaf becomes empty it must be detached from the parent,
752 * potentially recursing through to the filesystem root.
754 * This may reposition the cursor at one of the parent's of the
757 * Ignore deadlock errors, that simply means that btree_remove
758 * was unable to recurse and had to leave the subtree_offset
759 * in the parent set to 0.
761 KKASSERT(cursor->index <= ondisk->count);
762 if (ondisk->count == 0) {
764 error = btree_remove(cursor);
765 } while (error == EAGAIN);
766 if (error == EDEADLK)
771 KKASSERT(cursor->parent == NULL ||
772 cursor->parent_index < cursor->parent->ondisk->count);
777 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
779 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
781 * The search can begin ANYWHERE in the B-Tree. As a first step the search
782 * iterates up the tree as necessary to properly position itself prior to
783 * actually doing the sarch.
785 * INSERTIONS: The search will split full nodes and leaves on its way down
786 * and guarentee that the leaf it ends up on is not full. If we run out
787 * of space the search continues to the leaf (to position the cursor for
788 * the spike), but ENOSPC is returned.
790 * The search is only guarenteed to end up on a leaf if an error code of 0
791 * is returned, or if inserting and an error code of ENOENT is returned.
792 * Otherwise it can stop at an internal node. On success a search returns
795 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
796 * filesystem, and it is not simple code. Please note the following facts:
798 * - Internal node recursions have a boundary on the left AND right. The
799 * right boundary is non-inclusive. The create_tid is a generic part
800 * of the key for internal nodes.
802 * - Leaf nodes contain terminal elements only now.
804 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
805 * historical search. ASOF and INSERT are mutually exclusive. When
806 * doing an as-of lookup btree_search() checks for a right-edge boundary
807 * case. If while recursing down the left-edge differs from the key
808 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
809 * with cursor->create_check. This is used by btree_lookup() to iterate.
810 * The iteration backwards because as-of searches can wind up going
811 * down the wrong branch of the B-Tree.
815 btree_search(hammer_cursor_t cursor, int flags)
817 hammer_node_ondisk_t node;
818 hammer_btree_elm_t elm;
825 flags |= cursor->flags;
827 if (hammer_debug_btree) {
828 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx\n",
829 cursor->node->node_offset,
831 cursor->key_beg.obj_id,
832 cursor->key_beg.rec_type,
834 cursor->key_beg.create_tid
839 * Move our cursor up the tree until we find a node whos range covers
840 * the key we are trying to locate.
842 * The left bound is inclusive, the right bound is non-inclusive.
843 * It is ok to cursor up too far.
846 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
847 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
850 KKASSERT(cursor->parent);
851 error = hammer_cursor_up(cursor);
857 * The delete-checks below are based on node, not parent. Set the
858 * initial delete-check based on the parent.
861 KKASSERT(cursor->left_bound->create_tid != 1);
862 cursor->create_check = cursor->left_bound->create_tid - 1;
863 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
867 * We better have ended up with a node somewhere.
869 KKASSERT(cursor->node != NULL);
872 * If we are inserting we can't start at a full node if the parent
873 * is also full (because there is no way to split the node),
874 * continue running up the tree until the requirement is satisfied
875 * or we hit the root of the filesystem.
877 * (If inserting we aren't doing an as-of search so we don't have
878 * to worry about create_check).
880 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
881 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
882 if (btree_node_is_full(cursor->node->ondisk) == 0)
885 if (btree_node_is_full(cursor->node->ondisk) ==0)
888 if (cursor->node->ondisk->parent == 0 ||
889 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
892 error = hammer_cursor_up(cursor);
893 /* node may have become stale */
900 * Push down through internal nodes to locate the requested key.
902 node = cursor->node->ondisk;
903 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
905 * Scan the node to find the subtree index to push down into.
906 * We go one-past, then back-up.
908 * We must proactively remove deleted elements which may
909 * have been left over from a deadlocked btree_remove().
911 * The left and right boundaries are included in the loop
912 * in order to detect edge cases.
914 * If the separator only differs by create_tid (r == 1)
915 * and we are doing an as-of search, we may end up going
916 * down a branch to the left of the one containing the
917 * desired key. This requires numerous special cases.
919 if (hammer_debug_btree) {
920 kprintf("SEARCH-I %016llx count=%d\n",
921 cursor->node->node_offset,
924 for (i = 0; i <= node->count; ++i) {
925 elm = &node->elms[i];
926 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
927 if (hammer_debug_btree > 2) {
928 kprintf(" IELM %p %d r=%d\n",
929 &node->elms[i], i, r);
934 KKASSERT(elm->base.create_tid != 1);
935 cursor->create_check = elm->base.create_tid - 1;
936 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
939 if (hammer_debug_btree) {
940 kprintf("SEARCH-I preI=%d/%d r=%d\n",
945 * These cases occur when the parent's idea of the boundary
946 * is wider then the child's idea of the boundary, and
947 * require special handling. If not inserting we can
948 * terminate the search early for these cases but the
949 * child's boundaries cannot be unconditionally modified.
953 * If i == 0 the search terminated to the LEFT of the
954 * left_boundary but to the RIGHT of the parent's left
959 elm = &node->elms[0];
962 * If we aren't inserting we can stop here.
964 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
970 * Correct a left-hand boundary mismatch.
972 * We can only do this if we can upgrade the lock.
974 if ((error = hammer_cursor_upgrade(cursor)) != 0)
976 hammer_modify_node(cursor->node);
977 save = node->elms[0].base.btype;
978 node->elms[0].base = *cursor->left_bound;
979 node->elms[0].base.btype = save;
980 } else if (i == node->count + 1) {
982 * If i == node->count + 1 the search terminated to
983 * the RIGHT of the right boundary but to the LEFT
984 * of the parent's right boundary. If we aren't
985 * inserting we can stop here.
987 * Note that the last element in this case is
988 * elms[i-2] prior to adjustments to 'i'.
991 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
997 * Correct a right-hand boundary mismatch.
998 * (actual push-down record is i-2 prior to
1001 * We can only do this if we can upgrade the lock.
1003 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1005 elm = &node->elms[i];
1006 hammer_modify_node(cursor->node);
1007 elm->base = *cursor->right_bound;
1011 * The push-down index is now i - 1. If we had
1012 * terminated on the right boundary this will point
1013 * us at the last element.
1018 elm = &node->elms[i];
1020 if (hammer_debug_btree) {
1021 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1022 "key=%016llx cre=%016llx\n",
1023 cursor->node->node_offset,
1025 elm->internal.base.obj_id,
1026 elm->internal.base.rec_type,
1027 elm->internal.base.key,
1028 elm->internal.base.create_tid
1033 * When searching try to clean up any deleted
1034 * internal elements left over from btree_remove()
1037 * If we fail and we are doing an insertion lookup,
1038 * we have to return EDEADLK, because an insertion lookup
1039 * must terminate at a leaf.
1041 if (elm->internal.subtree_offset == 0) {
1042 error = btree_remove_deleted_element(cursor);
1045 if (error == EDEADLK &&
1046 (flags & HAMMER_CURSOR_INSERT) == 0) {
1054 * Handle insertion and deletion requirements.
1056 * If inserting split full nodes. The split code will
1057 * adjust cursor->node and cursor->index if the current
1058 * index winds up in the new node.
1060 * If inserting and a left or right edge case was detected,
1061 * we cannot correct the left or right boundary and must
1062 * prepend and append an empty leaf node in order to make
1063 * the boundary correction.
1065 * If we run out of space we set enospc and continue on
1066 * to a leaf to provide the spike code with a good point
1069 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1070 if (btree_node_is_full(node)) {
1071 error = btree_split_internal(cursor);
1073 if (error != ENOSPC)
1078 * reload stale pointers
1081 node = cursor->node->ondisk;
1086 * Push down (push into new node, existing node becomes
1087 * the parent) and continue the search.
1089 error = hammer_cursor_down(cursor);
1090 /* node may have become stale */
1093 node = cursor->node->ondisk;
1097 * We are at a leaf, do a linear search of the key array.
1099 * If we encounter a spike element type within the necessary
1100 * range we push into it.
1102 * On success the index is set to the matching element and 0
1105 * On failure the index is set to the insertion point and ENOENT
1108 * Boundaries are not stored in leaf nodes, so the index can wind
1109 * up to the left of element 0 (index == 0) or past the end of
1110 * the array (index == node->count).
1112 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1113 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1114 if (hammer_debug_btree) {
1115 kprintf("SEARCH-L %016llx count=%d\n",
1116 cursor->node->node_offset,
1120 for (i = 0; i < node->count; ++i) {
1121 elm = &node->elms[i];
1123 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1125 if (hammer_debug_btree > 1)
1126 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1129 * We are at a record element. Stop if we've flipped past
1130 * key_beg, not counting the create_tid test. Allow the
1131 * r == 1 case (key_beg > element but differs only by its
1132 * create_tid) to fall through to the AS-OF check.
1134 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1142 * Check our as-of timestamp against the element.
1144 if (flags & HAMMER_CURSOR_ASOF) {
1145 if (hammer_btree_chkts(cursor->asof,
1146 &node->elms[i].base) != 0) {
1151 if (r > 0) /* can only be +1 */
1157 if (hammer_debug_btree) {
1158 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1159 cursor->node->node_offset, i);
1165 * The search of the leaf node failed. i is the insertion point.
1168 if (hammer_debug_btree) {
1169 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1170 cursor->node->node_offset, i);
1174 * No exact match was found, i is now at the insertion point.
1176 * If inserting split a full leaf before returning. This
1177 * may have the side effect of adjusting cursor->node and
1181 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1182 btree_node_is_full(node)) {
1183 error = btree_split_leaf(cursor);
1185 if (error != ENOSPC)
1190 * reload stale pointers
1194 node = &cursor->node->internal;
1199 * We reached a leaf but did not find the key we were looking for.
1200 * If this is an insert we will be properly positioned for an insert
1201 * (ENOENT) or spike (ENOSPC) operation.
1203 error = enospc ? ENOSPC : ENOENT;
1209 /************************************************************************
1210 * SPLITTING AND MERGING *
1211 ************************************************************************
1213 * These routines do all the dirty work required to split and merge nodes.
1217 * Split an internal node into two nodes and move the separator at the split
1218 * point to the parent.
1220 * (cursor->node, cursor->index) indicates the element the caller intends
1221 * to push into. We will adjust node and index if that element winds
1222 * up in the split node.
1224 * If we are at the root of the filesystem a new root must be created with
1225 * two elements, one pointing to the original root and one pointing to the
1226 * newly allocated split node.
1230 btree_split_internal(hammer_cursor_t cursor)
1232 hammer_node_ondisk_t ondisk;
1235 hammer_node_t parent;
1236 hammer_node_t new_node;
1237 hammer_btree_elm_t elm;
1238 hammer_btree_elm_t parent_elm;
1239 hammer_node_locklist_t locklist = NULL;
1245 const int esize = sizeof(*elm);
1247 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1249 error = hammer_btree_lock_children(cursor, &locklist);
1254 * We are splitting but elms[split] will be promoted to the parent,
1255 * leaving the right hand node with one less element. If the
1256 * insertion point will be on the left-hand side adjust the split
1257 * point to give the right hand side one additional node.
1259 node = cursor->node;
1260 ondisk = node->ondisk;
1261 split = (ondisk->count + 1) / 2;
1262 if (cursor->index <= split)
1267 * If we are at the root of the filesystem, create a new root node
1268 * with 1 element and split normally. Avoid making major
1269 * modifications until we know the whole operation will work.
1271 if (ondisk->parent == 0) {
1272 parent = hammer_alloc_btree(hmp, &error);
1275 hammer_lock_ex(&parent->lock);
1276 hammer_modify_node(parent);
1277 ondisk = parent->ondisk;
1280 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1281 ondisk->elms[0].base = hmp->root_btree_beg;
1282 ondisk->elms[0].base.btype = node->ondisk->type;
1283 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1284 ondisk->elms[1].base = hmp->root_btree_end;
1285 /* ondisk->elms[1].base.btype - not used */
1287 parent_index = 0; /* index of current node in parent */
1290 parent = cursor->parent;
1291 parent_index = cursor->parent_index;
1295 * Split node into new_node at the split point.
1297 * B O O O P N N B <-- P = node->elms[split]
1298 * 0 1 2 3 4 5 6 <-- subtree indices
1303 * B O O O B B N N B <--- inner boundary points are 'P'
1307 new_node = hammer_alloc_btree(hmp, &error);
1308 if (new_node == NULL) {
1310 hammer_unlock(&parent->lock);
1311 parent->flags |= HAMMER_NODE_DELETED;
1312 hammer_rel_node(parent);
1316 hammer_lock_ex(&new_node->lock);
1319 * Create the new node. P becomes the left-hand boundary in the
1320 * new node. Copy the right-hand boundary as well.
1322 * elm is the new separator.
1324 hammer_modify_node(new_node);
1325 hammer_modify_node(node);
1326 ondisk = node->ondisk;
1327 elm = &ondisk->elms[split];
1328 bcopy(elm, &new_node->ondisk->elms[0],
1329 (ondisk->count - split + 1) * esize);
1330 new_node->ondisk->count = ondisk->count - split;
1331 new_node->ondisk->parent = parent->node_offset;
1332 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1333 KKASSERT(ondisk->type == new_node->ondisk->type);
1336 * Cleanup the original node. Elm (P) becomes the new boundary,
1337 * its subtree_offset was moved to the new node. If we had created
1338 * a new root its parent pointer may have changed.
1340 elm->internal.subtree_offset = 0;
1341 ondisk->count = split;
1344 * Insert the separator into the parent, fixup the parent's
1345 * reference to the original node, and reference the new node.
1346 * The separator is P.
1348 * Remember that base.count does not include the right-hand boundary.
1350 hammer_modify_node(parent);
1351 ondisk = parent->ondisk;
1352 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1353 parent_elm = &ondisk->elms[parent_index+1];
1354 bcopy(parent_elm, parent_elm + 1,
1355 (ondisk->count - parent_index) * esize);
1356 parent_elm->internal.base = elm->base; /* separator P */
1357 parent_elm->internal.base.btype = new_node->ondisk->type;
1358 parent_elm->internal.subtree_offset = new_node->node_offset;
1362 * The children of new_node need their parent pointer set to new_node.
1363 * The children have already been locked by
1364 * hammer_btree_lock_children().
1366 for (i = 0; i < new_node->ondisk->count; ++i) {
1367 elm = &new_node->ondisk->elms[i];
1368 error = btree_set_parent(new_node, elm);
1370 panic("btree_split_internal: btree-fixup problem");
1375 * The filesystem's root B-Tree pointer may have to be updated.
1378 hammer_volume_t volume;
1380 volume = hammer_get_root_volume(hmp, &error);
1381 KKASSERT(error == 0);
1383 hammer_modify_volume(volume, &volume->ondisk->vol0_btree_root,
1384 sizeof(hammer_off_t));
1385 volume->ondisk->vol0_btree_root = parent->node_offset;
1386 node->ondisk->parent = parent->node_offset;
1387 if (cursor->parent) {
1388 hammer_unlock(&cursor->parent->lock);
1389 hammer_rel_node(cursor->parent);
1391 cursor->parent = parent; /* lock'd and ref'd */
1392 hammer_rel_volume(volume, 0);
1397 * Ok, now adjust the cursor depending on which element the original
1398 * index was pointing at. If we are >= the split point the push node
1399 * is now in the new node.
1401 * NOTE: If we are at the split point itself we cannot stay with the
1402 * original node because the push index will point at the right-hand
1403 * boundary, which is illegal.
1405 * NOTE: The cursor's parent or parent_index must be adjusted for
1406 * the case where a new parent (new root) was created, and the case
1407 * where the cursor is now pointing at the split node.
1409 if (cursor->index >= split) {
1410 cursor->parent_index = parent_index + 1;
1411 cursor->index -= split;
1412 hammer_unlock(&cursor->node->lock);
1413 hammer_rel_node(cursor->node);
1414 cursor->node = new_node; /* locked and ref'd */
1416 cursor->parent_index = parent_index;
1417 hammer_unlock(&new_node->lock);
1418 hammer_rel_node(new_node);
1422 * Fixup left and right bounds
1424 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1425 cursor->left_bound = &parent_elm[0].internal.base;
1426 cursor->right_bound = &parent_elm[1].internal.base;
1427 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1428 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1429 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1430 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1433 hammer_btree_unlock_children(&locklist);
1434 hammer_cursor_downgrade(cursor);
1439 * Same as the above, but splits a full leaf node.
1445 btree_split_leaf(hammer_cursor_t cursor)
1447 hammer_node_ondisk_t ondisk;
1448 hammer_node_t parent;
1451 hammer_node_t new_leaf;
1452 hammer_btree_elm_t elm;
1453 hammer_btree_elm_t parent_elm;
1454 hammer_base_elm_t mid_boundary;
1459 const size_t esize = sizeof(*elm);
1461 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1465 * Calculate the split point. If the insertion point will be on
1466 * the left-hand side adjust the split point to give the right
1467 * hand side one additional node.
1469 * Spikes are made up of two leaf elements which cannot be
1472 leaf = cursor->node;
1473 ondisk = leaf->ondisk;
1474 split = (ondisk->count + 1) / 2;
1475 if (cursor->index <= split)
1480 elm = &ondisk->elms[split];
1483 * If we are at the root of the tree, create a new root node with
1484 * 1 element and split normally. Avoid making major modifications
1485 * until we know the whole operation will work.
1487 if (ondisk->parent == 0) {
1488 parent = hammer_alloc_btree(hmp, &error);
1491 hammer_lock_ex(&parent->lock);
1492 hammer_modify_node(parent);
1493 ondisk = parent->ondisk;
1496 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1497 ondisk->elms[0].base = hmp->root_btree_beg;
1498 ondisk->elms[0].base.btype = leaf->ondisk->type;
1499 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1500 ondisk->elms[1].base = hmp->root_btree_end;
1501 /* ondisk->elms[1].base.btype = not used */
1503 parent_index = 0; /* insertion point in parent */
1506 parent = cursor->parent;
1507 parent_index = cursor->parent_index;
1511 * Split leaf into new_leaf at the split point. Select a separator
1512 * value in-between the two leafs but with a bent towards the right
1513 * leaf since comparisons use an 'elm >= separator' inequality.
1522 new_leaf = hammer_alloc_btree(hmp, &error);
1523 if (new_leaf == NULL) {
1525 hammer_unlock(&parent->lock);
1526 parent->flags |= HAMMER_NODE_DELETED;
1527 hammer_rel_node(parent);
1531 hammer_lock_ex(&new_leaf->lock);
1534 * Create the new node. P (elm) become the left-hand boundary in the
1535 * new node. Copy the right-hand boundary as well.
1537 hammer_modify_node(leaf);
1538 hammer_modify_node(new_leaf);
1539 ondisk = leaf->ondisk;
1540 elm = &ondisk->elms[split];
1541 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1542 new_leaf->ondisk->count = ondisk->count - split;
1543 new_leaf->ondisk->parent = parent->node_offset;
1544 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1545 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1548 * Cleanup the original node. Because this is a leaf node and
1549 * leaf nodes do not have a right-hand boundary, there
1550 * aren't any special edge cases to clean up. We just fixup the
1553 ondisk->count = split;
1556 * Insert the separator into the parent, fixup the parent's
1557 * reference to the original node, and reference the new node.
1558 * The separator is P.
1560 * Remember that base.count does not include the right-hand boundary.
1561 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1563 hammer_modify_node(parent);
1564 ondisk = parent->ondisk;
1565 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1566 parent_elm = &ondisk->elms[parent_index+1];
1567 bcopy(parent_elm, parent_elm + 1,
1568 (ondisk->count - parent_index) * esize);
1570 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1571 parent_elm->internal.base.btype = new_leaf->ondisk->type;
1572 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1573 mid_boundary = &parent_elm->base;
1577 * The filesystem's root B-Tree pointer may have to be updated.
1580 hammer_volume_t volume;
1582 volume = hammer_get_root_volume(hmp, &error);
1583 KKASSERT(error == 0);
1585 hammer_modify_volume(volume, &volume->ondisk->vol0_btree_root,
1586 sizeof(hammer_off_t));
1587 volume->ondisk->vol0_btree_root = parent->node_offset;
1588 leaf->ondisk->parent = parent->node_offset;
1589 if (cursor->parent) {
1590 hammer_unlock(&cursor->parent->lock);
1591 hammer_rel_node(cursor->parent);
1593 cursor->parent = parent; /* lock'd and ref'd */
1594 hammer_rel_volume(volume, 0);
1598 * Ok, now adjust the cursor depending on which element the original
1599 * index was pointing at. If we are >= the split point the push node
1600 * is now in the new node.
1602 * NOTE: If we are at the split point itself we need to select the
1603 * old or new node based on where key_beg's insertion point will be.
1604 * If we pick the wrong side the inserted element will wind up in
1605 * the wrong leaf node and outside that node's bounds.
1607 if (cursor->index > split ||
1608 (cursor->index == split &&
1609 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1610 cursor->parent_index = parent_index + 1;
1611 cursor->index -= split;
1612 hammer_unlock(&cursor->node->lock);
1613 hammer_rel_node(cursor->node);
1614 cursor->node = new_leaf;
1616 cursor->parent_index = parent_index;
1617 hammer_unlock(&new_leaf->lock);
1618 hammer_rel_node(new_leaf);
1622 * Fixup left and right bounds
1624 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1625 cursor->left_bound = &parent_elm[0].internal.base;
1626 cursor->right_bound = &parent_elm[1].internal.base;
1629 * Assert that the bounds are correct.
1631 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1632 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1633 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1634 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1637 hammer_cursor_downgrade(cursor);
1642 * Recursively correct the right-hand boundary's create_tid to (tid) as
1643 * long as the rest of the key matches. We have to recurse upward in
1644 * the tree as well as down the left side of each parent's right node.
1646 * Return EDEADLK if we were only partially successful, forcing the caller
1647 * to try again. The original cursor is not modified. This routine can
1648 * also fail with EDEADLK if it is forced to throw away a portion of its
1651 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1654 TAILQ_ENTRY(hammer_rhb) entry;
1659 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1662 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1664 struct hammer_rhb_list rhb_list;
1665 hammer_base_elm_t elm;
1666 hammer_node_t orig_node;
1667 struct hammer_rhb *rhb;
1671 TAILQ_INIT(&rhb_list);
1674 * Save our position so we can restore it on return. This also
1675 * gives us a stable 'elm'.
1677 orig_node = cursor->node;
1678 hammer_ref_node(orig_node);
1679 hammer_lock_sh(&orig_node->lock);
1680 orig_index = cursor->index;
1681 elm = &orig_node->ondisk->elms[orig_index].base;
1684 * Now build a list of parents going up, allocating a rhb
1685 * structure for each one.
1687 while (cursor->parent) {
1689 * Stop if we no longer have any right-bounds to fix up
1691 if (elm->obj_id != cursor->right_bound->obj_id ||
1692 elm->rec_type != cursor->right_bound->rec_type ||
1693 elm->key != cursor->right_bound->key) {
1698 * Stop if the right-hand bound's create_tid does not
1699 * need to be corrected.
1701 if (cursor->right_bound->create_tid >= tid)
1704 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1705 rhb->node = cursor->parent;
1706 rhb->index = cursor->parent_index;
1707 hammer_ref_node(rhb->node);
1708 hammer_lock_sh(&rhb->node->lock);
1709 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1711 hammer_cursor_up(cursor);
1715 * now safely adjust the right hand bound for each rhb. This may
1716 * also require taking the right side of the tree and iterating down
1720 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1721 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1722 kprintf("CORRECT RHB %016llx index %d type=%c\n",
1723 rhb->node->node_offset,
1724 rhb->index, cursor->node->ondisk->type);
1727 TAILQ_REMOVE(&rhb_list, rhb, entry);
1728 hammer_unlock(&rhb->node->lock);
1729 hammer_rel_node(rhb->node);
1730 kfree(rhb, M_HAMMER);
1732 switch (cursor->node->ondisk->type) {
1733 case HAMMER_BTREE_TYPE_INTERNAL:
1735 * Right-boundary for parent at internal node
1736 * is one element to the right of the element whos
1737 * right boundary needs adjusting. We must then
1738 * traverse down the left side correcting any left
1739 * bounds (which may now be too far to the left).
1742 error = hammer_btree_correct_lhb(cursor, tid);
1745 panic("hammer_btree_correct_rhb(): Bad node type");
1754 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1755 TAILQ_REMOVE(&rhb_list, rhb, entry);
1756 hammer_unlock(&rhb->node->lock);
1757 hammer_rel_node(rhb->node);
1758 kfree(rhb, M_HAMMER);
1760 error = hammer_cursor_seek(cursor, orig_node, orig_index);
1761 hammer_unlock(&orig_node->lock);
1762 hammer_rel_node(orig_node);
1767 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
1768 * bound going downward starting at the current cursor position.
1770 * This function does not restore the cursor after use.
1773 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
1775 struct hammer_rhb_list rhb_list;
1776 hammer_base_elm_t elm;
1777 hammer_base_elm_t cmp;
1778 struct hammer_rhb *rhb;
1781 TAILQ_INIT(&rhb_list);
1783 cmp = &cursor->node->ondisk->elms[cursor->index].base;
1786 * Record the node and traverse down the left-hand side for all
1787 * matching records needing a boundary correction.
1791 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1792 rhb->node = cursor->node;
1793 rhb->index = cursor->index;
1794 hammer_ref_node(rhb->node);
1795 hammer_lock_sh(&rhb->node->lock);
1796 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1798 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1800 * Nothing to traverse down if we are at the right
1801 * boundary of an internal node.
1803 if (cursor->index == cursor->node->ondisk->count)
1806 elm = &cursor->node->ondisk->elms[cursor->index].base;
1807 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
1809 panic("Illegal leaf record type %02x", elm->btype);
1811 error = hammer_cursor_down(cursor);
1815 elm = &cursor->node->ondisk->elms[cursor->index].base;
1816 if (elm->obj_id != cmp->obj_id ||
1817 elm->rec_type != cmp->rec_type ||
1818 elm->key != cmp->key) {
1821 if (elm->create_tid >= tid)
1827 * Now we can safely adjust the left-hand boundary from the bottom-up.
1828 * The last element we remove from the list is the caller's right hand
1829 * boundary, which must also be adjusted.
1831 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1832 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1835 TAILQ_REMOVE(&rhb_list, rhb, entry);
1836 hammer_unlock(&rhb->node->lock);
1837 hammer_rel_node(rhb->node);
1838 kfree(rhb, M_HAMMER);
1840 elm = &cursor->node->ondisk->elms[cursor->index].base;
1841 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1842 kprintf("hammer_btree_correct_lhb-I @%016llx[%d]\n",
1843 cursor->node->node_offset, cursor->index);
1844 hammer_modify_node(cursor->node);
1845 elm->create_tid = tid;
1847 panic("hammer_btree_correct_lhb(): Bad element type");
1854 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1855 TAILQ_REMOVE(&rhb_list, rhb, entry);
1856 hammer_unlock(&rhb->node->lock);
1857 hammer_rel_node(rhb->node);
1858 kfree(rhb, M_HAMMER);
1864 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1865 * on success, EAGAIN if we could not acquire the necessary locks, or some
1866 * other error. This node can be a leaf node or an internal node.
1868 * On return the cursor may end up pointing at an internal node, suitable
1869 * for further iteration but not for an immediate insertion or deletion.
1871 * cursor->node may be an internal node or a leaf node.
1873 * NOTE: If cursor->node has one element it is the parent trying to delete
1874 * that element, make sure cursor->index is properly adjusted on success.
1877 btree_remove(hammer_cursor_t cursor)
1879 hammer_node_ondisk_t ondisk;
1880 hammer_btree_elm_t elm;
1882 hammer_node_t parent;
1883 const int esize = sizeof(*elm);
1886 node = cursor->node;
1889 * When deleting the root of the filesystem convert it to
1890 * an empty leaf node. Internal nodes cannot be empty.
1892 if (node->ondisk->parent == 0) {
1893 hammer_modify_node(node);
1894 ondisk = node->ondisk;
1895 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1902 * Zero-out the parent's reference to the child and flag the
1903 * child for destruction. This ensures that the child is not
1904 * reused while other references to it exist.
1906 parent = cursor->parent;
1907 hammer_modify_node(parent);
1908 ondisk = parent->ondisk;
1909 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1910 elm = &ondisk->elms[cursor->parent_index];
1911 KKASSERT(elm->internal.subtree_offset == node->node_offset);
1912 elm->internal.subtree_offset = 0;
1914 hammer_flush_node(node);
1915 node->flags |= HAMMER_NODE_DELETED;
1918 * If the parent would otherwise not become empty we can physically
1919 * remove the zero'd element. Note however that in order to
1920 * guarentee a valid cursor we still need to be able to cursor up
1921 * because we no longer have a node.
1923 * This collapse will change the parent's boundary elements, making
1924 * them wider. The new boundaries are recursively corrected in
1927 * XXX we can theoretically recalculate the midpoint but there isn't
1928 * much of a reason to do it.
1930 error = hammer_cursor_up(cursor);
1932 error = hammer_cursor_upgrade(cursor);
1935 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
1936 Debugger("BTREE_REMOVE");
1941 * Remove the internal element from the parent. The bcopy must
1942 * include the right boundary element.
1944 KKASSERT(parent == cursor->node && ondisk == parent->ondisk);
1947 /* ondisk is node's ondisk */
1948 /* elm is node's element */
1951 * Remove the internal element that we zero'd out. Tell the caller
1952 * to loop if it hits zero (to try to avoid eating up precious kernel
1955 KKASSERT(ondisk->count > 0);
1956 bcopy(&elm[1], &elm[0], (ondisk->count - cursor->index) * esize);
1958 if (ondisk->count == 0)
1964 * Attempt to remove the deleted internal element at the current cursor
1965 * position. If we are unable to remove the element we return EDEADLK.
1967 * If the current internal node becomes empty we delete it in the parent
1968 * and cursor up, looping until we finish or we deadlock.
1970 * On return, if successful, the cursor will be pointing at the next
1971 * iterative position in the B-Tree. If unsuccessful the cursor will be
1972 * pointing at the last deleted internal element that could not be
1977 btree_remove_deleted_element(hammer_cursor_t cursor)
1980 hammer_btree_elm_t elm;
1983 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1985 node = cursor->node;
1986 elm = &node->ondisk->elms[cursor->index];
1987 if (elm->internal.subtree_offset == 0) {
1989 error = btree_remove(cursor);
1990 kprintf("BTREE REMOVE DELETED ELEMENT %d\n", error);
1991 } while (error == EAGAIN);
1997 * The element (elm) has been moved to a new internal node (node).
1999 * If the element represents a pointer to an internal node that node's
2000 * parent must be adjusted to the element's new location.
2002 * XXX deadlock potential here with our exclusive locks
2006 btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm)
2008 hammer_node_t child;
2013 switch(elm->base.btype) {
2014 case HAMMER_BTREE_TYPE_INTERNAL:
2015 case HAMMER_BTREE_TYPE_LEAF:
2016 child = hammer_get_node(node->hmp,
2017 elm->internal.subtree_offset, &error);
2019 hammer_modify_node(child);
2020 child->ondisk->parent = node->node_offset;
2021 hammer_rel_node(child);
2031 * Exclusively lock all the children of node. This is used by the split
2032 * code to prevent anyone from accessing the children of a cursor node
2033 * while we fix-up its parent offset.
2035 * If we don't lock the children we can really mess up cursors which block
2036 * trying to cursor-up into our node.
2038 * On failure EDEADLK (or some other error) is returned. If a deadlock
2039 * error is returned the cursor is adjusted to block on termination.
2042 hammer_btree_lock_children(hammer_cursor_t cursor,
2043 struct hammer_node_locklist **locklistp)
2046 hammer_node_locklist_t item;
2047 hammer_node_ondisk_t ondisk;
2048 hammer_btree_elm_t elm;
2049 hammer_node_t child;
2053 node = cursor->node;
2054 ondisk = node->ondisk;
2056 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2057 elm = &ondisk->elms[i];
2059 switch(elm->base.btype) {
2060 case HAMMER_BTREE_TYPE_INTERNAL:
2061 case HAMMER_BTREE_TYPE_LEAF:
2062 child = hammer_get_node(node->hmp,
2063 elm->internal.subtree_offset,
2071 if (hammer_lock_ex_try(&child->lock) != 0) {
2072 if (cursor->deadlk_node == NULL) {
2073 cursor->deadlk_node = node;
2074 hammer_ref_node(cursor->deadlk_node);
2078 item = kmalloc(sizeof(*item),
2079 M_HAMMER, M_WAITOK);
2080 item->next = *locklistp;
2087 hammer_btree_unlock_children(locklistp);
2093 * Release previously obtained node locks.
2096 hammer_btree_unlock_children(struct hammer_node_locklist **locklistp)
2098 hammer_node_locklist_t item;
2100 while ((item = *locklistp) != NULL) {
2101 *locklistp = item->next;
2102 hammer_unlock(&item->node->lock);
2103 hammer_rel_node(item->node);
2104 kfree(item, M_HAMMER);
2108 /************************************************************************
2109 * MISCELLANIOUS SUPPORT *
2110 ************************************************************************/
2113 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2115 * Note that for this particular function a return value of -1, 0, or +1
2116 * can denote a match if create_tid is otherwise discounted. A create_tid
2117 * of zero is considered to be 'infinity' in comparisons.
2119 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2122 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2124 if (key1->obj_id < key2->obj_id)
2126 if (key1->obj_id > key2->obj_id)
2129 if (key1->rec_type < key2->rec_type)
2131 if (key1->rec_type > key2->rec_type)
2134 if (key1->key < key2->key)
2136 if (key1->key > key2->key)
2140 * A create_tid of zero indicates a record which is undeletable
2141 * and must be considered to have a value of positive infinity.
2143 if (key1->create_tid == 0) {
2144 if (key2->create_tid == 0)
2148 if (key2->create_tid == 0)
2150 if (key1->create_tid < key2->create_tid)
2152 if (key1->create_tid > key2->create_tid)
2158 * Test a timestamp against an element to determine whether the
2159 * element is visible. A timestamp of 0 means 'infinity'.
2162 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2165 if (base->delete_tid)
2169 if (asof < base->create_tid)
2171 if (base->delete_tid && asof >= base->delete_tid)
2177 * Create a separator half way inbetween key1 and key2. For fields just
2178 * one unit apart, the separator will match key2. key1 is on the left-hand
2179 * side and key2 is on the right-hand side.
2181 * create_tid has to be special cased because a value of 0 represents
2184 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2185 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2188 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2189 hammer_base_elm_t dest)
2191 bzero(dest, sizeof(*dest));
2192 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2193 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2194 MAKE_SEPARATOR(key1, key2, dest, key);
2196 if (key1->obj_id == key2->obj_id &&
2197 key1->rec_type == key2->rec_type &&
2198 key1->key == key2->key) {
2199 if (key1->create_tid == 0) {
2201 * Oops, a create_tid of 0 means 'infinity', so
2202 * if everything matches this just isn't legal.
2204 panic("key1->create_tid of 0 is impossible here");
2205 } else if (key2->create_tid == 0) {
2206 dest->create_tid = key1->create_tid + 1;
2208 MAKE_SEPARATOR(key1, key2, dest, create_tid);
2211 dest->create_tid = 0;
2215 #undef MAKE_SEPARATOR
2218 * Return whether a generic internal or leaf node is full
2221 btree_node_is_full(hammer_node_ondisk_t node)
2223 switch(node->type) {
2224 case HAMMER_BTREE_TYPE_INTERNAL:
2225 if (node->count == HAMMER_BTREE_INT_ELMS)
2228 case HAMMER_BTREE_TYPE_LEAF:
2229 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2233 panic("illegal btree subtype");
2240 btree_max_elements(u_int8_t type)
2242 if (type == HAMMER_BTREE_TYPE_LEAF)
2243 return(HAMMER_BTREE_LEAF_ELMS);
2244 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2245 return(HAMMER_BTREE_INT_ELMS);
2246 panic("btree_max_elements: bad type %d\n", type);
2251 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2253 hammer_btree_elm_t elm;
2256 kprintf("node %p count=%d parent=%016llx type=%c\n",
2257 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2260 * Dump both boundary elements if an internal node
2262 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2263 for (i = 0; i <= ondisk->count; ++i) {
2264 elm = &ondisk->elms[i];
2265 hammer_print_btree_elm(elm, ondisk->type, i);
2268 for (i = 0; i < ondisk->count; ++i) {
2269 elm = &ondisk->elms[i];
2270 hammer_print_btree_elm(elm, ondisk->type, i);
2276 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2279 kprintf("\tobj_id = %016llx\n", elm->base.obj_id);
2280 kprintf("\tkey = %016llx\n", elm->base.key);
2281 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2282 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2283 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2284 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2285 kprintf("\tbtype = %02x (%c)\n",
2287 (elm->base.btype ? elm->base.btype : '?'));
2290 case HAMMER_BTREE_TYPE_INTERNAL:
2291 kprintf("\tsubtree_off = %016llx\n",
2292 elm->internal.subtree_offset);
2294 case HAMMER_BTREE_TYPE_RECORD:
2295 kprintf("\trec_offset = %016llx\n", elm->leaf.rec_offset);
2296 kprintf("\tdata_offset = %016llx\n", elm->leaf.data_offset);
2297 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2298 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);