2 * Copyright (c) 2007-2008 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.37 2008/04/25 21:49:49 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 if (hammer_debug_btree) {
157 kprintf("BRACKETU %016llx[%d] -> %016llx[%d] (td=%p)\n",
158 cursor->node->node_offset,
160 (cursor->parent ? cursor->parent->node_offset : -1),
161 cursor->parent_index,
164 KKASSERT(cursor->parent == NULL || cursor->parent->ondisk->elms[cursor->parent_index].internal.subtree_offset == cursor->node->node_offset);
165 error = hammer_cursor_up(cursor);
168 /* reload stale pointer */
169 node = cursor->node->ondisk;
170 KKASSERT(cursor->index != node->count);
176 * Check internal or leaf element. Determine if the record
177 * at the cursor has gone beyond the end of our range.
179 * We recurse down through internal nodes.
181 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
182 elm = &node->elms[cursor->index];
183 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
184 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
185 if (hammer_debug_btree) {
186 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d (td=%p)\n",
187 cursor->node->node_offset,
189 elm[0].internal.base.obj_id,
190 elm[0].internal.base.rec_type,
191 elm[0].internal.base.key,
195 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
196 cursor->node->node_offset,
198 elm[1].internal.base.obj_id,
199 elm[1].internal.base.rec_type,
200 elm[1].internal.base.key,
209 if (r == 0 && (cursor->flags &
210 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
217 * When iterating try to clean up any deleted
218 * internal elements left over from btree_remove()
219 * deadlocks, but it is ok if we can't.
221 if (elm->internal.subtree_offset == 0) {
222 kprintf("REMOVE DELETED ELEMENT\n");
223 btree_remove_deleted_element(cursor);
224 /* note: elm also invalid */
225 } else if (elm->internal.subtree_offset != 0) {
226 error = hammer_cursor_down(cursor);
229 KKASSERT(cursor->index == 0);
231 /* reload stale pointer */
232 node = cursor->node->ondisk;
235 elm = &node->elms[cursor->index];
236 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
237 if (hammer_debug_btree) {
238 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
239 cursor->node->node_offset,
241 (elm[0].leaf.base.btype ?
242 elm[0].leaf.base.btype : '?'),
243 elm[0].leaf.base.obj_id,
244 elm[0].leaf.base.rec_type,
245 elm[0].leaf.base.key,
255 * We support both end-inclusive and
256 * end-exclusive searches.
259 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
264 switch(elm->leaf.base.btype) {
265 case HAMMER_BTREE_TYPE_RECORD:
266 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
267 hammer_btree_chkts(cursor->asof, &elm->base)) {
280 * node pointer invalid after loop
286 if (hammer_debug_btree) {
287 int i = cursor->index;
288 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
289 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
291 elm->internal.base.obj_id,
292 elm->internal.base.rec_type,
293 elm->internal.base.key
302 * Iterate in the reverse direction. This is used by the pruning code to
303 * avoid overlapping records.
306 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
308 hammer_node_ondisk_t node;
309 hammer_btree_elm_t elm;
315 * Skip past the current record. For various reasons the cursor
316 * may end up set to -1 or set to point at the end of the current
317 * node. These cases must be addressed.
319 node = cursor->node->ondisk;
322 if (cursor->index != -1 &&
323 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
326 if (cursor->index == cursor->node->ondisk->count)
330 * Loop until an element is found or we are done.
334 * We iterate up the tree and then index over one element
335 * while we are at the last element in the current node.
337 if (cursor->index == -1) {
338 error = hammer_cursor_up(cursor);
340 cursor->index = 0; /* sanity */
343 /* reload stale pointer */
344 node = cursor->node->ondisk;
345 KKASSERT(cursor->index != node->count);
351 * Check internal or leaf element. Determine if the record
352 * at the cursor has gone beyond the end of our range.
354 * We recurse down through internal nodes.
356 KKASSERT(cursor->index != node->count);
357 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
358 elm = &node->elms[cursor->index];
359 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
360 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
361 if (hammer_debug_btree) {
362 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
363 cursor->node->node_offset,
365 elm[0].internal.base.obj_id,
366 elm[0].internal.base.rec_type,
367 elm[0].internal.base.key,
370 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
371 cursor->node->node_offset,
373 elm[1].internal.base.obj_id,
374 elm[1].internal.base.rec_type,
375 elm[1].internal.base.key,
387 * When iterating try to clean up any deleted
388 * internal elements left over from btree_remove()
389 * deadlocks, but it is ok if we can't.
391 if (elm->internal.subtree_offset == 0) {
392 btree_remove_deleted_element(cursor);
393 /* note: elm also invalid */
394 } else if (elm->internal.subtree_offset != 0) {
395 error = hammer_cursor_down(cursor);
398 KKASSERT(cursor->index == 0);
399 cursor->index = cursor->node->ondisk->count - 1;
401 /* reload stale pointer */
402 node = cursor->node->ondisk;
405 elm = &node->elms[cursor->index];
406 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
407 if (hammer_debug_btree) {
408 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
409 cursor->node->node_offset,
411 (elm[0].leaf.base.btype ?
412 elm[0].leaf.base.btype : '?'),
413 elm[0].leaf.base.obj_id,
414 elm[0].leaf.base.rec_type,
415 elm[0].leaf.base.key,
424 switch(elm->leaf.base.btype) {
425 case HAMMER_BTREE_TYPE_RECORD:
426 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
427 hammer_btree_chkts(cursor->asof, &elm->base)) {
440 * node pointer invalid after loop
446 if (hammer_debug_btree) {
447 int i = cursor->index;
448 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
449 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
451 elm->internal.base.obj_id,
452 elm->internal.base.rec_type,
453 elm->internal.base.key
462 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
463 * could not be found, EDEADLK if inserting and a retry is needed, and a
464 * fatal error otherwise. When retrying, the caller must terminate the
465 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
467 * The cursor is suitably positioned for a deletion on success, and suitably
468 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
471 * The cursor may begin anywhere, the search will traverse the tree in
472 * either direction to locate the requested element.
474 * Most of the logic implementing historical searches is handled here. We
475 * do an initial lookup with create_tid set to the asof TID. Due to the
476 * way records are laid out, a backwards iteration may be required if
477 * ENOENT is returned to locate the historical record. Here's the
480 * create_tid: 10 15 20
484 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
485 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
486 * not visible and thus causes ENOENT to be returned. We really need
487 * to check record 11 in LEAF1. If it also fails then the search fails
488 * (e.g. it might represent the range 11-16 and thus still not match our
489 * AS-OF timestamp of 17).
491 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
492 * and the cursor->create_check TID if an iteration might be needed.
493 * In the above example create_check would be set to 14.
496 hammer_btree_lookup(hammer_cursor_t cursor)
500 if (cursor->flags & HAMMER_CURSOR_ASOF) {
501 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
502 cursor->key_beg.create_tid = cursor->asof;
504 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
505 error = btree_search(cursor, 0);
506 if (error != ENOENT ||
507 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
510 * Stop if error other then ENOENT.
511 * Stop if ENOENT and not special case.
515 if (hammer_debug_btree) {
516 kprintf("CREATE_CHECK %016llx\n",
517 cursor->create_check);
519 cursor->key_beg.create_tid = cursor->create_check;
523 error = btree_search(cursor, 0);
525 if (error == 0 && cursor->flags)
526 error = hammer_btree_extract(cursor, cursor->flags);
531 * Execute the logic required to start an iteration. The first record
532 * located within the specified range is returned and iteration control
533 * flags are adjusted for successive hammer_btree_iterate() calls.
536 hammer_btree_first(hammer_cursor_t cursor)
540 error = hammer_btree_lookup(cursor);
541 if (error == ENOENT) {
542 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
543 error = hammer_btree_iterate(cursor);
545 cursor->flags |= HAMMER_CURSOR_ATEDISK;
550 * Similarly but for an iteration in the reverse direction.
553 hammer_btree_last(hammer_cursor_t cursor)
555 struct hammer_base_elm save;
558 save = cursor->key_beg;
559 cursor->key_beg = cursor->key_end;
560 error = hammer_btree_lookup(cursor);
561 cursor->key_beg = save;
562 if (error == ENOENT ||
563 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
564 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
565 error = hammer_btree_iterate_reverse(cursor);
567 cursor->flags |= HAMMER_CURSOR_ATEDISK;
572 * Extract the record and/or data associated with the cursor's current
573 * position. Any prior record or data stored in the cursor is replaced.
574 * The cursor must be positioned at a leaf node.
576 * NOTE: All extractions occur at the leaf of the B-Tree.
579 hammer_btree_extract(hammer_cursor_t cursor, int flags)
582 hammer_node_ondisk_t node;
583 hammer_btree_elm_t elm;
584 hammer_off_t rec_off;
585 hammer_off_t data_off;
589 * The case where the data reference resolves to the same buffer
590 * as the record reference must be handled.
592 node = cursor->node->ondisk;
593 elm = &node->elms[cursor->index];
595 hmp = cursor->node->hmp;
596 flags |= cursor->flags & HAMMER_CURSOR_DATAEXTOK;
599 * There is nothing to extract for an internal element.
601 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
605 * Only record types have data.
607 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
608 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
609 flags &= ~HAMMER_CURSOR_GET_DATA;
610 data_off = elm->leaf.data_offset;
612 flags &= ~HAMMER_CURSOR_GET_DATA;
613 rec_off = elm->leaf.rec_offset;
616 * Extract the record if the record was requested or the data
617 * resides in the record buf.
619 if ((flags & HAMMER_CURSOR_GET_RECORD) ||
620 ((flags & HAMMER_CURSOR_GET_DATA) &&
621 ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) == 0)) {
622 cursor->record = hammer_bread(hmp, rec_off, &error,
623 &cursor->record_buffer);
628 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
629 if ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) {
631 * Data and record are in different buffers.
633 cursor->data = hammer_bread(hmp, data_off, &error,
634 &cursor->data_buffer);
637 * Data resides in same buffer as record.
639 cursor->data = (void *)
640 ((char *)cursor->record_buffer->ondisk +
641 ((int32_t)data_off & HAMMER_BUFMASK));
649 * Insert a leaf element into the B-Tree at the current cursor position.
650 * The cursor is positioned such that the element at and beyond the cursor
651 * are shifted to make room for the new record.
653 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
654 * flag set and that call must return ENOENT before this function can be
657 * ENOSPC is returned if there is no room to insert a new record.
660 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
662 hammer_node_ondisk_t node;
666 if ((error = hammer_cursor_upgrade(cursor)) != 0)
670 * Insert the element at the leaf node and update the count in the
671 * parent. It is possible for parent to be NULL, indicating that
672 * the filesystem's ROOT B-Tree node is a leaf itself, which is
673 * possible. The root inode can never be deleted so the leaf should
676 * Remember that the right-hand boundary is not included in the
679 hammer_modify_node_all(cursor->trans, cursor->node);
680 node = cursor->node->ondisk;
682 KKASSERT(elm->base.btype != 0);
683 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
684 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
685 if (i != node->count) {
686 bcopy(&node->elms[i], &node->elms[i+1],
687 (node->count - i) * sizeof(*elm));
689 node->elms[i] = *elm;
691 hammer_modify_node_done(cursor->node);
694 * Debugging sanity checks.
696 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
697 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
699 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->leaf.base) < 0);
701 if (i != node->count - 1)
702 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->leaf.base) > 0);
708 * Delete a record from the B-Tree at the current cursor position.
709 * The cursor is positioned such that the current element is the one
712 * On return the cursor will be positioned after the deleted element and
713 * MAY point to an internal node. It will be suitable for the continuation
714 * of an iteration but not for an insertion or deletion.
716 * Deletions will attempt to partially rebalance the B-Tree in an upward
717 * direction, but will terminate rather then deadlock. Empty leaves are
718 * not allowed. An early termination will leave an internal node with an
719 * element whos subtree_offset is 0, a case detected and handled by
722 * This function can return EDEADLK, requiring the caller to retry the
723 * operation after clearing the deadlock.
726 hammer_btree_delete(hammer_cursor_t cursor)
728 hammer_node_ondisk_t ondisk;
730 hammer_node_t parent;
734 if ((error = hammer_cursor_upgrade(cursor)) != 0)
738 * Delete the element from the leaf node.
740 * Remember that leaf nodes do not have boundaries.
743 ondisk = node->ondisk;
746 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
747 KKASSERT(i >= 0 && i < ondisk->count);
748 hammer_modify_node_all(cursor->trans, node);
749 if (i + 1 != ondisk->count) {
750 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
751 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
754 hammer_modify_node_done(node);
757 * Validate local parent
759 if (ondisk->parent) {
760 parent = cursor->parent;
762 KKASSERT(parent != NULL);
763 KKASSERT(parent->node_offset == ondisk->parent);
767 * If the leaf becomes empty it must be detached from the parent,
768 * potentially recursing through to the filesystem root.
770 * This may reposition the cursor at one of the parent's of the
773 * Ignore deadlock errors, that simply means that btree_remove
774 * was unable to recurse and had to leave the subtree_offset
775 * in the parent set to 0.
777 KKASSERT(cursor->index <= ondisk->count);
778 if (ondisk->count == 0) {
780 error = btree_remove(cursor);
781 } while (error == EAGAIN);
782 if (error == EDEADLK)
787 KKASSERT(cursor->parent == NULL ||
788 cursor->parent_index < cursor->parent->ondisk->count);
793 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
795 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
797 * The search can begin ANYWHERE in the B-Tree. As a first step the search
798 * iterates up the tree as necessary to properly position itself prior to
799 * actually doing the sarch.
801 * INSERTIONS: The search will split full nodes and leaves on its way down
802 * and guarentee that the leaf it ends up on is not full. If we run out
803 * of space the search continues to the leaf (to position the cursor for
804 * the spike), but ENOSPC is returned.
806 * The search is only guarenteed to end up on a leaf if an error code of 0
807 * is returned, or if inserting and an error code of ENOENT is returned.
808 * Otherwise it can stop at an internal node. On success a search returns
811 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
812 * filesystem, and it is not simple code. Please note the following facts:
814 * - Internal node recursions have a boundary on the left AND right. The
815 * right boundary is non-inclusive. The create_tid is a generic part
816 * of the key for internal nodes.
818 * - Leaf nodes contain terminal elements only now.
820 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
821 * historical search. ASOF and INSERT are mutually exclusive. When
822 * doing an as-of lookup btree_search() checks for a right-edge boundary
823 * case. If while recursing down the left-edge differs from the key
824 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
825 * with cursor->create_check. This is used by btree_lookup() to iterate.
826 * The iteration backwards because as-of searches can wind up going
827 * down the wrong branch of the B-Tree.
831 btree_search(hammer_cursor_t cursor, int flags)
833 hammer_node_ondisk_t node;
834 hammer_btree_elm_t elm;
841 flags |= cursor->flags;
843 if (hammer_debug_btree) {
844 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx (td = %p)\n",
845 cursor->node->node_offset,
847 cursor->key_beg.obj_id,
848 cursor->key_beg.rec_type,
850 cursor->key_beg.create_tid,
854 kprintf("SEARCHP %016llx[%d] (%016llx/%016llx %016llx/%016llx) (%p/%p %p/%p)\n",
855 cursor->parent->node_offset, cursor->parent_index,
856 cursor->left_bound->obj_id,
857 cursor->parent->ondisk->elms[cursor->parent_index].internal.base.obj_id,
858 cursor->right_bound->obj_id,
859 cursor->parent->ondisk->elms[cursor->parent_index+1].internal.base.obj_id,
861 &cursor->parent->ondisk->elms[cursor->parent_index],
863 &cursor->parent->ondisk->elms[cursor->parent_index+1]
868 * Move our cursor up the tree until we find a node whos range covers
869 * the key we are trying to locate.
871 * The left bound is inclusive, the right bound is non-inclusive.
872 * It is ok to cursor up too far.
875 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
876 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
879 KKASSERT(cursor->parent);
880 error = hammer_cursor_up(cursor);
886 * The delete-checks below are based on node, not parent. Set the
887 * initial delete-check based on the parent.
890 KKASSERT(cursor->left_bound->create_tid != 1);
891 cursor->create_check = cursor->left_bound->create_tid - 1;
892 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
896 * We better have ended up with a node somewhere.
898 KKASSERT(cursor->node != NULL);
901 * If we are inserting we can't start at a full node if the parent
902 * is also full (because there is no way to split the node),
903 * continue running up the tree until the requirement is satisfied
904 * or we hit the root of the filesystem.
906 * (If inserting we aren't doing an as-of search so we don't have
907 * to worry about create_check).
909 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
910 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
911 if (btree_node_is_full(cursor->node->ondisk) == 0)
914 if (btree_node_is_full(cursor->node->ondisk) ==0)
917 if (cursor->node->ondisk->parent == 0 ||
918 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
921 error = hammer_cursor_up(cursor);
922 /* node may have become stale */
929 * Push down through internal nodes to locate the requested key.
931 node = cursor->node->ondisk;
932 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
934 * Scan the node to find the subtree index to push down into.
935 * We go one-past, then back-up.
937 * We must proactively remove deleted elements which may
938 * have been left over from a deadlocked btree_remove().
940 * The left and right boundaries are included in the loop
941 * in order to detect edge cases.
943 * If the separator only differs by create_tid (r == 1)
944 * and we are doing an as-of search, we may end up going
945 * down a branch to the left of the one containing the
946 * desired key. This requires numerous special cases.
948 if (hammer_debug_btree) {
949 kprintf("SEARCH-I %016llx count=%d\n",
950 cursor->node->node_offset,
953 for (i = 0; i <= node->count; ++i) {
954 elm = &node->elms[i];
955 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
956 if (hammer_debug_btree > 2) {
957 kprintf(" IELM %p %d r=%d\n",
958 &node->elms[i], i, r);
963 KKASSERT(elm->base.create_tid != 1);
964 cursor->create_check = elm->base.create_tid - 1;
965 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
968 if (hammer_debug_btree) {
969 kprintf("SEARCH-I preI=%d/%d r=%d\n",
974 * These cases occur when the parent's idea of the boundary
975 * is wider then the child's idea of the boundary, and
976 * require special handling. If not inserting we can
977 * terminate the search early for these cases but the
978 * child's boundaries cannot be unconditionally modified.
982 * If i == 0 the search terminated to the LEFT of the
983 * left_boundary but to the RIGHT of the parent's left
988 elm = &node->elms[0];
991 * If we aren't inserting we can stop here.
993 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
999 * Correct a left-hand boundary mismatch.
1001 * We can only do this if we can upgrade the lock.
1003 * WARNING: We can only do this if inserting, i.e.
1004 * we are running on the backend.
1006 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1008 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1009 hammer_modify_node(cursor->trans, cursor->node,
1011 sizeof(node->elms[0]));
1012 save = node->elms[0].base.btype;
1013 node->elms[0].base = *cursor->left_bound;
1014 node->elms[0].base.btype = save;
1015 hammer_modify_node_done(cursor->node);
1016 } else if (i == node->count + 1) {
1018 * If i == node->count + 1 the search terminated to
1019 * the RIGHT of the right boundary but to the LEFT
1020 * of the parent's right boundary. If we aren't
1021 * inserting we can stop here.
1023 * Note that the last element in this case is
1024 * elms[i-2] prior to adjustments to 'i'.
1027 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1033 * Correct a right-hand boundary mismatch.
1034 * (actual push-down record is i-2 prior to
1035 * adjustments to i).
1037 * We can only do this if we can upgrade the lock.
1039 * WARNING: We can only do this if inserting, i.e.
1040 * we are running on the backend.
1042 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1044 elm = &node->elms[i];
1045 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1046 hammer_modify_node(cursor->trans, cursor->node,
1047 &elm->base, sizeof(elm->base));
1048 elm->base = *cursor->right_bound;
1049 hammer_modify_node_done(cursor->node);
1053 * The push-down index is now i - 1. If we had
1054 * terminated on the right boundary this will point
1055 * us at the last element.
1060 elm = &node->elms[i];
1062 if (hammer_debug_btree) {
1063 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1064 "key=%016llx cre=%016llx\n",
1065 cursor->node->node_offset,
1067 elm->internal.base.obj_id,
1068 elm->internal.base.rec_type,
1069 elm->internal.base.key,
1070 elm->internal.base.create_tid
1075 * When searching try to clean up any deleted
1076 * internal elements left over from btree_remove()
1079 * If we fail and we are doing an insertion lookup,
1080 * we have to return EDEADLK, because an insertion lookup
1081 * must terminate at a leaf.
1083 if (elm->internal.subtree_offset == 0) {
1084 error = btree_remove_deleted_element(cursor);
1087 if (error == EDEADLK &&
1088 (flags & HAMMER_CURSOR_INSERT) == 0) {
1096 * Handle insertion and deletion requirements.
1098 * If inserting split full nodes. The split code will
1099 * adjust cursor->node and cursor->index if the current
1100 * index winds up in the new node.
1102 * If inserting and a left or right edge case was detected,
1103 * we cannot correct the left or right boundary and must
1104 * prepend and append an empty leaf node in order to make
1105 * the boundary correction.
1107 * If we run out of space we set enospc and continue on
1108 * to a leaf to provide the spike code with a good point
1111 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1112 if (btree_node_is_full(node)) {
1113 error = btree_split_internal(cursor);
1115 if (error != ENOSPC)
1120 * reload stale pointers
1123 node = cursor->node->ondisk;
1128 * Push down (push into new node, existing node becomes
1129 * the parent) and continue the search.
1131 error = hammer_cursor_down(cursor);
1132 /* node may have become stale */
1135 node = cursor->node->ondisk;
1139 * We are at a leaf, do a linear search of the key array.
1141 * If we encounter a spike element type within the necessary
1142 * range we push into it.
1144 * On success the index is set to the matching element and 0
1147 * On failure the index is set to the insertion point and ENOENT
1150 * Boundaries are not stored in leaf nodes, so the index can wind
1151 * up to the left of element 0 (index == 0) or past the end of
1152 * the array (index == node->count).
1154 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1155 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1156 if (hammer_debug_btree) {
1157 kprintf("SEARCH-L %016llx count=%d\n",
1158 cursor->node->node_offset,
1162 for (i = 0; i < node->count; ++i) {
1163 elm = &node->elms[i];
1165 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1167 if (hammer_debug_btree > 1)
1168 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1171 * We are at a record element. Stop if we've flipped past
1172 * key_beg, not counting the create_tid test. Allow the
1173 * r == 1 case (key_beg > element but differs only by its
1174 * create_tid) to fall through to the AS-OF check.
1176 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1184 * Check our as-of timestamp against the element.
1186 if (flags & HAMMER_CURSOR_ASOF) {
1187 if (hammer_btree_chkts(cursor->asof,
1188 &node->elms[i].base) != 0) {
1193 if (r > 0) /* can only be +1 */
1199 if (hammer_debug_btree) {
1200 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1201 cursor->node->node_offset, i);
1207 * The search of the leaf node failed. i is the insertion point.
1210 if (hammer_debug_btree) {
1211 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1212 cursor->node->node_offset, i);
1216 * No exact match was found, i is now at the insertion point.
1218 * If inserting split a full leaf before returning. This
1219 * may have the side effect of adjusting cursor->node and
1223 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1224 btree_node_is_full(node)) {
1225 error = btree_split_leaf(cursor);
1227 if (error != ENOSPC)
1232 * reload stale pointers
1236 node = &cursor->node->internal;
1241 * We reached a leaf but did not find the key we were looking for.
1242 * If this is an insert we will be properly positioned for an insert
1243 * (ENOENT) or spike (ENOSPC) operation.
1245 error = enospc ? ENOSPC : ENOENT;
1251 /************************************************************************
1252 * SPLITTING AND MERGING *
1253 ************************************************************************
1255 * These routines do all the dirty work required to split and merge nodes.
1259 * Split an internal node into two nodes and move the separator at the split
1260 * point to the parent.
1262 * (cursor->node, cursor->index) indicates the element the caller intends
1263 * to push into. We will adjust node and index if that element winds
1264 * up in the split node.
1266 * If we are at the root of the filesystem a new root must be created with
1267 * two elements, one pointing to the original root and one pointing to the
1268 * newly allocated split node.
1272 btree_split_internal(hammer_cursor_t cursor)
1274 hammer_node_ondisk_t ondisk;
1276 hammer_node_t parent;
1277 hammer_node_t new_node;
1278 hammer_btree_elm_t elm;
1279 hammer_btree_elm_t parent_elm;
1280 hammer_node_locklist_t locklist = NULL;
1281 hammer_mount_t hmp = cursor->trans->hmp;
1287 const int esize = sizeof(*elm);
1289 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1291 error = hammer_btree_lock_children(cursor, &locklist);
1296 * We are splitting but elms[split] will be promoted to the parent,
1297 * leaving the right hand node with one less element. If the
1298 * insertion point will be on the left-hand side adjust the split
1299 * point to give the right hand side one additional node.
1301 node = cursor->node;
1302 ondisk = node->ondisk;
1303 split = (ondisk->count + 1) / 2;
1304 if (cursor->index <= split)
1308 * If we are at the root of the filesystem, create a new root node
1309 * with 1 element and split normally. Avoid making major
1310 * modifications until we know the whole operation will work.
1312 if (ondisk->parent == 0) {
1313 parent = hammer_alloc_btree(cursor->trans, &error);
1316 hammer_lock_ex(&parent->lock);
1317 hammer_modify_node_noundo(cursor->trans, parent);
1318 ondisk = parent->ondisk;
1321 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1322 ondisk->elms[0].base = hmp->root_btree_beg;
1323 ondisk->elms[0].base.btype = node->ondisk->type;
1324 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1325 ondisk->elms[1].base = hmp->root_btree_end;
1326 hammer_modify_node_done(parent);
1327 /* ondisk->elms[1].base.btype - not used */
1329 parent_index = 0; /* index of current node in parent */
1332 parent = cursor->parent;
1333 parent_index = cursor->parent_index;
1337 * Split node into new_node at the split point.
1339 * B O O O P N N B <-- P = node->elms[split]
1340 * 0 1 2 3 4 5 6 <-- subtree indices
1345 * B O O O B B N N B <--- inner boundary points are 'P'
1349 new_node = hammer_alloc_btree(cursor->trans, &error);
1350 if (new_node == NULL) {
1352 hammer_unlock(&parent->lock);
1353 hammer_delete_node(cursor->trans, parent);
1354 hammer_rel_node(parent);
1358 hammer_lock_ex(&new_node->lock);
1361 * Create the new node. P becomes the left-hand boundary in the
1362 * new node. Copy the right-hand boundary as well.
1364 * elm is the new separator.
1366 hammer_modify_node_noundo(cursor->trans, new_node);
1367 hammer_modify_node_all(cursor->trans, node);
1368 ondisk = node->ondisk;
1369 elm = &ondisk->elms[split];
1370 bcopy(elm, &new_node->ondisk->elms[0],
1371 (ondisk->count - split + 1) * esize);
1372 new_node->ondisk->count = ondisk->count - split;
1373 new_node->ondisk->parent = parent->node_offset;
1374 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1375 KKASSERT(ondisk->type == new_node->ondisk->type);
1378 * Cleanup the original node. Elm (P) becomes the new boundary,
1379 * its subtree_offset was moved to the new node. If we had created
1380 * a new root its parent pointer may have changed.
1382 elm->internal.subtree_offset = 0;
1383 ondisk->count = split;
1386 * Insert the separator into the parent, fixup the parent's
1387 * reference to the original node, and reference the new node.
1388 * The separator is P.
1390 * Remember that base.count does not include the right-hand boundary.
1392 hammer_modify_node_all(cursor->trans, parent);
1393 ondisk = parent->ondisk;
1394 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1395 parent_elm = &ondisk->elms[parent_index+1];
1396 bcopy(parent_elm, parent_elm + 1,
1397 (ondisk->count - parent_index) * esize);
1398 parent_elm->internal.base = elm->base; /* separator P */
1399 parent_elm->internal.base.btype = new_node->ondisk->type;
1400 parent_elm->internal.subtree_offset = new_node->node_offset;
1402 hammer_modify_node_done(parent);
1405 * The children of new_node need their parent pointer set to new_node.
1406 * The children have already been locked by
1407 * hammer_btree_lock_children().
1409 for (i = 0; i < new_node->ondisk->count; ++i) {
1410 elm = &new_node->ondisk->elms[i];
1411 error = btree_set_parent(cursor->trans, new_node, elm);
1413 panic("btree_split_internal: btree-fixup problem");
1416 hammer_modify_node_done(new_node);
1419 * The filesystem's root B-Tree pointer may have to be updated.
1422 hammer_volume_t volume;
1424 volume = hammer_get_root_volume(hmp, &error);
1425 KKASSERT(error == 0);
1427 hammer_modify_volume(cursor->trans, volume,
1428 &volume->ondisk->vol0_btree_root,
1429 sizeof(hammer_off_t));
1430 volume->ondisk->vol0_btree_root = parent->node_offset;
1431 hammer_modify_volume_done(volume);
1432 node->ondisk->parent = parent->node_offset;
1433 if (cursor->parent) {
1434 hammer_unlock(&cursor->parent->lock);
1435 hammer_rel_node(cursor->parent);
1437 cursor->parent = parent; /* lock'd and ref'd */
1438 hammer_rel_volume(volume, 0);
1440 hammer_modify_node_done(node);
1444 * Ok, now adjust the cursor depending on which element the original
1445 * index was pointing at. If we are >= the split point the push node
1446 * is now in the new node.
1448 * NOTE: If we are at the split point itself we cannot stay with the
1449 * original node because the push index will point at the right-hand
1450 * boundary, which is illegal.
1452 * NOTE: The cursor's parent or parent_index must be adjusted for
1453 * the case where a new parent (new root) was created, and the case
1454 * where the cursor is now pointing at the split node.
1456 if (cursor->index >= split) {
1457 cursor->parent_index = parent_index + 1;
1458 cursor->index -= split;
1459 hammer_unlock(&cursor->node->lock);
1460 hammer_rel_node(cursor->node);
1461 cursor->node = new_node; /* locked and ref'd */
1463 cursor->parent_index = parent_index;
1464 hammer_unlock(&new_node->lock);
1465 hammer_rel_node(new_node);
1469 * Fixup left and right bounds
1471 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1472 cursor->left_bound = &parent_elm[0].internal.base;
1473 cursor->right_bound = &parent_elm[1].internal.base;
1474 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1475 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1476 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1477 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1480 hammer_btree_unlock_children(&locklist);
1481 hammer_cursor_downgrade(cursor);
1486 * Same as the above, but splits a full leaf node.
1492 btree_split_leaf(hammer_cursor_t cursor)
1494 hammer_node_ondisk_t ondisk;
1495 hammer_node_t parent;
1498 hammer_node_t new_leaf;
1499 hammer_btree_elm_t elm;
1500 hammer_btree_elm_t parent_elm;
1501 hammer_base_elm_t mid_boundary;
1506 const size_t esize = sizeof(*elm);
1508 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1511 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1512 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1513 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1514 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1517 * Calculate the split point. If the insertion point will be on
1518 * the left-hand side adjust the split point to give the right
1519 * hand side one additional node.
1521 * Spikes are made up of two leaf elements which cannot be
1524 leaf = cursor->node;
1525 ondisk = leaf->ondisk;
1526 split = (ondisk->count + 1) / 2;
1527 if (cursor->index <= split)
1532 elm = &ondisk->elms[split];
1534 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1535 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1536 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1537 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1540 * If we are at the root of the tree, create a new root node with
1541 * 1 element and split normally. Avoid making major modifications
1542 * until we know the whole operation will work.
1544 if (ondisk->parent == 0) {
1545 parent = hammer_alloc_btree(cursor->trans, &error);
1548 hammer_lock_ex(&parent->lock);
1549 hammer_modify_node_noundo(cursor->trans, parent);
1550 ondisk = parent->ondisk;
1553 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1554 ondisk->elms[0].base = hmp->root_btree_beg;
1555 ondisk->elms[0].base.btype = leaf->ondisk->type;
1556 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1557 ondisk->elms[1].base = hmp->root_btree_end;
1558 /* ondisk->elms[1].base.btype = not used */
1559 hammer_modify_node_done(parent);
1561 parent_index = 0; /* insertion point in parent */
1564 parent = cursor->parent;
1565 parent_index = cursor->parent_index;
1569 * Split leaf into new_leaf at the split point. Select a separator
1570 * value in-between the two leafs but with a bent towards the right
1571 * leaf since comparisons use an 'elm >= separator' inequality.
1580 new_leaf = hammer_alloc_btree(cursor->trans, &error);
1581 if (new_leaf == NULL) {
1583 hammer_unlock(&parent->lock);
1584 hammer_delete_node(cursor->trans, parent);
1585 hammer_rel_node(parent);
1589 hammer_lock_ex(&new_leaf->lock);
1592 * Create the new node and copy the leaf elements from the split
1593 * point on to the new node.
1595 hammer_modify_node_all(cursor->trans, leaf);
1596 hammer_modify_node_noundo(cursor->trans, new_leaf);
1597 ondisk = leaf->ondisk;
1598 elm = &ondisk->elms[split];
1599 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1600 new_leaf->ondisk->count = ondisk->count - split;
1601 new_leaf->ondisk->parent = parent->node_offset;
1602 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1603 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1604 hammer_modify_node_done(new_leaf);
1607 * Cleanup the original node. Because this is a leaf node and
1608 * leaf nodes do not have a right-hand boundary, there
1609 * aren't any special edge cases to clean up. We just fixup the
1612 ondisk->count = split;
1615 * Insert the separator into the parent, fixup the parent's
1616 * reference to the original node, and reference the new node.
1617 * The separator is P.
1619 * Remember that base.count does not include the right-hand boundary.
1620 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1622 hammer_modify_node_all(cursor->trans, parent);
1623 ondisk = parent->ondisk;
1624 KKASSERT(split != 0);
1625 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1626 parent_elm = &ondisk->elms[parent_index+1];
1627 bcopy(parent_elm, parent_elm + 1,
1628 (ondisk->count - parent_index) * esize);
1630 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1631 parent_elm->internal.base.btype = new_leaf->ondisk->type;
1632 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1633 mid_boundary = &parent_elm->base;
1635 hammer_modify_node_done(parent);
1638 * The filesystem's root B-Tree pointer may have to be updated.
1641 hammer_volume_t volume;
1643 volume = hammer_get_root_volume(hmp, &error);
1644 KKASSERT(error == 0);
1646 hammer_modify_volume(cursor->trans, volume,
1647 &volume->ondisk->vol0_btree_root,
1648 sizeof(hammer_off_t));
1649 volume->ondisk->vol0_btree_root = parent->node_offset;
1650 hammer_modify_volume_done(volume);
1651 leaf->ondisk->parent = parent->node_offset;
1652 if (cursor->parent) {
1653 hammer_unlock(&cursor->parent->lock);
1654 hammer_rel_node(cursor->parent);
1656 cursor->parent = parent; /* lock'd and ref'd */
1657 hammer_rel_volume(volume, 0);
1659 hammer_modify_node_done(leaf);
1662 * Ok, now adjust the cursor depending on which element the original
1663 * index was pointing at. If we are >= the split point the push node
1664 * is now in the new node.
1666 * NOTE: If we are at the split point itself we need to select the
1667 * old or new node based on where key_beg's insertion point will be.
1668 * If we pick the wrong side the inserted element will wind up in
1669 * the wrong leaf node and outside that node's bounds.
1671 if (cursor->index > split ||
1672 (cursor->index == split &&
1673 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1674 cursor->parent_index = parent_index + 1;
1675 cursor->index -= split;
1676 hammer_unlock(&cursor->node->lock);
1677 hammer_rel_node(cursor->node);
1678 cursor->node = new_leaf;
1680 cursor->parent_index = parent_index;
1681 hammer_unlock(&new_leaf->lock);
1682 hammer_rel_node(new_leaf);
1686 * Fixup left and right bounds
1688 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1689 cursor->left_bound = &parent_elm[0].internal.base;
1690 cursor->right_bound = &parent_elm[1].internal.base;
1693 * Assert that the bounds are correct.
1695 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1696 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1697 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1698 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1699 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1700 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
1703 hammer_cursor_downgrade(cursor);
1708 * Recursively correct the right-hand boundary's create_tid to (tid) as
1709 * long as the rest of the key matches. We have to recurse upward in
1710 * the tree as well as down the left side of each parent's right node.
1712 * Return EDEADLK if we were only partially successful, forcing the caller
1713 * to try again. The original cursor is not modified. This routine can
1714 * also fail with EDEADLK if it is forced to throw away a portion of its
1717 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1720 TAILQ_ENTRY(hammer_rhb) entry;
1725 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1728 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1730 struct hammer_rhb_list rhb_list;
1731 hammer_base_elm_t elm;
1732 hammer_node_t orig_node;
1733 struct hammer_rhb *rhb;
1737 TAILQ_INIT(&rhb_list);
1740 * Save our position so we can restore it on return. This also
1741 * gives us a stable 'elm'.
1743 orig_node = cursor->node;
1744 hammer_ref_node(orig_node);
1745 hammer_lock_sh(&orig_node->lock);
1746 orig_index = cursor->index;
1747 elm = &orig_node->ondisk->elms[orig_index].base;
1750 * Now build a list of parents going up, allocating a rhb
1751 * structure for each one.
1753 while (cursor->parent) {
1755 * Stop if we no longer have any right-bounds to fix up
1757 if (elm->obj_id != cursor->right_bound->obj_id ||
1758 elm->rec_type != cursor->right_bound->rec_type ||
1759 elm->key != cursor->right_bound->key) {
1764 * Stop if the right-hand bound's create_tid does not
1765 * need to be corrected.
1767 if (cursor->right_bound->create_tid >= tid)
1770 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1771 rhb->node = cursor->parent;
1772 rhb->index = cursor->parent_index;
1773 hammer_ref_node(rhb->node);
1774 hammer_lock_sh(&rhb->node->lock);
1775 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1777 hammer_cursor_up(cursor);
1781 * now safely adjust the right hand bound for each rhb. This may
1782 * also require taking the right side of the tree and iterating down
1786 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1787 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1788 kprintf("CORRECT RHB %016llx index %d type=%c\n",
1789 rhb->node->node_offset,
1790 rhb->index, cursor->node->ondisk->type);
1793 TAILQ_REMOVE(&rhb_list, rhb, entry);
1794 hammer_unlock(&rhb->node->lock);
1795 hammer_rel_node(rhb->node);
1796 kfree(rhb, M_HAMMER);
1798 switch (cursor->node->ondisk->type) {
1799 case HAMMER_BTREE_TYPE_INTERNAL:
1801 * Right-boundary for parent at internal node
1802 * is one element to the right of the element whos
1803 * right boundary needs adjusting. We must then
1804 * traverse down the left side correcting any left
1805 * bounds (which may now be too far to the left).
1808 error = hammer_btree_correct_lhb(cursor, tid);
1811 panic("hammer_btree_correct_rhb(): Bad node type");
1820 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1821 TAILQ_REMOVE(&rhb_list, rhb, entry);
1822 hammer_unlock(&rhb->node->lock);
1823 hammer_rel_node(rhb->node);
1824 kfree(rhb, M_HAMMER);
1826 error = hammer_cursor_seek(cursor, orig_node, orig_index);
1827 hammer_unlock(&orig_node->lock);
1828 hammer_rel_node(orig_node);
1833 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
1834 * bound going downward starting at the current cursor position.
1836 * This function does not restore the cursor after use.
1839 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
1841 struct hammer_rhb_list rhb_list;
1842 hammer_base_elm_t elm;
1843 hammer_base_elm_t cmp;
1844 struct hammer_rhb *rhb;
1847 TAILQ_INIT(&rhb_list);
1849 cmp = &cursor->node->ondisk->elms[cursor->index].base;
1852 * Record the node and traverse down the left-hand side for all
1853 * matching records needing a boundary correction.
1857 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1858 rhb->node = cursor->node;
1859 rhb->index = cursor->index;
1860 hammer_ref_node(rhb->node);
1861 hammer_lock_sh(&rhb->node->lock);
1862 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1864 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1866 * Nothing to traverse down if we are at the right
1867 * boundary of an internal node.
1869 if (cursor->index == cursor->node->ondisk->count)
1872 elm = &cursor->node->ondisk->elms[cursor->index].base;
1873 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
1875 panic("Illegal leaf record type %02x", elm->btype);
1877 error = hammer_cursor_down(cursor);
1881 elm = &cursor->node->ondisk->elms[cursor->index].base;
1882 if (elm->obj_id != cmp->obj_id ||
1883 elm->rec_type != cmp->rec_type ||
1884 elm->key != cmp->key) {
1887 if (elm->create_tid >= tid)
1893 * Now we can safely adjust the left-hand boundary from the bottom-up.
1894 * The last element we remove from the list is the caller's right hand
1895 * boundary, which must also be adjusted.
1897 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1898 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1901 TAILQ_REMOVE(&rhb_list, rhb, entry);
1902 hammer_unlock(&rhb->node->lock);
1903 hammer_rel_node(rhb->node);
1904 kfree(rhb, M_HAMMER);
1906 elm = &cursor->node->ondisk->elms[cursor->index].base;
1907 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1908 kprintf("hammer_btree_correct_lhb-I @%016llx[%d]\n",
1909 cursor->node->node_offset, cursor->index);
1910 hammer_modify_node(cursor->trans, cursor->node,
1912 elm->create_tid = tid;
1913 hammer_modify_node_done(cursor->node);
1915 panic("hammer_btree_correct_lhb(): Bad element type");
1922 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1923 TAILQ_REMOVE(&rhb_list, rhb, entry);
1924 hammer_unlock(&rhb->node->lock);
1925 hammer_rel_node(rhb->node);
1926 kfree(rhb, M_HAMMER);
1932 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1933 * on success, EAGAIN if we could not acquire the necessary locks, or some
1934 * other error. This node can be a leaf node or an internal node.
1936 * On return the cursor may end up pointing at an internal node, suitable
1937 * for further iteration but not for an immediate insertion or deletion.
1939 * cursor->node may be an internal node or a leaf node.
1941 * NOTE: If cursor->node has one element it is the parent trying to delete
1942 * that element, make sure cursor->index is properly adjusted on success.
1945 btree_remove(hammer_cursor_t cursor)
1947 hammer_node_ondisk_t ondisk;
1948 hammer_btree_elm_t elm;
1950 hammer_node_t parent;
1951 const int esize = sizeof(*elm);
1954 node = cursor->node;
1957 * When deleting the root of the filesystem convert it to
1958 * an empty leaf node. Internal nodes cannot be empty.
1960 if (node->ondisk->parent == 0) {
1961 hammer_modify_node_all(cursor->trans, node);
1962 ondisk = node->ondisk;
1963 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1965 hammer_modify_node_done(node);
1971 * Zero-out the parent's reference to the child and flag the
1972 * child for destruction. This ensures that the child is not
1973 * reused while other references to it exist.
1975 parent = cursor->parent;
1976 hammer_modify_node_all(cursor->trans, parent);
1977 ondisk = parent->ondisk;
1978 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1979 elm = &ondisk->elms[cursor->parent_index];
1980 KKASSERT(elm->internal.subtree_offset == node->node_offset);
1981 elm->internal.subtree_offset = 0;
1983 hammer_flush_node(node);
1984 hammer_delete_node(cursor->trans, node);
1987 * If the parent would otherwise not become empty we can physically
1988 * remove the zero'd element. Note however that in order to
1989 * guarentee a valid cursor we still need to be able to cursor up
1990 * because we no longer have a node.
1992 * This collapse will change the parent's boundary elements, making
1993 * them wider. The new boundaries are recursively corrected in
1996 * XXX we can theoretically recalculate the midpoint but there isn't
1997 * much of a reason to do it.
1999 error = hammer_cursor_up(cursor);
2001 error = hammer_cursor_upgrade(cursor);
2004 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
2005 Debugger("BTREE_REMOVE");
2006 hammer_modify_node_done(parent);
2011 * Remove the internal element from the parent. The bcopy must
2012 * include the right boundary element.
2014 KKASSERT(parent == cursor->node && ondisk == parent->ondisk);
2017 /* ondisk is node's ondisk */
2018 /* elm is node's element */
2021 * Remove the internal element that we zero'd out. Tell the caller
2022 * to loop if it hits zero (to try to avoid eating up precious kernel
2025 KKASSERT(ondisk->count > 0);
2026 bcopy(&elm[1], &elm[0], (ondisk->count - cursor->index) * esize);
2028 if (ondisk->count == 0)
2030 hammer_modify_node_done(parent);
2035 * Attempt to remove the deleted internal element at the current cursor
2036 * position. If we are unable to remove the element we return EDEADLK.
2038 * If the current internal node becomes empty we delete it in the parent
2039 * and cursor up, looping until we finish or we deadlock.
2041 * On return, if successful, the cursor will be pointing at the next
2042 * iterative position in the B-Tree. If unsuccessful the cursor will be
2043 * pointing at the last deleted internal element that could not be
2048 btree_remove_deleted_element(hammer_cursor_t cursor)
2051 hammer_btree_elm_t elm;
2054 if ((error = hammer_cursor_upgrade(cursor)) != 0)
2056 node = cursor->node;
2057 elm = &node->ondisk->elms[cursor->index];
2058 if (elm->internal.subtree_offset == 0) {
2060 error = btree_remove(cursor);
2061 kprintf("BTREE REMOVE DELETED ELEMENT %d\n", error);
2062 } while (error == EAGAIN);
2068 * The element (elm) has been moved to a new internal node (node).
2070 * If the element represents a pointer to an internal node that node's
2071 * parent must be adjusted to the element's new location.
2073 * XXX deadlock potential here with our exclusive locks
2077 btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
2078 hammer_btree_elm_t elm)
2080 hammer_node_t child;
2085 switch(elm->base.btype) {
2086 case HAMMER_BTREE_TYPE_INTERNAL:
2087 case HAMMER_BTREE_TYPE_LEAF:
2088 child = hammer_get_node(node->hmp,
2089 elm->internal.subtree_offset, &error);
2091 hammer_modify_node(trans, child,
2092 &child->ondisk->parent,
2093 sizeof(child->ondisk->parent));
2094 child->ondisk->parent = node->node_offset;
2095 hammer_modify_node_done(child);
2096 hammer_rel_node(child);
2106 * Exclusively lock all the children of node. This is used by the split
2107 * code to prevent anyone from accessing the children of a cursor node
2108 * while we fix-up its parent offset.
2110 * If we don't lock the children we can really mess up cursors which block
2111 * trying to cursor-up into our node.
2113 * On failure EDEADLK (or some other error) is returned. If a deadlock
2114 * error is returned the cursor is adjusted to block on termination.
2117 hammer_btree_lock_children(hammer_cursor_t cursor,
2118 struct hammer_node_locklist **locklistp)
2121 hammer_node_locklist_t item;
2122 hammer_node_ondisk_t ondisk;
2123 hammer_btree_elm_t elm;
2124 hammer_node_t child;
2128 node = cursor->node;
2129 ondisk = node->ondisk;
2131 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2132 elm = &ondisk->elms[i];
2134 switch(elm->base.btype) {
2135 case HAMMER_BTREE_TYPE_INTERNAL:
2136 case HAMMER_BTREE_TYPE_LEAF:
2137 child = hammer_get_node(node->hmp,
2138 elm->internal.subtree_offset,
2146 if (hammer_lock_ex_try(&child->lock) != 0) {
2147 if (cursor->deadlk_node == NULL) {
2148 cursor->deadlk_node = child;
2149 hammer_ref_node(cursor->deadlk_node);
2152 hammer_rel_node(child);
2154 item = kmalloc(sizeof(*item),
2155 M_HAMMER, M_WAITOK);
2156 item->next = *locklistp;
2163 hammer_btree_unlock_children(locklistp);
2169 * Release previously obtained node locks.
2172 hammer_btree_unlock_children(struct hammer_node_locklist **locklistp)
2174 hammer_node_locklist_t item;
2176 while ((item = *locklistp) != NULL) {
2177 *locklistp = item->next;
2178 hammer_unlock(&item->node->lock);
2179 hammer_rel_node(item->node);
2180 kfree(item, M_HAMMER);
2184 /************************************************************************
2185 * MISCELLANIOUS SUPPORT *
2186 ************************************************************************/
2189 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2191 * Note that for this particular function a return value of -1, 0, or +1
2192 * can denote a match if create_tid is otherwise discounted. A create_tid
2193 * of zero is considered to be 'infinity' in comparisons.
2195 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2198 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2200 if (key1->obj_id < key2->obj_id)
2202 if (key1->obj_id > key2->obj_id)
2205 if (key1->rec_type < key2->rec_type)
2207 if (key1->rec_type > key2->rec_type)
2210 if (key1->key < key2->key)
2212 if (key1->key > key2->key)
2216 * A create_tid of zero indicates a record which is undeletable
2217 * and must be considered to have a value of positive infinity.
2219 if (key1->create_tid == 0) {
2220 if (key2->create_tid == 0)
2224 if (key2->create_tid == 0)
2226 if (key1->create_tid < key2->create_tid)
2228 if (key1->create_tid > key2->create_tid)
2234 * Test a timestamp against an element to determine whether the
2235 * element is visible. A timestamp of 0 means 'infinity'.
2238 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2241 if (base->delete_tid)
2245 if (asof < base->create_tid)
2247 if (base->delete_tid && asof >= base->delete_tid)
2253 * Create a separator half way inbetween key1 and key2. For fields just
2254 * one unit apart, the separator will match key2. key1 is on the left-hand
2255 * side and key2 is on the right-hand side.
2257 * key2 must be >= the separator. It is ok for the separator to match key2.
2259 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2262 * NOTE: It might be beneficial to just scrap this whole mess and just
2263 * set the separator to key2.
2265 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2266 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2269 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2270 hammer_base_elm_t dest)
2272 bzero(dest, sizeof(*dest));
2274 dest->rec_type = key2->rec_type;
2275 dest->key = key2->key;
2276 dest->create_tid = key2->create_tid;
2278 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2279 if (key1->obj_id == key2->obj_id) {
2280 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2281 if (key1->rec_type == key2->rec_type) {
2282 MAKE_SEPARATOR(key1, key2, dest, key);
2284 * Don't bother creating a separator for create_tid,
2285 * which also conveniently avoids having to handle
2286 * the create_tid == 0 (infinity) case. Just leave
2287 * create_tid set to key2.
2289 * Worst case, dest matches key2 exactly, which is
2296 #undef MAKE_SEPARATOR
2299 * Return whether a generic internal or leaf node is full
2302 btree_node_is_full(hammer_node_ondisk_t node)
2304 switch(node->type) {
2305 case HAMMER_BTREE_TYPE_INTERNAL:
2306 if (node->count == HAMMER_BTREE_INT_ELMS)
2309 case HAMMER_BTREE_TYPE_LEAF:
2310 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2314 panic("illegal btree subtype");
2321 btree_max_elements(u_int8_t type)
2323 if (type == HAMMER_BTREE_TYPE_LEAF)
2324 return(HAMMER_BTREE_LEAF_ELMS);
2325 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2326 return(HAMMER_BTREE_INT_ELMS);
2327 panic("btree_max_elements: bad type %d\n", type);
2332 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2334 hammer_btree_elm_t elm;
2337 kprintf("node %p count=%d parent=%016llx type=%c\n",
2338 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2341 * Dump both boundary elements if an internal node
2343 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2344 for (i = 0; i <= ondisk->count; ++i) {
2345 elm = &ondisk->elms[i];
2346 hammer_print_btree_elm(elm, ondisk->type, i);
2349 for (i = 0; i < ondisk->count; ++i) {
2350 elm = &ondisk->elms[i];
2351 hammer_print_btree_elm(elm, ondisk->type, i);
2357 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2360 kprintf("\tobj_id = %016llx\n", elm->base.obj_id);
2361 kprintf("\tkey = %016llx\n", elm->base.key);
2362 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2363 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2364 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2365 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2366 kprintf("\tbtype = %02x (%c)\n",
2368 (elm->base.btype ? elm->base.btype : '?'));
2371 case HAMMER_BTREE_TYPE_INTERNAL:
2372 kprintf("\tsubtree_off = %016llx\n",
2373 elm->internal.subtree_offset);
2375 case HAMMER_BTREE_TYPE_RECORD:
2376 kprintf("\trec_offset = %016llx\n", elm->leaf.rec_offset);
2377 kprintf("\tdata_offset = %016llx\n", elm->leaf.data_offset);
2378 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2379 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);