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.76 2008/08/06 15:38:58 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. If a
77 * deadlock occurs a deletion may not be able to remove an empty leaf.
78 * Deletions never allow internal nodes to become empty (that would blow
85 static int btree_search(hammer_cursor_t cursor
, int flags
);
86 static int btree_split_internal(hammer_cursor_t cursor
);
87 static int btree_split_leaf(hammer_cursor_t cursor
);
88 static int btree_remove(hammer_cursor_t cursor
);
89 static int btree_node_is_full(hammer_node_ondisk_t node
);
90 static int hammer_btree_mirror_propagate(hammer_cursor_t cursor
,
91 hammer_tid_t mirror_tid
);
92 static void hammer_make_separator(hammer_base_elm_t key1
,
93 hammer_base_elm_t key2
, hammer_base_elm_t dest
);
94 static void hammer_cursor_mirror_filter(hammer_cursor_t cursor
);
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 * If HAMMER_CURSOR_ITERATE_CHECK is set it is possible that the cursor
114 * was reverse indexed due to being moved to a parent while unlocked,
115 * and something else might have inserted an element outside the iteration
116 * range. When this case occurs the iterator just keeps iterating until
117 * it gets back into the iteration range (instead of asserting).
119 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
122 hammer_btree_iterate(hammer_cursor_t cursor
)
124 hammer_node_ondisk_t node
;
125 hammer_btree_elm_t elm
;
132 * Skip past the current record
134 hmp
= cursor
->trans
->hmp
;
135 node
= cursor
->node
->ondisk
;
138 if (cursor
->index
< node
->count
&&
139 (cursor
->flags
& HAMMER_CURSOR_ATEDISK
)) {
144 * HAMMER can wind up being cpu-bound.
146 if (++hmp
->check_yield
> hammer_yield_check
) {
147 hmp
->check_yield
= 0;
153 * Loop until an element is found or we are done.
157 * We iterate up the tree and then index over one element
158 * while we are at the last element in the current node.
160 * If we are at the root of the filesystem, cursor_up
163 * XXX this could be optimized by storing the information in
164 * the parent reference.
166 * XXX we can lose the node lock temporarily, this could mess
169 ++hammer_stats_btree_iterations
;
170 hammer_flusher_clean_loose_ios(hmp
);
172 if (cursor
->index
== node
->count
) {
173 if (hammer_debug_btree
) {
174 kprintf("BRACKETU %016llx[%d] -> %016llx[%d] (td=%p)\n",
175 (long long)cursor
->node
->node_offset
,
177 (long long)(cursor
->parent
? cursor
->parent
->node_offset
: -1),
178 cursor
->parent_index
,
181 KKASSERT(cursor
->parent
== NULL
|| cursor
->parent
->ondisk
->elms
[cursor
->parent_index
].internal
.subtree_offset
== cursor
->node
->node_offset
);
182 error
= hammer_cursor_up(cursor
);
185 /* reload stale pointer */
186 node
= cursor
->node
->ondisk
;
187 KKASSERT(cursor
->index
!= node
->count
);
190 * If we are reblocking we want to return internal
191 * nodes. Note that the internal node will be
192 * returned multiple times, on each upward recursion
193 * from its children. The caller selects which
194 * revisit it cares about (usually first or last only).
196 if (cursor
->flags
& HAMMER_CURSOR_REBLOCKING
) {
197 cursor
->flags
|= HAMMER_CURSOR_ATEDISK
;
205 * Check internal or leaf element. Determine if the record
206 * at the cursor has gone beyond the end of our range.
208 * We recurse down through internal nodes.
210 if (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
211 elm
= &node
->elms
[cursor
->index
];
213 r
= hammer_btree_cmp(&cursor
->key_end
, &elm
[0].base
);
214 s
= hammer_btree_cmp(&cursor
->key_beg
, &elm
[1].base
);
215 if (hammer_debug_btree
) {
216 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx lo=%02x %d (td=%p)\n",
217 (long long)cursor
->node
->node_offset
,
219 (long long)elm
[0].internal
.base
.obj_id
,
220 elm
[0].internal
.base
.rec_type
,
221 (long long)elm
[0].internal
.base
.key
,
222 elm
[0].internal
.base
.localization
,
226 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx lo=%02x %d\n",
227 (long long)cursor
->node
->node_offset
,
229 (long long)elm
[1].internal
.base
.obj_id
,
230 elm
[1].internal
.base
.rec_type
,
231 (long long)elm
[1].internal
.base
.key
,
232 elm
[1].internal
.base
.localization
,
241 if (r
== 0 && (cursor
->flags
&
242 HAMMER_CURSOR_END_INCLUSIVE
) == 0) {
250 KKASSERT(elm
->internal
.subtree_offset
!= 0);
254 * If running the mirror filter see if we
255 * can skip one or more entire sub-trees.
256 * If we can we return the internal node
257 * and the caller processes the skipped
258 * range (see mirror_read).
261 HAMMER_CURSOR_MIRROR_FILTERED
) {
262 if (elm
->internal
.mirror_tid
<
263 cursor
->cmirror
->mirror_tid
) {
264 hammer_cursor_mirror_filter(cursor
);
270 * Normally it would be impossible for the
271 * cursor to have gotten back-indexed,
272 * but it can happen if a node is deleted
273 * and the cursor is moved to its parent
274 * internal node. ITERATE_CHECK will be set.
276 KKASSERT(cursor
->flags
&
277 HAMMER_CURSOR_ITERATE_CHECK
);
278 kprintf("hammer_btree_iterate: "
279 "DEBUG: Caught parent seek "
280 "in internal iteration\n");
283 error
= hammer_cursor_down(cursor
);
286 KKASSERT(cursor
->index
== 0);
287 /* reload stale pointer */
288 node
= cursor
->node
->ondisk
;
291 elm
= &node
->elms
[cursor
->index
];
292 r
= hammer_btree_cmp(&cursor
->key_end
, &elm
->base
);
293 if (hammer_debug_btree
) {
294 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx lo=%02x %d\n",
295 (long long)cursor
->node
->node_offset
,
297 (elm
[0].leaf
.base
.btype
?
298 elm
[0].leaf
.base
.btype
: '?'),
299 (long long)elm
[0].leaf
.base
.obj_id
,
300 elm
[0].leaf
.base
.rec_type
,
301 (long long)elm
[0].leaf
.base
.key
,
302 elm
[0].leaf
.base
.localization
,
312 * We support both end-inclusive and
313 * end-exclusive searches.
316 (cursor
->flags
& HAMMER_CURSOR_END_INCLUSIVE
) == 0) {
322 * If ITERATE_CHECK is set an unlocked cursor may
323 * have been moved to a parent and the iterate can
324 * happen upon elements that are not in the requested
327 if (cursor
->flags
& HAMMER_CURSOR_ITERATE_CHECK
) {
328 s
= hammer_btree_cmp(&cursor
->key_beg
,
331 kprintf("hammer_btree_iterate: "
332 "DEBUG: Caught parent seek "
333 "in leaf iteration\n");
338 cursor
->flags
&= ~HAMMER_CURSOR_ITERATE_CHECK
;
343 switch(elm
->leaf
.base
.btype
) {
344 case HAMMER_BTREE_TYPE_RECORD
:
345 if ((cursor
->flags
& HAMMER_CURSOR_ASOF
) &&
346 hammer_btree_chkts(cursor
->asof
, &elm
->base
)) {
360 * node pointer invalid after loop
366 if (hammer_debug_btree
) {
367 int i
= cursor
->index
;
368 hammer_btree_elm_t elm
= &cursor
->node
->ondisk
->elms
[i
];
369 kprintf("ITERATE %p:%d %016llx %02x %016llx lo=%02x\n",
371 (long long)elm
->internal
.base
.obj_id
,
372 elm
->internal
.base
.rec_type
,
373 (long long)elm
->internal
.base
.key
,
374 elm
->internal
.base
.localization
383 * We hit an internal element that we could skip as part of a mirroring
384 * scan. Calculate the entire range being skipped.
386 * It is important to include any gaps between the parent's left_bound
387 * and the node's left_bound, and same goes for the right side.
390 hammer_cursor_mirror_filter(hammer_cursor_t cursor
)
392 struct hammer_cmirror
*cmirror
;
393 hammer_node_ondisk_t ondisk
;
394 hammer_btree_elm_t elm
;
396 ondisk
= cursor
->node
->ondisk
;
397 cmirror
= cursor
->cmirror
;
400 * Calculate the skipped range
402 elm
= &ondisk
->elms
[cursor
->index
];
403 if (cursor
->index
== 0)
404 cmirror
->skip_beg
= *cursor
->left_bound
;
406 cmirror
->skip_beg
= elm
->internal
.base
;
407 while (cursor
->index
< ondisk
->count
) {
408 if (elm
->internal
.mirror_tid
>= cmirror
->mirror_tid
)
413 if (cursor
->index
== ondisk
->count
)
414 cmirror
->skip_end
= *cursor
->right_bound
;
416 cmirror
->skip_end
= elm
->internal
.base
;
419 * clip the returned result.
421 if (hammer_btree_cmp(&cmirror
->skip_beg
, &cursor
->key_beg
) < 0)
422 cmirror
->skip_beg
= cursor
->key_beg
;
423 if (hammer_btree_cmp(&cmirror
->skip_end
, &cursor
->key_end
) > 0)
424 cmirror
->skip_end
= cursor
->key_end
;
428 * Iterate in the reverse direction. This is used by the pruning code to
429 * avoid overlapping records.
432 hammer_btree_iterate_reverse(hammer_cursor_t cursor
)
434 hammer_node_ondisk_t node
;
435 hammer_btree_elm_t elm
;
440 /* mirror filtering not supported for reverse iteration */
441 KKASSERT ((cursor
->flags
& HAMMER_CURSOR_MIRROR_FILTERED
) == 0);
444 * Skip past the current record. For various reasons the cursor
445 * may end up set to -1 or set to point at the end of the current
446 * node. These cases must be addressed.
448 node
= cursor
->node
->ondisk
;
451 if (cursor
->index
!= -1 &&
452 (cursor
->flags
& HAMMER_CURSOR_ATEDISK
)) {
455 if (cursor
->index
== cursor
->node
->ondisk
->count
)
459 * Loop until an element is found or we are done.
462 ++hammer_stats_btree_iterations
;
463 hammer_flusher_clean_loose_ios(cursor
->trans
->hmp
);
466 * We iterate up the tree and then index over one element
467 * while we are at the last element in the current node.
469 if (cursor
->index
== -1) {
470 error
= hammer_cursor_up(cursor
);
472 cursor
->index
= 0; /* sanity */
475 /* reload stale pointer */
476 node
= cursor
->node
->ondisk
;
477 KKASSERT(cursor
->index
!= node
->count
);
483 * Check internal or leaf element. Determine if the record
484 * at the cursor has gone beyond the end of our range.
486 * We recurse down through internal nodes.
488 KKASSERT(cursor
->index
!= node
->count
);
489 if (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
490 elm
= &node
->elms
[cursor
->index
];
491 r
= hammer_btree_cmp(&cursor
->key_end
, &elm
[0].base
);
492 s
= hammer_btree_cmp(&cursor
->key_beg
, &elm
[1].base
);
493 if (hammer_debug_btree
) {
494 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx lo=%02x %d\n",
495 (long long)cursor
->node
->node_offset
,
497 (long long)elm
[0].internal
.base
.obj_id
,
498 elm
[0].internal
.base
.rec_type
,
499 (long long)elm
[0].internal
.base
.key
,
500 elm
[0].internal
.base
.localization
,
503 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx lo=%02x %d\n",
504 (long long)cursor
->node
->node_offset
,
506 (long long)elm
[1].internal
.base
.obj_id
,
507 elm
[1].internal
.base
.rec_type
,
508 (long long)elm
[1].internal
.base
.key
,
509 elm
[1].internal
.base
.localization
,
520 * It shouldn't be possible to be seeked past key_end,
521 * even if the cursor got moved to a parent.
528 KKASSERT(elm
->internal
.subtree_offset
!= 0);
530 error
= hammer_cursor_down(cursor
);
533 KKASSERT(cursor
->index
== 0);
534 /* reload stale pointer */
535 node
= cursor
->node
->ondisk
;
537 /* this can assign -1 if the leaf was empty */
538 cursor
->index
= node
->count
- 1;
541 elm
= &node
->elms
[cursor
->index
];
542 s
= hammer_btree_cmp(&cursor
->key_beg
, &elm
->base
);
543 if (hammer_debug_btree
) {
544 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx lo=%02x %d\n",
545 (long long)cursor
->node
->node_offset
,
547 (elm
[0].leaf
.base
.btype
?
548 elm
[0].leaf
.base
.btype
: '?'),
549 (long long)elm
[0].leaf
.base
.obj_id
,
550 elm
[0].leaf
.base
.rec_type
,
551 (long long)elm
[0].leaf
.base
.key
,
552 elm
[0].leaf
.base
.localization
,
562 * It shouldn't be possible to be seeked past key_end,
563 * even if the cursor got moved to a parent.
565 cursor
->flags
&= ~HAMMER_CURSOR_ITERATE_CHECK
;
570 switch(elm
->leaf
.base
.btype
) {
571 case HAMMER_BTREE_TYPE_RECORD
:
572 if ((cursor
->flags
& HAMMER_CURSOR_ASOF
) &&
573 hammer_btree_chkts(cursor
->asof
, &elm
->base
)) {
587 * node pointer invalid after loop
593 if (hammer_debug_btree
) {
594 int i
= cursor
->index
;
595 hammer_btree_elm_t elm
= &cursor
->node
->ondisk
->elms
[i
];
596 kprintf("ITERATE %p:%d %016llx %02x %016llx lo=%02x\n",
598 (long long)elm
->internal
.base
.obj_id
,
599 elm
->internal
.base
.rec_type
,
600 (long long)elm
->internal
.base
.key
,
601 elm
->internal
.base
.localization
610 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
611 * could not be found, EDEADLK if inserting and a retry is needed, and a
612 * fatal error otherwise. When retrying, the caller must terminate the
613 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
615 * The cursor is suitably positioned for a deletion on success, and suitably
616 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
619 * The cursor may begin anywhere, the search will traverse the tree in
620 * either direction to locate the requested element.
622 * Most of the logic implementing historical searches is handled here. We
623 * do an initial lookup with create_tid set to the asof TID. Due to the
624 * way records are laid out, a backwards iteration may be required if
625 * ENOENT is returned to locate the historical record. Here's the
628 * create_tid: 10 15 20
632 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
633 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
634 * not visible and thus causes ENOENT to be returned. We really need
635 * to check record 11 in LEAF1. If it also fails then the search fails
636 * (e.g. it might represent the range 11-16 and thus still not match our
637 * AS-OF timestamp of 17). Note that LEAF1 could be empty, requiring
638 * further iterations.
640 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
641 * and the cursor->create_check TID if an iteration might be needed.
642 * In the above example create_check would be set to 14.
645 hammer_btree_lookup(hammer_cursor_t cursor
)
649 cursor
->flags
&= ~HAMMER_CURSOR_ITERATE_CHECK
;
650 KKASSERT ((cursor
->flags
& HAMMER_CURSOR_INSERT
) == 0 ||
651 cursor
->trans
->sync_lock_refs
> 0);
652 ++hammer_stats_btree_lookups
;
653 if (cursor
->flags
& HAMMER_CURSOR_ASOF
) {
654 KKASSERT((cursor
->flags
& HAMMER_CURSOR_INSERT
) == 0);
655 cursor
->key_beg
.create_tid
= cursor
->asof
;
657 cursor
->flags
&= ~HAMMER_CURSOR_CREATE_CHECK
;
658 error
= btree_search(cursor
, 0);
659 if (error
!= ENOENT
||
660 (cursor
->flags
& HAMMER_CURSOR_CREATE_CHECK
) == 0) {
663 * Stop if error other then ENOENT.
664 * Stop if ENOENT and not special case.
668 if (hammer_debug_btree
) {
669 kprintf("CREATE_CHECK %016llx\n",
670 (long long)cursor
->create_check
);
672 cursor
->key_beg
.create_tid
= cursor
->create_check
;
676 error
= btree_search(cursor
, 0);
679 error
= hammer_btree_extract(cursor
, cursor
->flags
);
684 * Execute the logic required to start an iteration. The first record
685 * located within the specified range is returned and iteration control
686 * flags are adjusted for successive hammer_btree_iterate() calls.
688 * Set ATEDISK so a low-level caller can call btree_first/btree_iterate
689 * in a loop without worrying about it. Higher-level merged searches will
690 * adjust the flag appropriately.
693 hammer_btree_first(hammer_cursor_t cursor
)
697 error
= hammer_btree_lookup(cursor
);
698 if (error
== ENOENT
) {
699 cursor
->flags
&= ~HAMMER_CURSOR_ATEDISK
;
700 error
= hammer_btree_iterate(cursor
);
702 cursor
->flags
|= HAMMER_CURSOR_ATEDISK
;
707 * Similarly but for an iteration in the reverse direction.
709 * Set ATEDISK when iterating backwards to skip the current entry,
710 * which after an ENOENT lookup will be pointing beyond our end point.
712 * Set ATEDISK so a low-level caller can call btree_last/btree_iterate_reverse
713 * in a loop without worrying about it. Higher-level merged searches will
714 * adjust the flag appropriately.
717 hammer_btree_last(hammer_cursor_t cursor
)
719 struct hammer_base_elm save
;
722 save
= cursor
->key_beg
;
723 cursor
->key_beg
= cursor
->key_end
;
724 error
= hammer_btree_lookup(cursor
);
725 cursor
->key_beg
= save
;
726 if (error
== ENOENT
||
727 (cursor
->flags
& HAMMER_CURSOR_END_INCLUSIVE
) == 0) {
728 cursor
->flags
|= HAMMER_CURSOR_ATEDISK
;
729 error
= hammer_btree_iterate_reverse(cursor
);
731 cursor
->flags
|= HAMMER_CURSOR_ATEDISK
;
736 * Extract the record and/or data associated with the cursor's current
737 * position. Any prior record or data stored in the cursor is replaced.
738 * The cursor must be positioned at a leaf node.
740 * NOTE: All extractions occur at the leaf of the B-Tree.
743 hammer_btree_extract(hammer_cursor_t cursor
, int flags
)
745 hammer_node_ondisk_t node
;
746 hammer_btree_elm_t elm
;
747 hammer_off_t data_off
;
753 * The case where the data reference resolves to the same buffer
754 * as the record reference must be handled.
756 node
= cursor
->node
->ondisk
;
757 elm
= &node
->elms
[cursor
->index
];
759 hmp
= cursor
->node
->hmp
;
762 * There is nothing to extract for an internal element.
764 if (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
)
768 * Only record types have data.
770 KKASSERT(node
->type
== HAMMER_BTREE_TYPE_LEAF
);
771 cursor
->leaf
= &elm
->leaf
;
773 if ((flags
& HAMMER_CURSOR_GET_DATA
) == 0)
775 if (elm
->leaf
.base
.btype
!= HAMMER_BTREE_TYPE_RECORD
)
777 data_off
= elm
->leaf
.data_offset
;
778 data_len
= elm
->leaf
.data_len
;
785 KKASSERT(data_len
>= 0 && data_len
<= HAMMER_XBUFSIZE
);
786 cursor
->data
= hammer_bread_ext(hmp
, data_off
, data_len
,
787 &error
, &cursor
->data_buffer
);
790 * Mark the data buffer as not being meta-data if it isn't
791 * meta-data (sometimes bulk data is accessed via a volume
795 switch(elm
->leaf
.base
.rec_type
) {
796 case HAMMER_RECTYPE_DATA
:
797 case HAMMER_RECTYPE_DB
:
798 hammer_io_notmeta(cursor
->data_buffer
);
806 * Deal with CRC errors on the extracted data.
809 hammer_crc_test_leaf(cursor
->data
, &elm
->leaf
) == 0) {
810 kprintf("CRC DATA @ %016llx/%d FAILED\n",
811 (long long)elm
->leaf
.data_offset
, elm
->leaf
.data_len
);
812 if (hammer_debug_critical
)
813 Debugger("CRC FAILED: DATA");
814 if (cursor
->trans
->flags
& HAMMER_TRANSF_CRCDOM
)
815 error
= EDOM
; /* less critical (mirroring) */
817 error
= EIO
; /* critical */
824 * Insert a leaf element into the B-Tree at the current cursor position.
825 * The cursor is positioned such that the element at and beyond the cursor
826 * are shifted to make room for the new record.
828 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
829 * flag set and that call must return ENOENT before this function can be
832 * The caller may depend on the cursor's exclusive lock after return to
833 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
835 * ENOSPC is returned if there is no room to insert a new record.
838 hammer_btree_insert(hammer_cursor_t cursor
, hammer_btree_leaf_elm_t elm
,
841 hammer_node_ondisk_t node
;
846 if ((error
= hammer_cursor_upgrade_node(cursor
)) != 0)
848 ++hammer_stats_btree_inserts
;
851 * Insert the element at the leaf node and update the count in the
852 * parent. It is possible for parent to be NULL, indicating that
853 * the filesystem's ROOT B-Tree node is a leaf itself, which is
854 * possible. The root inode can never be deleted so the leaf should
857 * Remember that the right-hand boundary is not included in the
860 hammer_modify_node_all(cursor
->trans
, cursor
->node
);
861 node
= cursor
->node
->ondisk
;
863 KKASSERT(elm
->base
.btype
!= 0);
864 KKASSERT(node
->type
== HAMMER_BTREE_TYPE_LEAF
);
865 KKASSERT(node
->count
< HAMMER_BTREE_LEAF_ELMS
);
866 if (i
!= node
->count
) {
867 bcopy(&node
->elms
[i
], &node
->elms
[i
+1],
868 (node
->count
- i
) * sizeof(*elm
));
870 node
->elms
[i
].leaf
= *elm
;
872 hammer_cursor_inserted_element(cursor
->node
, i
);
875 * Update the leaf node's aggregate mirror_tid for mirroring
878 if (node
->mirror_tid
< elm
->base
.delete_tid
) {
879 node
->mirror_tid
= elm
->base
.delete_tid
;
882 if (node
->mirror_tid
< elm
->base
.create_tid
) {
883 node
->mirror_tid
= elm
->base
.create_tid
;
886 hammer_modify_node_done(cursor
->node
);
889 * Debugging sanity checks.
891 KKASSERT(hammer_btree_cmp(cursor
->left_bound
, &elm
->base
) <= 0);
892 KKASSERT(hammer_btree_cmp(cursor
->right_bound
, &elm
->base
) > 0);
894 KKASSERT(hammer_btree_cmp(&node
->elms
[i
-1].leaf
.base
, &elm
->base
) < 0);
896 if (i
!= node
->count
- 1)
897 KKASSERT(hammer_btree_cmp(&node
->elms
[i
+1].leaf
.base
, &elm
->base
) > 0);
903 * Delete a record from the B-Tree at the current cursor position.
904 * The cursor is positioned such that the current element is the one
907 * On return the cursor will be positioned after the deleted element and
908 * MAY point to an internal node. It will be suitable for the continuation
909 * of an iteration but not for an insertion or deletion.
911 * Deletions will attempt to partially rebalance the B-Tree in an upward
912 * direction, but will terminate rather then deadlock. Empty internal nodes
913 * are never allowed by a deletion which deadlocks may end up giving us an
914 * empty leaf. The pruner will clean up and rebalance the tree.
916 * This function can return EDEADLK, requiring the caller to retry the
917 * operation after clearing the deadlock.
920 hammer_btree_delete(hammer_cursor_t cursor
)
922 hammer_node_ondisk_t ondisk
;
924 hammer_node_t parent
;
928 KKASSERT (cursor
->trans
->sync_lock_refs
> 0);
929 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
931 ++hammer_stats_btree_deletes
;
934 * Delete the element from the leaf node.
936 * Remember that leaf nodes do not have boundaries.
939 ondisk
= node
->ondisk
;
942 KKASSERT(ondisk
->type
== HAMMER_BTREE_TYPE_LEAF
);
943 KKASSERT(i
>= 0 && i
< ondisk
->count
);
944 hammer_modify_node_all(cursor
->trans
, node
);
945 if (i
+ 1 != ondisk
->count
) {
946 bcopy(&ondisk
->elms
[i
+1], &ondisk
->elms
[i
],
947 (ondisk
->count
- i
- 1) * sizeof(ondisk
->elms
[0]));
950 hammer_modify_node_done(node
);
951 hammer_cursor_deleted_element(node
, i
);
954 * Validate local parent
956 if (ondisk
->parent
) {
957 parent
= cursor
->parent
;
959 KKASSERT(parent
!= NULL
);
960 KKASSERT(parent
->node_offset
== ondisk
->parent
);
964 * If the leaf becomes empty it must be detached from the parent,
965 * potentially recursing through to the filesystem root.
967 * This may reposition the cursor at one of the parent's of the
970 * Ignore deadlock errors, that simply means that btree_remove
971 * was unable to recurse and had to leave us with an empty leaf.
973 KKASSERT(cursor
->index
<= ondisk
->count
);
974 if (ondisk
->count
== 0) {
975 error
= btree_remove(cursor
);
976 if (error
== EDEADLK
)
981 KKASSERT(cursor
->parent
== NULL
||
982 cursor
->parent_index
< cursor
->parent
->ondisk
->count
);
987 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
989 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
991 * The search can begin ANYWHERE in the B-Tree. As a first step the search
992 * iterates up the tree as necessary to properly position itself prior to
993 * actually doing the sarch.
995 * INSERTIONS: The search will split full nodes and leaves on its way down
996 * and guarentee that the leaf it ends up on is not full. If we run out
997 * of space the search continues to the leaf (to position the cursor for
998 * the spike), but ENOSPC is returned.
1000 * The search is only guarenteed to end up on a leaf if an error code of 0
1001 * is returned, or if inserting and an error code of ENOENT is returned.
1002 * Otherwise it can stop at an internal node. On success a search returns
1005 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
1006 * filesystem, and it is not simple code. Please note the following facts:
1008 * - Internal node recursions have a boundary on the left AND right. The
1009 * right boundary is non-inclusive. The create_tid is a generic part
1010 * of the key for internal nodes.
1012 * - Leaf nodes contain terminal elements only now.
1014 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
1015 * historical search. ASOF and INSERT are mutually exclusive. When
1016 * doing an as-of lookup btree_search() checks for a right-edge boundary
1017 * case. If while recursing down the left-edge differs from the key
1018 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
1019 * with cursor->create_check. This is used by btree_lookup() to iterate.
1020 * The iteration backwards because as-of searches can wind up going
1021 * down the wrong branch of the B-Tree.
1025 btree_search(hammer_cursor_t cursor
, int flags
)
1027 hammer_node_ondisk_t node
;
1028 hammer_btree_elm_t elm
;
1035 flags
|= cursor
->flags
;
1036 ++hammer_stats_btree_searches
;
1038 if (hammer_debug_btree
) {
1039 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx lo=%02x (td = %p)\n",
1040 (long long)cursor
->node
->node_offset
,
1042 (long long)cursor
->key_beg
.obj_id
,
1043 cursor
->key_beg
.rec_type
,
1044 (long long)cursor
->key_beg
.key
,
1045 (long long)cursor
->key_beg
.create_tid
,
1046 cursor
->key_beg
.localization
,
1050 kprintf("SEARCHP %016llx[%d] (%016llx/%016llx %016llx/%016llx) (%p/%p %p/%p)\n",
1051 (long long)cursor
->parent
->node_offset
,
1052 cursor
->parent_index
,
1053 (long long)cursor
->left_bound
->obj_id
,
1054 (long long)cursor
->parent
->ondisk
->elms
[cursor
->parent_index
].internal
.base
.obj_id
,
1055 (long long)cursor
->right_bound
->obj_id
,
1056 (long long)cursor
->parent
->ondisk
->elms
[cursor
->parent_index
+1].internal
.base
.obj_id
,
1058 &cursor
->parent
->ondisk
->elms
[cursor
->parent_index
],
1059 cursor
->right_bound
,
1060 &cursor
->parent
->ondisk
->elms
[cursor
->parent_index
+1]
1065 * Move our cursor up the tree until we find a node whos range covers
1066 * the key we are trying to locate.
1068 * The left bound is inclusive, the right bound is non-inclusive.
1069 * It is ok to cursor up too far.
1072 r
= hammer_btree_cmp(&cursor
->key_beg
, cursor
->left_bound
);
1073 s
= hammer_btree_cmp(&cursor
->key_beg
, cursor
->right_bound
);
1074 if (r
>= 0 && s
< 0)
1076 KKASSERT(cursor
->parent
);
1077 ++hammer_stats_btree_iterations
;
1078 error
= hammer_cursor_up(cursor
);
1084 * The delete-checks below are based on node, not parent. Set the
1085 * initial delete-check based on the parent.
1088 KKASSERT(cursor
->left_bound
->create_tid
!= 1);
1089 cursor
->create_check
= cursor
->left_bound
->create_tid
- 1;
1090 cursor
->flags
|= HAMMER_CURSOR_CREATE_CHECK
;
1094 * We better have ended up with a node somewhere.
1096 KKASSERT(cursor
->node
!= NULL
);
1099 * If we are inserting we can't start at a full node if the parent
1100 * is also full (because there is no way to split the node),
1101 * continue running up the tree until the requirement is satisfied
1102 * or we hit the root of the filesystem.
1104 * (If inserting we aren't doing an as-of search so we don't have
1105 * to worry about create_check).
1107 while ((flags
& HAMMER_CURSOR_INSERT
) && enospc
== 0) {
1108 if (cursor
->node
->ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
1109 if (btree_node_is_full(cursor
->node
->ondisk
) == 0)
1112 if (btree_node_is_full(cursor
->node
->ondisk
) ==0)
1115 if (cursor
->node
->ondisk
->parent
== 0 ||
1116 cursor
->parent
->ondisk
->count
!= HAMMER_BTREE_INT_ELMS
) {
1119 ++hammer_stats_btree_iterations
;
1120 error
= hammer_cursor_up(cursor
);
1121 /* node may have become stale */
1127 * Push down through internal nodes to locate the requested key.
1129 node
= cursor
->node
->ondisk
;
1130 while (node
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
1132 * Scan the node to find the subtree index to push down into.
1133 * We go one-past, then back-up.
1135 * We must proactively remove deleted elements which may
1136 * have been left over from a deadlocked btree_remove().
1138 * The left and right boundaries are included in the loop
1139 * in order to detect edge cases.
1141 * If the separator only differs by create_tid (r == 1)
1142 * and we are doing an as-of search, we may end up going
1143 * down a branch to the left of the one containing the
1144 * desired key. This requires numerous special cases.
1146 ++hammer_stats_btree_iterations
;
1147 if (hammer_debug_btree
) {
1148 kprintf("SEARCH-I %016llx count=%d\n",
1149 (long long)cursor
->node
->node_offset
,
1154 * Try to shortcut the search before dropping into the
1155 * linear loop. Locate the first node where r <= 1.
1157 i
= hammer_btree_search_node(&cursor
->key_beg
, node
);
1158 while (i
<= node
->count
) {
1159 ++hammer_stats_btree_elements
;
1160 elm
= &node
->elms
[i
];
1161 r
= hammer_btree_cmp(&cursor
->key_beg
, &elm
->base
);
1162 if (hammer_debug_btree
> 2) {
1163 kprintf(" IELM %p %d r=%d\n",
1164 &node
->elms
[i
], i
, r
);
1169 KKASSERT(elm
->base
.create_tid
!= 1);
1170 cursor
->create_check
= elm
->base
.create_tid
- 1;
1171 cursor
->flags
|= HAMMER_CURSOR_CREATE_CHECK
;
1175 if (hammer_debug_btree
) {
1176 kprintf("SEARCH-I preI=%d/%d r=%d\n",
1181 * These cases occur when the parent's idea of the boundary
1182 * is wider then the child's idea of the boundary, and
1183 * require special handling. If not inserting we can
1184 * terminate the search early for these cases but the
1185 * child's boundaries cannot be unconditionally modified.
1189 * If i == 0 the search terminated to the LEFT of the
1190 * left_boundary but to the RIGHT of the parent's left
1195 elm
= &node
->elms
[0];
1198 * If we aren't inserting we can stop here.
1200 if ((flags
& (HAMMER_CURSOR_INSERT
|
1201 HAMMER_CURSOR_PRUNING
)) == 0) {
1207 * Correct a left-hand boundary mismatch.
1209 * We can only do this if we can upgrade the lock,
1210 * and synchronized as a background cursor (i.e.
1211 * inserting or pruning).
1213 * WARNING: We can only do this if inserting, i.e.
1214 * we are running on the backend.
1216 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1218 KKASSERT(cursor
->flags
& HAMMER_CURSOR_BACKEND
);
1219 hammer_modify_node_field(cursor
->trans
, cursor
->node
,
1221 save
= node
->elms
[0].base
.btype
;
1222 node
->elms
[0].base
= *cursor
->left_bound
;
1223 node
->elms
[0].base
.btype
= save
;
1224 hammer_modify_node_done(cursor
->node
);
1225 } else if (i
== node
->count
+ 1) {
1227 * If i == node->count + 1 the search terminated to
1228 * the RIGHT of the right boundary but to the LEFT
1229 * of the parent's right boundary. If we aren't
1230 * inserting we can stop here.
1232 * Note that the last element in this case is
1233 * elms[i-2] prior to adjustments to 'i'.
1236 if ((flags
& (HAMMER_CURSOR_INSERT
|
1237 HAMMER_CURSOR_PRUNING
)) == 0) {
1243 * Correct a right-hand boundary mismatch.
1244 * (actual push-down record is i-2 prior to
1245 * adjustments to i).
1247 * We can only do this if we can upgrade the lock,
1248 * and synchronized as a background cursor (i.e.
1249 * inserting or pruning).
1251 * WARNING: We can only do this if inserting, i.e.
1252 * we are running on the backend.
1254 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1256 elm
= &node
->elms
[i
];
1257 KKASSERT(cursor
->flags
& HAMMER_CURSOR_BACKEND
);
1258 hammer_modify_node(cursor
->trans
, cursor
->node
,
1259 &elm
->base
, sizeof(elm
->base
));
1260 elm
->base
= *cursor
->right_bound
;
1261 hammer_modify_node_done(cursor
->node
);
1265 * The push-down index is now i - 1. If we had
1266 * terminated on the right boundary this will point
1267 * us at the last element.
1272 elm
= &node
->elms
[i
];
1274 if (hammer_debug_btree
) {
1275 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1276 "key=%016llx cre=%016llx lo=%02x\n",
1277 (long long)cursor
->node
->node_offset
,
1279 (long long)elm
->internal
.base
.obj_id
,
1280 elm
->internal
.base
.rec_type
,
1281 (long long)elm
->internal
.base
.key
,
1282 (long long)elm
->internal
.base
.create_tid
,
1283 elm
->internal
.base
.localization
1288 * We better have a valid subtree offset.
1290 KKASSERT(elm
->internal
.subtree_offset
!= 0);
1293 * Handle insertion and deletion requirements.
1295 * If inserting split full nodes. The split code will
1296 * adjust cursor->node and cursor->index if the current
1297 * index winds up in the new node.
1299 * If inserting and a left or right edge case was detected,
1300 * we cannot correct the left or right boundary and must
1301 * prepend and append an empty leaf node in order to make
1302 * the boundary correction.
1304 * If we run out of space we set enospc and continue on
1305 * to a leaf to provide the spike code with a good point
1308 if ((flags
& HAMMER_CURSOR_INSERT
) && enospc
== 0) {
1309 if (btree_node_is_full(node
)) {
1310 error
= btree_split_internal(cursor
);
1312 if (error
!= ENOSPC
)
1317 * reload stale pointers
1320 node
= cursor
->node
->ondisk
;
1325 * Push down (push into new node, existing node becomes
1326 * the parent) and continue the search.
1328 error
= hammer_cursor_down(cursor
);
1329 /* node may have become stale */
1332 node
= cursor
->node
->ondisk
;
1336 * We are at a leaf, do a linear search of the key array.
1338 * On success the index is set to the matching element and 0
1341 * On failure the index is set to the insertion point and ENOENT
1344 * Boundaries are not stored in leaf nodes, so the index can wind
1345 * up to the left of element 0 (index == 0) or past the end of
1346 * the array (index == node->count). It is also possible that the
1347 * leaf might be empty.
1349 ++hammer_stats_btree_iterations
;
1350 KKASSERT (node
->type
== HAMMER_BTREE_TYPE_LEAF
);
1351 KKASSERT(node
->count
<= HAMMER_BTREE_LEAF_ELMS
);
1352 if (hammer_debug_btree
) {
1353 kprintf("SEARCH-L %016llx count=%d\n",
1354 (long long)cursor
->node
->node_offset
,
1359 * Try to shortcut the search before dropping into the
1360 * linear loop. Locate the first node where r <= 1.
1362 i
= hammer_btree_search_node(&cursor
->key_beg
, node
);
1363 while (i
< node
->count
) {
1364 ++hammer_stats_btree_elements
;
1365 elm
= &node
->elms
[i
];
1367 r
= hammer_btree_cmp(&cursor
->key_beg
, &elm
->leaf
.base
);
1369 if (hammer_debug_btree
> 1)
1370 kprintf(" ELM %p %d r=%d\n", &node
->elms
[i
], i
, r
);
1373 * We are at a record element. Stop if we've flipped past
1374 * key_beg, not counting the create_tid test. Allow the
1375 * r == 1 case (key_beg > element but differs only by its
1376 * create_tid) to fall through to the AS-OF check.
1378 KKASSERT (elm
->leaf
.base
.btype
== HAMMER_BTREE_TYPE_RECORD
);
1388 * Check our as-of timestamp against the element.
1390 if (flags
& HAMMER_CURSOR_ASOF
) {
1391 if (hammer_btree_chkts(cursor
->asof
,
1392 &node
->elms
[i
].base
) != 0) {
1398 if (r
> 0) { /* can only be +1 */
1406 if (hammer_debug_btree
) {
1407 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1408 (long long)cursor
->node
->node_offset
, i
);
1414 * The search of the leaf node failed. i is the insertion point.
1417 if (hammer_debug_btree
) {
1418 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1419 (long long)cursor
->node
->node_offset
, i
);
1423 * No exact match was found, i is now at the insertion point.
1425 * If inserting split a full leaf before returning. This
1426 * may have the side effect of adjusting cursor->node and
1430 if ((flags
& HAMMER_CURSOR_INSERT
) && enospc
== 0 &&
1431 btree_node_is_full(node
)) {
1432 error
= btree_split_leaf(cursor
);
1434 if (error
!= ENOSPC
)
1439 * reload stale pointers
1443 node = &cursor->node->internal;
1448 * We reached a leaf but did not find the key we were looking for.
1449 * If this is an insert we will be properly positioned for an insert
1450 * (ENOENT) or spike (ENOSPC) operation.
1452 error
= enospc
? ENOSPC
: ENOENT
;
1458 * Heuristical search for the first element whos comparison is <= 1. May
1459 * return an index whos compare result is > 1 but may only return an index
1460 * whos compare result is <= 1 if it is the first element with that result.
1463 hammer_btree_search_node(hammer_base_elm_t elm
, hammer_node_ondisk_t node
)
1471 * Don't bother if the node does not have very many elements
1476 i
= b
+ (s
- b
) / 2;
1477 ++hammer_stats_btree_elements
;
1478 r
= hammer_btree_cmp(elm
, &node
->elms
[i
].leaf
.base
);
1489 /************************************************************************
1490 * SPLITTING AND MERGING *
1491 ************************************************************************
1493 * These routines do all the dirty work required to split and merge nodes.
1497 * Split an internal node into two nodes and move the separator at the split
1498 * point to the parent.
1500 * (cursor->node, cursor->index) indicates the element the caller intends
1501 * to push into. We will adjust node and index if that element winds
1502 * up in the split node.
1504 * If we are at the root of the filesystem a new root must be created with
1505 * two elements, one pointing to the original root and one pointing to the
1506 * newly allocated split node.
1510 btree_split_internal(hammer_cursor_t cursor
)
1512 hammer_node_ondisk_t ondisk
;
1514 hammer_node_t parent
;
1515 hammer_node_t new_node
;
1516 hammer_btree_elm_t elm
;
1517 hammer_btree_elm_t parent_elm
;
1518 struct hammer_node_lock lockroot
;
1519 hammer_mount_t hmp
= cursor
->trans
->hmp
;
1526 const int esize
= sizeof(*elm
);
1528 hammer_node_lock_init(&lockroot
, cursor
->node
);
1529 error
= hammer_btree_lock_children(cursor
, 1, &lockroot
);
1532 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1534 ++hammer_stats_btree_splits
;
1537 * Calculate the split point. If the insertion point is at the
1538 * end of the leaf we adjust the split point significantly to the
1539 * right to try to optimize node fill and flag it. If we hit
1540 * that same leaf again our heuristic failed and we don't try
1541 * to optimize node fill (it could lead to a degenerate case).
1543 node
= cursor
->node
;
1544 ondisk
= node
->ondisk
;
1545 KKASSERT(ondisk
->count
> 4);
1546 if (cursor
->index
== ondisk
->count
&&
1547 (node
->flags
& HAMMER_NODE_NONLINEAR
) == 0) {
1548 split
= (ondisk
->count
+ 1) * 3 / 4;
1549 node
->flags
|= HAMMER_NODE_NONLINEAR
;
1552 * We are splitting but elms[split] will be promoted to
1553 * the parent, leaving the right hand node with one less
1554 * element. If the insertion point will be on the
1555 * left-hand side adjust the split point to give the
1556 * right hand side one additional node.
1558 split
= (ondisk
->count
+ 1) / 2;
1559 if (cursor
->index
<= split
)
1564 * If we are at the root of the filesystem, create a new root node
1565 * with 1 element and split normally. Avoid making major
1566 * modifications until we know the whole operation will work.
1568 if (ondisk
->parent
== 0) {
1569 parent
= hammer_alloc_btree(cursor
->trans
, node
->node_offset
,
1573 hammer_lock_ex(&parent
->lock
);
1574 hammer_modify_node_noundo(cursor
->trans
, parent
);
1575 ondisk
= parent
->ondisk
;
1578 ondisk
->mirror_tid
= node
->ondisk
->mirror_tid
;
1579 ondisk
->type
= HAMMER_BTREE_TYPE_INTERNAL
;
1580 ondisk
->elms
[0].base
= hmp
->root_btree_beg
;
1581 ondisk
->elms
[0].base
.btype
= node
->ondisk
->type
;
1582 ondisk
->elms
[0].internal
.subtree_offset
= node
->node_offset
;
1583 ondisk
->elms
[1].base
= hmp
->root_btree_end
;
1584 hammer_modify_node_done(parent
);
1585 /* ondisk->elms[1].base.btype - not used */
1587 parent_index
= 0; /* index of current node in parent */
1590 parent
= cursor
->parent
;
1591 parent_index
= cursor
->parent_index
;
1595 * Calculate a hint for the allocation of the new B-Tree node.
1596 * The most likely expansion is coming from the insertion point
1597 * at cursor->index, so try to localize the allocation of our
1598 * new node to accomodate that sub-tree.
1600 * Use the right-most sub-tree when expandinging on the right edge.
1601 * This is a very common case when copying a directory tree.
1603 if (cursor
->index
== ondisk
->count
)
1604 hint
= ondisk
->elms
[cursor
->index
- 1].internal
.subtree_offset
;
1606 hint
= ondisk
->elms
[cursor
->index
].internal
.subtree_offset
;
1609 * Split node into new_node at the split point.
1611 * B O O O P N N B <-- P = node->elms[split] (index 4)
1612 * 0 1 2 3 4 5 6 <-- subtree indices
1617 * B O O O B B N N B <--- inner boundary points are 'P'
1620 new_node
= hammer_alloc_btree(cursor
->trans
, hint
, &error
);
1621 if (new_node
== NULL
) {
1623 hammer_unlock(&parent
->lock
);
1624 hammer_delete_node(cursor
->trans
, parent
);
1625 hammer_rel_node(parent
);
1629 hammer_lock_ex(&new_node
->lock
);
1632 * Create the new node. P becomes the left-hand boundary in the
1633 * new node. Copy the right-hand boundary as well.
1635 * elm is the new separator.
1637 hammer_modify_node_noundo(cursor
->trans
, new_node
);
1638 hammer_modify_node_all(cursor
->trans
, node
);
1639 ondisk
= node
->ondisk
;
1640 elm
= &ondisk
->elms
[split
];
1641 bcopy(elm
, &new_node
->ondisk
->elms
[0],
1642 (ondisk
->count
- split
+ 1) * esize
);
1643 new_node
->ondisk
->count
= ondisk
->count
- split
;
1644 new_node
->ondisk
->parent
= parent
->node_offset
;
1645 new_node
->ondisk
->type
= HAMMER_BTREE_TYPE_INTERNAL
;
1646 new_node
->ondisk
->mirror_tid
= ondisk
->mirror_tid
;
1647 KKASSERT(ondisk
->type
== new_node
->ondisk
->type
);
1648 hammer_cursor_split_node(node
, new_node
, split
);
1651 * Cleanup the original node. Elm (P) becomes the new boundary,
1652 * its subtree_offset was moved to the new node. If we had created
1653 * a new root its parent pointer may have changed.
1655 elm
->internal
.subtree_offset
= 0;
1656 ondisk
->count
= split
;
1659 * Insert the separator into the parent, fixup the parent's
1660 * reference to the original node, and reference the new node.
1661 * The separator is P.
1663 * Remember that base.count does not include the right-hand boundary.
1665 hammer_modify_node_all(cursor
->trans
, parent
);
1666 ondisk
= parent
->ondisk
;
1667 KKASSERT(ondisk
->count
!= HAMMER_BTREE_INT_ELMS
);
1668 parent_elm
= &ondisk
->elms
[parent_index
+1];
1669 bcopy(parent_elm
, parent_elm
+ 1,
1670 (ondisk
->count
- parent_index
) * esize
);
1671 parent_elm
->internal
.base
= elm
->base
; /* separator P */
1672 parent_elm
->internal
.base
.btype
= new_node
->ondisk
->type
;
1673 parent_elm
->internal
.subtree_offset
= new_node
->node_offset
;
1674 parent_elm
->internal
.mirror_tid
= new_node
->ondisk
->mirror_tid
;
1676 hammer_modify_node_done(parent
);
1677 hammer_cursor_inserted_element(parent
, parent_index
+ 1);
1680 * The children of new_node need their parent pointer set to new_node.
1681 * The children have already been locked by
1682 * hammer_btree_lock_children().
1684 for (i
= 0; i
< new_node
->ondisk
->count
; ++i
) {
1685 elm
= &new_node
->ondisk
->elms
[i
];
1686 error
= btree_set_parent(cursor
->trans
, new_node
, elm
);
1688 panic("btree_split_internal: btree-fixup problem");
1691 hammer_modify_node_done(new_node
);
1694 * The filesystem's root B-Tree pointer may have to be updated.
1697 hammer_volume_t volume
;
1699 volume
= hammer_get_root_volume(hmp
, &error
);
1700 KKASSERT(error
== 0);
1702 hammer_modify_volume_field(cursor
->trans
, volume
,
1704 volume
->ondisk
->vol0_btree_root
= parent
->node_offset
;
1705 hammer_modify_volume_done(volume
);
1706 node
->ondisk
->parent
= parent
->node_offset
;
1707 if (cursor
->parent
) {
1708 hammer_unlock(&cursor
->parent
->lock
);
1709 hammer_rel_node(cursor
->parent
);
1711 cursor
->parent
= parent
; /* lock'd and ref'd */
1712 hammer_rel_volume(volume
, 0);
1714 hammer_modify_node_done(node
);
1717 * Ok, now adjust the cursor depending on which element the original
1718 * index was pointing at. If we are >= the split point the push node
1719 * is now in the new node.
1721 * NOTE: If we are at the split point itself we cannot stay with the
1722 * original node because the push index will point at the right-hand
1723 * boundary, which is illegal.
1725 * NOTE: The cursor's parent or parent_index must be adjusted for
1726 * the case where a new parent (new root) was created, and the case
1727 * where the cursor is now pointing at the split node.
1729 if (cursor
->index
>= split
) {
1730 cursor
->parent_index
= parent_index
+ 1;
1731 cursor
->index
-= split
;
1732 hammer_unlock(&cursor
->node
->lock
);
1733 hammer_rel_node(cursor
->node
);
1734 cursor
->node
= new_node
; /* locked and ref'd */
1736 cursor
->parent_index
= parent_index
;
1737 hammer_unlock(&new_node
->lock
);
1738 hammer_rel_node(new_node
);
1742 * Fixup left and right bounds
1744 parent_elm
= &parent
->ondisk
->elms
[cursor
->parent_index
];
1745 cursor
->left_bound
= &parent_elm
[0].internal
.base
;
1746 cursor
->right_bound
= &parent_elm
[1].internal
.base
;
1747 KKASSERT(hammer_btree_cmp(cursor
->left_bound
,
1748 &cursor
->node
->ondisk
->elms
[0].internal
.base
) <= 0);
1749 KKASSERT(hammer_btree_cmp(cursor
->right_bound
,
1750 &cursor
->node
->ondisk
->elms
[cursor
->node
->ondisk
->count
].internal
.base
) >= 0);
1753 hammer_btree_unlock_children(cursor
, &lockroot
);
1754 hammer_cursor_downgrade(cursor
);
1759 * Same as the above, but splits a full leaf node.
1765 btree_split_leaf(hammer_cursor_t cursor
)
1767 hammer_node_ondisk_t ondisk
;
1768 hammer_node_t parent
;
1771 hammer_node_t new_leaf
;
1772 hammer_btree_elm_t elm
;
1773 hammer_btree_elm_t parent_elm
;
1774 hammer_base_elm_t mid_boundary
;
1780 const size_t esize
= sizeof(*elm
);
1782 if ((error
= hammer_cursor_upgrade(cursor
)) != 0)
1784 ++hammer_stats_btree_splits
;
1786 KKASSERT(hammer_btree_cmp(cursor
->left_bound
,
1787 &cursor
->node
->ondisk
->elms
[0].leaf
.base
) <= 0);
1788 KKASSERT(hammer_btree_cmp(cursor
->right_bound
,
1789 &cursor
->node
->ondisk
->elms
[cursor
->node
->ondisk
->count
-1].leaf
.base
) > 0);
1792 * Calculate the split point. If the insertion point is at the
1793 * end of the leaf we adjust the split point significantly to the
1794 * right to try to optimize node fill and flag it. If we hit
1795 * that same leaf again our heuristic failed and we don't try
1796 * to optimize node fill (it could lead to a degenerate case).
1798 * Spikes are made up of two leaf elements which cannot be
1801 leaf
= cursor
->node
;
1802 ondisk
= leaf
->ondisk
;
1803 KKASSERT(ondisk
->count
> 4);
1804 if (cursor
->index
== ondisk
->count
&&
1805 (leaf
->flags
& HAMMER_NODE_NONLINEAR
) == 0) {
1806 split
= (ondisk
->count
+ 1) * 3 / 4;
1807 leaf
->flags
|= HAMMER_NODE_NONLINEAR
;
1809 split
= (ondisk
->count
+ 1) / 2;
1814 * If the insertion point is at the split point shift the
1815 * split point left so we don't have to worry about
1817 if (cursor
->index
== split
)
1820 KKASSERT(split
> 0 && split
< ondisk
->count
);
1825 elm
= &ondisk
->elms
[split
];
1827 KKASSERT(hammer_btree_cmp(cursor
->left_bound
, &elm
[-1].leaf
.base
) <= 0);
1828 KKASSERT(hammer_btree_cmp(cursor
->left_bound
, &elm
->leaf
.base
) <= 0);
1829 KKASSERT(hammer_btree_cmp(cursor
->right_bound
, &elm
->leaf
.base
) > 0);
1830 KKASSERT(hammer_btree_cmp(cursor
->right_bound
, &elm
[1].leaf
.base
) > 0);
1833 * If we are at the root of the tree, create a new root node with
1834 * 1 element and split normally. Avoid making major modifications
1835 * until we know the whole operation will work.
1837 if (ondisk
->parent
== 0) {
1838 parent
= hammer_alloc_btree(cursor
->trans
, leaf
->node_offset
,
1842 hammer_lock_ex(&parent
->lock
);
1843 hammer_modify_node_noundo(cursor
->trans
, parent
);
1844 ondisk
= parent
->ondisk
;
1847 ondisk
->mirror_tid
= leaf
->ondisk
->mirror_tid
;
1848 ondisk
->type
= HAMMER_BTREE_TYPE_INTERNAL
;
1849 ondisk
->elms
[0].base
= hmp
->root_btree_beg
;
1850 ondisk
->elms
[0].base
.btype
= leaf
->ondisk
->type
;
1851 ondisk
->elms
[0].internal
.subtree_offset
= leaf
->node_offset
;
1852 ondisk
->elms
[1].base
= hmp
->root_btree_end
;
1853 /* ondisk->elms[1].base.btype = not used */
1854 hammer_modify_node_done(parent
);
1856 parent_index
= 0; /* insertion point in parent */
1859 parent
= cursor
->parent
;
1860 parent_index
= cursor
->parent_index
;
1864 * Calculate a hint for the allocation of the new B-Tree leaf node.
1865 * For now just try to localize it within the same bigblock as
1868 * If the insertion point is at the end of the leaf we recognize a
1869 * likely append sequence of some sort (data, meta-data, inodes,
1870 * whatever). Set the hint to zero to allocate out of linear space
1871 * instead of trying to completely fill previously hinted space.
1873 * This also sets the stage for recursive splits to localize using
1876 ondisk
= leaf
->ondisk
;
1877 if (cursor
->index
== ondisk
->count
)
1880 hint
= leaf
->node_offset
;
1883 * Split leaf into new_leaf at the split point. Select a separator
1884 * value in-between the two leafs but with a bent towards the right
1885 * leaf since comparisons use an 'elm >= separator' inequality.
1894 new_leaf
= hammer_alloc_btree(cursor
->trans
, hint
, &error
);
1895 if (new_leaf
== NULL
) {
1897 hammer_unlock(&parent
->lock
);
1898 hammer_delete_node(cursor
->trans
, parent
);
1899 hammer_rel_node(parent
);
1903 hammer_lock_ex(&new_leaf
->lock
);
1906 * Create the new node and copy the leaf elements from the split
1907 * point on to the new node.
1909 hammer_modify_node_all(cursor
->trans
, leaf
);
1910 hammer_modify_node_noundo(cursor
->trans
, new_leaf
);
1911 ondisk
= leaf
->ondisk
;
1912 elm
= &ondisk
->elms
[split
];
1913 bcopy(elm
, &new_leaf
->ondisk
->elms
[0], (ondisk
->count
- split
) * esize
);
1914 new_leaf
->ondisk
->count
= ondisk
->count
- split
;
1915 new_leaf
->ondisk
->parent
= parent
->node_offset
;
1916 new_leaf
->ondisk
->type
= HAMMER_BTREE_TYPE_LEAF
;
1917 new_leaf
->ondisk
->mirror_tid
= ondisk
->mirror_tid
;
1918 KKASSERT(ondisk
->type
== new_leaf
->ondisk
->type
);
1919 hammer_modify_node_done(new_leaf
);
1920 hammer_cursor_split_node(leaf
, new_leaf
, split
);
1923 * Cleanup the original node. Because this is a leaf node and
1924 * leaf nodes do not have a right-hand boundary, there
1925 * aren't any special edge cases to clean up. We just fixup the
1928 ondisk
->count
= split
;
1931 * Insert the separator into the parent, fixup the parent's
1932 * reference to the original node, and reference the new node.
1933 * The separator is P.
1935 * Remember that base.count does not include the right-hand boundary.
1936 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1938 hammer_modify_node_all(cursor
->trans
, parent
);
1939 ondisk
= parent
->ondisk
;
1940 KKASSERT(split
!= 0);
1941 KKASSERT(ondisk
->count
!= HAMMER_BTREE_INT_ELMS
);
1942 parent_elm
= &ondisk
->elms
[parent_index
+1];
1943 bcopy(parent_elm
, parent_elm
+ 1,
1944 (ondisk
->count
- parent_index
) * esize
);
1946 hammer_make_separator(&elm
[-1].base
, &elm
[0].base
, &parent_elm
->base
);
1947 parent_elm
->internal
.base
.btype
= new_leaf
->ondisk
->type
;
1948 parent_elm
->internal
.subtree_offset
= new_leaf
->node_offset
;
1949 parent_elm
->internal
.mirror_tid
= new_leaf
->ondisk
->mirror_tid
;
1950 mid_boundary
= &parent_elm
->base
;
1952 hammer_modify_node_done(parent
);
1953 hammer_cursor_inserted_element(parent
, parent_index
+ 1);
1956 * The filesystem's root B-Tree pointer may have to be updated.
1959 hammer_volume_t volume
;
1961 volume
= hammer_get_root_volume(hmp
, &error
);
1962 KKASSERT(error
== 0);
1964 hammer_modify_volume_field(cursor
->trans
, volume
,
1966 volume
->ondisk
->vol0_btree_root
= parent
->node_offset
;
1967 hammer_modify_volume_done(volume
);
1968 leaf
->ondisk
->parent
= parent
->node_offset
;
1969 if (cursor
->parent
) {
1970 hammer_unlock(&cursor
->parent
->lock
);
1971 hammer_rel_node(cursor
->parent
);
1973 cursor
->parent
= parent
; /* lock'd and ref'd */
1974 hammer_rel_volume(volume
, 0);
1976 hammer_modify_node_done(leaf
);
1979 * Ok, now adjust the cursor depending on which element the original
1980 * index was pointing at. If we are >= the split point the push node
1981 * is now in the new node.
1983 * NOTE: If we are at the split point itself we need to select the
1984 * old or new node based on where key_beg's insertion point will be.
1985 * If we pick the wrong side the inserted element will wind up in
1986 * the wrong leaf node and outside that node's bounds.
1988 if (cursor
->index
> split
||
1989 (cursor
->index
== split
&&
1990 hammer_btree_cmp(&cursor
->key_beg
, mid_boundary
) >= 0)) {
1991 cursor
->parent_index
= parent_index
+ 1;
1992 cursor
->index
-= split
;
1993 hammer_unlock(&cursor
->node
->lock
);
1994 hammer_rel_node(cursor
->node
);
1995 cursor
->node
= new_leaf
;
1997 cursor
->parent_index
= parent_index
;
1998 hammer_unlock(&new_leaf
->lock
);
1999 hammer_rel_node(new_leaf
);
2003 * Fixup left and right bounds
2005 parent_elm
= &parent
->ondisk
->elms
[cursor
->parent_index
];
2006 cursor
->left_bound
= &parent_elm
[0].internal
.base
;
2007 cursor
->right_bound
= &parent_elm
[1].internal
.base
;
2010 * Assert that the bounds are correct.
2012 KKASSERT(hammer_btree_cmp(cursor
->left_bound
,
2013 &cursor
->node
->ondisk
->elms
[0].leaf
.base
) <= 0);
2014 KKASSERT(hammer_btree_cmp(cursor
->right_bound
,
2015 &cursor
->node
->ondisk
->elms
[cursor
->node
->ondisk
->count
-1].leaf
.base
) > 0);
2016 KKASSERT(hammer_btree_cmp(cursor
->left_bound
, &cursor
->key_beg
) <= 0);
2017 KKASSERT(hammer_btree_cmp(cursor
->right_bound
, &cursor
->key_beg
) > 0);
2020 hammer_cursor_downgrade(cursor
);
2027 * Recursively correct the right-hand boundary's create_tid to (tid) as
2028 * long as the rest of the key matches. We have to recurse upward in
2029 * the tree as well as down the left side of each parent's right node.
2031 * Return EDEADLK if we were only partially successful, forcing the caller
2032 * to try again. The original cursor is not modified. This routine can
2033 * also fail with EDEADLK if it is forced to throw away a portion of its
2036 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
2039 TAILQ_ENTRY(hammer_rhb
) entry
;
2044 TAILQ_HEAD(hammer_rhb_list
, hammer_rhb
);
2047 hammer_btree_correct_rhb(hammer_cursor_t cursor
, hammer_tid_t tid
)
2049 struct hammer_mount
*hmp
;
2050 struct hammer_rhb_list rhb_list
;
2051 hammer_base_elm_t elm
;
2052 hammer_node_t orig_node
;
2053 struct hammer_rhb
*rhb
;
2057 TAILQ_INIT(&rhb_list
);
2058 hmp
= cursor
->trans
->hmp
;
2061 * Save our position so we can restore it on return. This also
2062 * gives us a stable 'elm'.
2064 orig_node
= cursor
->node
;
2065 hammer_ref_node(orig_node
);
2066 hammer_lock_sh(&orig_node
->lock
);
2067 orig_index
= cursor
->index
;
2068 elm
= &orig_node
->ondisk
->elms
[orig_index
].base
;
2071 * Now build a list of parents going up, allocating a rhb
2072 * structure for each one.
2074 while (cursor
->parent
) {
2076 * Stop if we no longer have any right-bounds to fix up
2078 if (elm
->obj_id
!= cursor
->right_bound
->obj_id
||
2079 elm
->rec_type
!= cursor
->right_bound
->rec_type
||
2080 elm
->key
!= cursor
->right_bound
->key
) {
2085 * Stop if the right-hand bound's create_tid does not
2086 * need to be corrected.
2088 if (cursor
->right_bound
->create_tid
>= tid
)
2091 rhb
= kmalloc(sizeof(*rhb
), hmp
->m_misc
, M_WAITOK
|M_ZERO
);
2092 rhb
->node
= cursor
->parent
;
2093 rhb
->index
= cursor
->parent_index
;
2094 hammer_ref_node(rhb
->node
);
2095 hammer_lock_sh(&rhb
->node
->lock
);
2096 TAILQ_INSERT_HEAD(&rhb_list
, rhb
, entry
);
2098 hammer_cursor_up(cursor
);
2102 * now safely adjust the right hand bound for each rhb. This may
2103 * also require taking the right side of the tree and iterating down
2107 while (error
== 0 && (rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
2108 error
= hammer_cursor_seek(cursor
, rhb
->node
, rhb
->index
);
2111 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
2112 hammer_unlock(&rhb
->node
->lock
);
2113 hammer_rel_node(rhb
->node
);
2114 kfree(rhb
, hmp
->m_misc
);
2116 switch (cursor
->node
->ondisk
->type
) {
2117 case HAMMER_BTREE_TYPE_INTERNAL
:
2119 * Right-boundary for parent at internal node
2120 * is one element to the right of the element whos
2121 * right boundary needs adjusting. We must then
2122 * traverse down the left side correcting any left
2123 * bounds (which may now be too far to the left).
2126 error
= hammer_btree_correct_lhb(cursor
, tid
);
2129 panic("hammer_btree_correct_rhb(): Bad node type");
2138 while ((rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
2139 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
2140 hammer_unlock(&rhb
->node
->lock
);
2141 hammer_rel_node(rhb
->node
);
2142 kfree(rhb
, hmp
->m_misc
);
2144 error
= hammer_cursor_seek(cursor
, orig_node
, orig_index
);
2145 hammer_unlock(&orig_node
->lock
);
2146 hammer_rel_node(orig_node
);
2151 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
2152 * bound going downward starting at the current cursor position.
2154 * This function does not restore the cursor after use.
2157 hammer_btree_correct_lhb(hammer_cursor_t cursor
, hammer_tid_t tid
)
2159 struct hammer_rhb_list rhb_list
;
2160 hammer_base_elm_t elm
;
2161 hammer_base_elm_t cmp
;
2162 struct hammer_rhb
*rhb
;
2163 struct hammer_mount
*hmp
;
2166 TAILQ_INIT(&rhb_list
);
2167 hmp
= cursor
->trans
->hmp
;
2169 cmp
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
2172 * Record the node and traverse down the left-hand side for all
2173 * matching records needing a boundary correction.
2177 rhb
= kmalloc(sizeof(*rhb
), hmp
->m_misc
, M_WAITOK
|M_ZERO
);
2178 rhb
->node
= cursor
->node
;
2179 rhb
->index
= cursor
->index
;
2180 hammer_ref_node(rhb
->node
);
2181 hammer_lock_sh(&rhb
->node
->lock
);
2182 TAILQ_INSERT_HEAD(&rhb_list
, rhb
, entry
);
2184 if (cursor
->node
->ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
2186 * Nothing to traverse down if we are at the right
2187 * boundary of an internal node.
2189 if (cursor
->index
== cursor
->node
->ondisk
->count
)
2192 elm
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
2193 if (elm
->btype
== HAMMER_BTREE_TYPE_RECORD
)
2195 panic("Illegal leaf record type %02x", elm
->btype
);
2197 error
= hammer_cursor_down(cursor
);
2201 elm
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
2202 if (elm
->obj_id
!= cmp
->obj_id
||
2203 elm
->rec_type
!= cmp
->rec_type
||
2204 elm
->key
!= cmp
->key
) {
2207 if (elm
->create_tid
>= tid
)
2213 * Now we can safely adjust the left-hand boundary from the bottom-up.
2214 * The last element we remove from the list is the caller's right hand
2215 * boundary, which must also be adjusted.
2217 while (error
== 0 && (rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
2218 error
= hammer_cursor_seek(cursor
, rhb
->node
, rhb
->index
);
2221 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
2222 hammer_unlock(&rhb
->node
->lock
);
2223 hammer_rel_node(rhb
->node
);
2224 kfree(rhb
, hmp
->m_misc
);
2226 elm
= &cursor
->node
->ondisk
->elms
[cursor
->index
].base
;
2227 if (cursor
->node
->ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
2228 hammer_modify_node(cursor
->trans
, cursor
->node
,
2230 sizeof(elm
->create_tid
));
2231 elm
->create_tid
= tid
;
2232 hammer_modify_node_done(cursor
->node
);
2234 panic("hammer_btree_correct_lhb(): Bad element type");
2241 while ((rhb
= TAILQ_FIRST(&rhb_list
)) != NULL
) {
2242 TAILQ_REMOVE(&rhb_list
, rhb
, entry
);
2243 hammer_unlock(&rhb
->node
->lock
);
2244 hammer_rel_node(rhb
->node
);
2245 kfree(rhb
, hmp
->m_misc
);
2253 * Attempt to remove the locked, empty or want-to-be-empty B-Tree node at
2254 * (cursor->node). Returns 0 on success, EDEADLK if we could not complete
2255 * the operation due to a deadlock, or some other error.
2257 * This routine is initially called with an empty leaf and may be
2258 * recursively called with single-element internal nodes.
2260 * It should also be noted that when removing empty leaves we must be sure
2261 * to test and update mirror_tid because another thread may have deadlocked
2262 * against us (or someone) trying to propagate it up and cannot retry once
2263 * the node has been deleted.
2265 * On return the cursor may end up pointing to an internal node, suitable
2266 * for further iteration but not for an immediate insertion or deletion.
2269 btree_remove(hammer_cursor_t cursor
)
2271 hammer_node_ondisk_t ondisk
;
2272 hammer_btree_elm_t elm
;
2274 hammer_node_t parent
;
2275 const int esize
= sizeof(*elm
);
2278 node
= cursor
->node
;
2281 * When deleting the root of the filesystem convert it to
2282 * an empty leaf node. Internal nodes cannot be empty.
2284 ondisk
= node
->ondisk
;
2285 if (ondisk
->parent
== 0) {
2286 KKASSERT(cursor
->parent
== NULL
);
2287 hammer_modify_node_all(cursor
->trans
, node
);
2288 KKASSERT(ondisk
== node
->ondisk
);
2289 ondisk
->type
= HAMMER_BTREE_TYPE_LEAF
;
2291 hammer_modify_node_done(node
);
2296 parent
= cursor
->parent
;
2299 * Attempt to remove the parent's reference to the child. If the
2300 * parent would become empty we have to recurse. If we fail we
2301 * leave the parent pointing to an empty leaf node.
2303 * We have to recurse successfully before we can delete the internal
2304 * node as it is illegal to have empty internal nodes. Even though
2305 * the operation may be aborted we must still fixup any unlocked
2306 * cursors as if we had deleted the element prior to recursing
2307 * (by calling hammer_cursor_deleted_element()) so those cursors
2308 * are properly forced up the chain by the recursion.
2310 if (parent
->ondisk
->count
== 1) {
2312 * This special cursor_up_locked() call leaves the original
2313 * node exclusively locked and referenced, leaves the
2314 * original parent locked (as the new node), and locks the
2315 * new parent. It can return EDEADLK.
2317 * We cannot call hammer_cursor_removed_node() until we are
2318 * actually able to remove the node. If we did then tracked
2319 * cursors in the middle of iterations could be repointed
2320 * to a parent node. If this occurs they could end up
2321 * scanning newly inserted records into the node (that could
2322 * not be deleted) when they push down again.
2324 * Due to the way the recursion works the final parent is left
2325 * in cursor->parent after the recursion returns. Each
2326 * layer on the way back up is thus able to call
2327 * hammer_cursor_removed_node() and 'jump' the node up to
2328 * the (same) final parent.
2330 * NOTE! The local variable 'parent' is invalid after we
2331 * call hammer_cursor_up_locked().
2333 error
= hammer_cursor_up_locked(cursor
);
2337 hammer_cursor_deleted_element(cursor
->node
, 0);
2338 error
= btree_remove(cursor
);
2340 KKASSERT(node
!= cursor
->node
);
2341 hammer_cursor_removed_node(
2344 hammer_modify_node_all(cursor
->trans
, node
);
2345 ondisk
= node
->ondisk
;
2346 ondisk
->type
= HAMMER_BTREE_TYPE_DELETED
;
2348 hammer_modify_node_done(node
);
2349 hammer_flush_node(node
, 0);
2350 hammer_delete_node(cursor
->trans
, node
);
2353 * Defer parent removal because we could not
2354 * get the lock, just let the leaf remain
2359 hammer_unlock(&node
->lock
);
2360 hammer_rel_node(node
);
2363 * Defer parent removal because we could not
2364 * get the lock, just let the leaf remain
2370 KKASSERT(parent
->ondisk
->count
> 1);
2372 hammer_modify_node_all(cursor
->trans
, parent
);
2373 ondisk
= parent
->ondisk
;
2374 KKASSERT(ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
);
2376 elm
= &ondisk
->elms
[cursor
->parent_index
];
2377 KKASSERT(elm
->internal
.subtree_offset
== node
->node_offset
);
2378 KKASSERT(ondisk
->count
> 0);
2381 * We must retain the highest mirror_tid. The deleted
2382 * range is now encompassed by the element to the left.
2383 * If we are already at the left edge the new left edge
2384 * inherits mirror_tid.
2386 * Note that bounds of the parent to our parent may create
2387 * a gap to the left of our left-most node or to the right
2388 * of our right-most node. The gap is silently included
2389 * in the mirror_tid's area of effect from the point of view
2392 if (cursor
->parent_index
) {
2393 if (elm
[-1].internal
.mirror_tid
<
2394 elm
[0].internal
.mirror_tid
) {
2395 elm
[-1].internal
.mirror_tid
=
2396 elm
[0].internal
.mirror_tid
;
2399 if (elm
[1].internal
.mirror_tid
<
2400 elm
[0].internal
.mirror_tid
) {
2401 elm
[1].internal
.mirror_tid
=
2402 elm
[0].internal
.mirror_tid
;
2407 * Delete the subtree reference in the parent. Include
2408 * boundary element at end.
2410 bcopy(&elm
[1], &elm
[0],
2411 (ondisk
->count
- cursor
->parent_index
) * esize
);
2413 hammer_modify_node_done(parent
);
2414 hammer_cursor_removed_node(node
, parent
, cursor
->parent_index
);
2415 hammer_cursor_deleted_element(parent
, cursor
->parent_index
);
2416 hammer_flush_node(node
, 0);
2417 hammer_delete_node(cursor
->trans
, node
);
2420 * cursor->node is invalid, cursor up to make the cursor
2423 error
= hammer_cursor_up(cursor
);
2429 * Propagate cursor->trans->tid up the B-Tree starting at the current
2430 * cursor position using pseudofs info gleaned from the passed inode.
2432 * The passed inode has no relationship to the cursor position other
2433 * then being in the same pseudofs as the insertion or deletion we
2434 * are propagating the mirror_tid for.
2436 * WARNING! Because we push and pop the passed cursor, it may be
2437 * modified by other B-Tree operations while it is unlocked
2438 * and things like the node & leaf pointers, and indexes might
2442 hammer_btree_do_propagation(hammer_cursor_t cursor
,
2443 hammer_pseudofs_inmem_t pfsm
,
2444 hammer_btree_leaf_elm_t leaf
)
2446 hammer_cursor_t ncursor
;
2447 hammer_tid_t mirror_tid
;
2451 * We do not propagate a mirror_tid if the filesystem was mounted
2452 * in no-mirror mode.
2454 if (cursor
->trans
->hmp
->master_id
< 0)
2458 * This is a bit of a hack because we cannot deadlock or return
2459 * EDEADLK here. The related operation has already completed and
2460 * we must propagate the mirror_tid now regardless.
2462 * Generate a new cursor which inherits the original's locks and
2463 * unlock the original. Use the new cursor to propagate the
2464 * mirror_tid. Then clean up the new cursor and reacquire locks
2467 * hammer_dup_cursor() cannot dup locks. The dup inherits the
2468 * original's locks and the original is tracked and must be
2471 mirror_tid
= cursor
->node
->ondisk
->mirror_tid
;
2472 KKASSERT(mirror_tid
!= 0);
2473 ncursor
= hammer_push_cursor(cursor
);
2474 error
= hammer_btree_mirror_propagate(ncursor
, mirror_tid
);
2475 KKASSERT(error
== 0);
2476 hammer_pop_cursor(cursor
, ncursor
);
2477 /* WARNING: cursor's leaf pointer may change after pop */
2482 * Propagate a mirror TID update upwards through the B-Tree to the root.
2484 * A locked internal node must be passed in. The node will remain locked
2487 * This function syncs mirror_tid at the specified internal node's element,
2488 * adjusts the node's aggregation mirror_tid, and then recurses upwards.
2491 hammer_btree_mirror_propagate(hammer_cursor_t cursor
, hammer_tid_t mirror_tid
)
2493 hammer_btree_internal_elm_t elm
;
2498 error
= hammer_cursor_up(cursor
);
2500 error
= hammer_cursor_upgrade(cursor
);
2503 * We can ignore HAMMER_CURSOR_ITERATE_CHECK, the
2504 * cursor will still be properly positioned for
2505 * mirror propagation, just not for iterations.
2507 while (error
== EDEADLK
) {
2508 hammer_recover_cursor(cursor
);
2509 error
= hammer_cursor_upgrade(cursor
);
2515 * If the cursor deadlocked it could end up at a leaf
2516 * after we lost the lock.
2518 node
= cursor
->node
;
2519 if (node
->ondisk
->type
!= HAMMER_BTREE_TYPE_INTERNAL
)
2523 * Adjust the node's element
2525 elm
= &node
->ondisk
->elms
[cursor
->index
].internal
;
2526 if (elm
->mirror_tid
>= mirror_tid
)
2528 hammer_modify_node(cursor
->trans
, node
, &elm
->mirror_tid
,
2529 sizeof(elm
->mirror_tid
));
2530 elm
->mirror_tid
= mirror_tid
;
2531 hammer_modify_node_done(node
);
2532 if (hammer_debug_general
& 0x0002) {
2533 kprintf("mirror_propagate: propagate "
2534 "%016llx @%016llx:%d\n",
2535 (long long)mirror_tid
,
2536 (long long)node
->node_offset
,
2542 * Adjust the node's mirror_tid aggregator
2544 if (node
->ondisk
->mirror_tid
>= mirror_tid
)
2546 hammer_modify_node_field(cursor
->trans
, node
, mirror_tid
);
2547 node
->ondisk
->mirror_tid
= mirror_tid
;
2548 hammer_modify_node_done(node
);
2549 if (hammer_debug_general
& 0x0002) {
2550 kprintf("mirror_propagate: propagate "
2551 "%016llx @%016llx\n",
2552 (long long)mirror_tid
,
2553 (long long)node
->node_offset
);
2556 if (error
== ENOENT
)
2562 hammer_btree_get_parent(hammer_transaction_t trans
, hammer_node_t node
,
2563 int *parent_indexp
, int *errorp
, int try_exclusive
)
2565 hammer_node_t parent
;
2566 hammer_btree_elm_t elm
;
2572 parent
= hammer_get_node(trans
, node
->ondisk
->parent
, 0, errorp
);
2574 KKASSERT(parent
== NULL
);
2577 KKASSERT ((parent
->flags
& HAMMER_NODE_DELETED
) == 0);
2582 if (try_exclusive
) {
2583 if (hammer_lock_ex_try(&parent
->lock
)) {
2584 hammer_rel_node(parent
);
2589 hammer_lock_sh(&parent
->lock
);
2593 * Figure out which element in the parent is pointing to the
2596 if (node
->ondisk
->count
) {
2597 i
= hammer_btree_search_node(&node
->ondisk
->elms
[0].base
,
2602 while (i
< parent
->ondisk
->count
) {
2603 elm
= &parent
->ondisk
->elms
[i
];
2604 if (elm
->internal
.subtree_offset
== node
->node_offset
)
2608 if (i
== parent
->ondisk
->count
) {
2609 hammer_unlock(&parent
->lock
);
2610 panic("Bad B-Tree link: parent %p node %p\n", parent
, node
);
2613 KKASSERT(*errorp
== 0);
2618 * The element (elm) has been moved to a new internal node (node).
2620 * If the element represents a pointer to an internal node that node's
2621 * parent must be adjusted to the element's new location.
2623 * XXX deadlock potential here with our exclusive locks
2626 btree_set_parent(hammer_transaction_t trans
, hammer_node_t node
,
2627 hammer_btree_elm_t elm
)
2629 hammer_node_t child
;
2634 switch(elm
->base
.btype
) {
2635 case HAMMER_BTREE_TYPE_INTERNAL
:
2636 case HAMMER_BTREE_TYPE_LEAF
:
2637 child
= hammer_get_node(trans
, elm
->internal
.subtree_offset
,
2640 hammer_modify_node_field(trans
, child
, parent
);
2641 child
->ondisk
->parent
= node
->node_offset
;
2642 hammer_modify_node_done(child
);
2643 hammer_rel_node(child
);
2653 * Initialize the root of a recursive B-Tree node lock list structure.
2656 hammer_node_lock_init(hammer_node_lock_t parent
, hammer_node_t node
)
2658 TAILQ_INIT(&parent
->list
);
2659 parent
->parent
= NULL
;
2660 parent
->node
= node
;
2662 parent
->count
= node
->ondisk
->count
;
2663 parent
->copy
= NULL
;
2668 * Exclusively lock all the children of node. This is used by the split
2669 * code to prevent anyone from accessing the children of a cursor node
2670 * while we fix-up its parent offset.
2672 * If we don't lock the children we can really mess up cursors which block
2673 * trying to cursor-up into our node.
2675 * On failure EDEADLK (or some other error) is returned. If a deadlock
2676 * error is returned the cursor is adjusted to block on termination.
2678 * The caller is responsible for managing parent->node, the root's node
2679 * is usually aliased from a cursor.
2682 hammer_btree_lock_children(hammer_cursor_t cursor
, int depth
,
2683 hammer_node_lock_t parent
)
2686 hammer_node_lock_t item
;
2687 hammer_node_ondisk_t ondisk
;
2688 hammer_btree_elm_t elm
;
2689 hammer_node_t child
;
2690 struct hammer_mount
*hmp
;
2694 node
= parent
->node
;
2695 ondisk
= node
->ondisk
;
2697 hmp
= cursor
->trans
->hmp
;
2700 * We really do not want to block on I/O with exclusive locks held,
2701 * pre-get the children before trying to lock the mess. This is
2702 * only done one-level deep for now.
2704 for (i
= 0; i
< ondisk
->count
; ++i
) {
2705 ++hammer_stats_btree_elements
;
2706 elm
= &ondisk
->elms
[i
];
2707 if (elm
->base
.btype
!= HAMMER_BTREE_TYPE_LEAF
&&
2708 elm
->base
.btype
!= HAMMER_BTREE_TYPE_INTERNAL
) {
2711 child
= hammer_get_node(cursor
->trans
,
2712 elm
->internal
.subtree_offset
,
2715 hammer_rel_node(child
);
2721 for (i
= 0; error
== 0 && i
< ondisk
->count
; ++i
) {
2722 ++hammer_stats_btree_elements
;
2723 elm
= &ondisk
->elms
[i
];
2725 switch(elm
->base
.btype
) {
2726 case HAMMER_BTREE_TYPE_INTERNAL
:
2727 case HAMMER_BTREE_TYPE_LEAF
:
2728 KKASSERT(elm
->internal
.subtree_offset
!= 0);
2729 child
= hammer_get_node(cursor
->trans
,
2730 elm
->internal
.subtree_offset
,
2738 if (hammer_lock_ex_try(&child
->lock
) != 0) {
2739 if (cursor
->deadlk_node
== NULL
) {
2740 cursor
->deadlk_node
= child
;
2741 hammer_ref_node(cursor
->deadlk_node
);
2744 hammer_rel_node(child
);
2746 item
= kmalloc(sizeof(*item
), hmp
->m_misc
,
2748 TAILQ_INSERT_TAIL(&parent
->list
, item
, entry
);
2749 TAILQ_INIT(&item
->list
);
2750 item
->parent
= parent
;
2753 item
->count
= child
->ondisk
->count
;
2756 * Recurse (used by the rebalancing code)
2758 if (depth
> 1 && elm
->base
.btype
== HAMMER_BTREE_TYPE_INTERNAL
) {
2759 error
= hammer_btree_lock_children(
2768 hammer_btree_unlock_children(cursor
, parent
);
2773 * Create an in-memory copy of all B-Tree nodes listed, recursively,
2774 * including the parent.
2777 hammer_btree_lock_copy(hammer_cursor_t cursor
, hammer_node_lock_t parent
)
2779 hammer_mount_t hmp
= cursor
->trans
->hmp
;
2780 hammer_node_lock_t item
;
2782 if (parent
->copy
== NULL
) {
2783 parent
->copy
= kmalloc(sizeof(*parent
->copy
), hmp
->m_misc
,
2785 *parent
->copy
= *parent
->node
->ondisk
;
2787 TAILQ_FOREACH(item
, &parent
->list
, entry
) {
2788 hammer_btree_lock_copy(cursor
, item
);
2793 * Recursively sync modified copies to the media.
2796 hammer_btree_sync_copy(hammer_cursor_t cursor
, hammer_node_lock_t parent
)
2798 hammer_node_lock_t item
;
2801 if (parent
->flags
& HAMMER_NODE_LOCK_UPDATED
) {
2803 hammer_modify_node_all(cursor
->trans
, parent
->node
);
2804 *parent
->node
->ondisk
= *parent
->copy
;
2805 hammer_modify_node_done(parent
->node
);
2806 if (parent
->copy
->type
== HAMMER_BTREE_TYPE_DELETED
) {
2807 hammer_flush_node(parent
->node
, 0);
2808 hammer_delete_node(cursor
->trans
, parent
->node
);
2811 TAILQ_FOREACH(item
, &parent
->list
, entry
) {
2812 count
+= hammer_btree_sync_copy(cursor
, item
);
2818 * Release previously obtained node locks. The caller is responsible for
2819 * cleaning up parent->node itself (its usually just aliased from a cursor),
2820 * but this function will take care of the copies.
2823 hammer_btree_unlock_children(hammer_cursor_t cursor
, hammer_node_lock_t parent
)
2825 hammer_node_lock_t item
;
2828 kfree(parent
->copy
, cursor
->trans
->hmp
->m_misc
);
2829 parent
->copy
= NULL
; /* safety */
2831 while ((item
= TAILQ_FIRST(&parent
->list
)) != NULL
) {
2832 TAILQ_REMOVE(&parent
->list
, item
, entry
);
2833 hammer_btree_unlock_children(cursor
, item
);
2834 hammer_unlock(&item
->node
->lock
);
2835 hammer_rel_node(item
->node
);
2836 kfree(item
, cursor
->trans
->hmp
->m_misc
);
2840 /************************************************************************
2841 * MISCELLANIOUS SUPPORT *
2842 ************************************************************************/
2845 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2847 * Note that for this particular function a return value of -1, 0, or +1
2848 * can denote a match if create_tid is otherwise discounted. A create_tid
2849 * of zero is considered to be 'infinity' in comparisons.
2851 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2854 hammer_btree_cmp(hammer_base_elm_t key1
, hammer_base_elm_t key2
)
2856 if (key1
->localization
< key2
->localization
)
2858 if (key1
->localization
> key2
->localization
)
2861 if (key1
->obj_id
< key2
->obj_id
)
2863 if (key1
->obj_id
> key2
->obj_id
)
2866 if (key1
->rec_type
< key2
->rec_type
)
2868 if (key1
->rec_type
> key2
->rec_type
)
2871 if (key1
->key
< key2
->key
)
2873 if (key1
->key
> key2
->key
)
2877 * A create_tid of zero indicates a record which is undeletable
2878 * and must be considered to have a value of positive infinity.
2880 if (key1
->create_tid
== 0) {
2881 if (key2
->create_tid
== 0)
2885 if (key2
->create_tid
== 0)
2887 if (key1
->create_tid
< key2
->create_tid
)
2889 if (key1
->create_tid
> key2
->create_tid
)
2895 * Test a timestamp against an element to determine whether the
2896 * element is visible. A timestamp of 0 means 'infinity'.
2899 hammer_btree_chkts(hammer_tid_t asof
, hammer_base_elm_t base
)
2902 if (base
->delete_tid
)
2906 if (asof
< base
->create_tid
)
2908 if (base
->delete_tid
&& asof
>= base
->delete_tid
)
2914 * Create a separator half way inbetween key1 and key2. For fields just
2915 * one unit apart, the separator will match key2. key1 is on the left-hand
2916 * side and key2 is on the right-hand side.
2918 * key2 must be >= the separator. It is ok for the separator to match key2.
2920 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2923 * NOTE: It might be beneficial to just scrap this whole mess and just
2924 * set the separator to key2.
2926 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2927 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2930 hammer_make_separator(hammer_base_elm_t key1
, hammer_base_elm_t key2
,
2931 hammer_base_elm_t dest
)
2933 bzero(dest
, sizeof(*dest
));
2935 dest
->rec_type
= key2
->rec_type
;
2936 dest
->key
= key2
->key
;
2937 dest
->obj_id
= key2
->obj_id
;
2938 dest
->create_tid
= key2
->create_tid
;
2940 MAKE_SEPARATOR(key1
, key2
, dest
, localization
);
2941 if (key1
->localization
== key2
->localization
) {
2942 MAKE_SEPARATOR(key1
, key2
, dest
, obj_id
);
2943 if (key1
->obj_id
== key2
->obj_id
) {
2944 MAKE_SEPARATOR(key1
, key2
, dest
, rec_type
);
2945 if (key1
->rec_type
== key2
->rec_type
) {
2946 MAKE_SEPARATOR(key1
, key2
, dest
, key
);
2948 * Don't bother creating a separator for
2949 * create_tid, which also conveniently avoids
2950 * having to handle the create_tid == 0
2951 * (infinity) case. Just leave create_tid
2954 * Worst case, dest matches key2 exactly,
2955 * which is acceptable.
2962 #undef MAKE_SEPARATOR
2965 * Return whether a generic internal or leaf node is full
2968 btree_node_is_full(hammer_node_ondisk_t node
)
2970 switch(node
->type
) {
2971 case HAMMER_BTREE_TYPE_INTERNAL
:
2972 if (node
->count
== HAMMER_BTREE_INT_ELMS
)
2975 case HAMMER_BTREE_TYPE_LEAF
:
2976 if (node
->count
== HAMMER_BTREE_LEAF_ELMS
)
2980 panic("illegal btree subtype");
2987 btree_max_elements(u_int8_t type
)
2989 if (type
== HAMMER_BTREE_TYPE_LEAF
)
2990 return(HAMMER_BTREE_LEAF_ELMS
);
2991 if (type
== HAMMER_BTREE_TYPE_INTERNAL
)
2992 return(HAMMER_BTREE_INT_ELMS
);
2993 panic("btree_max_elements: bad type %d\n", type
);
2998 hammer_print_btree_node(hammer_node_ondisk_t ondisk
)
3000 hammer_btree_elm_t elm
;
3003 kprintf("node %p count=%d parent=%016llx type=%c\n",
3004 ondisk
, ondisk
->count
,
3005 (long long)ondisk
->parent
, ondisk
->type
);
3008 * Dump both boundary elements if an internal node
3010 if (ondisk
->type
== HAMMER_BTREE_TYPE_INTERNAL
) {
3011 for (i
= 0; i
<= ondisk
->count
; ++i
) {
3012 elm
= &ondisk
->elms
[i
];
3013 hammer_print_btree_elm(elm
, ondisk
->type
, i
);
3016 for (i
= 0; i
< ondisk
->count
; ++i
) {
3017 elm
= &ondisk
->elms
[i
];
3018 hammer_print_btree_elm(elm
, ondisk
->type
, i
);
3024 hammer_print_btree_elm(hammer_btree_elm_t elm
, u_int8_t type
, int i
)
3027 kprintf("\tobj_id = %016llx\n", (long long)elm
->base
.obj_id
);
3028 kprintf("\tkey = %016llx\n", (long long)elm
->base
.key
);
3029 kprintf("\tcreate_tid = %016llx\n", (long long)elm
->base
.create_tid
);
3030 kprintf("\tdelete_tid = %016llx\n", (long long)elm
->base
.delete_tid
);
3031 kprintf("\trec_type = %04x\n", elm
->base
.rec_type
);
3032 kprintf("\tobj_type = %02x\n", elm
->base
.obj_type
);
3033 kprintf("\tbtype = %02x (%c)\n",
3035 (elm
->base
.btype
? elm
->base
.btype
: '?'));
3036 kprintf("\tlocalization = %02x\n", elm
->base
.localization
);
3039 case HAMMER_BTREE_TYPE_INTERNAL
:
3040 kprintf("\tsubtree_off = %016llx\n",
3041 (long long)elm
->internal
.subtree_offset
);
3043 case HAMMER_BTREE_TYPE_RECORD
:
3044 kprintf("\tdata_offset = %016llx\n",
3045 (long long)elm
->leaf
.data_offset
);
3046 kprintf("\tdata_len = %08x\n", elm
->leaf
.data_len
);
3047 kprintf("\tdata_crc = %08x\n", elm
->leaf
.data_crc
);