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.34 2008/03/19 20:49:46 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_transaction_t trans, hammer_node_t node,
92 hammer_btree_elm_t elm);
93 static int btree_node_is_full(hammer_node_ondisk_t node);
94 static void hammer_make_separator(hammer_base_elm_t key1,
95 hammer_base_elm_t key2, hammer_base_elm_t dest);
96 static void hammer_btree_unlock_children(
97 struct hammer_node_locklist **locklistp);
100 * Iterate records after a search. The cursor is iterated forwards past
101 * the current record until a record matching the key-range requirements
102 * is found. ENOENT is returned if the iteration goes past the ending
105 * The iteration is inclusive of key_beg and can be inclusive or exclusive
106 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
108 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
109 * may be modified by B-Tree functions.
111 * cursor->key_beg may or may not be modified by this function during
112 * the iteration. XXX future - in case of an inverted lock we may have
113 * to reinitiate the lookup and set key_beg to properly pick up where we
116 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
119 hammer_btree_iterate(hammer_cursor_t cursor)
121 hammer_node_ondisk_t node;
122 hammer_btree_elm_t elm;
128 * Skip past the current record
130 node = cursor->node->ondisk;
133 if (cursor->index < node->count &&
134 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
139 * Loop until an element is found or we are done.
143 * We iterate up the tree and then index over one element
144 * while we are at the last element in the current node.
146 * If we are at the root of the filesystem, cursor_up
149 * XXX this could be optimized by storing the information in
150 * the parent reference.
152 * XXX we can lose the node lock temporarily, this could mess
155 if (cursor->index == node->count) {
156 error = hammer_cursor_up(cursor);
159 /* reload stale pointer */
160 node = cursor->node->ondisk;
161 KKASSERT(cursor->index != node->count);
167 * Check internal or leaf element. Determine if the record
168 * at the cursor has gone beyond the end of our range.
170 * We recurse down through internal nodes.
172 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
173 elm = &node->elms[cursor->index];
174 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
175 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
176 if (hammer_debug_btree) {
177 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
178 cursor->node->node_offset,
180 elm[0].internal.base.obj_id,
181 elm[0].internal.base.rec_type,
182 elm[0].internal.base.key,
185 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
186 cursor->node->node_offset,
188 elm[1].internal.base.obj_id,
189 elm[1].internal.base.rec_type,
190 elm[1].internal.base.key,
199 if (r == 0 && (cursor->flags &
200 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
207 * When iterating try to clean up any deleted
208 * internal elements left over from btree_remove()
209 * deadlocks, but it is ok if we can't.
211 if (elm->internal.subtree_offset == 0) {
212 btree_remove_deleted_element(cursor);
213 /* note: elm also invalid */
214 } else if (elm->internal.subtree_offset != 0) {
215 error = hammer_cursor_down(cursor);
218 KKASSERT(cursor->index == 0);
220 /* reload stale pointer */
221 node = cursor->node->ondisk;
224 elm = &node->elms[cursor->index];
225 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
226 if (hammer_debug_btree) {
227 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
228 cursor->node->node_offset,
230 (elm[0].leaf.base.btype ?
231 elm[0].leaf.base.btype : '?'),
232 elm[0].leaf.base.obj_id,
233 elm[0].leaf.base.rec_type,
234 elm[0].leaf.base.key,
244 * We support both end-inclusive and
245 * end-exclusive searches.
248 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
253 switch(elm->leaf.base.btype) {
254 case HAMMER_BTREE_TYPE_RECORD:
255 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
256 hammer_btree_chkts(cursor->asof, &elm->base)) {
269 * node pointer invalid after loop
275 if (hammer_debug_btree) {
276 int i = cursor->index;
277 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
278 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
280 elm->internal.base.obj_id,
281 elm->internal.base.rec_type,
282 elm->internal.base.key
291 * Iterate in the reverse direction. This is used by the pruning code to
292 * avoid overlapping records.
295 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
297 hammer_node_ondisk_t node;
298 hammer_btree_elm_t elm;
304 * Skip past the current record. For various reasons the cursor
305 * may end up set to -1 or set to point at the end of the current
306 * node. These cases must be addressed.
308 node = cursor->node->ondisk;
311 if (cursor->index != -1 &&
312 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
315 if (cursor->index == cursor->node->ondisk->count)
319 * Loop until an element is found or we are done.
323 * We iterate up the tree and then index over one element
324 * while we are at the last element in the current node.
326 if (cursor->index == -1) {
327 error = hammer_cursor_up(cursor);
329 cursor->index = 0; /* sanity */
332 /* reload stale pointer */
333 node = cursor->node->ondisk;
334 KKASSERT(cursor->index != node->count);
340 * Check internal or leaf element. Determine if the record
341 * at the cursor has gone beyond the end of our range.
343 * We recurse down through internal nodes.
345 KKASSERT(cursor->index != node->count);
346 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
347 elm = &node->elms[cursor->index];
348 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
349 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
350 if (hammer_debug_btree) {
351 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
352 cursor->node->node_offset,
354 elm[0].internal.base.obj_id,
355 elm[0].internal.base.rec_type,
356 elm[0].internal.base.key,
359 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
360 cursor->node->node_offset,
362 elm[1].internal.base.obj_id,
363 elm[1].internal.base.rec_type,
364 elm[1].internal.base.key,
376 * When iterating try to clean up any deleted
377 * internal elements left over from btree_remove()
378 * deadlocks, but it is ok if we can't.
380 if (elm->internal.subtree_offset == 0) {
381 btree_remove_deleted_element(cursor);
382 /* note: elm also invalid */
383 } else if (elm->internal.subtree_offset != 0) {
384 error = hammer_cursor_down(cursor);
387 KKASSERT(cursor->index == 0);
388 cursor->index = cursor->node->ondisk->count - 1;
390 /* reload stale pointer */
391 node = cursor->node->ondisk;
394 elm = &node->elms[cursor->index];
395 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
396 if (hammer_debug_btree) {
397 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
398 cursor->node->node_offset,
400 (elm[0].leaf.base.btype ?
401 elm[0].leaf.base.btype : '?'),
402 elm[0].leaf.base.obj_id,
403 elm[0].leaf.base.rec_type,
404 elm[0].leaf.base.key,
413 switch(elm->leaf.base.btype) {
414 case HAMMER_BTREE_TYPE_RECORD:
415 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
416 hammer_btree_chkts(cursor->asof, &elm->base)) {
429 * node pointer invalid after loop
435 if (hammer_debug_btree) {
436 int i = cursor->index;
437 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
438 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
440 elm->internal.base.obj_id,
441 elm->internal.base.rec_type,
442 elm->internal.base.key
451 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
452 * could not be found, EDEADLK if inserting and a retry is needed, and a
453 * fatal error otherwise. When retrying, the caller must terminate the
454 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
456 * The cursor is suitably positioned for a deletion on success, and suitably
457 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
460 * The cursor may begin anywhere, the search will traverse the tree in
461 * either direction to locate the requested element.
463 * Most of the logic implementing historical searches is handled here. We
464 * do an initial lookup with create_tid set to the asof TID. Due to the
465 * way records are laid out, a backwards iteration may be required if
466 * ENOENT is returned to locate the historical record. Here's the
469 * create_tid: 10 15 20
473 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
474 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
475 * not visible and thus causes ENOENT to be returned. We really need
476 * to check record 11 in LEAF1. If it also fails then the search fails
477 * (e.g. it might represent the range 11-16 and thus still not match our
478 * AS-OF timestamp of 17).
480 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
481 * and the cursor->create_check TID if an iteration might be needed.
482 * In the above example create_check would be set to 14.
485 hammer_btree_lookup(hammer_cursor_t cursor)
489 if (cursor->flags & HAMMER_CURSOR_ASOF) {
490 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
491 cursor->key_beg.create_tid = cursor->asof;
493 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
494 error = btree_search(cursor, 0);
495 if (error != ENOENT ||
496 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
499 * Stop if error other then ENOENT.
500 * Stop if ENOENT and not special case.
504 if (hammer_debug_btree) {
505 kprintf("CREATE_CHECK %016llx\n",
506 cursor->create_check);
508 cursor->key_beg.create_tid = cursor->create_check;
512 error = btree_search(cursor, 0);
514 if (error == 0 && cursor->flags)
515 error = hammer_btree_extract(cursor, cursor->flags);
520 * Execute the logic required to start an iteration. The first record
521 * located within the specified range is returned and iteration control
522 * flags are adjusted for successive hammer_btree_iterate() calls.
525 hammer_btree_first(hammer_cursor_t cursor)
529 error = hammer_btree_lookup(cursor);
530 if (error == ENOENT) {
531 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
532 error = hammer_btree_iterate(cursor);
534 cursor->flags |= HAMMER_CURSOR_ATEDISK;
539 * Similarly but for an iteration in the reverse direction.
542 hammer_btree_last(hammer_cursor_t cursor)
544 struct hammer_base_elm save;
547 save = cursor->key_beg;
548 cursor->key_beg = cursor->key_end;
549 error = hammer_btree_lookup(cursor);
550 cursor->key_beg = save;
551 if (error == ENOENT ||
552 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
553 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
554 error = hammer_btree_iterate_reverse(cursor);
556 cursor->flags |= HAMMER_CURSOR_ATEDISK;
561 * Extract the record and/or data associated with the cursor's current
562 * position. Any prior record or data stored in the cursor is replaced.
563 * The cursor must be positioned at a leaf node.
565 * NOTE: All extractions occur at the leaf of the B-Tree.
568 hammer_btree_extract(hammer_cursor_t cursor, int flags)
571 hammer_node_ondisk_t node;
572 hammer_btree_elm_t elm;
573 hammer_off_t rec_off;
574 hammer_off_t data_off;
578 * The case where the data reference resolves to the same buffer
579 * as the record reference must be handled.
581 node = cursor->node->ondisk;
582 elm = &node->elms[cursor->index];
584 hmp = cursor->node->hmp;
585 flags |= cursor->flags & HAMMER_CURSOR_DATAEXTOK;
588 * There is nothing to extract for an internal element.
590 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
594 * Only record types have data.
596 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
597 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
598 flags &= ~HAMMER_CURSOR_GET_DATA;
599 data_off = elm->leaf.data_offset;
601 flags &= ~HAMMER_CURSOR_GET_DATA;
602 rec_off = elm->leaf.rec_offset;
605 * Extract the record if the record was requested or the data
606 * resides in the record buf.
608 if ((flags & HAMMER_CURSOR_GET_RECORD) ||
609 ((flags & HAMMER_CURSOR_GET_DATA) &&
610 ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) == 0)) {
611 cursor->record = hammer_bread(hmp, rec_off, &error,
612 &cursor->record_buffer);
617 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
618 if ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) {
620 * Data and record are in different buffers.
622 cursor->data = hammer_bread(hmp, data_off, &error,
623 &cursor->data_buffer);
626 * Data resides in same buffer as record.
628 cursor->data = (void *)
629 ((char *)cursor->record_buffer->ondisk +
630 ((int32_t)data_off & HAMMER_BUFMASK));
638 * Insert a leaf element into the B-Tree at the current cursor position.
639 * The cursor is positioned such that the element at and beyond the cursor
640 * are shifted to make room for the new record.
642 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
643 * flag set and that call must return ENOENT before this function can be
646 * ENOSPC is returned if there is no room to insert a new record.
649 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
651 hammer_node_ondisk_t node;
655 if ((error = hammer_cursor_upgrade(cursor)) != 0)
659 * Insert the element at the leaf node and update the count in the
660 * parent. It is possible for parent to be NULL, indicating that
661 * the filesystem's ROOT B-Tree node is a leaf itself, which is
662 * possible. The root inode can never be deleted so the leaf should
665 * Remember that the right-hand boundary is not included in the
668 hammer_modify_node_all(cursor->trans, cursor->node);
669 node = cursor->node->ondisk;
671 KKASSERT(elm->base.btype != 0);
672 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
673 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
674 if (i != node->count) {
675 bcopy(&node->elms[i], &node->elms[i+1],
676 (node->count - i) * sizeof(*elm));
678 node->elms[i] = *elm;
682 * Debugging sanity checks.
684 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
685 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
687 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->leaf.base) < 0);
689 if (i != node->count - 1)
690 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->leaf.base) > 0);
696 * Delete a record from the B-Tree at the current cursor position.
697 * The cursor is positioned such that the current element is the one
700 * On return the cursor will be positioned after the deleted element and
701 * MAY point to an internal node. It will be suitable for the continuation
702 * of an iteration but not for an insertion or deletion.
704 * Deletions will attempt to partially rebalance the B-Tree in an upward
705 * direction, but will terminate rather then deadlock. Empty leaves are
706 * not allowed. An early termination will leave an internal node with an
707 * element whos subtree_offset is 0, a case detected and handled by
710 * This function can return EDEADLK, requiring the caller to retry the
711 * operation after clearing the deadlock.
714 hammer_btree_delete(hammer_cursor_t cursor)
716 hammer_node_ondisk_t ondisk;
718 hammer_node_t parent;
722 if ((error = hammer_cursor_upgrade(cursor)) != 0)
726 * Delete the element from the leaf node.
728 * Remember that leaf nodes do not have boundaries.
731 ondisk = node->ondisk;
734 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
735 KKASSERT(i >= 0 && i < ondisk->count);
736 hammer_modify_node_all(cursor->trans, node);
737 if (i + 1 != ondisk->count) {
738 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
739 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
744 * Validate local parent
746 if (ondisk->parent) {
747 parent = cursor->parent;
749 KKASSERT(parent != NULL);
750 KKASSERT(parent->node_offset == ondisk->parent);
754 * If the leaf becomes empty it must be detached from the parent,
755 * potentially recursing through to the filesystem root.
757 * This may reposition the cursor at one of the parent's of the
760 * Ignore deadlock errors, that simply means that btree_remove
761 * was unable to recurse and had to leave the subtree_offset
762 * in the parent set to 0.
764 KKASSERT(cursor->index <= ondisk->count);
765 if (ondisk->count == 0) {
767 error = btree_remove(cursor);
768 } while (error == EAGAIN);
769 if (error == EDEADLK)
774 KKASSERT(cursor->parent == NULL ||
775 cursor->parent_index < cursor->parent->ondisk->count);
780 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
782 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
784 * The search can begin ANYWHERE in the B-Tree. As a first step the search
785 * iterates up the tree as necessary to properly position itself prior to
786 * actually doing the sarch.
788 * INSERTIONS: The search will split full nodes and leaves on its way down
789 * and guarentee that the leaf it ends up on is not full. If we run out
790 * of space the search continues to the leaf (to position the cursor for
791 * the spike), but ENOSPC is returned.
793 * The search is only guarenteed to end up on a leaf if an error code of 0
794 * is returned, or if inserting and an error code of ENOENT is returned.
795 * Otherwise it can stop at an internal node. On success a search returns
798 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
799 * filesystem, and it is not simple code. Please note the following facts:
801 * - Internal node recursions have a boundary on the left AND right. The
802 * right boundary is non-inclusive. The create_tid is a generic part
803 * of the key for internal nodes.
805 * - Leaf nodes contain terminal elements only now.
807 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
808 * historical search. ASOF and INSERT are mutually exclusive. When
809 * doing an as-of lookup btree_search() checks for a right-edge boundary
810 * case. If while recursing down the left-edge differs from the key
811 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
812 * with cursor->create_check. This is used by btree_lookup() to iterate.
813 * The iteration backwards because as-of searches can wind up going
814 * down the wrong branch of the B-Tree.
818 btree_search(hammer_cursor_t cursor, int flags)
820 hammer_node_ondisk_t node;
821 hammer_btree_elm_t elm;
828 flags |= cursor->flags;
830 if (hammer_debug_btree) {
831 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx\n",
832 cursor->node->node_offset,
834 cursor->key_beg.obj_id,
835 cursor->key_beg.rec_type,
837 cursor->key_beg.create_tid
842 * Move our cursor up the tree until we find a node whos range covers
843 * the key we are trying to locate.
845 * The left bound is inclusive, the right bound is non-inclusive.
846 * It is ok to cursor up too far.
849 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
850 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
853 KKASSERT(cursor->parent);
854 error = hammer_cursor_up(cursor);
860 * The delete-checks below are based on node, not parent. Set the
861 * initial delete-check based on the parent.
864 KKASSERT(cursor->left_bound->create_tid != 1);
865 cursor->create_check = cursor->left_bound->create_tid - 1;
866 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
870 * We better have ended up with a node somewhere.
872 KKASSERT(cursor->node != NULL);
875 * If we are inserting we can't start at a full node if the parent
876 * is also full (because there is no way to split the node),
877 * continue running up the tree until the requirement is satisfied
878 * or we hit the root of the filesystem.
880 * (If inserting we aren't doing an as-of search so we don't have
881 * to worry about create_check).
883 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
884 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
885 if (btree_node_is_full(cursor->node->ondisk) == 0)
888 if (btree_node_is_full(cursor->node->ondisk) ==0)
891 if (cursor->node->ondisk->parent == 0 ||
892 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
895 error = hammer_cursor_up(cursor);
896 /* node may have become stale */
903 * Push down through internal nodes to locate the requested key.
905 node = cursor->node->ondisk;
906 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
908 * Scan the node to find the subtree index to push down into.
909 * We go one-past, then back-up.
911 * We must proactively remove deleted elements which may
912 * have been left over from a deadlocked btree_remove().
914 * The left and right boundaries are included in the loop
915 * in order to detect edge cases.
917 * If the separator only differs by create_tid (r == 1)
918 * and we are doing an as-of search, we may end up going
919 * down a branch to the left of the one containing the
920 * desired key. This requires numerous special cases.
922 if (hammer_debug_btree) {
923 kprintf("SEARCH-I %016llx count=%d\n",
924 cursor->node->node_offset,
927 for (i = 0; i <= node->count; ++i) {
928 elm = &node->elms[i];
929 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
930 if (hammer_debug_btree > 2) {
931 kprintf(" IELM %p %d r=%d\n",
932 &node->elms[i], i, r);
937 KKASSERT(elm->base.create_tid != 1);
938 cursor->create_check = elm->base.create_tid - 1;
939 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
942 if (hammer_debug_btree) {
943 kprintf("SEARCH-I preI=%d/%d r=%d\n",
948 * These cases occur when the parent's idea of the boundary
949 * is wider then the child's idea of the boundary, and
950 * require special handling. If not inserting we can
951 * terminate the search early for these cases but the
952 * child's boundaries cannot be unconditionally modified.
956 * If i == 0 the search terminated to the LEFT of the
957 * left_boundary but to the RIGHT of the parent's left
962 elm = &node->elms[0];
965 * If we aren't inserting we can stop here.
967 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
973 * Correct a left-hand boundary mismatch.
975 * We can only do this if we can upgrade the lock.
977 if ((error = hammer_cursor_upgrade(cursor)) != 0)
979 hammer_modify_node(cursor->trans, cursor->node,
981 sizeof(node->elms[0]));
982 save = node->elms[0].base.btype;
983 node->elms[0].base = *cursor->left_bound;
984 node->elms[0].base.btype = save;
985 } else if (i == node->count + 1) {
987 * If i == node->count + 1 the search terminated to
988 * the RIGHT of the right boundary but to the LEFT
989 * of the parent's right boundary. If we aren't
990 * inserting we can stop here.
992 * Note that the last element in this case is
993 * elms[i-2] prior to adjustments to 'i'.
996 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1002 * Correct a right-hand boundary mismatch.
1003 * (actual push-down record is i-2 prior to
1004 * adjustments to i).
1006 * We can only do this if we can upgrade the lock.
1008 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1010 elm = &node->elms[i];
1011 hammer_modify_node(cursor->trans, cursor->node,
1012 &elm->base, sizeof(elm->base));
1013 elm->base = *cursor->right_bound;
1017 * The push-down index is now i - 1. If we had
1018 * terminated on the right boundary this will point
1019 * us at the last element.
1024 elm = &node->elms[i];
1026 if (hammer_debug_btree) {
1027 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1028 "key=%016llx cre=%016llx\n",
1029 cursor->node->node_offset,
1031 elm->internal.base.obj_id,
1032 elm->internal.base.rec_type,
1033 elm->internal.base.key,
1034 elm->internal.base.create_tid
1039 * When searching try to clean up any deleted
1040 * internal elements left over from btree_remove()
1043 * If we fail and we are doing an insertion lookup,
1044 * we have to return EDEADLK, because an insertion lookup
1045 * must terminate at a leaf.
1047 if (elm->internal.subtree_offset == 0) {
1048 error = btree_remove_deleted_element(cursor);
1051 if (error == EDEADLK &&
1052 (flags & HAMMER_CURSOR_INSERT) == 0) {
1060 * Handle insertion and deletion requirements.
1062 * If inserting split full nodes. The split code will
1063 * adjust cursor->node and cursor->index if the current
1064 * index winds up in the new node.
1066 * If inserting and a left or right edge case was detected,
1067 * we cannot correct the left or right boundary and must
1068 * prepend and append an empty leaf node in order to make
1069 * the boundary correction.
1071 * If we run out of space we set enospc and continue on
1072 * to a leaf to provide the spike code with a good point
1075 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1076 if (btree_node_is_full(node)) {
1077 error = btree_split_internal(cursor);
1079 if (error != ENOSPC)
1084 * reload stale pointers
1087 node = cursor->node->ondisk;
1092 * Push down (push into new node, existing node becomes
1093 * the parent) and continue the search.
1095 error = hammer_cursor_down(cursor);
1096 /* node may have become stale */
1099 node = cursor->node->ondisk;
1103 * We are at a leaf, do a linear search of the key array.
1105 * If we encounter a spike element type within the necessary
1106 * range we push into it.
1108 * On success the index is set to the matching element and 0
1111 * On failure the index is set to the insertion point and ENOENT
1114 * Boundaries are not stored in leaf nodes, so the index can wind
1115 * up to the left of element 0 (index == 0) or past the end of
1116 * the array (index == node->count).
1118 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1119 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1120 if (hammer_debug_btree) {
1121 kprintf("SEARCH-L %016llx count=%d\n",
1122 cursor->node->node_offset,
1126 for (i = 0; i < node->count; ++i) {
1127 elm = &node->elms[i];
1129 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1131 if (hammer_debug_btree > 1)
1132 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1135 * We are at a record element. Stop if we've flipped past
1136 * key_beg, not counting the create_tid test. Allow the
1137 * r == 1 case (key_beg > element but differs only by its
1138 * create_tid) to fall through to the AS-OF check.
1140 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1148 * Check our as-of timestamp against the element.
1150 if (flags & HAMMER_CURSOR_ASOF) {
1151 if (hammer_btree_chkts(cursor->asof,
1152 &node->elms[i].base) != 0) {
1157 if (r > 0) /* can only be +1 */
1163 if (hammer_debug_btree) {
1164 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1165 cursor->node->node_offset, i);
1171 * The search of the leaf node failed. i is the insertion point.
1174 if (hammer_debug_btree) {
1175 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1176 cursor->node->node_offset, i);
1180 * No exact match was found, i is now at the insertion point.
1182 * If inserting split a full leaf before returning. This
1183 * may have the side effect of adjusting cursor->node and
1187 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1188 btree_node_is_full(node)) {
1189 error = btree_split_leaf(cursor);
1191 if (error != ENOSPC)
1196 * reload stale pointers
1200 node = &cursor->node->internal;
1205 * We reached a leaf but did not find the key we were looking for.
1206 * If this is an insert we will be properly positioned for an insert
1207 * (ENOENT) or spike (ENOSPC) operation.
1209 error = enospc ? ENOSPC : ENOENT;
1215 /************************************************************************
1216 * SPLITTING AND MERGING *
1217 ************************************************************************
1219 * These routines do all the dirty work required to split and merge nodes.
1223 * Split an internal node into two nodes and move the separator at the split
1224 * point to the parent.
1226 * (cursor->node, cursor->index) indicates the element the caller intends
1227 * to push into. We will adjust node and index if that element winds
1228 * up in the split node.
1230 * If we are at the root of the filesystem a new root must be created with
1231 * two elements, one pointing to the original root and one pointing to the
1232 * newly allocated split node.
1236 btree_split_internal(hammer_cursor_t cursor)
1238 hammer_node_ondisk_t ondisk;
1240 hammer_node_t parent;
1241 hammer_node_t new_node;
1242 hammer_btree_elm_t elm;
1243 hammer_btree_elm_t parent_elm;
1244 hammer_node_locklist_t locklist = NULL;
1245 hammer_mount_t hmp = cursor->trans->hmp;
1251 const int esize = sizeof(*elm);
1253 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1255 error = hammer_btree_lock_children(cursor, &locklist);
1260 * We are splitting but elms[split] will be promoted to the parent,
1261 * leaving the right hand node with one less element. If the
1262 * insertion point will be on the left-hand side adjust the split
1263 * point to give the right hand side one additional node.
1265 node = cursor->node;
1266 ondisk = node->ondisk;
1267 split = (ondisk->count + 1) / 2;
1268 if (cursor->index <= split)
1272 * If we are at the root of the filesystem, create a new root node
1273 * with 1 element and split normally. Avoid making major
1274 * modifications until we know the whole operation will work.
1276 if (ondisk->parent == 0) {
1277 parent = hammer_alloc_btree(cursor->trans, &error);
1280 hammer_lock_ex(&parent->lock);
1281 hammer_modify_node_noundo(cursor->trans, parent);
1282 ondisk = parent->ondisk;
1285 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1286 ondisk->elms[0].base = hmp->root_btree_beg;
1287 ondisk->elms[0].base.btype = node->ondisk->type;
1288 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1289 ondisk->elms[1].base = hmp->root_btree_end;
1290 /* ondisk->elms[1].base.btype - not used */
1292 parent_index = 0; /* index of current node in parent */
1295 parent = cursor->parent;
1296 parent_index = cursor->parent_index;
1300 * Split node into new_node at the split point.
1302 * B O O O P N N B <-- P = node->elms[split]
1303 * 0 1 2 3 4 5 6 <-- subtree indices
1308 * B O O O B B N N B <--- inner boundary points are 'P'
1312 new_node = hammer_alloc_btree(cursor->trans, &error);
1313 if (new_node == NULL) {
1315 hammer_unlock(&parent->lock);
1316 hammer_delete_node(cursor->trans, parent);
1317 hammer_rel_node(parent);
1321 hammer_lock_ex(&new_node->lock);
1324 * Create the new node. P becomes the left-hand boundary in the
1325 * new node. Copy the right-hand boundary as well.
1327 * elm is the new separator.
1329 hammer_modify_node_noundo(cursor->trans, new_node);
1330 hammer_modify_node_all(cursor->trans, node);
1331 ondisk = node->ondisk;
1332 elm = &ondisk->elms[split];
1333 bcopy(elm, &new_node->ondisk->elms[0],
1334 (ondisk->count - split + 1) * esize);
1335 new_node->ondisk->count = ondisk->count - split;
1336 new_node->ondisk->parent = parent->node_offset;
1337 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1338 KKASSERT(ondisk->type == new_node->ondisk->type);
1341 * Cleanup the original node. Elm (P) becomes the new boundary,
1342 * its subtree_offset was moved to the new node. If we had created
1343 * a new root its parent pointer may have changed.
1345 elm->internal.subtree_offset = 0;
1346 ondisk->count = split;
1349 * Insert the separator into the parent, fixup the parent's
1350 * reference to the original node, and reference the new node.
1351 * The separator is P.
1353 * Remember that base.count does not include the right-hand boundary.
1355 hammer_modify_node_all(cursor->trans, parent);
1356 ondisk = parent->ondisk;
1357 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1358 parent_elm = &ondisk->elms[parent_index+1];
1359 bcopy(parent_elm, parent_elm + 1,
1360 (ondisk->count - parent_index) * esize);
1361 parent_elm->internal.base = elm->base; /* separator P */
1362 parent_elm->internal.base.btype = new_node->ondisk->type;
1363 parent_elm->internal.subtree_offset = new_node->node_offset;
1367 * The children of new_node need their parent pointer set to new_node.
1368 * The children have already been locked by
1369 * hammer_btree_lock_children().
1371 for (i = 0; i < new_node->ondisk->count; ++i) {
1372 elm = &new_node->ondisk->elms[i];
1373 error = btree_set_parent(cursor->trans, new_node, elm);
1375 panic("btree_split_internal: btree-fixup problem");
1380 * The filesystem's root B-Tree pointer may have to be updated.
1383 hammer_volume_t volume;
1385 volume = hammer_get_root_volume(hmp, &error);
1386 KKASSERT(error == 0);
1388 hammer_modify_volume(cursor->trans, volume,
1389 &volume->ondisk->vol0_btree_root,
1390 sizeof(hammer_off_t));
1391 volume->ondisk->vol0_btree_root = parent->node_offset;
1392 node->ondisk->parent = parent->node_offset;
1393 if (cursor->parent) {
1394 hammer_unlock(&cursor->parent->lock);
1395 hammer_rel_node(cursor->parent);
1397 cursor->parent = parent; /* lock'd and ref'd */
1398 hammer_rel_volume(volume, 0);
1403 * Ok, now adjust the cursor depending on which element the original
1404 * index was pointing at. If we are >= the split point the push node
1405 * is now in the new node.
1407 * NOTE: If we are at the split point itself we cannot stay with the
1408 * original node because the push index will point at the right-hand
1409 * boundary, which is illegal.
1411 * NOTE: The cursor's parent or parent_index must be adjusted for
1412 * the case where a new parent (new root) was created, and the case
1413 * where the cursor is now pointing at the split node.
1415 if (cursor->index >= split) {
1416 cursor->parent_index = parent_index + 1;
1417 cursor->index -= split;
1418 hammer_unlock(&cursor->node->lock);
1419 hammer_rel_node(cursor->node);
1420 cursor->node = new_node; /* locked and ref'd */
1422 cursor->parent_index = parent_index;
1423 hammer_unlock(&new_node->lock);
1424 hammer_rel_node(new_node);
1428 * Fixup left and right bounds
1430 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1431 cursor->left_bound = &parent_elm[0].internal.base;
1432 cursor->right_bound = &parent_elm[1].internal.base;
1433 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1434 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1435 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1436 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1439 hammer_btree_unlock_children(&locklist);
1440 hammer_cursor_downgrade(cursor);
1445 * Same as the above, but splits a full leaf node.
1451 btree_split_leaf(hammer_cursor_t cursor)
1453 hammer_node_ondisk_t ondisk;
1454 hammer_node_t parent;
1457 hammer_node_t new_leaf;
1458 hammer_btree_elm_t elm;
1459 hammer_btree_elm_t parent_elm;
1460 hammer_base_elm_t mid_boundary;
1465 const size_t esize = sizeof(*elm);
1467 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1470 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1471 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1472 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1473 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1476 * Calculate the split point. If the insertion point will be on
1477 * the left-hand side adjust the split point to give the right
1478 * hand side one additional node.
1480 * Spikes are made up of two leaf elements which cannot be
1483 leaf = cursor->node;
1484 ondisk = leaf->ondisk;
1485 split = (ondisk->count + 1) / 2;
1486 if (cursor->index <= split)
1491 elm = &ondisk->elms[split];
1493 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1494 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1495 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1496 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1499 * If we are at the root of the tree, create a new root node with
1500 * 1 element and split normally. Avoid making major modifications
1501 * until we know the whole operation will work.
1503 if (ondisk->parent == 0) {
1504 parent = hammer_alloc_btree(cursor->trans, &error);
1507 hammer_lock_ex(&parent->lock);
1508 hammer_modify_node_noundo(cursor->trans, parent);
1509 ondisk = parent->ondisk;
1512 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1513 ondisk->elms[0].base = hmp->root_btree_beg;
1514 ondisk->elms[0].base.btype = leaf->ondisk->type;
1515 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1516 ondisk->elms[1].base = hmp->root_btree_end;
1517 /* ondisk->elms[1].base.btype = not used */
1519 parent_index = 0; /* insertion point in parent */
1522 parent = cursor->parent;
1523 parent_index = cursor->parent_index;
1527 * Split leaf into new_leaf at the split point. Select a separator
1528 * value in-between the two leafs but with a bent towards the right
1529 * leaf since comparisons use an 'elm >= separator' inequality.
1538 new_leaf = hammer_alloc_btree(cursor->trans, &error);
1539 if (new_leaf == NULL) {
1541 hammer_unlock(&parent->lock);
1542 hammer_delete_node(cursor->trans, parent);
1543 hammer_rel_node(parent);
1547 hammer_lock_ex(&new_leaf->lock);
1550 * Create the new node and copy the leaf elements from the split
1551 * point on to the new node.
1553 hammer_modify_node_all(cursor->trans, leaf);
1554 hammer_modify_node_noundo(cursor->trans, new_leaf);
1555 ondisk = leaf->ondisk;
1556 elm = &ondisk->elms[split];
1557 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1558 new_leaf->ondisk->count = ondisk->count - split;
1559 new_leaf->ondisk->parent = parent->node_offset;
1560 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1561 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1564 * Cleanup the original node. Because this is a leaf node and
1565 * leaf nodes do not have a right-hand boundary, there
1566 * aren't any special edge cases to clean up. We just fixup the
1569 ondisk->count = split;
1572 * Insert the separator into the parent, fixup the parent's
1573 * reference to the original node, and reference the new node.
1574 * The separator is P.
1576 * Remember that base.count does not include the right-hand boundary.
1577 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1579 hammer_modify_node_all(cursor->trans, parent);
1580 ondisk = parent->ondisk;
1581 KKASSERT(split != 0);
1582 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1583 parent_elm = &ondisk->elms[parent_index+1];
1584 bcopy(parent_elm, parent_elm + 1,
1585 (ondisk->count - parent_index) * esize);
1587 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1588 parent_elm->internal.base.btype = new_leaf->ondisk->type;
1589 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1590 mid_boundary = &parent_elm->base;
1594 * The filesystem's root B-Tree pointer may have to be updated.
1597 hammer_volume_t volume;
1599 volume = hammer_get_root_volume(hmp, &error);
1600 KKASSERT(error == 0);
1602 hammer_modify_volume(cursor->trans, volume,
1603 &volume->ondisk->vol0_btree_root,
1604 sizeof(hammer_off_t));
1605 volume->ondisk->vol0_btree_root = parent->node_offset;
1606 leaf->ondisk->parent = parent->node_offset;
1607 if (cursor->parent) {
1608 hammer_unlock(&cursor->parent->lock);
1609 hammer_rel_node(cursor->parent);
1611 cursor->parent = parent; /* lock'd and ref'd */
1612 hammer_rel_volume(volume, 0);
1616 * Ok, now adjust the cursor depending on which element the original
1617 * index was pointing at. If we are >= the split point the push node
1618 * is now in the new node.
1620 * NOTE: If we are at the split point itself we need to select the
1621 * old or new node based on where key_beg's insertion point will be.
1622 * If we pick the wrong side the inserted element will wind up in
1623 * the wrong leaf node and outside that node's bounds.
1625 if (cursor->index > split ||
1626 (cursor->index == split &&
1627 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1628 cursor->parent_index = parent_index + 1;
1629 cursor->index -= split;
1630 hammer_unlock(&cursor->node->lock);
1631 hammer_rel_node(cursor->node);
1632 cursor->node = new_leaf;
1634 cursor->parent_index = parent_index;
1635 hammer_unlock(&new_leaf->lock);
1636 hammer_rel_node(new_leaf);
1640 * Fixup left and right bounds
1642 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1643 cursor->left_bound = &parent_elm[0].internal.base;
1644 cursor->right_bound = &parent_elm[1].internal.base;
1647 * Assert that the bounds are correct.
1649 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1650 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1651 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1652 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1653 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1654 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
1657 hammer_cursor_downgrade(cursor);
1662 * Recursively correct the right-hand boundary's create_tid to (tid) as
1663 * long as the rest of the key matches. We have to recurse upward in
1664 * the tree as well as down the left side of each parent's right node.
1666 * Return EDEADLK if we were only partially successful, forcing the caller
1667 * to try again. The original cursor is not modified. This routine can
1668 * also fail with EDEADLK if it is forced to throw away a portion of its
1671 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1674 TAILQ_ENTRY(hammer_rhb) entry;
1679 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1682 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1684 struct hammer_rhb_list rhb_list;
1685 hammer_base_elm_t elm;
1686 hammer_node_t orig_node;
1687 struct hammer_rhb *rhb;
1691 TAILQ_INIT(&rhb_list);
1694 * Save our position so we can restore it on return. This also
1695 * gives us a stable 'elm'.
1697 orig_node = cursor->node;
1698 hammer_ref_node(orig_node);
1699 hammer_lock_sh(&orig_node->lock);
1700 orig_index = cursor->index;
1701 elm = &orig_node->ondisk->elms[orig_index].base;
1704 * Now build a list of parents going up, allocating a rhb
1705 * structure for each one.
1707 while (cursor->parent) {
1709 * Stop if we no longer have any right-bounds to fix up
1711 if (elm->obj_id != cursor->right_bound->obj_id ||
1712 elm->rec_type != cursor->right_bound->rec_type ||
1713 elm->key != cursor->right_bound->key) {
1718 * Stop if the right-hand bound's create_tid does not
1719 * need to be corrected.
1721 if (cursor->right_bound->create_tid >= tid)
1724 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1725 rhb->node = cursor->parent;
1726 rhb->index = cursor->parent_index;
1727 hammer_ref_node(rhb->node);
1728 hammer_lock_sh(&rhb->node->lock);
1729 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1731 hammer_cursor_up(cursor);
1735 * now safely adjust the right hand bound for each rhb. This may
1736 * also require taking the right side of the tree and iterating down
1740 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1741 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1742 kprintf("CORRECT RHB %016llx index %d type=%c\n",
1743 rhb->node->node_offset,
1744 rhb->index, cursor->node->ondisk->type);
1747 TAILQ_REMOVE(&rhb_list, rhb, entry);
1748 hammer_unlock(&rhb->node->lock);
1749 hammer_rel_node(rhb->node);
1750 kfree(rhb, M_HAMMER);
1752 switch (cursor->node->ondisk->type) {
1753 case HAMMER_BTREE_TYPE_INTERNAL:
1755 * Right-boundary for parent at internal node
1756 * is one element to the right of the element whos
1757 * right boundary needs adjusting. We must then
1758 * traverse down the left side correcting any left
1759 * bounds (which may now be too far to the left).
1762 error = hammer_btree_correct_lhb(cursor, tid);
1765 panic("hammer_btree_correct_rhb(): Bad node type");
1774 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1775 TAILQ_REMOVE(&rhb_list, rhb, entry);
1776 hammer_unlock(&rhb->node->lock);
1777 hammer_rel_node(rhb->node);
1778 kfree(rhb, M_HAMMER);
1780 error = hammer_cursor_seek(cursor, orig_node, orig_index);
1781 hammer_unlock(&orig_node->lock);
1782 hammer_rel_node(orig_node);
1787 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
1788 * bound going downward starting at the current cursor position.
1790 * This function does not restore the cursor after use.
1793 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
1795 struct hammer_rhb_list rhb_list;
1796 hammer_base_elm_t elm;
1797 hammer_base_elm_t cmp;
1798 struct hammer_rhb *rhb;
1801 TAILQ_INIT(&rhb_list);
1803 cmp = &cursor->node->ondisk->elms[cursor->index].base;
1806 * Record the node and traverse down the left-hand side for all
1807 * matching records needing a boundary correction.
1811 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1812 rhb->node = cursor->node;
1813 rhb->index = cursor->index;
1814 hammer_ref_node(rhb->node);
1815 hammer_lock_sh(&rhb->node->lock);
1816 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1818 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1820 * Nothing to traverse down if we are at the right
1821 * boundary of an internal node.
1823 if (cursor->index == cursor->node->ondisk->count)
1826 elm = &cursor->node->ondisk->elms[cursor->index].base;
1827 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
1829 panic("Illegal leaf record type %02x", elm->btype);
1831 error = hammer_cursor_down(cursor);
1835 elm = &cursor->node->ondisk->elms[cursor->index].base;
1836 if (elm->obj_id != cmp->obj_id ||
1837 elm->rec_type != cmp->rec_type ||
1838 elm->key != cmp->key) {
1841 if (elm->create_tid >= tid)
1847 * Now we can safely adjust the left-hand boundary from the bottom-up.
1848 * The last element we remove from the list is the caller's right hand
1849 * boundary, which must also be adjusted.
1851 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1852 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1855 TAILQ_REMOVE(&rhb_list, rhb, entry);
1856 hammer_unlock(&rhb->node->lock);
1857 hammer_rel_node(rhb->node);
1858 kfree(rhb, M_HAMMER);
1860 elm = &cursor->node->ondisk->elms[cursor->index].base;
1861 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1862 kprintf("hammer_btree_correct_lhb-I @%016llx[%d]\n",
1863 cursor->node->node_offset, cursor->index);
1864 hammer_modify_node(cursor->trans, cursor->node,
1866 elm->create_tid = tid;
1868 panic("hammer_btree_correct_lhb(): Bad element type");
1875 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1876 TAILQ_REMOVE(&rhb_list, rhb, entry);
1877 hammer_unlock(&rhb->node->lock);
1878 hammer_rel_node(rhb->node);
1879 kfree(rhb, M_HAMMER);
1885 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1886 * on success, EAGAIN if we could not acquire the necessary locks, or some
1887 * other error. This node can be a leaf node or an internal node.
1889 * On return the cursor may end up pointing at an internal node, suitable
1890 * for further iteration but not for an immediate insertion or deletion.
1892 * cursor->node may be an internal node or a leaf node.
1894 * NOTE: If cursor->node has one element it is the parent trying to delete
1895 * that element, make sure cursor->index is properly adjusted on success.
1898 btree_remove(hammer_cursor_t cursor)
1900 hammer_node_ondisk_t ondisk;
1901 hammer_btree_elm_t elm;
1903 hammer_node_t parent;
1904 const int esize = sizeof(*elm);
1907 node = cursor->node;
1910 * When deleting the root of the filesystem convert it to
1911 * an empty leaf node. Internal nodes cannot be empty.
1913 if (node->ondisk->parent == 0) {
1914 hammer_modify_node_all(cursor->trans, node);
1915 ondisk = node->ondisk;
1916 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1923 * Zero-out the parent's reference to the child and flag the
1924 * child for destruction. This ensures that the child is not
1925 * reused while other references to it exist.
1927 parent = cursor->parent;
1928 hammer_modify_node_all(cursor->trans, parent);
1929 ondisk = parent->ondisk;
1930 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1931 elm = &ondisk->elms[cursor->parent_index];
1932 KKASSERT(elm->internal.subtree_offset == node->node_offset);
1933 elm->internal.subtree_offset = 0;
1935 hammer_flush_node(node);
1936 hammer_delete_node(cursor->trans, node);
1939 * If the parent would otherwise not become empty we can physically
1940 * remove the zero'd element. Note however that in order to
1941 * guarentee a valid cursor we still need to be able to cursor up
1942 * because we no longer have a node.
1944 * This collapse will change the parent's boundary elements, making
1945 * them wider. The new boundaries are recursively corrected in
1948 * XXX we can theoretically recalculate the midpoint but there isn't
1949 * much of a reason to do it.
1951 error = hammer_cursor_up(cursor);
1953 error = hammer_cursor_upgrade(cursor);
1956 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
1957 Debugger("BTREE_REMOVE");
1962 * Remove the internal element from the parent. The bcopy must
1963 * include the right boundary element.
1965 KKASSERT(parent == cursor->node && ondisk == parent->ondisk);
1968 /* ondisk is node's ondisk */
1969 /* elm is node's element */
1972 * Remove the internal element that we zero'd out. Tell the caller
1973 * to loop if it hits zero (to try to avoid eating up precious kernel
1976 KKASSERT(ondisk->count > 0);
1977 bcopy(&elm[1], &elm[0], (ondisk->count - cursor->index) * esize);
1979 if (ondisk->count == 0)
1985 * Attempt to remove the deleted internal element at the current cursor
1986 * position. If we are unable to remove the element we return EDEADLK.
1988 * If the current internal node becomes empty we delete it in the parent
1989 * and cursor up, looping until we finish or we deadlock.
1991 * On return, if successful, the cursor will be pointing at the next
1992 * iterative position in the B-Tree. If unsuccessful the cursor will be
1993 * pointing at the last deleted internal element that could not be
1998 btree_remove_deleted_element(hammer_cursor_t cursor)
2001 hammer_btree_elm_t elm;
2004 if ((error = hammer_cursor_upgrade(cursor)) != 0)
2006 node = cursor->node;
2007 elm = &node->ondisk->elms[cursor->index];
2008 if (elm->internal.subtree_offset == 0) {
2010 error = btree_remove(cursor);
2011 kprintf("BTREE REMOVE DELETED ELEMENT %d\n", error);
2012 } while (error == EAGAIN);
2018 * The element (elm) has been moved to a new internal node (node).
2020 * If the element represents a pointer to an internal node that node's
2021 * parent must be adjusted to the element's new location.
2023 * XXX deadlock potential here with our exclusive locks
2027 btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
2028 hammer_btree_elm_t elm)
2030 hammer_node_t child;
2035 switch(elm->base.btype) {
2036 case HAMMER_BTREE_TYPE_INTERNAL:
2037 case HAMMER_BTREE_TYPE_LEAF:
2038 child = hammer_get_node(node->hmp,
2039 elm->internal.subtree_offset, &error);
2041 hammer_modify_node(trans, child,
2042 &child->ondisk->parent,
2043 sizeof(child->ondisk->parent));
2044 child->ondisk->parent = node->node_offset;
2045 hammer_rel_node(child);
2055 * Exclusively lock all the children of node. This is used by the split
2056 * code to prevent anyone from accessing the children of a cursor node
2057 * while we fix-up its parent offset.
2059 * If we don't lock the children we can really mess up cursors which block
2060 * trying to cursor-up into our node.
2062 * On failure EDEADLK (or some other error) is returned. If a deadlock
2063 * error is returned the cursor is adjusted to block on termination.
2066 hammer_btree_lock_children(hammer_cursor_t cursor,
2067 struct hammer_node_locklist **locklistp)
2070 hammer_node_locklist_t item;
2071 hammer_node_ondisk_t ondisk;
2072 hammer_btree_elm_t elm;
2073 hammer_node_t child;
2077 node = cursor->node;
2078 ondisk = node->ondisk;
2080 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2081 elm = &ondisk->elms[i];
2083 switch(elm->base.btype) {
2084 case HAMMER_BTREE_TYPE_INTERNAL:
2085 case HAMMER_BTREE_TYPE_LEAF:
2086 child = hammer_get_node(node->hmp,
2087 elm->internal.subtree_offset,
2095 if (hammer_lock_ex_try(&child->lock) != 0) {
2096 if (cursor->deadlk_node == NULL) {
2097 cursor->deadlk_node = child;
2098 hammer_ref_node(cursor->deadlk_node);
2102 item = kmalloc(sizeof(*item),
2103 M_HAMMER, M_WAITOK);
2104 item->next = *locklistp;
2111 hammer_btree_unlock_children(locklistp);
2117 * Release previously obtained node locks.
2120 hammer_btree_unlock_children(struct hammer_node_locklist **locklistp)
2122 hammer_node_locklist_t item;
2124 while ((item = *locklistp) != NULL) {
2125 *locklistp = item->next;
2126 hammer_unlock(&item->node->lock);
2127 hammer_rel_node(item->node);
2128 kfree(item, M_HAMMER);
2132 /************************************************************************
2133 * MISCELLANIOUS SUPPORT *
2134 ************************************************************************/
2137 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2139 * Note that for this particular function a return value of -1, 0, or +1
2140 * can denote a match if create_tid is otherwise discounted. A create_tid
2141 * of zero is considered to be 'infinity' in comparisons.
2143 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2146 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2148 if (key1->obj_id < key2->obj_id)
2150 if (key1->obj_id > key2->obj_id)
2153 if (key1->rec_type < key2->rec_type)
2155 if (key1->rec_type > key2->rec_type)
2158 if (key1->key < key2->key)
2160 if (key1->key > key2->key)
2164 * A create_tid of zero indicates a record which is undeletable
2165 * and must be considered to have a value of positive infinity.
2167 if (key1->create_tid == 0) {
2168 if (key2->create_tid == 0)
2172 if (key2->create_tid == 0)
2174 if (key1->create_tid < key2->create_tid)
2176 if (key1->create_tid > key2->create_tid)
2182 * Test a timestamp against an element to determine whether the
2183 * element is visible. A timestamp of 0 means 'infinity'.
2186 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2189 if (base->delete_tid)
2193 if (asof < base->create_tid)
2195 if (base->delete_tid && asof >= base->delete_tid)
2201 * Create a separator half way inbetween key1 and key2. For fields just
2202 * one unit apart, the separator will match key2. key1 is on the left-hand
2203 * side and key2 is on the right-hand side.
2205 * key2 must be >= the separator. It is ok for the separator to match key2.
2207 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2210 * NOTE: It might be beneficial to just scrap this whole mess and just
2211 * set the separator to key2.
2213 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2214 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2217 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2218 hammer_base_elm_t dest)
2220 bzero(dest, sizeof(*dest));
2222 dest->rec_type = key2->rec_type;
2223 dest->key = key2->key;
2224 dest->create_tid = key2->create_tid;
2226 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2227 if (key1->obj_id == key2->obj_id) {
2228 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2229 if (key1->rec_type == key2->rec_type) {
2230 MAKE_SEPARATOR(key1, key2, dest, key);
2232 * Don't bother creating a separator for create_tid,
2233 * which also conveniently avoids having to handle
2234 * the create_tid == 0 (infinity) case. Just leave
2235 * create_tid set to key2.
2237 * Worst case, dest matches key2 exactly, which is
2244 #undef MAKE_SEPARATOR
2247 * Return whether a generic internal or leaf node is full
2250 btree_node_is_full(hammer_node_ondisk_t node)
2252 switch(node->type) {
2253 case HAMMER_BTREE_TYPE_INTERNAL:
2254 if (node->count == HAMMER_BTREE_INT_ELMS)
2257 case HAMMER_BTREE_TYPE_LEAF:
2258 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2262 panic("illegal btree subtype");
2269 btree_max_elements(u_int8_t type)
2271 if (type == HAMMER_BTREE_TYPE_LEAF)
2272 return(HAMMER_BTREE_LEAF_ELMS);
2273 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2274 return(HAMMER_BTREE_INT_ELMS);
2275 panic("btree_max_elements: bad type %d\n", type);
2280 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2282 hammer_btree_elm_t elm;
2285 kprintf("node %p count=%d parent=%016llx type=%c\n",
2286 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2289 * Dump both boundary elements if an internal node
2291 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2292 for (i = 0; i <= ondisk->count; ++i) {
2293 elm = &ondisk->elms[i];
2294 hammer_print_btree_elm(elm, ondisk->type, i);
2297 for (i = 0; i < ondisk->count; ++i) {
2298 elm = &ondisk->elms[i];
2299 hammer_print_btree_elm(elm, ondisk->type, i);
2305 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2308 kprintf("\tobj_id = %016llx\n", elm->base.obj_id);
2309 kprintf("\tkey = %016llx\n", elm->base.key);
2310 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2311 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2312 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2313 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2314 kprintf("\tbtype = %02x (%c)\n",
2316 (elm->base.btype ? elm->base.btype : '?'));
2319 case HAMMER_BTREE_TYPE_INTERNAL:
2320 kprintf("\tsubtree_off = %016llx\n",
2321 elm->internal.subtree_offset);
2323 case HAMMER_BTREE_TYPE_RECORD:
2324 kprintf("\trec_offset = %016llx\n", elm->leaf.rec_offset);
2325 kprintf("\tdata_offset = %016llx\n", elm->leaf.data_offset);
2326 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2327 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);