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.29 2008/02/08 08:30:59 dillon Exp $
40 * HAMMER implements a modified B+Tree. In documentation this will
41 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
42 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
43 * of the tree), but adds two additional boundary elements which describe
44 * the left-most and right-most element a node is able to represent. In
45 * otherwords, we have boundary elements at the two ends of a B-Tree node
46 * instead of sub-tree pointers.
48 * A B-Tree internal node looks like this:
50 * B N N N N N N B <-- boundary and internal elements
51 * S S S S S S S <-- subtree pointers
53 * A B-Tree leaf node basically looks like this:
55 * L L L L L L L L <-- leaf elemenets
57 * The radix for an internal node is 1 less then a leaf but we get a
58 * number of significant benefits for our troubles.
60 * The big benefit to using a B-Tree containing boundary information
61 * is that it is possible to cache pointers into the middle of the tree
62 * and not have to start searches, insertions, OR deletions at the root
63 * node. In particular, searches are able to progress in a definitive
64 * direction from any point in the tree without revisting nodes. This
65 * greatly improves the efficiency of many operations, most especially
68 * B-Trees also make the stacking of trees fairly straightforward.
70 * INSERTIONS: A search performed with the intention of doing
71 * an insert will guarantee that the terminal leaf node is not full by
72 * splitting full nodes. Splits occur top-down during the dive down the
75 * DELETIONS: A deletion makes no attempt to proactively balance the
76 * tree and will recursively remove nodes that become empty. Empty
77 * nodes are not allowed and a deletion may recurse upwards from the leaf.
78 * Rather then allow a deadlock a deletion may terminate early by setting
79 * an internal node's element's subtree_offset to 0. The deletion will
80 * then be resumed the next time a search encounters the element.
86 static int btree_search(hammer_cursor_t cursor
, int flags
);
87 static int btree_split_internal(hammer_cursor_t cursor
);
88 static int btree_split_leaf(hammer_cursor_t cursor
);
89 static int btree_remove(hammer_cursor_t cursor
);
90 static int btree_remove_deleted_element(hammer_cursor_t cursor
);
91 static int btree_set_parent(hammer_node_t node
, hammer_btree_elm_t elm
);
92 static int btree_node_is_full(hammer_node_ondisk_t node
);
93 static void hammer_make_separator(hammer_base_elm_t key1
,
94 hammer_base_elm_t key2
, hammer_base_elm_t dest
);
97 * Iterate records after a search. The cursor is iterated forwards past
98 * the current record until a record matching the key-range requirements
99 * is found. ENOENT is returned if the iteration goes past the ending
102 * The iteration is inclusive of key_beg and can be inclusive or exclusive
103 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
105 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
106 * may be modified by B-Tree functions.
108 * cursor->key_beg may or may not be modified by this function during
109 * the iteration. XXX future - in case of an inverted lock we may have
110 * to reinitiate the lookup and set key_beg to properly pick up where we
113 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
116 hammer_btree_iterate(hammer_cursor_t cursor
)
118 hammer_node_ondisk_t node
;
119 hammer_btree_elm_t elm
;
125 * Skip past the current record
127 node
= cursor
->node
->ondisk
;
130 if (cursor
->index
< node
->count
&&
131 (cursor
->flags
& HAMMER_CURSOR_ATEDISK
)) {
136 * Loop until an element is found or we are done.
140 * We iterate up the tree and then index over one element
141 * while we are at the last element in the current node.
143 * If we are at the root of the filesystem, cursor_up
146 * XXX this could be optimized by storing the information in
147 * the parent reference.
149 * XXX we can lose the node lock temporarily, this could mess
152 if (cursor
->index
== node
->count
) {
153 error
= hammer_cursor_up(cursor
);
156 /* reload stale pointer */
157 node
= cursor
->node
->ondisk
;
158 KKASSERT(cursor
->index
!= node
->count
);
164 * Check internal or leaf element. Determine if the record
165 * at the cursor has gone beyond the end of our range.
167 * We recurse down through internal nodes.
169 if (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
170 elm
= &node
->elms
[cursor
->index
];
171 r
= hammer_btree_cmp(&cursor
->key_end
, &elm
[0].base
);
172 s
= hammer_btree_cmp(&cursor
->key_beg
, &elm
[1].base
);
173 if (hammer_debug_btree
) {
174 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
175 cursor
->node
->node_offset
,
177 elm
[0].internal
.base
.obj_id
,
178 elm
[0].internal
.base
.rec_type
,
179 elm
[0].internal
.base
.key
,
182 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
183 cursor
->node
->node_offset
,
185 elm
[1].internal
.base
.obj_id
,
186 elm
[1].internal
.base
.rec_type
,
187 elm
[1].internal
.base
.key
,
196 if (r
== 0 && (cursor
->flags
&
197 HAMMER_CURSOR_END_INCLUSIVE
) == 0) {
204 * When iterating try to clean up any deleted
205 * internal elements left over from btree_remove()
206 * deadlocks, but it is ok if we can't.
208 if (elm
->internal
.subtree_offset
== 0) {
209 btree_remove_deleted_element(cursor
);
210 /* note: elm also invalid */
211 } else if (elm
->internal
.subtree_offset
!= 0) {
212 error
= hammer_cursor_down(cursor
);
215 KKASSERT(cursor
->index
== 0);
217 /* reload stale pointer */
218 node
= cursor
->node
->ondisk
;
221 elm
= &node
->elms
[cursor
->index
];
222 r
= hammer_btree_cmp(&cursor
->key_end
, &elm
->base
);
223 if (hammer_debug_btree
) {
224 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
225 cursor
->node
->node_offset
,
227 (elm
[0].leaf
.base
.btype
?
228 elm
[0].leaf
.base
.btype
: '?'),
229 elm
[0].leaf
.base
.obj_id
,
230 elm
[0].leaf
.base
.rec_type
,
231 elm
[0].leaf
.base
.key
,
241 * We support both end-inclusive and
242 * end-exclusive searches.
245 (cursor
->flags
& HAMMER_CURSOR_END_INCLUSIVE
) == 0) {
250 switch(elm
->leaf
.base
.btype
) {
251 case HAMMER_BTREE_TYPE_RECORD
:
252 if ((cursor
->flags
& HAMMER_CURSOR_ASOF
) &&
253 hammer_btree_chkts(cursor
->asof
, &elm
->base
)) {
266 * node pointer invalid after loop
272 if (hammer_debug_btree
) {
273 int i
= cursor
->index
;
274 hammer_btree_elm_t elm
= &cursor
->node
->ondisk
->elms
[i
];
275 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
277 elm
->internal
.base
.obj_id
,
278 elm
->internal
.base
.rec_type
,
279 elm
->internal
.base
.key
288 * Iterate in the reverse direction. This is used by the pruning code to
289 * avoid overlapping records.
292 hammer_btree_iterate_reverse(hammer_cursor_t cursor
)
294 hammer_node_ondisk_t node
;
295 hammer_btree_elm_t elm
;
301 * Skip past the current record. For various reasons the cursor
302 * may end up set to -1 or set to point at the end of the current
303 * node. These cases must be addressed.
305 node
= cursor
->node
->ondisk
;
308 if (cursor
->index
!= -1 &&
309 (cursor
->flags
& HAMMER_CURSOR_ATEDISK
)) {
312 if (cursor
->index
== cursor
->node
->ondisk
->count
)
316 * Loop until an element is found or we are done.
320 * We iterate up the tree and then index over one element
321 * while we are at the last element in the current node.
323 if (cursor
->index
== -1) {
324 error
= hammer_cursor_up(cursor
);
326 cursor
->index
= 0; /* sanity */
329 /* reload stale pointer */
330 node
= cursor
->node
->ondisk
;
331 KKASSERT(cursor
->index
!= node
->count
);
337 * Check internal or leaf element. Determine if the record
338 * at the cursor has gone beyond the end of our range.
340 * We recurse down through internal nodes.
342 KKASSERT(cursor
->index
!= node
->count
);
343 if (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
344 elm
= &node
->elms
[cursor
->index
];
345 r
= hammer_btree_cmp(&cursor
->key_end
, &elm
[0].base
);
346 s
= hammer_btree_cmp(&cursor
->key_beg
, &elm
[1].base
);
347 if (hammer_debug_btree
) {
348 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
349 cursor
->node
->node_offset
,
351 elm
[0].internal
.base
.obj_id
,
352 elm
[0].internal
.base
.rec_type
,
353 elm
[0].internal
.base
.key
,
356 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
357 cursor
->node
->node_offset
,
359 elm
[1].internal
.base
.obj_id
,
360 elm
[1].internal
.base
.rec_type
,
361 elm
[1].internal
.base
.key
,
373 * When iterating try to clean up any deleted
374 * internal elements left over from btree_remove()
375 * deadlocks, but it is ok if we can't.
377 if (elm
->internal
.subtree_offset
== 0) {
378 btree_remove_deleted_element(cursor
);
379 /* note: elm also invalid */
380 } else if (elm
->internal
.subtree_offset
!= 0) {
381 error
= hammer_cursor_down(cursor
);
384 KKASSERT(cursor
->index
== 0);
385 cursor
->index
= cursor
->node
->ondisk
->count
- 1;
387 /* reload stale pointer */
388 node
= cursor
->node
->ondisk
;
391 elm
= &node
->elms
[cursor
->index
];
392 s
= hammer_btree_cmp(&cursor
->key_beg
, &elm
->base
);
393 if (hammer_debug_btree
) {
394 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
395 cursor
->node
->node_offset
,
397 (elm
[0].leaf
.base
.btype
?
398 elm
[0].leaf
.base
.btype
: '?'),
399 elm
[0].leaf
.base
.obj_id
,
400 elm
[0].leaf
.base
.rec_type
,
401 elm
[0].leaf
.base
.key
,
410 switch(elm
->leaf
.base
.btype
) {
411 case HAMMER_BTREE_TYPE_RECORD
:
412 if ((cursor
->flags
& HAMMER_CURSOR_ASOF
) &&
413 hammer_btree_chkts(cursor
->asof
, &elm
->base
)) {
426 * node pointer invalid after loop
432 if (hammer_debug_btree
) {
433 int i
= cursor
->index
;
434 hammer_btree_elm_t elm
= &cursor
->node
->ondisk
->elms
[i
];
435 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
437 elm
->internal
.base
.obj_id
,
438 elm
->internal
.base
.rec_type
,
439 elm
->internal
.base
.key
448 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
449 * could not be found, EDEADLK if inserting and a retry is needed, and a
450 * fatal error otherwise. When retrying, the caller must terminate the
451 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
453 * The cursor is suitably positioned for a deletion on success, and suitably
454 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
457 * The cursor may begin anywhere, the search will traverse the tree in
458 * either direction to locate the requested element.
460 * Most of the logic implementing historical searches is handled here. We
461 * do an initial lookup with create_tid set to the asof TID. Due to the
462 * way records are laid out, a backwards iteration may be required if
463 * ENOENT is returned to locate the historical record. Here's the
466 * create_tid: 10 15 20
470 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
471 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
472 * not visible and thus causes ENOENT to be returned. We really need
473 * to check record 11 in LEAF1. If it also fails then the search fails
474 * (e.g. it might represent the range 11-16 and thus still not match our
475 * AS-OF timestamp of 17).
477 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
478 * and the cursor->create_check TID if an iteration might be needed.
479 * In the above example create_check would be set to 14.
482 hammer_btree_lookup(hammer_cursor_t cursor
)
486 if (cursor
->flags
& HAMMER_CURSOR_ASOF
) {
487 KKASSERT((cursor
->flags
& HAMMER_CURSOR_INSERT
) == 0);
488 cursor
->key_beg
.create_tid
= cursor
->asof
;
490 cursor
->flags
&= ~HAMMER_CURSOR_CREATE_CHECK
;
491 error
= btree_search(cursor
, 0);
492 if (error
!= ENOENT
||
493 (cursor
->flags
& HAMMER_CURSOR_CREATE_CHECK
) == 0) {
496 * Stop if error other then ENOENT.
497 * Stop if ENOENT and not special case.
501 if (hammer_debug_btree
) {
502 kprintf("CREATE_CHECK %016llx\n",
503 cursor
->create_check
);
505 cursor
->key_beg
.create_tid
= cursor
->create_check
;
509 error
= btree_search(cursor
, 0);
511 if (error
== 0 && cursor
->flags
)
512 error
= hammer_btree_extract(cursor
, cursor
->flags
);
517 * Execute the logic required to start an iteration. The first record
518 * located within the specified range is returned and iteration control
519 * flags are adjusted for successive hammer_btree_iterate() calls.
522 hammer_btree_first(hammer_cursor_t cursor
)
526 error
= hammer_btree_lookup(cursor
);
527 if (error
== ENOENT
) {
528 cursor
->flags
&= ~HAMMER_CURSOR_ATEDISK
;
529 error
= hammer_btree_iterate(cursor
);
531 cursor
->flags
|= HAMMER_CURSOR_ATEDISK
;
536 * Similarly but for an iteration in the reverse direction.
539 hammer_btree_last(hammer_cursor_t cursor
)
541 struct hammer_base_elm save
;
544 save
= cursor
->key_beg
;
545 cursor
->key_beg
= cursor
->key_end
;
546 error
= hammer_btree_lookup(cursor
);
547 cursor
->key_beg
= save
;
548 if (error
== ENOENT
||
549 (cursor
->flags
& HAMMER_CURSOR_END_INCLUSIVE
) == 0) {
550 cursor
->flags
&= ~HAMMER_CURSOR_ATEDISK
;
551 error
= hammer_btree_iterate_reverse(cursor
);
553 cursor
->flags
|= HAMMER_CURSOR_ATEDISK
;
558 * Extract the record and/or data associated with the cursor's current
559 * position. Any prior record or data stored in the cursor is replaced.
560 * The cursor must be positioned at a leaf node.
562 * NOTE: All extractions occur at the leaf of the B-Tree.
565 hammer_btree_extract(hammer_cursor_t cursor
, int flags
)
568 hammer_node_ondisk_t node
;
569 hammer_btree_elm_t elm
;
570 hammer_off_t rec_off
;
571 hammer_off_t data_off
;
572 hammer_off_t data_end
;
576 * The case where the data reference resolves to the same buffer
577 * as the record reference must be handled.
579 node
= cursor
->node
->ondisk
;
580 elm
= &node
->elms
[cursor
->index
];
581 cursor
->data1
= NULL
;
582 cursor
->data2
= NULL
;
583 cursor
->data_split
= 0;
584 hmp
= cursor
->node
->volume
->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
;
600 data_end
= data_off
+ elm
->leaf
.data_len
- 1;
602 flags
&= ~HAMMER_CURSOR_GET_DATA
;
603 rec_off
= elm
->leaf
.rec_offset
;
606 * Extract the record if the record was requested or the data
607 * resides in the record buf.
609 if ((flags
& HAMMER_CURSOR_GET_RECORD
) ||
610 ((flags
& HAMMER_CURSOR_GET_DATA
) &&
611 ((rec_off
^ data_off
) & ~HAMMER_BUFMASK64
) == 0)) {
612 cursor
->record
= hammer_bread(hmp
, rec_off
, &error
,
613 &cursor
->record_buffer
);
618 if ((flags
& HAMMER_CURSOR_GET_DATA
) && error
== 0) {
619 if ((rec_off
^ data_off
) & ~HAMMER_BUFMASK64
) {
621 * The data is not in the same buffer as the last
622 * record we cached, but it could still be embedded
623 * in a record. Note that we may not have loaded the
624 * record's buffer above, depending on flags.
626 * Assert that the data does not cross into additional
629 cursor
->data_split
= 0;
630 cursor
->data2
= hammer_bread(hmp
, data_off
,
631 &error
, &cursor
->data_buffer
);
632 KKASSERT(((data_off
^ data_end
) &
633 ~HAMMER_BUFMASK64
) == 0);
636 * The data starts in same buffer as record. Check
637 * to determine if the data extends into another
640 cursor
->data1
= (void *)
641 ((char *)cursor
->record_buffer
->ondisk
+
642 ((int32_t)data_off
& HAMMER_BUFMASK
));
643 if ((data_off
^ data_end
) & ~HAMMER_BUFMASK64
) {
644 cursor
->data_split
= HAMMER_BUFSIZE
-
645 ((int32_t)data_off
& HAMMER_BUFMASK
);
646 if (flags
& HAMMER_CURSOR_DATAEXTOK
) {
648 * NOTE: Assumes data buffer does not
649 * cross a volume boundary.
651 cursor
->data2
= hammer_bread(hmp
, data_off
+ cursor
->data_split
,
652 &error
, &cursor
->data_buffer
);
654 panic("Illegal data extension");
657 cursor
->data_split
= elm
->leaf
.data_len
;
666 * Insert a leaf element into the B-Tree at the current cursor position.
667 * The cursor is positioned such that the element at and beyond the cursor
668 * are shifted to make room for the new record.
670 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
671 * flag set and that call must return ENOENT before this function can be
674 * ENOSPC is returned if there is no room to insert a new record.
677 hammer_btree_insert(hammer_cursor_t cursor
, hammer_btree_elm_t elm
)
679 hammer_node_ondisk_t node
;
683 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
687 * Insert the element at the leaf node and update the count in the
688 * parent. It is possible for parent to be NULL, indicating that
689 * the filesystem's ROOT B-Tree node is a leaf itself, which is
690 * possible. The root inode can never be deleted so the leaf should
693 * Remember that the right-hand boundary is not included in the
696 hammer_modify_node(cursor
->node
);
697 node
= cursor
->node
->ondisk
;
699 KKASSERT(elm
->base
.btype
!= 0);
700 KKASSERT(node
->type
== HAMMER_BTREE_TYPE_LEAF
);
701 KKASSERT(node
->count
< HAMMER_BTREE_LEAF_ELMS
);
702 if (i
!= node
->count
) {
703 bcopy(&node
->elms
[i
], &node
->elms
[i
+1],
704 (node
->count
- i
) * sizeof(*elm
));
706 node
->elms
[i
] = *elm
;
710 * Debugging sanity checks.
712 KKASSERT(hammer_btree_cmp(cursor
->left_bound
, &elm
->leaf
.base
) <= 0);
713 KKASSERT(hammer_btree_cmp(cursor
->right_bound
, &elm
->leaf
.base
) > 0);
715 KKASSERT(hammer_btree_cmp(&node
->elms
[i
-1].leaf
.base
, &elm
->leaf
.base
) < 0);
717 if (i
!= node
->count
- 1)
718 KKASSERT(hammer_btree_cmp(&node
->elms
[i
+1].leaf
.base
, &elm
->leaf
.base
) > 0);
724 * Delete a record from the B-Tree at the current cursor position.
725 * The cursor is positioned such that the current element is the one
728 * On return the cursor will be positioned after the deleted element and
729 * MAY point to an internal node. It will be suitable for the continuation
730 * of an iteration but not for an insertion or deletion.
732 * Deletions will attempt to partially rebalance the B-Tree in an upward
733 * direction, but will terminate rather then deadlock. Empty leaves are
734 * not allowed. An early termination will leave an internal node with an
735 * element whos subtree_offset is 0, a case detected and handled by
738 * This function can return EDEADLK, requiring the caller to retry the
739 * operation after clearing the deadlock.
742 hammer_btree_delete(hammer_cursor_t cursor
)
744 hammer_node_ondisk_t ondisk
;
746 hammer_node_t parent
;
750 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
754 * Delete the element from the leaf node.
756 * Remember that leaf nodes do not have boundaries.
759 ondisk
= node
->ondisk
;
762 KKASSERT(ondisk
->type
== HAMMER_BTREE_TYPE_LEAF
);
763 KKASSERT(i
>= 0 && i
< ondisk
->count
);
764 hammer_modify_node(node
);
765 if (i
+ 1 != ondisk
->count
) {
766 bcopy(&ondisk
->elms
[i
+1], &ondisk
->elms
[i
],
767 (ondisk
->count
- i
- 1) * sizeof(ondisk
->elms
[0]));
772 * Validate local parent
774 if (ondisk
->parent
) {
775 parent
= cursor
->parent
;
777 KKASSERT(parent
!= NULL
);
778 KKASSERT(parent
->node_offset
== ondisk
->parent
);
782 * If the leaf becomes empty it must be detached from the parent,
783 * potentially recursing through to the filesystem root.
785 * This may reposition the cursor at one of the parent's of the
788 * Ignore deadlock errors, that simply means that btree_remove
789 * was unable to recurse and had to leave the subtree_offset
790 * in the parent set to 0.
792 KKASSERT(cursor
->index
<= ondisk
->count
);
793 if (ondisk
->count
== 0) {
795 error
= btree_remove(cursor
);
796 } while (error
== EAGAIN
);
797 if (error
== EDEADLK
)
802 KKASSERT(cursor
->parent
== NULL
||
803 cursor
->parent_index
< cursor
->parent
->ondisk
->count
);
808 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
810 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
812 * The search can begin ANYWHERE in the B-Tree. As a first step the search
813 * iterates up the tree as necessary to properly position itself prior to
814 * actually doing the sarch.
816 * INSERTIONS: The search will split full nodes and leaves on its way down
817 * and guarentee that the leaf it ends up on is not full. If we run out
818 * of space the search continues to the leaf (to position the cursor for
819 * the spike), but ENOSPC is returned.
821 * The search is only guarenteed to end up on a leaf if an error code of 0
822 * is returned, or if inserting and an error code of ENOENT is returned.
823 * Otherwise it can stop at an internal node. On success a search returns
826 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
827 * filesystem, and it is not simple code. Please note the following facts:
829 * - Internal node recursions have a boundary on the left AND right. The
830 * right boundary is non-inclusive. The create_tid is a generic part
831 * of the key for internal nodes.
833 * - Leaf nodes contain terminal elements only now.
835 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
836 * historical search. ASOF and INSERT are mutually exclusive. When
837 * doing an as-of lookup btree_search() checks for a right-edge boundary
838 * case. If while recursing down the left-edge differs from the key
839 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
840 * with cursor->create_check. This is used by btree_lookup() to iterate.
841 * The iteration backwards because as-of searches can wind up going
842 * down the wrong branch of the B-Tree.
846 btree_search(hammer_cursor_t cursor
, int flags
)
848 hammer_node_ondisk_t node
;
849 hammer_btree_elm_t elm
;
856 flags
|= cursor
->flags
;
858 if (hammer_debug_btree
) {
859 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx\n",
860 cursor
->node
->node_offset
,
862 cursor
->key_beg
.obj_id
,
863 cursor
->key_beg
.rec_type
,
865 cursor
->key_beg
.create_tid
870 * Move our cursor up the tree until we find a node whos range covers
871 * the key we are trying to locate.
873 * The left bound is inclusive, the right bound is non-inclusive.
874 * It is ok to cursor up too far.
877 r
= hammer_btree_cmp(&cursor
->key_beg
, cursor
->left_bound
);
878 s
= hammer_btree_cmp(&cursor
->key_beg
, cursor
->right_bound
);
881 KKASSERT(cursor
->parent
);
882 error
= hammer_cursor_up(cursor
);
888 * The delete-checks below are based on node, not parent. Set the
889 * initial delete-check based on the parent.
892 KKASSERT(cursor
->left_bound
->create_tid
!= 1);
893 cursor
->create_check
= cursor
->left_bound
->create_tid
- 1;
894 cursor
->flags
|= HAMMER_CURSOR_CREATE_CHECK
;
898 * We better have ended up with a node somewhere.
900 KKASSERT(cursor
->node
!= NULL
);
903 * If we are inserting we can't start at a full node if the parent
904 * is also full (because there is no way to split the node),
905 * continue running up the tree until the requirement is satisfied
906 * or we hit the root of the filesystem.
908 * (If inserting we aren't doing an as-of search so we don't have
909 * to worry about create_check).
911 while ((flags
& HAMMER_CURSOR_INSERT
) && enospc
== 0) {
912 if (cursor
->node
->ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
913 if (btree_node_is_full(cursor
->node
->ondisk
) == 0)
916 if (btree_node_is_full(cursor
->node
->ondisk
) ==0)
919 if (cursor
->node
->ondisk
->parent
== 0 ||
920 cursor
->parent
->ondisk
->count
!= HAMMER_BTREE_INT_ELMS
) {
923 error
= hammer_cursor_up(cursor
);
924 /* node may have become stale */
931 * Push down through internal nodes to locate the requested key.
933 node
= cursor
->node
->ondisk
;
934 while (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
936 * Scan the node to find the subtree index to push down into.
937 * We go one-past, then back-up.
939 * We must proactively remove deleted elements which may
940 * have been left over from a deadlocked btree_remove().
942 * The left and right boundaries are included in the loop
943 * in order to detect edge cases.
945 * If the separator only differs by create_tid (r == 1)
946 * and we are doing an as-of search, we may end up going
947 * down a branch to the left of the one containing the
948 * desired key. This requires numerous special cases.
950 if (hammer_debug_btree
) {
951 kprintf("SEARCH-I %016llx count=%d\n",
952 cursor
->node
->node_offset
,
955 for (i
= 0; i
<= node
->count
; ++i
) {
956 elm
= &node
->elms
[i
];
957 r
= hammer_btree_cmp(&cursor
->key_beg
, &elm
->base
);
958 if (hammer_debug_btree
> 2) {
959 kprintf(" IELM %p %d r=%d\n",
960 &node
->elms
[i
], i
, r
);
965 KKASSERT(elm
->base
.create_tid
!= 1);
966 cursor
->create_check
= elm
->base
.create_tid
- 1;
967 cursor
->flags
|= HAMMER_CURSOR_CREATE_CHECK
;
970 if (hammer_debug_btree
) {
971 kprintf("SEARCH-I preI=%d/%d r=%d\n",
976 * These cases occur when the parent's idea of the boundary
977 * is wider then the child's idea of the boundary, and
978 * require special handling. If not inserting we can
979 * terminate the search early for these cases but the
980 * child's boundaries cannot be unconditionally modified.
984 * If i == 0 the search terminated to the LEFT of the
985 * left_boundary but to the RIGHT of the parent's left
990 elm
= &node
->elms
[0];
993 * If we aren't inserting we can stop here.
995 if ((flags
& HAMMER_CURSOR_INSERT
) == 0) {
1001 * Correct a left-hand boundary mismatch.
1003 * We can only do this if we can upgrade the lock.
1005 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1007 hammer_modify_node(cursor
->node
);
1008 save
= node
->elms
[0].base
.btype
;
1009 node
->elms
[0].base
= *cursor
->left_bound
;
1010 node
->elms
[0].base
.btype
= save
;
1011 } else if (i
== node
->count
+ 1) {
1013 * If i == node->count + 1 the search terminated to
1014 * the RIGHT of the right boundary but to the LEFT
1015 * of the parent's right boundary. If we aren't
1016 * inserting we can stop here.
1018 * Note that the last element in this case is
1019 * elms[i-2] prior to adjustments to 'i'.
1022 if ((flags
& HAMMER_CURSOR_INSERT
) == 0) {
1028 * Correct a right-hand boundary mismatch.
1029 * (actual push-down record is i-2 prior to
1030 * adjustments to i).
1032 * We can only do this if we can upgrade the lock.
1034 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1036 elm
= &node
->elms
[i
];
1037 hammer_modify_node(cursor
->node
);
1038 elm
->base
= *cursor
->right_bound
;
1042 * The push-down index is now i - 1. If we had
1043 * terminated on the right boundary this will point
1044 * us at the last element.
1049 elm
= &node
->elms
[i
];
1051 if (hammer_debug_btree
) {
1052 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1053 "key=%016llx cre=%016llx\n",
1054 cursor
->node
->node_offset
,
1056 elm
->internal
.base
.obj_id
,
1057 elm
->internal
.base
.rec_type
,
1058 elm
->internal
.base
.key
,
1059 elm
->internal
.base
.create_tid
1064 * When searching try to clean up any deleted
1065 * internal elements left over from btree_remove()
1068 * If we fail and we are doing an insertion lookup,
1069 * we have to return EDEADLK, because an insertion lookup
1070 * must terminate at a leaf.
1072 if (elm
->internal
.subtree_offset
== 0) {
1073 error
= btree_remove_deleted_element(cursor
);
1076 if (error
== EDEADLK
&&
1077 (flags
& HAMMER_CURSOR_INSERT
) == 0) {
1085 * Handle insertion and deletion requirements.
1087 * If inserting split full nodes. The split code will
1088 * adjust cursor->node and cursor->index if the current
1089 * index winds up in the new node.
1091 * If inserting and a left or right edge case was detected,
1092 * we cannot correct the left or right boundary and must
1093 * prepend and append an empty leaf node in order to make
1094 * the boundary correction.
1096 * If we run out of space we set enospc and continue on
1097 * to a leaf to provide the spike code with a good point
1100 if ((flags
& HAMMER_CURSOR_INSERT
) && enospc
== 0) {
1101 if (btree_node_is_full(node
)) {
1102 error
= btree_split_internal(cursor
);
1104 if (error
!= ENOSPC
)
1109 * reload stale pointers
1112 node
= cursor
->node
->ondisk
;
1117 * Push down (push into new node, existing node becomes
1118 * the parent) and continue the search.
1120 error
= hammer_cursor_down(cursor
);
1121 /* node may have become stale */
1124 node
= cursor
->node
->ondisk
;
1128 * We are at a leaf, do a linear search of the key array.
1130 * If we encounter a spike element type within the necessary
1131 * range we push into it.
1133 * On success the index is set to the matching element and 0
1136 * On failure the index is set to the insertion point and ENOENT
1139 * Boundaries are not stored in leaf nodes, so the index can wind
1140 * up to the left of element 0 (index == 0) or past the end of
1141 * the array (index == node->count).
1143 KKASSERT (node
->type
== HAMMER_BTREE_TYPE_LEAF
);
1144 KKASSERT(node
->count
<= HAMMER_BTREE_LEAF_ELMS
);
1145 if (hammer_debug_btree
) {
1146 kprintf("SEARCH-L %016llx count=%d\n",
1147 cursor
->node
->node_offset
,
1151 for (i
= 0; i
< node
->count
; ++i
) {
1152 elm
= &node
->elms
[i
];
1154 r
= hammer_btree_cmp(&cursor
->key_beg
, &elm
->leaf
.base
);
1156 if (hammer_debug_btree
> 1)
1157 kprintf(" ELM %p %d r=%d\n", &node
->elms
[i
], i
, r
);
1160 * We are at a record element. Stop if we've flipped past
1161 * key_beg, not counting the create_tid test. Allow the
1162 * r == 1 case (key_beg > element but differs only by its
1163 * create_tid) to fall through to the AS-OF check.
1165 KKASSERT (elm
->leaf
.base
.btype
== HAMMER_BTREE_TYPE_RECORD
);
1173 * Check our as-of timestamp against the element.
1175 if (flags
& HAMMER_CURSOR_ASOF
) {
1176 if (hammer_btree_chkts(cursor
->asof
,
1177 &node
->elms
[i
].base
) != 0) {
1182 if (r
> 0) /* can only be +1 */
1188 if (hammer_debug_btree
) {
1189 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1190 cursor
->node
->node_offset
, i
);
1196 * The search of the leaf node failed. i is the insertion point.
1199 if (hammer_debug_btree
) {
1200 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1201 cursor
->node
->node_offset
, i
);
1205 * No exact match was found, i is now at the insertion point.
1207 * If inserting split a full leaf before returning. This
1208 * may have the side effect of adjusting cursor->node and
1212 if ((flags
& HAMMER_CURSOR_INSERT
) && enospc
== 0 &&
1213 btree_node_is_full(node
)) {
1214 error
= btree_split_leaf(cursor
);
1216 if (error
!= ENOSPC
)
1221 * reload stale pointers
1225 node = &cursor->node->internal;
1230 * We reached a leaf but did not find the key we were looking for.
1231 * If this is an insert we will be properly positioned for an insert
1232 * (ENOENT) or spike (ENOSPC) operation.
1234 error
= enospc
? ENOSPC
: ENOENT
;
1240 /************************************************************************
1241 * SPLITTING AND MERGING *
1242 ************************************************************************
1244 * These routines do all the dirty work required to split and merge nodes.
1248 * Split an internal node into two nodes and move the separator at the split
1249 * point to the parent.
1251 * (cursor->node, cursor->index) indicates the element the caller intends
1252 * to push into. We will adjust node and index if that element winds
1253 * up in the split node.
1255 * If we are at the root of the filesystem a new root must be created with
1256 * two elements, one pointing to the original root and one pointing to the
1257 * newly allocated split node.
1261 btree_split_internal(hammer_cursor_t cursor
)
1263 hammer_node_ondisk_t ondisk
;
1266 hammer_node_t parent
;
1267 hammer_node_t new_node
;
1268 hammer_btree_elm_t elm
;
1269 hammer_btree_elm_t parent_elm
;
1270 hammer_node_locklist_t locklist
= NULL
;
1276 const int esize
= sizeof(*elm
);
1278 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1280 error
= hammer_btree_lock_children(cursor
, &locklist
);
1285 * We are splitting but elms[split] will be promoted to the parent,
1286 * leaving the right hand node with one less element. If the
1287 * insertion point will be on the left-hand side adjust the split
1288 * point to give the right hand side one additional node.
1290 node
= cursor
->node
;
1291 ondisk
= node
->ondisk
;
1292 split
= (ondisk
->count
+ 1) / 2;
1293 if (cursor
->index
<= split
)
1295 hmp
= node
->volume
->hmp
;
1298 * If we are at the root of the filesystem, create a new root node
1299 * with 1 element and split normally. Avoid making major
1300 * modifications until we know the whole operation will work.
1302 if (ondisk
->parent
== 0) {
1303 parent
= hammer_alloc_btree(hmp
, &error
);
1306 hammer_lock_ex(&parent
->lock
);
1307 hammer_modify_node(parent
);
1308 ondisk
= parent
->ondisk
;
1311 ondisk
->type
= HAMMER_BTREE_TYPE_INTERNAL
;
1312 ondisk
->elms
[0].base
= hmp
->root_btree_beg
;
1313 ondisk
->elms
[0].base
.btype
= node
->ondisk
->type
;
1314 ondisk
->elms
[0].internal
.subtree_offset
= node
->node_offset
;
1315 ondisk
->elms
[1].base
= hmp
->root_btree_end
;
1316 /* ondisk->elms[1].base.btype - not used */
1318 parent_index
= 0; /* index of current node in parent */
1321 parent
= cursor
->parent
;
1322 parent_index
= cursor
->parent_index
;
1326 * Split node into new_node at the split point.
1328 * B O O O P N N B <-- P = node->elms[split]
1329 * 0 1 2 3 4 5 6 <-- subtree indices
1334 * B O O O B B N N B <--- inner boundary points are 'P'
1338 new_node
= hammer_alloc_btree(hmp
, &error
);
1339 if (new_node
== NULL
) {
1341 hammer_unlock(&parent
->lock
);
1342 parent
->flags
|= HAMMER_NODE_DELETED
;
1343 hammer_rel_node(parent
);
1347 hammer_lock_ex(&new_node
->lock
);
1350 * Create the new node. P becomes the left-hand boundary in the
1351 * new node. Copy the right-hand boundary as well.
1353 * elm is the new separator.
1355 hammer_modify_node(new_node
);
1356 hammer_modify_node(node
);
1357 ondisk
= node
->ondisk
;
1358 elm
= &ondisk
->elms
[split
];
1359 bcopy(elm
, &new_node
->ondisk
->elms
[0],
1360 (ondisk
->count
- split
+ 1) * esize
);
1361 new_node
->ondisk
->count
= ondisk
->count
- split
;
1362 new_node
->ondisk
->parent
= parent
->node_offset
;
1363 new_node
->ondisk
->type
= HAMMER_BTREE_TYPE_INTERNAL
;
1364 KKASSERT(ondisk
->type
== new_node
->ondisk
->type
);
1367 * Cleanup the original node. Elm (P) becomes the new boundary,
1368 * its subtree_offset was moved to the new node. If we had created
1369 * a new root its parent pointer may have changed.
1371 elm
->internal
.subtree_offset
= 0;
1372 ondisk
->count
= split
;
1375 * Insert the separator into the parent, fixup the parent's
1376 * reference to the original node, and reference the new node.
1377 * The separator is P.
1379 * Remember that base.count does not include the right-hand boundary.
1381 hammer_modify_node(parent
);
1382 ondisk
= parent
->ondisk
;
1383 KKASSERT(ondisk
->count
!= HAMMER_BTREE_INT_ELMS
);
1384 parent_elm
= &ondisk
->elms
[parent_index
+1];
1385 bcopy(parent_elm
, parent_elm
+ 1,
1386 (ondisk
->count
- parent_index
) * esize
);
1387 parent_elm
->internal
.base
= elm
->base
; /* separator P */
1388 parent_elm
->internal
.base
.btype
= new_node
->ondisk
->type
;
1389 parent_elm
->internal
.subtree_offset
= new_node
->node_offset
;
1393 * The children of new_node need their parent pointer set to new_node.
1394 * The children have already been locked by
1395 * hammer_btree_lock_children().
1397 for (i
= 0; i
< new_node
->ondisk
->count
; ++i
) {
1398 elm
= &new_node
->ondisk
->elms
[i
];
1399 error
= btree_set_parent(new_node
, elm
);
1401 panic("btree_split_internal: btree-fixup problem");
1406 * The filesystem's root B-Tree pointer may have to be updated.
1409 hammer_volume_t volume
;
1411 volume
= hammer_get_root_volume(hmp
, &error
);
1412 KKASSERT(error
== 0);
1414 hammer_modify_volume(volume
, &volume
->ondisk
->vol0_btree_root
,
1415 sizeof(hammer_off_t
));
1416 volume
->ondisk
->vol0_btree_root
= parent
->node_offset
;
1417 node
->ondisk
->parent
= parent
->node_offset
;
1418 if (cursor
->parent
) {
1419 hammer_unlock(&cursor
->parent
->lock
);
1420 hammer_rel_node(cursor
->parent
);
1422 cursor
->parent
= parent
; /* lock'd and ref'd */
1423 hammer_rel_volume(volume
, 0);
1428 * Ok, now adjust the cursor depending on which element the original
1429 * index was pointing at. If we are >= the split point the push node
1430 * is now in the new node.
1432 * NOTE: If we are at the split point itself we cannot stay with the
1433 * original node because the push index will point at the right-hand
1434 * boundary, which is illegal.
1436 * NOTE: The cursor's parent or parent_index must be adjusted for
1437 * the case where a new parent (new root) was created, and the case
1438 * where the cursor is now pointing at the split node.
1440 if (cursor
->index
>= split
) {
1441 cursor
->parent_index
= parent_index
+ 1;
1442 cursor
->index
-= split
;
1443 hammer_unlock(&cursor
->node
->lock
);
1444 hammer_rel_node(cursor
->node
);
1445 cursor
->node
= new_node
; /* locked and ref'd */
1447 cursor
->parent_index
= parent_index
;
1448 hammer_unlock(&new_node
->lock
);
1449 hammer_rel_node(new_node
);
1453 * Fixup left and right bounds
1455 parent_elm
= &parent
->ondisk
->elms
[cursor
->parent_index
];
1456 cursor
->left_bound
= &parent_elm
[0].internal
.base
;
1457 cursor
->right_bound
= &parent_elm
[1].internal
.base
;
1458 KKASSERT(hammer_btree_cmp(cursor
->left_bound
,
1459 &cursor
->node
->ondisk
->elms
[0].internal
.base
) <= 0);
1460 KKASSERT(hammer_btree_cmp(cursor
->right_bound
,
1461 &cursor
->node
->ondisk
->elms
[cursor
->node
->ondisk
->count
].internal
.base
) >= 0);
1464 hammer_btree_unlock_children(&locklist
);
1465 hammer_cursor_downgrade(cursor
);
1470 * Same as the above, but splits a full leaf node.
1476 btree_split_leaf(hammer_cursor_t cursor
)
1478 hammer_node_ondisk_t ondisk
;
1479 hammer_node_t parent
;
1482 hammer_node_t new_leaf
;
1483 hammer_btree_elm_t elm
;
1484 hammer_btree_elm_t parent_elm
;
1485 hammer_base_elm_t mid_boundary
;
1490 const size_t esize
= sizeof(*elm
);
1492 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1496 * Calculate the split point. If the insertion point will be on
1497 * the left-hand side adjust the split point to give the right
1498 * hand side one additional node.
1500 * Spikes are made up of two leaf elements which cannot be
1503 leaf
= cursor
->node
;
1504 ondisk
= leaf
->ondisk
;
1505 split
= (ondisk
->count
+ 1) / 2;
1506 if (cursor
->index
<= split
)
1509 hmp
= leaf
->volume
->hmp
;
1511 elm
= &ondisk
->elms
[split
];
1514 * If we are at the root of the tree, create a new root node with
1515 * 1 element and split normally. Avoid making major modifications
1516 * until we know the whole operation will work.
1518 if (ondisk
->parent
== 0) {
1519 parent
= hammer_alloc_btree(hmp
, &error
);
1522 hammer_lock_ex(&parent
->lock
);
1523 hammer_modify_node(parent
);
1524 ondisk
= parent
->ondisk
;
1527 ondisk
->type
= HAMMER_BTREE_TYPE_INTERNAL
;
1528 ondisk
->elms
[0].base
= hmp
->root_btree_beg
;
1529 ondisk
->elms
[0].base
.btype
= leaf
->ondisk
->type
;
1530 ondisk
->elms
[0].internal
.subtree_offset
= leaf
->node_offset
;
1531 ondisk
->elms
[1].base
= hmp
->root_btree_end
;
1532 /* ondisk->elms[1].base.btype = not used */
1534 parent_index
= 0; /* insertion point in parent */
1537 parent
= cursor
->parent
;
1538 parent_index
= cursor
->parent_index
;
1542 * Split leaf into new_leaf at the split point. Select a separator
1543 * value in-between the two leafs but with a bent towards the right
1544 * leaf since comparisons use an 'elm >= separator' inequality.
1553 new_leaf
= hammer_alloc_btree(hmp
, &error
);
1554 if (new_leaf
== NULL
) {
1556 hammer_unlock(&parent
->lock
);
1557 parent
->flags
|= HAMMER_NODE_DELETED
;
1558 hammer_rel_node(parent
);
1562 hammer_lock_ex(&new_leaf
->lock
);
1565 * Create the new node. P (elm) become the left-hand boundary in the
1566 * new node. Copy the right-hand boundary as well.
1568 hammer_modify_node(leaf
);
1569 hammer_modify_node(new_leaf
);
1570 ondisk
= leaf
->ondisk
;
1571 elm
= &ondisk
->elms
[split
];
1572 bcopy(elm
, &new_leaf
->ondisk
->elms
[0], (ondisk
->count
- split
) * esize
);
1573 new_leaf
->ondisk
->count
= ondisk
->count
- split
;
1574 new_leaf
->ondisk
->parent
= parent
->node_offset
;
1575 new_leaf
->ondisk
->type
= HAMMER_BTREE_TYPE_LEAF
;
1576 KKASSERT(ondisk
->type
== new_leaf
->ondisk
->type
);
1579 * Cleanup the original node. Because this is a leaf node and
1580 * leaf nodes do not have a right-hand boundary, there
1581 * aren't any special edge cases to clean up. We just fixup the
1584 ondisk
->count
= split
;
1587 * Insert the separator into the parent, fixup the parent's
1588 * reference to the original node, and reference the new node.
1589 * The separator is P.
1591 * Remember that base.count does not include the right-hand boundary.
1592 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1594 hammer_modify_node(parent
);
1595 ondisk
= parent
->ondisk
;
1596 KKASSERT(ondisk
->count
!= HAMMER_BTREE_INT_ELMS
);
1597 parent_elm
= &ondisk
->elms
[parent_index
+1];
1598 bcopy(parent_elm
, parent_elm
+ 1,
1599 (ondisk
->count
- parent_index
) * esize
);
1601 hammer_make_separator(&elm
[-1].base
, &elm
[0].base
, &parent_elm
->base
);
1602 parent_elm
->internal
.base
.btype
= new_leaf
->ondisk
->type
;
1603 parent_elm
->internal
.subtree_offset
= new_leaf
->node_offset
;
1604 mid_boundary
= &parent_elm
->base
;
1608 * The filesystem's root B-Tree pointer may have to be updated.
1611 hammer_volume_t volume
;
1613 volume
= hammer_get_root_volume(hmp
, &error
);
1614 KKASSERT(error
== 0);
1616 hammer_modify_volume(volume
, &volume
->ondisk
->vol0_btree_root
,
1617 sizeof(hammer_off_t
));
1618 volume
->ondisk
->vol0_btree_root
= parent
->node_offset
;
1619 leaf
->ondisk
->parent
= parent
->node_offset
;
1620 if (cursor
->parent
) {
1621 hammer_unlock(&cursor
->parent
->lock
);
1622 hammer_rel_node(cursor
->parent
);
1624 cursor
->parent
= parent
; /* lock'd and ref'd */
1625 hammer_rel_volume(volume
, 0);
1629 * Ok, now adjust the cursor depending on which element the original
1630 * index was pointing at. If we are >= the split point the push node
1631 * is now in the new node.
1633 * NOTE: If we are at the split point itself we need to select the
1634 * old or new node based on where key_beg's insertion point will be.
1635 * If we pick the wrong side the inserted element will wind up in
1636 * the wrong leaf node and outside that node's bounds.
1638 if (cursor
->index
> split
||
1639 (cursor
->index
== split
&&
1640 hammer_btree_cmp(&cursor
->key_beg
, mid_boundary
) >= 0)) {
1641 cursor
->parent_index
= parent_index
+ 1;
1642 cursor
->index
-= split
;
1643 hammer_unlock(&cursor
->node
->lock
);
1644 hammer_rel_node(cursor
->node
);
1645 cursor
->node
= new_leaf
;
1647 cursor
->parent_index
= parent_index
;
1648 hammer_unlock(&new_leaf
->lock
);
1649 hammer_rel_node(new_leaf
);
1653 * Fixup left and right bounds
1655 parent_elm
= &parent
->ondisk
->elms
[cursor
->parent_index
];
1656 cursor
->left_bound
= &parent_elm
[0].internal
.base
;
1657 cursor
->right_bound
= &parent_elm
[1].internal
.base
;
1660 * Assert that the bounds are correct.
1662 KKASSERT(hammer_btree_cmp(cursor
->left_bound
,
1663 &cursor
->node
->ondisk
->elms
[0].leaf
.base
) <= 0);
1664 KKASSERT(hammer_btree_cmp(cursor
->right_bound
,
1665 &cursor
->node
->ondisk
->elms
[cursor
->node
->ondisk
->count
-1].leaf
.base
) > 0);
1668 hammer_cursor_downgrade(cursor
);
1673 * Recursively correct the right-hand boundary's create_tid to (tid) as
1674 * long as the rest of the key matches. We have to recurse upward in
1675 * the tree as well as down the left side of each parent's right node.
1677 * Return EDEADLK if we were only partially successful, forcing the caller
1678 * to try again. The original cursor is not modified. This routine can
1679 * also fail with EDEADLK if it is forced to throw away a portion of its
1682 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1685 TAILQ_ENTRY(hammer_rhb
) entry
;
1690 TAILQ_HEAD(hammer_rhb_list
, hammer_rhb
);
1693 hammer_btree_correct_rhb(hammer_cursor_t cursor
, hammer_tid_t tid
)
1695 struct hammer_rhb_list rhb_list
;
1696 hammer_base_elm_t elm
;
1697 hammer_node_t orig_node
;
1698 struct hammer_rhb
*rhb
;
1702 TAILQ_INIT(&rhb_list
);
1705 * Save our position so we can restore it on return. This also
1706 * gives us a stable 'elm'.
1708 orig_node
= cursor
->node
;
1709 hammer_ref_node(orig_node
);
1710 hammer_lock_sh(&orig_node
->lock
);
1711 orig_index
= cursor
->index
;
1712 elm
= &orig_node
->ondisk
->elms
[orig_index
].base
;
1715 * Now build a list of parents going up, allocating a rhb
1716 * structure for each one.
1718 while (cursor
->parent
) {
1720 * Stop if we no longer have any right-bounds to fix up
1722 if (elm
->obj_id
!= cursor
->right_bound
->obj_id
||
1723 elm
->rec_type
!= cursor
->right_bound
->rec_type
||
1724 elm
->key
!= cursor
->right_bound
->key
) {
1729 * Stop if the right-hand bound's create_tid does not
1730 * need to be corrected.
1732 if (cursor
->right_bound
->create_tid
>= tid
)
1735 rhb
= kmalloc(sizeof(*rhb
), M_HAMMER
, M_WAITOK
|M_ZERO
);
1736 rhb
->node
= cursor
->parent
;
1737 rhb
->index
= cursor
->parent_index
;
1738 hammer_ref_node(rhb
->node
);
1739 hammer_lock_sh(&rhb
->node
->lock
);
1740 TAILQ_INSERT_HEAD(&rhb_list
, rhb
, entry
);
1742 hammer_cursor_up(cursor
);
1746 * now safely adjust the right hand bound for each rhb. This may
1747 * also require taking the right side of the tree and iterating down
1751 while (error
== 0 && (rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
1752 error
= hammer_cursor_seek(cursor
, rhb
->node
, rhb
->index
);
1753 kprintf("CORRECT RHB %016llx index %d type=%c\n",
1754 rhb
->node
->node_offset
,
1755 rhb
->index
, cursor
->node
->ondisk
->type
);
1758 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
1759 hammer_unlock(&rhb
->node
->lock
);
1760 hammer_rel_node(rhb
->node
);
1761 kfree(rhb
, M_HAMMER
);
1763 switch (cursor
->node
->ondisk
->type
) {
1764 case HAMMER_BTREE_TYPE_INTERNAL
:
1766 * Right-boundary for parent at internal node
1767 * is one element to the right of the element whos
1768 * right boundary needs adjusting. We must then
1769 * traverse down the left side correcting any left
1770 * bounds (which may now be too far to the left).
1773 error
= hammer_btree_correct_lhb(cursor
, tid
);
1776 panic("hammer_btree_correct_rhb(): Bad node type");
1785 while ((rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
1786 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
1787 hammer_unlock(&rhb
->node
->lock
);
1788 hammer_rel_node(rhb
->node
);
1789 kfree(rhb
, M_HAMMER
);
1791 error
= hammer_cursor_seek(cursor
, orig_node
, orig_index
);
1792 hammer_unlock(&orig_node
->lock
);
1793 hammer_rel_node(orig_node
);
1798 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
1799 * bound going downward starting at the current cursor position.
1801 * This function does not restore the cursor after use.
1804 hammer_btree_correct_lhb(hammer_cursor_t cursor
, hammer_tid_t tid
)
1806 struct hammer_rhb_list rhb_list
;
1807 hammer_base_elm_t elm
;
1808 hammer_base_elm_t cmp
;
1809 struct hammer_rhb
*rhb
;
1812 TAILQ_INIT(&rhb_list
);
1814 cmp
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
1817 * Record the node and traverse down the left-hand side for all
1818 * matching records needing a boundary correction.
1822 rhb
= kmalloc(sizeof(*rhb
), M_HAMMER
, M_WAITOK
|M_ZERO
);
1823 rhb
->node
= cursor
->node
;
1824 rhb
->index
= cursor
->index
;
1825 hammer_ref_node(rhb
->node
);
1826 hammer_lock_sh(&rhb
->node
->lock
);
1827 TAILQ_INSERT_HEAD(&rhb_list
, rhb
, entry
);
1829 if (cursor
->node
->ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
1831 * Nothing to traverse down if we are at the right
1832 * boundary of an internal node.
1834 if (cursor
->index
== cursor
->node
->ondisk
->count
)
1837 elm
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
1838 if (elm
->btype
== HAMMER_BTREE_TYPE_RECORD
)
1840 panic("Illegal leaf record type %02x", elm
->btype
);
1842 error
= hammer_cursor_down(cursor
);
1846 elm
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
1847 if (elm
->obj_id
!= cmp
->obj_id
||
1848 elm
->rec_type
!= cmp
->rec_type
||
1849 elm
->key
!= cmp
->key
) {
1852 if (elm
->create_tid
>= tid
)
1858 * Now we can safely adjust the left-hand boundary from the bottom-up.
1859 * The last element we remove from the list is the caller's right hand
1860 * boundary, which must also be adjusted.
1862 while (error
== 0 && (rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
1863 error
= hammer_cursor_seek(cursor
, rhb
->node
, rhb
->index
);
1866 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
1867 hammer_unlock(&rhb
->node
->lock
);
1868 hammer_rel_node(rhb
->node
);
1869 kfree(rhb
, M_HAMMER
);
1871 elm
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
1872 if (cursor
->node
->ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
1873 kprintf("hammer_btree_correct_lhb-I @%016llx[%d]\n",
1874 cursor
->node
->node_offset
, cursor
->index
);
1875 hammer_modify_node(cursor
->node
);
1876 elm
->create_tid
= tid
;
1878 panic("hammer_btree_correct_lhb(): Bad element type");
1885 while ((rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
1886 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
1887 hammer_unlock(&rhb
->node
->lock
);
1888 hammer_rel_node(rhb
->node
);
1889 kfree(rhb
, M_HAMMER
);
1895 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1896 * on success, EAGAIN if we could not acquire the necessary locks, or some
1897 * other error. This node can be a leaf node or an internal node.
1899 * On return the cursor may end up pointing at an internal node, suitable
1900 * for further iteration but not for an immediate insertion or deletion.
1902 * cursor->node may be an internal node or a leaf node.
1904 * NOTE: If cursor->node has one element it is the parent trying to delete
1905 * that element, make sure cursor->index is properly adjusted on success.
1908 btree_remove(hammer_cursor_t cursor
)
1910 hammer_node_ondisk_t ondisk
;
1911 hammer_btree_elm_t elm
;
1913 hammer_node_t parent
;
1914 const int esize
= sizeof(*elm
);
1917 node
= cursor
->node
;
1920 * When deleting the root of the filesystem convert it to
1921 * an empty leaf node. Internal nodes cannot be empty.
1923 if (node
->ondisk
->parent
== 0) {
1924 hammer_modify_node(node
);
1925 ondisk
= node
->ondisk
;
1926 ondisk
->type
= HAMMER_BTREE_TYPE_LEAF
;
1933 * Zero-out the parent's reference to the child and flag the
1934 * child for destruction. This ensures that the child is not
1935 * reused while other references to it exist.
1937 parent
= cursor
->parent
;
1938 hammer_modify_node(parent
);
1939 ondisk
= parent
->ondisk
;
1940 KKASSERT(ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
);
1941 elm
= &ondisk
->elms
[cursor
->parent_index
];
1942 KKASSERT(elm
->internal
.subtree_offset
== node
->node_offset
);
1943 elm
->internal
.subtree_offset
= 0;
1945 hammer_flush_node(node
);
1946 node
->flags
|= HAMMER_NODE_DELETED
;
1949 * If the parent would otherwise not become empty we can physically
1950 * remove the zero'd element. Note however that in order to
1951 * guarentee a valid cursor we still need to be able to cursor up
1952 * because we no longer have a node.
1954 * This collapse will change the parent's boundary elements, making
1955 * them wider. The new boundaries are recursively corrected in
1958 * XXX we can theoretically recalculate the midpoint but there isn't
1959 * much of a reason to do it.
1961 error
= hammer_cursor_up(cursor
);
1963 error
= hammer_cursor_upgrade(cursor
);
1966 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
1967 Debugger("BTREE_REMOVE");
1972 * Remove the internal element from the parent. The bcopy must
1973 * include the right boundary element.
1975 KKASSERT(parent
== cursor
->node
&& ondisk
== parent
->ondisk
);
1978 /* ondisk is node's ondisk */
1979 /* elm is node's element */
1982 * Remove the internal element that we zero'd out. Tell the caller
1983 * to loop if it hits zero (to try to avoid eating up precious kernel
1986 KKASSERT(ondisk
->count
> 0);
1987 bcopy(&elm
[1], &elm
[0], (ondisk
->count
- cursor
->index
) * esize
);
1989 if (ondisk
->count
== 0)
1995 * Attempt to remove the deleted internal element at the current cursor
1996 * position. If we are unable to remove the element we return EDEADLK.
1998 * If the current internal node becomes empty we delete it in the parent
1999 * and cursor up, looping until we finish or we deadlock.
2001 * On return, if successful, the cursor will be pointing at the next
2002 * iterative position in the B-Tree. If unsuccessful the cursor will be
2003 * pointing at the last deleted internal element that could not be
2008 btree_remove_deleted_element(hammer_cursor_t cursor
)
2011 hammer_btree_elm_t elm
;
2014 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
2016 node
= cursor
->node
;
2017 elm
= &node
->ondisk
->elms
[cursor
->index
];
2018 if (elm
->internal
.subtree_offset
== 0) {
2020 error
= btree_remove(cursor
);
2021 kprintf("BTREE REMOVE DELETED ELEMENT %d\n", error
);
2022 } while (error
== EAGAIN
);
2028 * The element (elm) has been moved to a new internal node (node).
2030 * If the element represents a pointer to an internal node that node's
2031 * parent must be adjusted to the element's new location.
2033 * XXX deadlock potential here with our exclusive locks
2037 btree_set_parent(hammer_node_t node
, hammer_btree_elm_t elm
)
2039 hammer_node_t child
;
2044 switch(elm
->base
.btype
) {
2045 case HAMMER_BTREE_TYPE_INTERNAL
:
2046 case HAMMER_BTREE_TYPE_LEAF
:
2047 child
= hammer_get_node(node
->volume
->hmp
,
2048 elm
->internal
.subtree_offset
, &error
);
2050 hammer_modify_node(child
);
2051 child
->ondisk
->parent
= node
->node_offset
;
2052 hammer_rel_node(child
);
2062 * Exclusively lock all the children of node. This is used by the split
2063 * code to prevent anyone from accessing the children of a cursor node
2064 * while we fix-up its parent offset.
2066 * If we don't lock the children we can really mess up cursors which block
2067 * trying to cursor-up into our node.
2069 * On failure EDEADLK (or some other error) is returned. If a deadlock
2070 * error is returned the cursor is adjusted to block on termination.
2073 hammer_btree_lock_children(hammer_cursor_t cursor
,
2074 struct hammer_node_locklist
**locklistp
)
2077 hammer_node_locklist_t item
;
2078 hammer_node_ondisk_t ondisk
;
2079 hammer_btree_elm_t elm
;
2080 hammer_node_t child
;
2084 node
= cursor
->node
;
2085 ondisk
= node
->ondisk
;
2087 for (i
= 0; error
== 0 && i
< ondisk
->count
; ++i
) {
2088 elm
= &ondisk
->elms
[i
];
2090 switch(elm
->base
.btype
) {
2091 case HAMMER_BTREE_TYPE_INTERNAL
:
2092 case HAMMER_BTREE_TYPE_LEAF
:
2093 child
= hammer_get_node(node
->volume
->hmp
,
2094 elm
->internal
.subtree_offset
,
2102 if (hammer_lock_ex_try(&child
->lock
) != 0) {
2103 if (cursor
->deadlk_node
== NULL
) {
2104 cursor
->deadlk_node
= node
;
2105 hammer_ref_node(cursor
->deadlk_node
);
2109 item
= kmalloc(sizeof(*item
),
2110 M_HAMMER
, M_WAITOK
);
2111 item
->next
= *locklistp
;
2118 hammer_btree_unlock_children(locklistp
);
2124 * Release previously obtained node locks.
2127 hammer_btree_unlock_children(struct hammer_node_locklist
**locklistp
)
2129 hammer_node_locklist_t item
;
2131 while ((item
= *locklistp
) != NULL
) {
2132 *locklistp
= item
->next
;
2133 hammer_unlock(&item
->node
->lock
);
2134 hammer_rel_node(item
->node
);
2135 kfree(item
, M_HAMMER
);
2139 /************************************************************************
2140 * MISCELLANIOUS SUPPORT *
2141 ************************************************************************/
2144 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2146 * Note that for this particular function a return value of -1, 0, or +1
2147 * can denote a match if create_tid is otherwise discounted. A create_tid
2148 * of zero is considered to be 'infinity' in comparisons.
2150 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2153 hammer_btree_cmp(hammer_base_elm_t key1
, hammer_base_elm_t key2
)
2155 if (key1
->obj_id
< key2
->obj_id
)
2157 if (key1
->obj_id
> key2
->obj_id
)
2160 if (key1
->rec_type
< key2
->rec_type
)
2162 if (key1
->rec_type
> key2
->rec_type
)
2165 if (key1
->key
< key2
->key
)
2167 if (key1
->key
> key2
->key
)
2171 * A create_tid of zero indicates a record which is undeletable
2172 * and must be considered to have a value of positive infinity.
2174 if (key1
->create_tid
== 0) {
2175 if (key2
->create_tid
== 0)
2179 if (key2
->create_tid
== 0)
2181 if (key1
->create_tid
< key2
->create_tid
)
2183 if (key1
->create_tid
> key2
->create_tid
)
2189 * Test a timestamp against an element to determine whether the
2190 * element is visible. A timestamp of 0 means 'infinity'.
2193 hammer_btree_chkts(hammer_tid_t asof
, hammer_base_elm_t base
)
2196 if (base
->delete_tid
)
2200 if (asof
< base
->create_tid
)
2202 if (base
->delete_tid
&& asof
>= base
->delete_tid
)
2208 * Create a separator half way inbetween key1 and key2. For fields just
2209 * one unit apart, the separator will match key2. key1 is on the left-hand
2210 * side and key2 is on the right-hand side.
2212 * create_tid has to be special cased because a value of 0 represents
2215 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2216 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2219 hammer_make_separator(hammer_base_elm_t key1
, hammer_base_elm_t key2
,
2220 hammer_base_elm_t dest
)
2222 bzero(dest
, sizeof(*dest
));
2223 MAKE_SEPARATOR(key1
, key2
, dest
, obj_id
);
2224 MAKE_SEPARATOR(key1
, key2
, dest
, rec_type
);
2225 MAKE_SEPARATOR(key1
, key2
, dest
, key
);
2227 if (key1
->obj_id
== key2
->obj_id
&&
2228 key1
->rec_type
== key2
->rec_type
&&
2229 key1
->key
== key2
->key
) {
2230 if (key1
->create_tid
== 0) {
2232 * Oops, a create_tid of 0 means 'infinity', so
2233 * if everything matches this just isn't legal.
2235 panic("key1->create_tid of 0 is impossible here");
2236 } else if (key2
->create_tid
== 0) {
2237 dest
->create_tid
= key1
->create_tid
+ 1;
2239 MAKE_SEPARATOR(key1
, key2
, dest
, create_tid
);
2242 dest
->create_tid
= 0;
2246 #undef MAKE_SEPARATOR
2249 * Return whether a generic internal or leaf node is full
2252 btree_node_is_full(hammer_node_ondisk_t node
)
2254 switch(node
->type
) {
2255 case HAMMER_BTREE_TYPE_INTERNAL
:
2256 if (node
->count
== HAMMER_BTREE_INT_ELMS
)
2259 case HAMMER_BTREE_TYPE_LEAF
:
2260 if (node
->count
== HAMMER_BTREE_LEAF_ELMS
)
2264 panic("illegal btree subtype");
2271 btree_max_elements(u_int8_t type
)
2273 if (type
== HAMMER_BTREE_TYPE_LEAF
)
2274 return(HAMMER_BTREE_LEAF_ELMS
);
2275 if (type
== HAMMER_BTREE_TYPE_INTERNAL
)
2276 return(HAMMER_BTREE_INT_ELMS
);
2277 panic("btree_max_elements: bad type %d\n", type
);
2282 hammer_print_btree_node(hammer_node_ondisk_t ondisk
)
2284 hammer_btree_elm_t elm
;
2287 kprintf("node %p count=%d parent=%016llx type=%c\n",
2288 ondisk
, ondisk
->count
, ondisk
->parent
, ondisk
->type
);
2291 * Dump both boundary elements if an internal node
2293 if (ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
2294 for (i
= 0; i
<= ondisk
->count
; ++i
) {
2295 elm
= &ondisk
->elms
[i
];
2296 hammer_print_btree_elm(elm
, ondisk
->type
, i
);
2299 for (i
= 0; i
< ondisk
->count
; ++i
) {
2300 elm
= &ondisk
->elms
[i
];
2301 hammer_print_btree_elm(elm
, ondisk
->type
, i
);
2307 hammer_print_btree_elm(hammer_btree_elm_t elm
, u_int8_t type
, int i
)
2310 kprintf("\tobj_id = %016llx\n", elm
->base
.obj_id
);
2311 kprintf("\tkey = %016llx\n", elm
->base
.key
);
2312 kprintf("\tcreate_tid = %016llx\n", elm
->base
.create_tid
);
2313 kprintf("\tdelete_tid = %016llx\n", elm
->base
.delete_tid
);
2314 kprintf("\trec_type = %04x\n", elm
->base
.rec_type
);
2315 kprintf("\tobj_type = %02x\n", elm
->base
.obj_type
);
2316 kprintf("\tbtype = %02x (%c)\n",
2318 (elm
->base
.btype
? elm
->base
.btype
: '?'));
2321 case HAMMER_BTREE_TYPE_INTERNAL
:
2322 kprintf("\tsubtree_off = %016llx\n",
2323 elm
->internal
.subtree_offset
);
2325 case HAMMER_BTREE_TYPE_RECORD
:
2326 kprintf("\trec_offset = %016llx\n", elm
->leaf
.rec_offset
);
2327 kprintf("\tdata_offset = %016llx\n", elm
->leaf
.data_offset
);
2328 kprintf("\tdata_len = %08x\n", elm
->leaf
.data_len
);
2329 kprintf("\tdata_crc = %08x\n", elm
->leaf
.data_crc
);