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.45 2008/05/12 05:13:11 dillon Exp $
40 * HAMMER implements a modified B+Tree. In documentation this will
41 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
42 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
43 * of the tree), but adds two additional boundary elements which describe
44 * the left-most and right-most element a node is able to represent. In
45 * otherwords, we have boundary elements at the two ends of a B-Tree node
46 * instead of sub-tree pointers.
48 * A B-Tree internal node looks like this:
50 * B N N N N N N B <-- boundary and internal elements
51 * S S S S S S S <-- subtree pointers
53 * A B-Tree leaf node basically looks like this:
55 * L L L L L L L L <-- leaf elemenets
57 * The radix for an internal node is 1 less then a leaf but we get a
58 * number of significant benefits for our troubles.
60 * The big benefit to using a B-Tree containing boundary information
61 * is that it is possible to cache pointers into the middle of the tree
62 * and not have to start searches, insertions, OR deletions at the root
63 * node. In particular, searches are able to progress in a definitive
64 * direction from any point in the tree without revisting nodes. This
65 * greatly improves the efficiency of many operations, most especially
68 * B-Trees also make the stacking of trees fairly straightforward.
70 * INSERTIONS: A search performed with the intention of doing
71 * an insert will guarantee that the terminal leaf node is not full by
72 * splitting full nodes. Splits occur top-down during the dive down the
75 * DELETIONS: A deletion makes no attempt to proactively balance the
76 * tree and will recursively remove nodes that become empty. Empty
77 * nodes are not allowed and a deletion may recurse upwards from the leaf.
78 * Rather then allow a deadlock a deletion may terminate early by setting
79 * an internal node's element's subtree_offset to 0. The deletion will
80 * then be resumed the next time a search encounters the element.
86 static int btree_search(hammer_cursor_t cursor, int flags);
87 static int btree_split_internal(hammer_cursor_t cursor);
88 static int btree_split_leaf(hammer_cursor_t cursor);
89 static int btree_remove(hammer_cursor_t cursor);
90 static int btree_remove_deleted_element(hammer_cursor_t cursor);
91 static int btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
92 hammer_btree_elm_t elm);
93 static int btree_node_is_full(hammer_node_ondisk_t node);
94 static void hammer_make_separator(hammer_base_elm_t key1,
95 hammer_base_elm_t key2, hammer_base_elm_t dest);
96 static void hammer_btree_unlock_children(
97 struct hammer_node_locklist **locklistp);
100 * Iterate records after a search. The cursor is iterated forwards past
101 * the current record until a record matching the key-range requirements
102 * is found. ENOENT is returned if the iteration goes past the ending
105 * The iteration is inclusive of key_beg and can be inclusive or exclusive
106 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
108 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
109 * may be modified by B-Tree functions.
111 * cursor->key_beg may or may not be modified by this function during
112 * the iteration. XXX future - in case of an inverted lock we may have
113 * to reinitiate the lookup and set key_beg to properly pick up where we
116 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
119 hammer_btree_iterate(hammer_cursor_t cursor)
121 hammer_node_ondisk_t node;
122 hammer_btree_elm_t elm;
128 * Skip past the current record
130 node = cursor->node->ondisk;
133 if (cursor->index < node->count &&
134 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
139 * Loop until an element is found or we are done.
143 * We iterate up the tree and then index over one element
144 * while we are at the last element in the current node.
146 * If we are at the root of the filesystem, cursor_up
149 * XXX this could be optimized by storing the information in
150 * the parent reference.
152 * XXX we can lose the node lock temporarily, this could mess
155 if (cursor->index == node->count) {
156 if (hammer_debug_btree) {
157 kprintf("BRACKETU %016llx[%d] -> %016llx[%d] (td=%p)\n",
158 cursor->node->node_offset,
160 (cursor->parent ? cursor->parent->node_offset : -1),
161 cursor->parent_index,
164 KKASSERT(cursor->parent == NULL || cursor->parent->ondisk->elms[cursor->parent_index].internal.subtree_offset == cursor->node->node_offset);
165 error = hammer_cursor_up(cursor);
168 /* reload stale pointer */
169 node = cursor->node->ondisk;
170 KKASSERT(cursor->index != node->count);
176 * Check internal or leaf element. Determine if the record
177 * at the cursor has gone beyond the end of our range.
179 * We recurse down through internal nodes.
181 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
182 elm = &node->elms[cursor->index];
183 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
184 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
185 if (hammer_debug_btree) {
186 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d (td=%p)\n",
187 cursor->node->node_offset,
189 elm[0].internal.base.obj_id,
190 elm[0].internal.base.rec_type,
191 elm[0].internal.base.key,
195 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
196 cursor->node->node_offset,
198 elm[1].internal.base.obj_id,
199 elm[1].internal.base.rec_type,
200 elm[1].internal.base.key,
209 if (r == 0 && (cursor->flags &
210 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
217 * When iterating try to clean up any deleted
218 * internal elements left over from btree_remove()
219 * deadlocks, but it is ok if we can't.
221 if (elm->internal.subtree_offset == 0) {
222 hkprintf("REMOVE DELETED ELEMENT\n");
223 btree_remove_deleted_element(cursor);
224 /* note: elm also invalid */
225 } else if (elm->internal.subtree_offset != 0) {
226 error = hammer_cursor_down(cursor);
229 KKASSERT(cursor->index == 0);
231 /* reload stale pointer */
232 node = cursor->node->ondisk;
235 elm = &node->elms[cursor->index];
236 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
237 if (hammer_debug_btree) {
238 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
239 cursor->node->node_offset,
241 (elm[0].leaf.base.btype ?
242 elm[0].leaf.base.btype : '?'),
243 elm[0].leaf.base.obj_id,
244 elm[0].leaf.base.rec_type,
245 elm[0].leaf.base.key,
255 * We support both end-inclusive and
256 * end-exclusive searches.
259 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
264 switch(elm->leaf.base.btype) {
265 case HAMMER_BTREE_TYPE_RECORD:
266 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
267 hammer_btree_chkts(cursor->asof, &elm->base)) {
280 * node pointer invalid after loop
286 if (hammer_debug_btree) {
287 int i = cursor->index;
288 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
289 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
291 elm->internal.base.obj_id,
292 elm->internal.base.rec_type,
293 elm->internal.base.key
302 * Iterate in the reverse direction. This is used by the pruning code to
303 * avoid overlapping records.
306 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
308 hammer_node_ondisk_t node;
309 hammer_btree_elm_t elm;
315 * Skip past the current record. For various reasons the cursor
316 * may end up set to -1 or set to point at the end of the current
317 * node. These cases must be addressed.
319 node = cursor->node->ondisk;
322 if (cursor->index != -1 &&
323 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
326 if (cursor->index == cursor->node->ondisk->count)
330 * Loop until an element is found or we are done.
334 * We iterate up the tree and then index over one element
335 * while we are at the last element in the current node.
337 if (cursor->index == -1) {
338 error = hammer_cursor_up(cursor);
340 cursor->index = 0; /* sanity */
343 /* reload stale pointer */
344 node = cursor->node->ondisk;
345 KKASSERT(cursor->index != node->count);
351 * Check internal or leaf element. Determine if the record
352 * at the cursor has gone beyond the end of our range.
354 * We recurse down through internal nodes.
356 KKASSERT(cursor->index != node->count);
357 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
358 elm = &node->elms[cursor->index];
359 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
360 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
361 if (hammer_debug_btree) {
362 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx %d\n",
363 cursor->node->node_offset,
365 elm[0].internal.base.obj_id,
366 elm[0].internal.base.rec_type,
367 elm[0].internal.base.key,
370 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx %d\n",
371 cursor->node->node_offset,
373 elm[1].internal.base.obj_id,
374 elm[1].internal.base.rec_type,
375 elm[1].internal.base.key,
387 * When iterating try to clean up any deleted
388 * internal elements left over from btree_remove()
389 * deadlocks, but it is ok if we can't.
391 if (elm->internal.subtree_offset == 0) {
392 btree_remove_deleted_element(cursor);
393 /* note: elm also invalid */
394 } else if (elm->internal.subtree_offset != 0) {
395 error = hammer_cursor_down(cursor);
398 KKASSERT(cursor->index == 0);
399 cursor->index = cursor->node->ondisk->count - 1;
401 /* reload stale pointer */
402 node = cursor->node->ondisk;
405 elm = &node->elms[cursor->index];
406 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
407 if (hammer_debug_btree) {
408 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx %d\n",
409 cursor->node->node_offset,
411 (elm[0].leaf.base.btype ?
412 elm[0].leaf.base.btype : '?'),
413 elm[0].leaf.base.obj_id,
414 elm[0].leaf.base.rec_type,
415 elm[0].leaf.base.key,
424 switch(elm->leaf.base.btype) {
425 case HAMMER_BTREE_TYPE_RECORD:
426 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
427 hammer_btree_chkts(cursor->asof, &elm->base)) {
440 * node pointer invalid after loop
446 if (hammer_debug_btree) {
447 int i = cursor->index;
448 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
449 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
451 elm->internal.base.obj_id,
452 elm->internal.base.rec_type,
453 elm->internal.base.key
462 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
463 * could not be found, EDEADLK if inserting and a retry is needed, and a
464 * fatal error otherwise. When retrying, the caller must terminate the
465 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
467 * The cursor is suitably positioned for a deletion on success, and suitably
468 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
471 * The cursor may begin anywhere, the search will traverse the tree in
472 * either direction to locate the requested element.
474 * Most of the logic implementing historical searches is handled here. We
475 * do an initial lookup with create_tid set to the asof TID. Due to the
476 * way records are laid out, a backwards iteration may be required if
477 * ENOENT is returned to locate the historical record. Here's the
480 * create_tid: 10 15 20
484 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
485 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
486 * not visible and thus causes ENOENT to be returned. We really need
487 * to check record 11 in LEAF1. If it also fails then the search fails
488 * (e.g. it might represent the range 11-16 and thus still not match our
489 * AS-OF timestamp of 17).
491 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
492 * and the cursor->create_check TID if an iteration might be needed.
493 * In the above example create_check would be set to 14.
496 hammer_btree_lookup(hammer_cursor_t cursor)
500 if (cursor->flags & HAMMER_CURSOR_ASOF) {
501 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
502 cursor->key_beg.create_tid = cursor->asof;
504 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
505 error = btree_search(cursor, 0);
506 if (error != ENOENT ||
507 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
510 * Stop if error other then ENOENT.
511 * Stop if ENOENT and not special case.
515 if (hammer_debug_btree) {
516 kprintf("CREATE_CHECK %016llx\n",
517 cursor->create_check);
519 cursor->key_beg.create_tid = cursor->create_check;
523 error = btree_search(cursor, 0);
525 if (error == 0 && cursor->flags)
526 error = hammer_btree_extract(cursor, cursor->flags);
531 * Execute the logic required to start an iteration. The first record
532 * located within the specified range is returned and iteration control
533 * flags are adjusted for successive hammer_btree_iterate() calls.
536 hammer_btree_first(hammer_cursor_t cursor)
540 error = hammer_btree_lookup(cursor);
541 if (error == ENOENT) {
542 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
543 error = hammer_btree_iterate(cursor);
545 cursor->flags |= HAMMER_CURSOR_ATEDISK;
550 * Similarly but for an iteration in the reverse direction.
552 * Set ATEDISK when iterating backwards to skip the current entry,
553 * which after an ENOENT lookup will be pointing beyond our end point.
556 hammer_btree_last(hammer_cursor_t cursor)
558 struct hammer_base_elm save;
561 save = cursor->key_beg;
562 cursor->key_beg = cursor->key_end;
563 error = hammer_btree_lookup(cursor);
564 cursor->key_beg = save;
565 if (error == ENOENT ||
566 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
567 cursor->flags |= HAMMER_CURSOR_ATEDISK;
568 error = hammer_btree_iterate_reverse(cursor);
570 cursor->flags |= HAMMER_CURSOR_ATEDISK;
575 * Extract the record and/or data associated with the cursor's current
576 * position. Any prior record or data stored in the cursor is replaced.
577 * The cursor must be positioned at a leaf node.
579 * NOTE: All extractions occur at the leaf of the B-Tree.
582 hammer_btree_extract(hammer_cursor_t cursor, int flags)
585 hammer_node_ondisk_t node;
586 hammer_btree_elm_t elm;
587 hammer_off_t rec_off;
588 hammer_off_t data_off;
593 * The case where the data reference resolves to the same buffer
594 * as the record reference must be handled.
596 node = cursor->node->ondisk;
597 elm = &node->elms[cursor->index];
599 hmp = cursor->node->hmp;
600 flags |= cursor->flags & HAMMER_CURSOR_DATAEXTOK;
603 * There is nothing to extract for an internal element.
605 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
609 * Only record types have data.
611 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
612 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
613 flags &= ~HAMMER_CURSOR_GET_DATA;
614 data_off = elm->leaf.data_offset;
615 data_len = elm->leaf.data_len;
617 flags &= ~HAMMER_CURSOR_GET_DATA;
618 rec_off = elm->leaf.rec_offset;
621 * Extract the record if the record was requested or the data
622 * resides in the record buf.
624 if ((flags & HAMMER_CURSOR_GET_RECORD) ||
625 ((flags & HAMMER_CURSOR_GET_DATA) &&
626 ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) == 0)) {
627 cursor->record = hammer_bread(hmp, rec_off, &error,
628 &cursor->record_buffer);
629 if (hammer_crc_test_record(cursor->record) == 0) {
630 Debugger("CRC FAILED: RECORD");
636 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
637 if ((rec_off ^ data_off) & ~HAMMER_BUFMASK64) {
639 * Data and record are in different buffers.
641 cursor->data = hammer_bread(hmp, data_off, &error,
642 &cursor->data_buffer);
645 * Data resides in same buffer as record.
647 cursor->data = (void *)
648 ((char *)cursor->record_buffer->ondisk +
649 ((int32_t)data_off & HAMMER_BUFMASK));
651 KKASSERT(data_len >= 0 && data_len <= HAMMER_BUFSIZE);
653 crc32(cursor->data, data_len) != elm->leaf.data_crc) {
654 Debugger("CRC FAILED: DATA");
662 * Insert a leaf element into the B-Tree at the current cursor position.
663 * The cursor is positioned such that the element at and beyond the cursor
664 * are shifted to make room for the new record.
666 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
667 * flag set and that call must return ENOENT before this function can be
670 * The caller may depend on the cursor's exclusive lock after return to
671 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
673 * ENOSPC is returned if there is no room to insert a new record.
676 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
678 hammer_node_ondisk_t node;
682 if ((error = hammer_cursor_upgrade(cursor)) != 0)
686 * Insert the element at the leaf node and update the count in the
687 * parent. It is possible for parent to be NULL, indicating that
688 * the filesystem's ROOT B-Tree node is a leaf itself, which is
689 * possible. The root inode can never be deleted so the leaf should
692 * Remember that the right-hand boundary is not included in the
695 hammer_modify_node_all(cursor->trans, cursor->node);
696 node = cursor->node->ondisk;
698 KKASSERT(elm->base.btype != 0);
699 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
700 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
701 if (i != node->count) {
702 bcopy(&node->elms[i], &node->elms[i+1],
703 (node->count - i) * sizeof(*elm));
705 node->elms[i] = *elm;
707 hammer_modify_node_done(cursor->node);
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_all(cursor->trans, 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]));
770 hammer_modify_node_done(node);
773 * Validate local parent
775 if (ondisk->parent) {
776 parent = cursor->parent;
778 KKASSERT(parent != NULL);
779 KKASSERT(parent->node_offset == ondisk->parent);
783 * If the leaf becomes empty it must be detached from the parent,
784 * potentially recursing through to the filesystem root.
786 * This may reposition the cursor at one of the parent's of the
789 * Ignore deadlock errors, that simply means that btree_remove
790 * was unable to recurse and had to leave the subtree_offset
791 * in the parent set to 0.
793 KKASSERT(cursor->index <= ondisk->count);
794 if (ondisk->count == 0) {
796 error = btree_remove(cursor);
797 } while (error == EAGAIN);
798 if (error == EDEADLK)
803 KKASSERT(cursor->parent == NULL ||
804 cursor->parent_index < cursor->parent->ondisk->count);
809 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
811 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
813 * The search can begin ANYWHERE in the B-Tree. As a first step the search
814 * iterates up the tree as necessary to properly position itself prior to
815 * actually doing the sarch.
817 * INSERTIONS: The search will split full nodes and leaves on its way down
818 * and guarentee that the leaf it ends up on is not full. If we run out
819 * of space the search continues to the leaf (to position the cursor for
820 * the spike), but ENOSPC is returned.
822 * The search is only guarenteed to end up on a leaf if an error code of 0
823 * is returned, or if inserting and an error code of ENOENT is returned.
824 * Otherwise it can stop at an internal node. On success a search returns
827 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
828 * filesystem, and it is not simple code. Please note the following facts:
830 * - Internal node recursions have a boundary on the left AND right. The
831 * right boundary is non-inclusive. The create_tid is a generic part
832 * of the key for internal nodes.
834 * - Leaf nodes contain terminal elements only now.
836 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
837 * historical search. ASOF and INSERT are mutually exclusive. When
838 * doing an as-of lookup btree_search() checks for a right-edge boundary
839 * case. If while recursing down the left-edge differs from the key
840 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
841 * with cursor->create_check. This is used by btree_lookup() to iterate.
842 * The iteration backwards because as-of searches can wind up going
843 * down the wrong branch of the B-Tree.
847 btree_search(hammer_cursor_t cursor, int flags)
849 hammer_node_ondisk_t node;
850 hammer_btree_elm_t elm;
857 flags |= cursor->flags;
859 if (hammer_debug_btree) {
860 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx (td = %p)\n",
861 cursor->node->node_offset,
863 cursor->key_beg.obj_id,
864 cursor->key_beg.rec_type,
866 cursor->key_beg.create_tid,
870 kprintf("SEARCHP %016llx[%d] (%016llx/%016llx %016llx/%016llx) (%p/%p %p/%p)\n",
871 cursor->parent->node_offset, cursor->parent_index,
872 cursor->left_bound->obj_id,
873 cursor->parent->ondisk->elms[cursor->parent_index].internal.base.obj_id,
874 cursor->right_bound->obj_id,
875 cursor->parent->ondisk->elms[cursor->parent_index+1].internal.base.obj_id,
877 &cursor->parent->ondisk->elms[cursor->parent_index],
879 &cursor->parent->ondisk->elms[cursor->parent_index+1]
884 * Move our cursor up the tree until we find a node whos range covers
885 * the key we are trying to locate.
887 * The left bound is inclusive, the right bound is non-inclusive.
888 * It is ok to cursor up too far.
891 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
892 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
895 KKASSERT(cursor->parent);
896 error = hammer_cursor_up(cursor);
902 * The delete-checks below are based on node, not parent. Set the
903 * initial delete-check based on the parent.
906 KKASSERT(cursor->left_bound->create_tid != 1);
907 cursor->create_check = cursor->left_bound->create_tid - 1;
908 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
912 * We better have ended up with a node somewhere.
914 KKASSERT(cursor->node != NULL);
917 * If we are inserting we can't start at a full node if the parent
918 * is also full (because there is no way to split the node),
919 * continue running up the tree until the requirement is satisfied
920 * or we hit the root of the filesystem.
922 * (If inserting we aren't doing an as-of search so we don't have
923 * to worry about create_check).
925 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
926 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
927 if (btree_node_is_full(cursor->node->ondisk) == 0)
930 if (btree_node_is_full(cursor->node->ondisk) ==0)
933 if (cursor->node->ondisk->parent == 0 ||
934 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
937 error = hammer_cursor_up(cursor);
938 /* node may have become stale */
945 * Push down through internal nodes to locate the requested key.
947 node = cursor->node->ondisk;
948 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
950 * Scan the node to find the subtree index to push down into.
951 * We go one-past, then back-up.
953 * We must proactively remove deleted elements which may
954 * have been left over from a deadlocked btree_remove().
956 * The left and right boundaries are included in the loop
957 * in order to detect edge cases.
959 * If the separator only differs by create_tid (r == 1)
960 * and we are doing an as-of search, we may end up going
961 * down a branch to the left of the one containing the
962 * desired key. This requires numerous special cases.
964 if (hammer_debug_btree) {
965 kprintf("SEARCH-I %016llx count=%d\n",
966 cursor->node->node_offset,
969 for (i = 0; i <= node->count; ++i) {
970 elm = &node->elms[i];
971 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
972 if (hammer_debug_btree > 2) {
973 kprintf(" IELM %p %d r=%d\n",
974 &node->elms[i], i, r);
979 KKASSERT(elm->base.create_tid != 1);
980 cursor->create_check = elm->base.create_tid - 1;
981 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
984 if (hammer_debug_btree) {
985 kprintf("SEARCH-I preI=%d/%d r=%d\n",
990 * These cases occur when the parent's idea of the boundary
991 * is wider then the child's idea of the boundary, and
992 * require special handling. If not inserting we can
993 * terminate the search early for these cases but the
994 * child's boundaries cannot be unconditionally modified.
998 * If i == 0 the search terminated to the LEFT of the
999 * left_boundary but to the RIGHT of the parent's left
1004 elm = &node->elms[0];
1007 * If we aren't inserting we can stop here.
1009 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1015 * Correct a left-hand boundary mismatch.
1017 * We can only do this if we can upgrade the lock.
1019 * WARNING: We can only do this if inserting, i.e.
1020 * we are running on the backend.
1022 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1024 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1025 hammer_modify_node_field(cursor->trans, cursor->node,
1027 save = node->elms[0].base.btype;
1028 node->elms[0].base = *cursor->left_bound;
1029 node->elms[0].base.btype = save;
1030 hammer_modify_node_done(cursor->node);
1031 } else if (i == node->count + 1) {
1033 * If i == node->count + 1 the search terminated to
1034 * the RIGHT of the right boundary but to the LEFT
1035 * of the parent's right boundary. If we aren't
1036 * inserting we can stop here.
1038 * Note that the last element in this case is
1039 * elms[i-2] prior to adjustments to 'i'.
1042 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1048 * Correct a right-hand boundary mismatch.
1049 * (actual push-down record is i-2 prior to
1050 * adjustments to i).
1052 * We can only do this if we can upgrade the lock.
1054 * WARNING: We can only do this if inserting, i.e.
1055 * we are running on the backend.
1057 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1059 elm = &node->elms[i];
1060 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1061 hammer_modify_node(cursor->trans, cursor->node,
1062 &elm->base, sizeof(elm->base));
1063 elm->base = *cursor->right_bound;
1064 hammer_modify_node_done(cursor->node);
1068 * The push-down index is now i - 1. If we had
1069 * terminated on the right boundary this will point
1070 * us at the last element.
1075 elm = &node->elms[i];
1077 if (hammer_debug_btree) {
1078 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1079 "key=%016llx cre=%016llx\n",
1080 cursor->node->node_offset,
1082 elm->internal.base.obj_id,
1083 elm->internal.base.rec_type,
1084 elm->internal.base.key,
1085 elm->internal.base.create_tid
1090 * When searching try to clean up any deleted
1091 * internal elements left over from btree_remove()
1094 * If we fail and we are doing an insertion lookup,
1095 * we have to return EDEADLK, because an insertion lookup
1096 * must terminate at a leaf.
1098 if (elm->internal.subtree_offset == 0) {
1099 error = btree_remove_deleted_element(cursor);
1102 if (error == EDEADLK &&
1103 (flags & HAMMER_CURSOR_INSERT) == 0) {
1111 * Handle insertion and deletion requirements.
1113 * If inserting split full nodes. The split code will
1114 * adjust cursor->node and cursor->index if the current
1115 * index winds up in the new node.
1117 * If inserting and a left or right edge case was detected,
1118 * we cannot correct the left or right boundary and must
1119 * prepend and append an empty leaf node in order to make
1120 * the boundary correction.
1122 * If we run out of space we set enospc and continue on
1123 * to a leaf to provide the spike code with a good point
1126 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1127 if (btree_node_is_full(node)) {
1128 error = btree_split_internal(cursor);
1130 if (error != ENOSPC)
1135 * reload stale pointers
1138 node = cursor->node->ondisk;
1143 * Push down (push into new node, existing node becomes
1144 * the parent) and continue the search.
1146 error = hammer_cursor_down(cursor);
1147 /* node may have become stale */
1150 node = cursor->node->ondisk;
1154 * We are at a leaf, do a linear search of the key array.
1156 * If we encounter a spike element type within the necessary
1157 * range we push into it.
1159 * On success the index is set to the matching element and 0
1162 * On failure the index is set to the insertion point and ENOENT
1165 * Boundaries are not stored in leaf nodes, so the index can wind
1166 * up to the left of element 0 (index == 0) or past the end of
1167 * the array (index == node->count).
1169 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1170 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1171 if (hammer_debug_btree) {
1172 kprintf("SEARCH-L %016llx count=%d\n",
1173 cursor->node->node_offset,
1177 for (i = 0; i < node->count; ++i) {
1178 elm = &node->elms[i];
1180 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1182 if (hammer_debug_btree > 1)
1183 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1186 * We are at a record element. Stop if we've flipped past
1187 * key_beg, not counting the create_tid test. Allow the
1188 * r == 1 case (key_beg > element but differs only by its
1189 * create_tid) to fall through to the AS-OF check.
1191 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1199 * Check our as-of timestamp against the element.
1201 if (flags & HAMMER_CURSOR_ASOF) {
1202 if (hammer_btree_chkts(cursor->asof,
1203 &node->elms[i].base) != 0) {
1208 if (r > 0) /* can only be +1 */
1214 if (hammer_debug_btree) {
1215 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1216 cursor->node->node_offset, i);
1222 * The search of the leaf node failed. i is the insertion point.
1225 if (hammer_debug_btree) {
1226 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1227 cursor->node->node_offset, i);
1231 * No exact match was found, i is now at the insertion point.
1233 * If inserting split a full leaf before returning. This
1234 * may have the side effect of adjusting cursor->node and
1238 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1239 btree_node_is_full(node)) {
1240 error = btree_split_leaf(cursor);
1242 if (error != ENOSPC)
1247 * reload stale pointers
1251 node = &cursor->node->internal;
1256 * We reached a leaf but did not find the key we were looking for.
1257 * If this is an insert we will be properly positioned for an insert
1258 * (ENOENT) or spike (ENOSPC) operation.
1260 error = enospc ? ENOSPC : ENOENT;
1266 /************************************************************************
1267 * SPLITTING AND MERGING *
1268 ************************************************************************
1270 * These routines do all the dirty work required to split and merge nodes.
1274 * Split an internal node into two nodes and move the separator at the split
1275 * point to the parent.
1277 * (cursor->node, cursor->index) indicates the element the caller intends
1278 * to push into. We will adjust node and index if that element winds
1279 * up in the split node.
1281 * If we are at the root of the filesystem a new root must be created with
1282 * two elements, one pointing to the original root and one pointing to the
1283 * newly allocated split node.
1287 btree_split_internal(hammer_cursor_t cursor)
1289 hammer_node_ondisk_t ondisk;
1291 hammer_node_t parent;
1292 hammer_node_t new_node;
1293 hammer_btree_elm_t elm;
1294 hammer_btree_elm_t parent_elm;
1295 hammer_node_locklist_t locklist = NULL;
1296 hammer_mount_t hmp = cursor->trans->hmp;
1302 const int esize = sizeof(*elm);
1304 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1306 error = hammer_btree_lock_children(cursor, &locklist);
1311 * We are splitting but elms[split] will be promoted to the parent,
1312 * leaving the right hand node with one less element. If the
1313 * insertion point will be on the left-hand side adjust the split
1314 * point to give the right hand side one additional node.
1316 node = cursor->node;
1317 ondisk = node->ondisk;
1318 split = (ondisk->count + 1) / 2;
1319 if (cursor->index <= split)
1323 * If we are at the root of the filesystem, create a new root node
1324 * with 1 element and split normally. Avoid making major
1325 * modifications until we know the whole operation will work.
1327 if (ondisk->parent == 0) {
1328 parent = hammer_alloc_btree(cursor->trans, &error);
1331 hammer_lock_ex(&parent->lock);
1332 hammer_modify_node_noundo(cursor->trans, parent);
1333 ondisk = parent->ondisk;
1336 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1337 ondisk->elms[0].base = hmp->root_btree_beg;
1338 ondisk->elms[0].base.btype = node->ondisk->type;
1339 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1340 ondisk->elms[1].base = hmp->root_btree_end;
1341 hammer_modify_node_done(parent);
1342 /* ondisk->elms[1].base.btype - not used */
1344 parent_index = 0; /* index of current node in parent */
1347 parent = cursor->parent;
1348 parent_index = cursor->parent_index;
1352 * Split node into new_node at the split point.
1354 * B O O O P N N B <-- P = node->elms[split]
1355 * 0 1 2 3 4 5 6 <-- subtree indices
1360 * B O O O B B N N B <--- inner boundary points are 'P'
1364 new_node = hammer_alloc_btree(cursor->trans, &error);
1365 if (new_node == NULL) {
1367 hammer_unlock(&parent->lock);
1368 hammer_delete_node(cursor->trans, parent);
1369 hammer_rel_node(parent);
1373 hammer_lock_ex(&new_node->lock);
1376 * Create the new node. P becomes the left-hand boundary in the
1377 * new node. Copy the right-hand boundary as well.
1379 * elm is the new separator.
1381 hammer_modify_node_noundo(cursor->trans, new_node);
1382 hammer_modify_node_all(cursor->trans, node);
1383 ondisk = node->ondisk;
1384 elm = &ondisk->elms[split];
1385 bcopy(elm, &new_node->ondisk->elms[0],
1386 (ondisk->count - split + 1) * esize);
1387 new_node->ondisk->count = ondisk->count - split;
1388 new_node->ondisk->parent = parent->node_offset;
1389 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1390 KKASSERT(ondisk->type == new_node->ondisk->type);
1393 * Cleanup the original node. Elm (P) becomes the new boundary,
1394 * its subtree_offset was moved to the new node. If we had created
1395 * a new root its parent pointer may have changed.
1397 elm->internal.subtree_offset = 0;
1398 ondisk->count = split;
1401 * Insert the separator into the parent, fixup the parent's
1402 * reference to the original node, and reference the new node.
1403 * The separator is P.
1405 * Remember that base.count does not include the right-hand boundary.
1407 hammer_modify_node_all(cursor->trans, parent);
1408 ondisk = parent->ondisk;
1409 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1410 parent_elm = &ondisk->elms[parent_index+1];
1411 bcopy(parent_elm, parent_elm + 1,
1412 (ondisk->count - parent_index) * esize);
1413 parent_elm->internal.base = elm->base; /* separator P */
1414 parent_elm->internal.base.btype = new_node->ondisk->type;
1415 parent_elm->internal.subtree_offset = new_node->node_offset;
1417 hammer_modify_node_done(parent);
1420 * The children of new_node need their parent pointer set to new_node.
1421 * The children have already been locked by
1422 * hammer_btree_lock_children().
1424 for (i = 0; i < new_node->ondisk->count; ++i) {
1425 elm = &new_node->ondisk->elms[i];
1426 error = btree_set_parent(cursor->trans, new_node, elm);
1428 panic("btree_split_internal: btree-fixup problem");
1431 hammer_modify_node_done(new_node);
1434 * The filesystem's root B-Tree pointer may have to be updated.
1437 hammer_volume_t volume;
1439 volume = hammer_get_root_volume(hmp, &error);
1440 KKASSERT(error == 0);
1442 hammer_modify_volume_field(cursor->trans, volume,
1444 volume->ondisk->vol0_btree_root = parent->node_offset;
1445 hammer_modify_volume_done(volume);
1446 node->ondisk->parent = parent->node_offset;
1447 if (cursor->parent) {
1448 hammer_unlock(&cursor->parent->lock);
1449 hammer_rel_node(cursor->parent);
1451 cursor->parent = parent; /* lock'd and ref'd */
1452 hammer_rel_volume(volume, 0);
1454 hammer_modify_node_done(node);
1458 * Ok, now adjust the cursor depending on which element the original
1459 * index was pointing at. If we are >= the split point the push node
1460 * is now in the new node.
1462 * NOTE: If we are at the split point itself we cannot stay with the
1463 * original node because the push index will point at the right-hand
1464 * boundary, which is illegal.
1466 * NOTE: The cursor's parent or parent_index must be adjusted for
1467 * the case where a new parent (new root) was created, and the case
1468 * where the cursor is now pointing at the split node.
1470 if (cursor->index >= split) {
1471 cursor->parent_index = parent_index + 1;
1472 cursor->index -= split;
1473 hammer_unlock(&cursor->node->lock);
1474 hammer_rel_node(cursor->node);
1475 cursor->node = new_node; /* locked and ref'd */
1477 cursor->parent_index = parent_index;
1478 hammer_unlock(&new_node->lock);
1479 hammer_rel_node(new_node);
1483 * Fixup left and right bounds
1485 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1486 cursor->left_bound = &parent_elm[0].internal.base;
1487 cursor->right_bound = &parent_elm[1].internal.base;
1488 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1489 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1490 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1491 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1494 hammer_btree_unlock_children(&locklist);
1495 hammer_cursor_downgrade(cursor);
1500 * Same as the above, but splits a full leaf node.
1506 btree_split_leaf(hammer_cursor_t cursor)
1508 hammer_node_ondisk_t ondisk;
1509 hammer_node_t parent;
1512 hammer_node_t new_leaf;
1513 hammer_btree_elm_t elm;
1514 hammer_btree_elm_t parent_elm;
1515 hammer_base_elm_t mid_boundary;
1520 const size_t esize = sizeof(*elm);
1522 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1525 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1526 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1527 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1528 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1531 * Calculate the split point. If the insertion point will be on
1532 * the left-hand side adjust the split point to give the right
1533 * hand side one additional node.
1535 * Spikes are made up of two leaf elements which cannot be
1538 leaf = cursor->node;
1539 ondisk = leaf->ondisk;
1540 split = (ondisk->count + 1) / 2;
1541 if (cursor->index <= split)
1546 elm = &ondisk->elms[split];
1548 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1549 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1550 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1551 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1554 * If we are at the root of the tree, create a new root node with
1555 * 1 element and split normally. Avoid making major modifications
1556 * until we know the whole operation will work.
1558 if (ondisk->parent == 0) {
1559 parent = hammer_alloc_btree(cursor->trans, &error);
1562 hammer_lock_ex(&parent->lock);
1563 hammer_modify_node_noundo(cursor->trans, parent);
1564 ondisk = parent->ondisk;
1567 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1568 ondisk->elms[0].base = hmp->root_btree_beg;
1569 ondisk->elms[0].base.btype = leaf->ondisk->type;
1570 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1571 ondisk->elms[1].base = hmp->root_btree_end;
1572 /* ondisk->elms[1].base.btype = not used */
1573 hammer_modify_node_done(parent);
1575 parent_index = 0; /* insertion point in parent */
1578 parent = cursor->parent;
1579 parent_index = cursor->parent_index;
1583 * Split leaf into new_leaf at the split point. Select a separator
1584 * value in-between the two leafs but with a bent towards the right
1585 * leaf since comparisons use an 'elm >= separator' inequality.
1594 new_leaf = hammer_alloc_btree(cursor->trans, &error);
1595 if (new_leaf == NULL) {
1597 hammer_unlock(&parent->lock);
1598 hammer_delete_node(cursor->trans, parent);
1599 hammer_rel_node(parent);
1603 hammer_lock_ex(&new_leaf->lock);
1606 * Create the new node and copy the leaf elements from the split
1607 * point on to the new node.
1609 hammer_modify_node_all(cursor->trans, leaf);
1610 hammer_modify_node_noundo(cursor->trans, new_leaf);
1611 ondisk = leaf->ondisk;
1612 elm = &ondisk->elms[split];
1613 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1614 new_leaf->ondisk->count = ondisk->count - split;
1615 new_leaf->ondisk->parent = parent->node_offset;
1616 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1617 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1618 hammer_modify_node_done(new_leaf);
1621 * Cleanup the original node. Because this is a leaf node and
1622 * leaf nodes do not have a right-hand boundary, there
1623 * aren't any special edge cases to clean up. We just fixup the
1626 ondisk->count = split;
1629 * Insert the separator into the parent, fixup the parent's
1630 * reference to the original node, and reference the new node.
1631 * The separator is P.
1633 * Remember that base.count does not include the right-hand boundary.
1634 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1636 hammer_modify_node_all(cursor->trans, parent);
1637 ondisk = parent->ondisk;
1638 KKASSERT(split != 0);
1639 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1640 parent_elm = &ondisk->elms[parent_index+1];
1641 bcopy(parent_elm, parent_elm + 1,
1642 (ondisk->count - parent_index) * esize);
1644 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1645 parent_elm->internal.base.btype = new_leaf->ondisk->type;
1646 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1647 mid_boundary = &parent_elm->base;
1649 hammer_modify_node_done(parent);
1652 * The filesystem's root B-Tree pointer may have to be updated.
1655 hammer_volume_t volume;
1657 volume = hammer_get_root_volume(hmp, &error);
1658 KKASSERT(error == 0);
1660 hammer_modify_volume_field(cursor->trans, volume,
1662 volume->ondisk->vol0_btree_root = parent->node_offset;
1663 hammer_modify_volume_done(volume);
1664 leaf->ondisk->parent = parent->node_offset;
1665 if (cursor->parent) {
1666 hammer_unlock(&cursor->parent->lock);
1667 hammer_rel_node(cursor->parent);
1669 cursor->parent = parent; /* lock'd and ref'd */
1670 hammer_rel_volume(volume, 0);
1672 hammer_modify_node_done(leaf);
1675 * Ok, now adjust the cursor depending on which element the original
1676 * index was pointing at. If we are >= the split point the push node
1677 * is now in the new node.
1679 * NOTE: If we are at the split point itself we need to select the
1680 * old or new node based on where key_beg's insertion point will be.
1681 * If we pick the wrong side the inserted element will wind up in
1682 * the wrong leaf node and outside that node's bounds.
1684 if (cursor->index > split ||
1685 (cursor->index == split &&
1686 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1687 cursor->parent_index = parent_index + 1;
1688 cursor->index -= split;
1689 hammer_unlock(&cursor->node->lock);
1690 hammer_rel_node(cursor->node);
1691 cursor->node = new_leaf;
1693 cursor->parent_index = parent_index;
1694 hammer_unlock(&new_leaf->lock);
1695 hammer_rel_node(new_leaf);
1699 * Fixup left and right bounds
1701 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1702 cursor->left_bound = &parent_elm[0].internal.base;
1703 cursor->right_bound = &parent_elm[1].internal.base;
1706 * Assert that the bounds are correct.
1708 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1709 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1710 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1711 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1712 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1713 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
1716 hammer_cursor_downgrade(cursor);
1721 * Recursively correct the right-hand boundary's create_tid to (tid) as
1722 * long as the rest of the key matches. We have to recurse upward in
1723 * the tree as well as down the left side of each parent's right node.
1725 * Return EDEADLK if we were only partially successful, forcing the caller
1726 * to try again. The original cursor is not modified. This routine can
1727 * also fail with EDEADLK if it is forced to throw away a portion of its
1730 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1733 TAILQ_ENTRY(hammer_rhb) entry;
1738 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1741 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1743 struct hammer_rhb_list rhb_list;
1744 hammer_base_elm_t elm;
1745 hammer_node_t orig_node;
1746 struct hammer_rhb *rhb;
1750 TAILQ_INIT(&rhb_list);
1753 * Save our position so we can restore it on return. This also
1754 * gives us a stable 'elm'.
1756 orig_node = cursor->node;
1757 hammer_ref_node(orig_node);
1758 hammer_lock_sh(&orig_node->lock);
1759 orig_index = cursor->index;
1760 elm = &orig_node->ondisk->elms[orig_index].base;
1763 * Now build a list of parents going up, allocating a rhb
1764 * structure for each one.
1766 while (cursor->parent) {
1768 * Stop if we no longer have any right-bounds to fix up
1770 if (elm->obj_id != cursor->right_bound->obj_id ||
1771 elm->rec_type != cursor->right_bound->rec_type ||
1772 elm->key != cursor->right_bound->key) {
1777 * Stop if the right-hand bound's create_tid does not
1778 * need to be corrected.
1780 if (cursor->right_bound->create_tid >= tid)
1783 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1784 rhb->node = cursor->parent;
1785 rhb->index = cursor->parent_index;
1786 hammer_ref_node(rhb->node);
1787 hammer_lock_sh(&rhb->node->lock);
1788 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1790 hammer_cursor_up(cursor);
1794 * now safely adjust the right hand bound for each rhb. This may
1795 * also require taking the right side of the tree and iterating down
1799 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1800 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1801 hkprintf("CORRECT RHB %016llx index %d type=%c\n",
1802 rhb->node->node_offset,
1803 rhb->index, cursor->node->ondisk->type);
1806 TAILQ_REMOVE(&rhb_list, rhb, entry);
1807 hammer_unlock(&rhb->node->lock);
1808 hammer_rel_node(rhb->node);
1809 kfree(rhb, M_HAMMER);
1811 switch (cursor->node->ondisk->type) {
1812 case HAMMER_BTREE_TYPE_INTERNAL:
1814 * Right-boundary for parent at internal node
1815 * is one element to the right of the element whos
1816 * right boundary needs adjusting. We must then
1817 * traverse down the left side correcting any left
1818 * bounds (which may now be too far to the left).
1821 error = hammer_btree_correct_lhb(cursor, tid);
1824 panic("hammer_btree_correct_rhb(): Bad node type");
1833 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1834 TAILQ_REMOVE(&rhb_list, rhb, entry);
1835 hammer_unlock(&rhb->node->lock);
1836 hammer_rel_node(rhb->node);
1837 kfree(rhb, M_HAMMER);
1839 error = hammer_cursor_seek(cursor, orig_node, orig_index);
1840 hammer_unlock(&orig_node->lock);
1841 hammer_rel_node(orig_node);
1846 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
1847 * bound going downward starting at the current cursor position.
1849 * This function does not restore the cursor after use.
1852 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
1854 struct hammer_rhb_list rhb_list;
1855 hammer_base_elm_t elm;
1856 hammer_base_elm_t cmp;
1857 struct hammer_rhb *rhb;
1860 TAILQ_INIT(&rhb_list);
1862 cmp = &cursor->node->ondisk->elms[cursor->index].base;
1865 * Record the node and traverse down the left-hand side for all
1866 * matching records needing a boundary correction.
1870 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1871 rhb->node = cursor->node;
1872 rhb->index = cursor->index;
1873 hammer_ref_node(rhb->node);
1874 hammer_lock_sh(&rhb->node->lock);
1875 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1877 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1879 * Nothing to traverse down if we are at the right
1880 * boundary of an internal node.
1882 if (cursor->index == cursor->node->ondisk->count)
1885 elm = &cursor->node->ondisk->elms[cursor->index].base;
1886 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
1888 panic("Illegal leaf record type %02x", elm->btype);
1890 error = hammer_cursor_down(cursor);
1894 elm = &cursor->node->ondisk->elms[cursor->index].base;
1895 if (elm->obj_id != cmp->obj_id ||
1896 elm->rec_type != cmp->rec_type ||
1897 elm->key != cmp->key) {
1900 if (elm->create_tid >= tid)
1906 * Now we can safely adjust the left-hand boundary from the bottom-up.
1907 * The last element we remove from the list is the caller's right hand
1908 * boundary, which must also be adjusted.
1910 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1911 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1914 TAILQ_REMOVE(&rhb_list, rhb, entry);
1915 hammer_unlock(&rhb->node->lock);
1916 hammer_rel_node(rhb->node);
1917 kfree(rhb, M_HAMMER);
1919 elm = &cursor->node->ondisk->elms[cursor->index].base;
1920 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1921 hkprintf("hammer_btree_correct_lhb-I @%016llx[%d]\n",
1922 cursor->node->node_offset, cursor->index);
1923 hammer_modify_node(cursor->trans, cursor->node,
1925 sizeof(elm->create_tid));
1926 elm->create_tid = tid;
1927 hammer_modify_node_done(cursor->node);
1929 panic("hammer_btree_correct_lhb(): Bad element type");
1936 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1937 TAILQ_REMOVE(&rhb_list, rhb, entry);
1938 hammer_unlock(&rhb->node->lock);
1939 hammer_rel_node(rhb->node);
1940 kfree(rhb, M_HAMMER);
1946 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1947 * on success, EAGAIN if we could not acquire the necessary locks, or some
1948 * other error. This node can be a leaf node or an internal node.
1950 * On return the cursor may end up pointing at an internal node, suitable
1951 * for further iteration but not for an immediate insertion or deletion.
1953 * cursor->node may be an internal node or a leaf node.
1955 * NOTE: If cursor->node has one element it is the parent trying to delete
1956 * that element, make sure cursor->index is properly adjusted on success.
1959 btree_remove(hammer_cursor_t cursor)
1961 hammer_node_ondisk_t ondisk;
1962 hammer_btree_elm_t elm;
1964 hammer_node_t parent;
1965 const int esize = sizeof(*elm);
1968 node = cursor->node;
1971 * When deleting the root of the filesystem convert it to
1972 * an empty leaf node. Internal nodes cannot be empty.
1974 if (node->ondisk->parent == 0) {
1975 hammer_modify_node_all(cursor->trans, node);
1976 ondisk = node->ondisk;
1977 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1979 hammer_modify_node_done(node);
1985 * Zero-out the parent's reference to the child and flag the
1986 * child for destruction. This ensures that the child is not
1987 * reused while other references to it exist.
1989 parent = cursor->parent;
1990 hammer_modify_node_all(cursor->trans, parent);
1991 ondisk = parent->ondisk;
1992 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1993 elm = &ondisk->elms[cursor->parent_index];
1994 KKASSERT(elm->internal.subtree_offset == node->node_offset);
1995 elm->internal.subtree_offset = 0;
1997 hammer_flush_node(node);
1998 hammer_delete_node(cursor->trans, node);
2001 * If the parent would otherwise not become empty we can physically
2002 * remove the zero'd element. Note however that in order to
2003 * guarentee a valid cursor we still need to be able to cursor up
2004 * because we no longer have a node.
2006 * This collapse will change the parent's boundary elements, making
2007 * them wider. The new boundaries are recursively corrected in
2010 * XXX we can theoretically recalculate the midpoint but there isn't
2011 * much of a reason to do it.
2013 error = hammer_cursor_up(cursor);
2015 error = hammer_cursor_upgrade(cursor);
2018 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
2019 Debugger("BTREE_REMOVE");
2020 hammer_modify_node_done(parent);
2025 * Remove the internal element from the parent. The bcopy must
2026 * include the right boundary element.
2028 KKASSERT(parent == cursor->node && ondisk == parent->ondisk);
2031 /* ondisk is node's ondisk */
2032 /* elm is node's element */
2035 * Remove the internal element that we zero'd out. Tell the caller
2036 * to loop if it hits zero (to try to avoid eating up precious kernel
2039 KKASSERT(ondisk->count > 0);
2040 bcopy(&elm[1], &elm[0], (ondisk->count - cursor->index) * esize);
2042 if (ondisk->count == 0)
2044 hammer_modify_node_done(node);
2049 * Attempt to remove the deleted internal element at the current cursor
2050 * position. If we are unable to remove the element we return EDEADLK.
2052 * If the current internal node becomes empty we delete it in the parent
2053 * and cursor up, looping until we finish or we deadlock.
2055 * On return, if successful, the cursor will be pointing at the next
2056 * iterative position in the B-Tree. If unsuccessful the cursor will be
2057 * pointing at the last deleted internal element that could not be
2062 btree_remove_deleted_element(hammer_cursor_t cursor)
2065 hammer_btree_elm_t elm;
2068 if ((error = hammer_cursor_upgrade(cursor)) != 0)
2070 node = cursor->node;
2071 elm = &node->ondisk->elms[cursor->index];
2072 if (elm->internal.subtree_offset == 0) {
2074 error = btree_remove(cursor);
2075 hkprintf("BTREE REMOVE DELETED ELEMENT %d\n", error);
2076 } while (error == EAGAIN);
2082 * The element (elm) has been moved to a new internal node (node).
2084 * If the element represents a pointer to an internal node that node's
2085 * parent must be adjusted to the element's new location.
2087 * XXX deadlock potential here with our exclusive locks
2091 btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
2092 hammer_btree_elm_t elm)
2094 hammer_node_t child;
2099 switch(elm->base.btype) {
2100 case HAMMER_BTREE_TYPE_INTERNAL:
2101 case HAMMER_BTREE_TYPE_LEAF:
2102 child = hammer_get_node(node->hmp, elm->internal.subtree_offset,
2105 hammer_modify_node_field(trans, child, parent);
2106 child->ondisk->parent = node->node_offset;
2107 hammer_modify_node_done(child);
2108 hammer_rel_node(child);
2118 * Exclusively lock all the children of node. This is used by the split
2119 * code to prevent anyone from accessing the children of a cursor node
2120 * while we fix-up its parent offset.
2122 * If we don't lock the children we can really mess up cursors which block
2123 * trying to cursor-up into our node.
2125 * On failure EDEADLK (or some other error) is returned. If a deadlock
2126 * error is returned the cursor is adjusted to block on termination.
2129 hammer_btree_lock_children(hammer_cursor_t cursor,
2130 struct hammer_node_locklist **locklistp)
2133 hammer_node_locklist_t item;
2134 hammer_node_ondisk_t ondisk;
2135 hammer_btree_elm_t elm;
2136 hammer_node_t child;
2140 node = cursor->node;
2141 ondisk = node->ondisk;
2143 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2144 elm = &ondisk->elms[i];
2146 switch(elm->base.btype) {
2147 case HAMMER_BTREE_TYPE_INTERNAL:
2148 case HAMMER_BTREE_TYPE_LEAF:
2149 child = hammer_get_node(node->hmp,
2150 elm->internal.subtree_offset,
2158 if (hammer_lock_ex_try(&child->lock) != 0) {
2159 if (cursor->deadlk_node == NULL) {
2160 cursor->deadlk_node = child;
2161 hammer_ref_node(cursor->deadlk_node);
2164 hammer_rel_node(child);
2166 item = kmalloc(sizeof(*item),
2167 M_HAMMER, M_WAITOK);
2168 item->next = *locklistp;
2175 hammer_btree_unlock_children(locklistp);
2181 * Release previously obtained node locks.
2184 hammer_btree_unlock_children(struct hammer_node_locklist **locklistp)
2186 hammer_node_locklist_t item;
2188 while ((item = *locklistp) != NULL) {
2189 *locklistp = item->next;
2190 hammer_unlock(&item->node->lock);
2191 hammer_rel_node(item->node);
2192 kfree(item, M_HAMMER);
2196 /************************************************************************
2197 * MISCELLANIOUS SUPPORT *
2198 ************************************************************************/
2201 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2203 * Note that for this particular function a return value of -1, 0, or +1
2204 * can denote a match if create_tid is otherwise discounted. A create_tid
2205 * of zero is considered to be 'infinity' in comparisons.
2207 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2210 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2212 if (key1->obj_id < key2->obj_id)
2214 if (key1->obj_id > key2->obj_id)
2217 if (key1->rec_type < key2->rec_type)
2219 if (key1->rec_type > key2->rec_type)
2222 if (key1->key < key2->key)
2224 if (key1->key > key2->key)
2228 * A create_tid of zero indicates a record which is undeletable
2229 * and must be considered to have a value of positive infinity.
2231 if (key1->create_tid == 0) {
2232 if (key2->create_tid == 0)
2236 if (key2->create_tid == 0)
2238 if (key1->create_tid < key2->create_tid)
2240 if (key1->create_tid > key2->create_tid)
2246 * Test a timestamp against an element to determine whether the
2247 * element is visible. A timestamp of 0 means 'infinity'.
2250 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2253 if (base->delete_tid)
2257 if (asof < base->create_tid)
2259 if (base->delete_tid && asof >= base->delete_tid)
2265 * Create a separator half way inbetween key1 and key2. For fields just
2266 * one unit apart, the separator will match key2. key1 is on the left-hand
2267 * side and key2 is on the right-hand side.
2269 * key2 must be >= the separator. It is ok for the separator to match key2.
2271 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2274 * NOTE: It might be beneficial to just scrap this whole mess and just
2275 * set the separator to key2.
2277 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2278 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2281 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2282 hammer_base_elm_t dest)
2284 bzero(dest, sizeof(*dest));
2286 dest->rec_type = key2->rec_type;
2287 dest->key = key2->key;
2288 dest->create_tid = key2->create_tid;
2290 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2291 if (key1->obj_id == key2->obj_id) {
2292 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2293 if (key1->rec_type == key2->rec_type) {
2294 MAKE_SEPARATOR(key1, key2, dest, key);
2296 * Don't bother creating a separator for create_tid,
2297 * which also conveniently avoids having to handle
2298 * the create_tid == 0 (infinity) case. Just leave
2299 * create_tid set to key2.
2301 * Worst case, dest matches key2 exactly, which is
2308 #undef MAKE_SEPARATOR
2311 * Return whether a generic internal or leaf node is full
2314 btree_node_is_full(hammer_node_ondisk_t node)
2316 switch(node->type) {
2317 case HAMMER_BTREE_TYPE_INTERNAL:
2318 if (node->count == HAMMER_BTREE_INT_ELMS)
2321 case HAMMER_BTREE_TYPE_LEAF:
2322 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2326 panic("illegal btree subtype");
2333 btree_max_elements(u_int8_t type)
2335 if (type == HAMMER_BTREE_TYPE_LEAF)
2336 return(HAMMER_BTREE_LEAF_ELMS);
2337 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2338 return(HAMMER_BTREE_INT_ELMS);
2339 panic("btree_max_elements: bad type %d\n", type);
2344 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2346 hammer_btree_elm_t elm;
2349 kprintf("node %p count=%d parent=%016llx type=%c\n",
2350 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2353 * Dump both boundary elements if an internal node
2355 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2356 for (i = 0; i <= ondisk->count; ++i) {
2357 elm = &ondisk->elms[i];
2358 hammer_print_btree_elm(elm, ondisk->type, i);
2361 for (i = 0; i < ondisk->count; ++i) {
2362 elm = &ondisk->elms[i];
2363 hammer_print_btree_elm(elm, ondisk->type, i);
2369 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2372 kprintf("\tobj_id = %016llx\n", elm->base.obj_id);
2373 kprintf("\tkey = %016llx\n", elm->base.key);
2374 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2375 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2376 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2377 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2378 kprintf("\tbtype = %02x (%c)\n",
2380 (elm->base.btype ? elm->base.btype : '?'));
2383 case HAMMER_BTREE_TYPE_INTERNAL:
2384 kprintf("\tsubtree_off = %016llx\n",
2385 elm->internal.subtree_offset);
2387 case HAMMER_BTREE_TYPE_RECORD:
2388 kprintf("\trec_offset = %016llx\n", elm->leaf.rec_offset);
2389 kprintf("\tdata_offset = %016llx\n", elm->leaf.data_offset);
2390 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2391 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);