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
38 * HAMMER implements a modified B+Tree. In documentation this will
39 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
40 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
41 * of the tree), but adds two additional boundary elements which describe
42 * the left-most and right-most element a node is able to represent. In
43 * otherwords, we have boundary elements at the two ends of a B-Tree node
44 * with no valid sub-tree pointer for the right-most element.
46 * A B-Tree internal node looks like this:
48 * B N N N N N N B <-- boundary and internal elements
49 * S S S S S S S <-- subtree pointers
51 * A B-Tree leaf node basically looks like this:
53 * L L L L L L L L <-- leaf elemenets
55 * The radix for an internal node is 1 less then a leaf but we get a
56 * number of significant benefits for our troubles.
57 * The left-hand boundary (B in the left) is integrated into the first
58 * element so it doesn't require 2 elements to accomodate boundaries.
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
83 static int btree_search(hammer_cursor_t cursor, int flags);
84 static int btree_split_internal(hammer_cursor_t cursor);
85 static int btree_split_leaf(hammer_cursor_t cursor);
86 static int btree_remove(hammer_cursor_t cursor, int *ndelete);
87 static __inline int btree_node_is_full(hammer_node_ondisk_t node);
88 static __inline int btree_max_elements(u_int8_t type);
89 static int hammer_btree_mirror_propagate(hammer_cursor_t cursor,
90 hammer_tid_t mirror_tid);
91 static void hammer_make_separator(hammer_base_elm_t key1,
92 hammer_base_elm_t key2, hammer_base_elm_t dest);
93 static void hammer_cursor_mirror_filter(hammer_cursor_t cursor);
94 static __inline void hammer_debug_btree_elm(hammer_cursor_t cursor,
95 hammer_btree_elm_t elm, const char *s, int res);
96 static __inline void hammer_debug_btree_parent(hammer_cursor_t cursor,
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 * If HAMMER_CURSOR_ITERATE_CHECK is set it is possible that the cursor
117 * was reverse indexed due to being moved to a parent while unlocked,
118 * and something else might have inserted an element outside the iteration
119 * range. When this case occurs the iterator just keeps iterating until
120 * it gets back into the iteration range (instead of asserting).
122 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
125 hammer_btree_iterate(hammer_cursor_t cursor)
127 hammer_node_ondisk_t node;
128 hammer_btree_elm_t elm;
135 * Skip past the current record
137 hmp = cursor->trans->hmp;
138 node = cursor->node->ondisk;
141 if (cursor->index < node->count &&
142 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
147 * HAMMER can wind up being cpu-bound.
149 if (++hmp->check_yield > hammer_yield_check) {
150 hmp->check_yield = 0;
156 * Loop until an element is found or we are done.
160 * We iterate up the tree and then index over one element
161 * while we are at the last element in the current node.
163 * If we are at the root of the filesystem, cursor_up
166 * XXX this could be optimized by storing the information in
167 * the parent reference.
169 * XXX we can lose the node lock temporarily, this could mess
172 ++hammer_stats_btree_iterations;
173 hammer_flusher_clean_loose_ios(hmp);
175 if (cursor->index == node->count) {
176 if (hammer_debug_btree) {
177 kprintf("BRACKETU %016llx[%d] -> %016llx[%d] td=%p\n",
178 (long long)cursor->node->node_offset,
180 (long long)(cursor->parent ? cursor->parent->node_offset : -1),
181 cursor->parent_index,
184 KKASSERT(cursor->parent == NULL ||
185 cursor->parent->ondisk->elms[cursor->parent_index].internal.subtree_offset == cursor->node->node_offset);
186 error = hammer_cursor_up(cursor);
189 /* reload stale pointer */
190 node = cursor->node->ondisk;
191 KKASSERT(cursor->index != node->count);
194 * If we are reblocking we want to return internal
195 * nodes. Note that the internal node will be
196 * returned multiple times, on each upward recursion
197 * from its children. The caller selects which
198 * revisit it cares about (usually first or last only).
200 if (cursor->flags & HAMMER_CURSOR_REBLOCKING) {
201 cursor->flags |= HAMMER_CURSOR_ATEDISK;
209 * Check internal or leaf element. Determine if the record
210 * at the cursor has gone beyond the end of our range.
212 * We recurse down through internal nodes.
214 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
215 elm = &node->elms[cursor->index];
217 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
218 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
219 if (hammer_debug_btree) {
220 hammer_debug_btree_elm(cursor, elm, "BRACKETL", r);
221 hammer_debug_btree_elm(cursor, elm + 1, "BRACKETR", s);
228 if (r == 0 && (cursor->flags &
229 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
237 KKASSERT(elm->internal.subtree_offset != 0);
241 * If running the mirror filter see if we
242 * can skip one or more entire sub-trees.
243 * If we can we return the internal node
244 * and the caller processes the skipped
245 * range (see mirror_read).
248 HAMMER_CURSOR_MIRROR_FILTERED) {
249 if (elm->internal.mirror_tid <
250 cursor->cmirror->mirror_tid) {
251 hammer_cursor_mirror_filter(cursor);
257 * Normally it would be impossible for the
258 * cursor to have gotten back-indexed,
259 * but it can happen if a node is deleted
260 * and the cursor is moved to its parent
261 * internal node. ITERATE_CHECK will be set.
263 KKASSERT(cursor->flags &
264 HAMMER_CURSOR_ITERATE_CHECK);
265 kprintf("hammer_btree_iterate: "
266 "DEBUG: Caught parent seek "
267 "in internal iteration\n");
270 error = hammer_cursor_down(cursor);
273 KKASSERT(cursor->index == 0);
274 /* reload stale pointer */
275 node = cursor->node->ondisk;
278 elm = &node->elms[cursor->index];
279 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
280 if (hammer_debug_btree) {
281 hammer_debug_btree_elm(cursor, elm, "ELEMENT", r);
289 * We support both end-inclusive and
290 * end-exclusive searches.
293 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
299 * If ITERATE_CHECK is set an unlocked cursor may
300 * have been moved to a parent and the iterate can
301 * happen upon elements that are not in the requested
304 if (cursor->flags & HAMMER_CURSOR_ITERATE_CHECK) {
305 s = hammer_btree_cmp(&cursor->key_beg,
308 kprintf("hammer_btree_iterate: "
309 "DEBUG: Caught parent seek "
310 "in leaf iteration\n");
315 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
320 switch(elm->leaf.base.btype) {
321 case HAMMER_BTREE_TYPE_RECORD:
322 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
323 hammer_btree_chkts(cursor->asof, &elm->base)) {
340 if (hammer_debug_btree) {
341 elm = &cursor->node->ondisk->elms[cursor->index];
342 hammer_debug_btree_elm(cursor, elm, "ITERATE", 0xffff);
350 * We hit an internal element that we could skip as part of a mirroring
351 * scan. Calculate the entire range being skipped.
353 * It is important to include any gaps between the parent's left_bound
354 * and the node's left_bound, and same goes for the right side.
357 hammer_cursor_mirror_filter(hammer_cursor_t cursor)
359 struct hammer_cmirror *cmirror;
360 hammer_node_ondisk_t ondisk;
361 hammer_btree_elm_t elm;
363 ondisk = cursor->node->ondisk;
364 cmirror = cursor->cmirror;
367 * Calculate the skipped range
369 elm = &ondisk->elms[cursor->index];
370 if (cursor->index == 0)
371 cmirror->skip_beg = *cursor->left_bound;
373 cmirror->skip_beg = elm->internal.base;
374 while (cursor->index < ondisk->count) {
375 if (elm->internal.mirror_tid >= cmirror->mirror_tid)
380 if (cursor->index == ondisk->count)
381 cmirror->skip_end = *cursor->right_bound;
383 cmirror->skip_end = elm->internal.base;
386 * clip the returned result.
388 if (hammer_btree_cmp(&cmirror->skip_beg, &cursor->key_beg) < 0)
389 cmirror->skip_beg = cursor->key_beg;
390 if (hammer_btree_cmp(&cmirror->skip_end, &cursor->key_end) > 0)
391 cmirror->skip_end = cursor->key_end;
395 * Iterate in the reverse direction. This is used by the pruning code to
396 * avoid overlapping records.
399 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
401 hammer_node_ondisk_t node;
402 hammer_btree_elm_t elm;
408 /* mirror filtering not supported for reverse iteration */
409 KKASSERT ((cursor->flags & HAMMER_CURSOR_MIRROR_FILTERED) == 0);
412 * Skip past the current record. For various reasons the cursor
413 * may end up set to -1 or set to point at the end of the current
414 * node. These cases must be addressed.
416 node = cursor->node->ondisk;
419 if (cursor->index != -1 &&
420 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
423 if (cursor->index == cursor->node->ondisk->count)
427 * HAMMER can wind up being cpu-bound.
429 hmp = cursor->trans->hmp;
430 if (++hmp->check_yield > hammer_yield_check) {
431 hmp->check_yield = 0;
436 * Loop until an element is found or we are done.
439 ++hammer_stats_btree_iterations;
440 hammer_flusher_clean_loose_ios(hmp);
443 * We iterate up the tree and then index over one element
444 * while we are at the last element in the current node.
446 if (cursor->index == -1) {
447 error = hammer_cursor_up(cursor);
449 cursor->index = 0; /* sanity */
452 /* reload stale pointer */
453 node = cursor->node->ondisk;
454 KKASSERT(cursor->index != node->count);
460 * Check internal or leaf element. Determine if the record
461 * at the cursor has gone beyond the end of our range.
463 * We recurse down through internal nodes.
465 KKASSERT(cursor->index != node->count);
466 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
467 elm = &node->elms[cursor->index];
469 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
470 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
471 if (hammer_debug_btree) {
472 hammer_debug_btree_elm(cursor, elm, "BRACKETL", r);
473 hammer_debug_btree_elm(cursor, elm + 1, "BRACKETR", s);
482 * It shouldn't be possible to be seeked past key_end,
483 * even if the cursor got moved to a parent.
490 KKASSERT(elm->internal.subtree_offset != 0);
492 error = hammer_cursor_down(cursor);
495 KKASSERT(cursor->index == 0);
496 /* reload stale pointer */
497 node = cursor->node->ondisk;
499 /* this can assign -1 if the leaf was empty */
500 cursor->index = node->count - 1;
503 elm = &node->elms[cursor->index];
504 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
505 if (hammer_debug_btree) {
506 hammer_debug_btree_elm(cursor, elm, "ELEMENTR", s);
514 * It shouldn't be possible to be seeked past key_end,
515 * even if the cursor got moved to a parent.
517 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
522 switch(elm->leaf.base.btype) {
523 case HAMMER_BTREE_TYPE_RECORD:
524 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
525 hammer_btree_chkts(cursor->asof, &elm->base)) {
542 if (hammer_debug_btree) {
543 elm = &cursor->node->ondisk->elms[cursor->index];
544 hammer_debug_btree_elm(cursor, elm, "ITERATER", 0xffff);
552 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
553 * could not be found, EDEADLK if inserting and a retry is needed, and a
554 * fatal error otherwise. When retrying, the caller must terminate the
555 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
557 * The cursor is suitably positioned for a deletion on success, and suitably
558 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
561 * The cursor may begin anywhere, the search will traverse the tree in
562 * either direction to locate the requested element.
564 * Most of the logic implementing historical searches is handled here. We
565 * do an initial lookup with create_tid set to the asof TID. Due to the
566 * way records are laid out, a backwards iteration may be required if
567 * ENOENT is returned to locate the historical record. Here's the
570 * create_tid: 10 15 20
574 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
575 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
576 * not visible and thus causes ENOENT to be returned. We really need
577 * to check record 11 in LEAF1. If it also fails then the search fails
578 * (e.g. it might represent the range 11-16 and thus still not match our
579 * AS-OF timestamp of 17). Note that LEAF1 could be empty, requiring
580 * further iterations.
582 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
583 * and the cursor->create_check TID if an iteration might be needed.
584 * In the above example create_check would be set to 14.
587 hammer_btree_lookup(hammer_cursor_t cursor)
591 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
592 KKASSERT ((cursor->flags & HAMMER_CURSOR_INSERT) == 0 ||
593 cursor->trans->sync_lock_refs > 0);
594 ++hammer_stats_btree_lookups;
595 if (cursor->flags & HAMMER_CURSOR_ASOF) {
596 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
597 cursor->key_beg.create_tid = cursor->asof;
599 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
600 error = btree_search(cursor, 0);
601 if (error != ENOENT ||
602 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
605 * Stop if error other then ENOENT.
606 * Stop if ENOENT and not special case.
610 if (hammer_debug_btree) {
611 kprintf("CREATE_CHECK %016llx\n",
612 (long long)cursor->create_check);
614 cursor->key_beg.create_tid = cursor->create_check;
618 error = btree_search(cursor, 0);
621 error = hammer_btree_extract(cursor, cursor->flags);
626 * Execute the logic required to start an iteration. The first record
627 * located within the specified range is returned and iteration control
628 * flags are adjusted for successive hammer_btree_iterate() calls.
630 * Set ATEDISK so a low-level caller can call btree_first/btree_iterate
631 * in a loop without worrying about it. Higher-level merged searches will
632 * adjust the flag appropriately.
635 hammer_btree_first(hammer_cursor_t cursor)
639 error = hammer_btree_lookup(cursor);
640 if (error == ENOENT) {
641 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
642 error = hammer_btree_iterate(cursor);
644 cursor->flags |= HAMMER_CURSOR_ATEDISK;
649 * Similarly but for an iteration in the reverse direction.
651 * Set ATEDISK when iterating backwards to skip the current entry,
652 * which after an ENOENT lookup will be pointing beyond our end point.
654 * Set ATEDISK so a low-level caller can call btree_last/btree_iterate_reverse
655 * in a loop without worrying about it. Higher-level merged searches will
656 * adjust the flag appropriately.
659 hammer_btree_last(hammer_cursor_t cursor)
661 struct hammer_base_elm save;
664 save = cursor->key_beg;
665 cursor->key_beg = cursor->key_end;
666 error = hammer_btree_lookup(cursor);
667 cursor->key_beg = save;
668 if (error == ENOENT ||
669 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
670 cursor->flags |= HAMMER_CURSOR_ATEDISK;
671 error = hammer_btree_iterate_reverse(cursor);
673 cursor->flags |= HAMMER_CURSOR_ATEDISK;
678 * Extract the record and/or data associated with the cursor's current
679 * position. Any prior record or data stored in the cursor is replaced.
681 * NOTE: All extractions occur at the leaf of the B-Tree.
684 hammer_btree_extract(hammer_cursor_t cursor, int flags)
686 hammer_node_ondisk_t node;
687 hammer_btree_elm_t elm;
688 hammer_off_t data_off;
694 * Certain types of corruption can result in a NULL node pointer.
696 if (cursor->node == NULL) {
697 kprintf("HAMMER: NULL cursor->node, filesystem might "
698 "have gotten corrupted\n");
703 * The case where the data reference resolves to the same buffer
704 * as the record reference must be handled.
706 node = cursor->node->ondisk;
707 elm = &node->elms[cursor->index];
709 hmp = cursor->node->hmp;
712 * There is nothing to extract for an internal element.
714 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
718 * Only record types have data.
720 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
721 cursor->leaf = &elm->leaf;
723 if ((flags & HAMMER_CURSOR_GET_DATA) == 0)
725 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
727 data_off = elm->leaf.data_offset;
728 data_len = elm->leaf.data_len;
735 KKASSERT(data_len >= 0 && data_len <= HAMMER_XBUFSIZE);
736 cursor->data = hammer_bread_ext(hmp, data_off, data_len,
737 &error, &cursor->data_buffer);
740 * Mark the data buffer as not being meta-data if it isn't
741 * meta-data (sometimes bulk data is accessed via a volume
745 switch(elm->leaf.base.rec_type) {
746 case HAMMER_RECTYPE_DATA:
747 case HAMMER_RECTYPE_DB:
748 if ((data_off & HAMMER_ZONE_LARGE_DATA) == 0)
750 if (hammer_double_buffer == 0 ||
751 (cursor->flags & HAMMER_CURSOR_NOSWAPCACHE)) {
752 hammer_io_notmeta(cursor->data_buffer);
761 * Deal with CRC errors on the extracted data.
764 hammer_crc_test_leaf(cursor->data, &elm->leaf) == 0) {
765 kprintf("CRC DATA @ %016llx/%d FAILED\n",
766 (long long)elm->leaf.data_offset, elm->leaf.data_len);
767 if (hammer_debug_critical)
768 Debugger("CRC FAILED: DATA");
769 if (cursor->trans->flags & HAMMER_TRANSF_CRCDOM)
770 error = EDOM; /* less critical (mirroring) */
772 error = EIO; /* critical */
779 * Insert a leaf element into the B-Tree at the current cursor position.
780 * The cursor is positioned such that the element at and beyond the cursor
781 * are shifted to make room for the new record.
783 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
784 * flag set and that call must return ENOENT before this function can be
785 * called. ENOSPC is returned if there is no room to insert a new record.
787 * The caller may depend on the cursor's exclusive lock after return to
788 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
791 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_leaf_elm_t elm,
794 hammer_node_ondisk_t node;
799 if ((error = hammer_cursor_upgrade_node(cursor)) != 0)
801 ++hammer_stats_btree_inserts;
804 * Insert the element at the leaf node and update the count in the
805 * parent. It is possible for parent to be NULL, indicating that
806 * the filesystem's ROOT B-Tree node is a leaf itself, which is
807 * possible. The root inode can never be deleted so the leaf should
810 * Remember that leaf nodes do not have boundaries.
812 hammer_modify_node_all(cursor->trans, cursor->node);
813 node = cursor->node->ondisk;
815 KKASSERT(elm->base.btype != 0);
816 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
817 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
818 if (i != node->count) {
819 bcopy(&node->elms[i], &node->elms[i+1],
820 (node->count - i) * sizeof(*elm));
822 node->elms[i].leaf = *elm;
824 hammer_cursor_inserted_element(cursor->node, i);
827 * Update the leaf node's aggregate mirror_tid for mirroring
830 if (node->mirror_tid < elm->base.delete_tid) {
831 node->mirror_tid = elm->base.delete_tid;
834 if (node->mirror_tid < elm->base.create_tid) {
835 node->mirror_tid = elm->base.create_tid;
838 hammer_modify_node_done(cursor->node);
841 * Debugging sanity checks.
843 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->base) <= 0);
844 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->base) > 0);
846 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->base) < 0);
848 if (i != node->count - 1)
849 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->base) > 0);
855 * Delete a record from the B-Tree at the current cursor position.
856 * The cursor is positioned such that the current element is the one
859 * On return the cursor will be positioned after the deleted element and
860 * MAY point to an internal node. It will be suitable for the continuation
861 * of an iteration but not for an insertion or deletion.
863 * Deletions will attempt to partially rebalance the B-Tree in an upward
864 * direction, but will terminate rather then deadlock. Empty internal nodes
865 * are never allowed by a deletion which deadlocks may end up giving us an
866 * empty leaf. The pruner will clean up and rebalance the tree.
868 * This function can return EDEADLK, requiring the caller to retry the
869 * operation after clearing the deadlock.
871 * This function will store the number of deleted btree nodes in *ndelete
872 * if ndelete is not NULL.
875 hammer_btree_delete(hammer_cursor_t cursor, int *ndelete)
877 hammer_node_ondisk_t ondisk;
879 hammer_node_t parent __debugvar;
883 KKASSERT (cursor->trans->sync_lock_refs > 0);
886 if ((error = hammer_cursor_upgrade(cursor)) != 0)
888 ++hammer_stats_btree_deletes;
891 * Delete the element from the leaf node.
893 * Remember that leaf nodes do not have boundaries.
896 ondisk = node->ondisk;
899 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
900 KKASSERT(i >= 0 && i < ondisk->count);
901 hammer_modify_node_all(cursor->trans, node);
902 if (i + 1 != ondisk->count) {
903 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
904 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
907 hammer_modify_node_done(node);
908 hammer_cursor_deleted_element(node, i);
911 * Validate local parent
913 if (ondisk->parent) {
914 parent = cursor->parent;
916 KKASSERT(parent != NULL);
917 KKASSERT(parent->node_offset == ondisk->parent);
921 * If the leaf becomes empty it must be detached from the parent,
922 * potentially recursing through to the filesystem root.
924 * This may reposition the cursor at one of the parent's of the
927 * Ignore deadlock errors, that simply means that btree_remove
928 * was unable to recurse and had to leave us with an empty leaf.
930 KKASSERT(cursor->index <= ondisk->count);
931 if (ondisk->count == 0) {
932 error = btree_remove(cursor, ndelete);
933 if (error == EDEADLK)
938 KKASSERT(cursor->parent == NULL ||
939 cursor->parent_index < cursor->parent->ondisk->count);
944 * PRIMARY B-TREE SEARCH SUPPORT PROCEDURE
946 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
948 * The search can begin ANYWHERE in the B-Tree. As a first step the search
949 * iterates up the tree as necessary to properly position itself prior to
950 * actually doing the sarch.
952 * INSERTIONS: The search will split full nodes and leaves on its way down
953 * and guarentee that the leaf it ends up on is not full. If we run out
954 * of space the search continues to the leaf, but ENOSPC is returned.
956 * The search is only guarenteed to end up on a leaf if an error code of 0
957 * is returned, or if inserting and an error code of ENOENT is returned.
958 * Otherwise it can stop at an internal node. On success a search returns
961 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
962 * filesystem, and it is not simple code. Please note the following facts:
964 * - Internal node recursions have a boundary on the left AND right. The
965 * right boundary is non-inclusive. The create_tid is a generic part
966 * of the key for internal nodes.
968 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
969 * historical search. ASOF and INSERT are mutually exclusive. When
970 * doing an as-of lookup btree_search() checks for a right-edge boundary
971 * case. If while recursing down the left-edge differs from the key
972 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
973 * with cursor->create_check. This is used by btree_lookup() to iterate.
974 * The iteration backwards because as-of searches can wind up going
975 * down the wrong branch of the B-Tree.
979 btree_search(hammer_cursor_t cursor, int flags)
981 hammer_node_ondisk_t node;
982 hammer_btree_elm_t elm;
989 flags |= cursor->flags;
990 ++hammer_stats_btree_searches;
992 if (hammer_debug_btree) {
993 hammer_debug_btree_elm(cursor,
994 (hammer_btree_elm_t)&cursor->key_beg,
997 hammer_debug_btree_parent(cursor, "SEARCHP");
1001 * Move our cursor up the tree until we find a node whos range covers
1002 * the key we are trying to locate.
1004 * The left bound is inclusive, the right bound is non-inclusive.
1005 * It is ok to cursor up too far.
1008 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
1009 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
1010 if (r >= 0 && s < 0)
1012 KKASSERT(cursor->parent);
1013 ++hammer_stats_btree_iterations;
1014 error = hammer_cursor_up(cursor);
1020 * The delete-checks below are based on node, not parent. Set the
1021 * initial delete-check based on the parent.
1024 KKASSERT(cursor->left_bound->create_tid != 1);
1025 cursor->create_check = cursor->left_bound->create_tid - 1;
1026 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
1030 * We better have ended up with a node somewhere.
1032 KKASSERT(cursor->node != NULL);
1035 * If we are inserting we can't start at a full node if the parent
1036 * is also full (because there is no way to split the node),
1037 * continue running up the tree until the requirement is satisfied
1038 * or we hit the root of the filesystem.
1040 * (If inserting we aren't doing an as-of search so we don't have
1041 * to worry about create_check).
1043 while (flags & HAMMER_CURSOR_INSERT) {
1044 if (btree_node_is_full(cursor->node->ondisk) == 0)
1046 if (cursor->node->ondisk->parent == 0 ||
1047 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
1050 ++hammer_stats_btree_iterations;
1051 error = hammer_cursor_up(cursor);
1052 /* node may have become stale */
1058 * Push down through internal nodes to locate the requested key.
1060 node = cursor->node->ondisk;
1061 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
1063 * Scan the node to find the subtree index to push down into.
1064 * We go one-past, then back-up.
1066 * We must proactively remove deleted elements which may
1067 * have been left over from a deadlocked btree_remove().
1069 * The left and right boundaries are included in the loop
1070 * in order to detect edge cases.
1072 * If the separator only differs by create_tid (r == 1)
1073 * and we are doing an as-of search, we may end up going
1074 * down a branch to the left of the one containing the
1075 * desired key. This requires numerous special cases.
1077 ++hammer_stats_btree_iterations;
1078 if (hammer_debug_btree) {
1079 kprintf("SEARCH-I %016llx count=%d\n",
1080 (long long)cursor->node->node_offset,
1085 * Try to shortcut the search before dropping into the
1086 * linear loop. Locate the first node where r <= 1.
1088 i = hammer_btree_search_node(&cursor->key_beg, node);
1089 while (i <= node->count) {
1090 ++hammer_stats_btree_elements;
1091 elm = &node->elms[i];
1092 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
1093 if (hammer_debug_btree > 2) {
1094 kprintf(" IELM %p [%d] r=%d\n",
1095 &node->elms[i], i, r);
1100 KKASSERT(elm->base.create_tid != 1);
1101 cursor->create_check = elm->base.create_tid - 1;
1102 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
1106 if (hammer_debug_btree) {
1107 kprintf("SEARCH-I preI=%d/%d r=%d\n",
1112 * The first two cases (i == 0 or i == node->count + 1)
1113 * occur when the parent's idea of the boundary
1114 * is wider then the child's idea of the boundary, and
1115 * require special handling. If not inserting we can
1116 * terminate the search early for these cases but the
1117 * child's boundaries cannot be unconditionally modified.
1119 * The last case (neither of the above) fits in child's
1120 * idea of the boundary, so we can simply push down the
1125 * If i == 0 the search terminated to the LEFT of the
1126 * left_boundary but to the RIGHT of the parent's left
1131 elm = &node->elms[0];
1134 * If we aren't inserting we can stop here.
1136 if ((flags & (HAMMER_CURSOR_INSERT |
1137 HAMMER_CURSOR_PRUNING)) == 0) {
1143 * Correct a left-hand boundary mismatch.
1145 * We can only do this if we can upgrade the lock,
1146 * and synchronized as a background cursor (i.e.
1147 * inserting or pruning).
1149 * WARNING: We can only do this if inserting, i.e.
1150 * we are running on the backend.
1152 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1154 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1155 hammer_modify_node_field(cursor->trans, cursor->node,
1157 save = node->elms[0].base.btype;
1158 node->elms[0].base = *cursor->left_bound;
1159 node->elms[0].base.btype = save;
1160 hammer_modify_node_done(cursor->node);
1161 } else if (i == node->count + 1) {
1163 * If i == node->count + 1 the search terminated to
1164 * the RIGHT of the right boundary but to the LEFT
1165 * of the parent's right boundary. If we aren't
1166 * inserting we can stop here.
1168 * Note that the last element in this case is
1169 * elms[i-2] prior to adjustments to 'i'.
1172 if ((flags & (HAMMER_CURSOR_INSERT |
1173 HAMMER_CURSOR_PRUNING)) == 0) {
1179 * Correct a right-hand boundary mismatch.
1180 * (actual push-down record is i-2 prior to
1181 * adjustments to i).
1183 * We can only do this if we can upgrade the lock,
1184 * and synchronized as a background cursor (i.e.
1185 * inserting or pruning).
1187 * WARNING: We can only do this if inserting, i.e.
1188 * we are running on the backend.
1190 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1192 elm = &node->elms[i];
1193 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1194 hammer_modify_node(cursor->trans, cursor->node,
1195 &elm->base, sizeof(elm->base));
1196 elm->base = *cursor->right_bound;
1197 hammer_modify_node_done(cursor->node);
1201 * The push-down index is now i - 1. If we had
1202 * terminated on the right boundary this will point
1203 * us at the last element.
1208 elm = &node->elms[i];
1210 if (hammer_debug_btree) {
1211 hammer_debug_btree_elm(cursor, elm, "RESULT-I", 0xffff);
1215 * We better have a valid subtree offset.
1217 KKASSERT(elm->internal.subtree_offset != 0);
1220 * Handle insertion and deletion requirements.
1222 * If inserting split full nodes. The split code will
1223 * adjust cursor->node and cursor->index if the current
1224 * index winds up in the new node.
1226 * If inserting and a left or right edge case was detected,
1227 * we cannot correct the left or right boundary and must
1228 * prepend and append an empty leaf node in order to make
1229 * the boundary correction.
1231 * If we run out of space we set enospc but continue on
1234 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1235 if (btree_node_is_full(node)) {
1236 error = btree_split_internal(cursor);
1238 if (error != ENOSPC)
1243 * reload stale pointers
1246 node = cursor->node->ondisk;
1251 * Push down (push into new node, existing node becomes
1252 * the parent) and continue the search.
1254 error = hammer_cursor_down(cursor);
1255 /* node may have become stale */
1258 node = cursor->node->ondisk;
1262 * We are at a leaf, do a linear search of the key array.
1264 * On success the index is set to the matching element and 0
1267 * On failure the index is set to the insertion point and ENOENT
1270 * Boundaries are not stored in leaf nodes, so the index can wind
1271 * up to the left of element 0 (index == 0) or past the end of
1272 * the array (index == node->count). It is also possible that the
1273 * leaf might be empty.
1275 ++hammer_stats_btree_iterations;
1276 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1277 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1278 if (hammer_debug_btree) {
1279 kprintf("SEARCH-L %016llx count=%d\n",
1280 (long long)cursor->node->node_offset,
1285 * Try to shortcut the search before dropping into the
1286 * linear loop. Locate the first node where r <= 1.
1288 i = hammer_btree_search_node(&cursor->key_beg, node);
1289 while (i < node->count) {
1290 ++hammer_stats_btree_elements;
1291 elm = &node->elms[i];
1293 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1295 if (hammer_debug_btree > 1)
1296 kprintf(" LELM %p [%d] r=%d\n", &node->elms[i], i, r);
1299 * We are at a record element. Stop if we've flipped past
1300 * key_beg, not counting the create_tid test. Allow the
1301 * r == 1 case (key_beg > element but differs only by its
1302 * create_tid) to fall through to the AS-OF check.
1304 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1314 * Check our as-of timestamp against the element.
1316 if (flags & HAMMER_CURSOR_ASOF) {
1317 if (hammer_btree_chkts(cursor->asof,
1318 &node->elms[i].base) != 0) {
1324 if (r > 0) { /* can only be +1 */
1332 if (hammer_debug_btree) {
1333 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1334 (long long)cursor->node->node_offset, i);
1340 * The search of the leaf node failed. i is the insertion point.
1343 if (hammer_debug_btree) {
1344 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1345 (long long)cursor->node->node_offset, i);
1349 * No exact match was found, i is now at the insertion point.
1351 * If inserting split a full leaf before returning. This
1352 * may have the side effect of adjusting cursor->node and
1356 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1357 btree_node_is_full(node)) {
1358 error = btree_split_leaf(cursor);
1360 if (error != ENOSPC)
1365 * reload stale pointers
1369 node = &cursor->node->internal;
1374 * We reached a leaf but did not find the key we were looking for.
1375 * If this is an insert we will be properly positioned for an insert
1376 * (ENOENT) or unable to insert (ENOSPC).
1378 error = enospc ? ENOSPC : ENOENT;
1384 * Heuristical search for the first element whos comparison is <= 1. May
1385 * return an index whos compare result is > 1 but may only return an index
1386 * whos compare result is <= 1 if it is the first element with that result.
1389 hammer_btree_search_node(hammer_base_elm_t elm, hammer_node_ondisk_t node)
1397 * Don't bother if the node does not have very many elements
1402 i = b + (s - b) / 2;
1403 ++hammer_stats_btree_elements;
1404 r = hammer_btree_cmp(elm, &node->elms[i].leaf.base);
1415 /************************************************************************
1416 * SPLITTING AND MERGING *
1417 ************************************************************************
1419 * These routines do all the dirty work required to split and merge nodes.
1423 * Split an internal node into two nodes and move the separator at the split
1424 * point to the parent.
1426 * (cursor->node, cursor->index) indicates the element the caller intends
1427 * to push into. We will adjust node and index if that element winds
1428 * up in the split node.
1430 * If we are at the root of the filesystem a new root must be created with
1431 * two elements, one pointing to the original root and one pointing to the
1432 * newly allocated split node.
1436 btree_split_internal(hammer_cursor_t cursor)
1438 hammer_node_ondisk_t ondisk;
1440 hammer_node_t parent;
1441 hammer_node_t new_node;
1442 hammer_btree_elm_t elm;
1443 hammer_btree_elm_t parent_elm;
1444 struct hammer_node_lock lockroot;
1445 hammer_mount_t hmp = cursor->trans->hmp;
1451 const int esize = sizeof(*elm);
1453 hammer_node_lock_init(&lockroot, cursor->node);
1454 error = hammer_btree_lock_children(cursor, 1, &lockroot, NULL);
1457 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1459 ++hammer_stats_btree_splits;
1462 * Calculate the split point. If the insertion point is at the
1463 * end of the leaf we adjust the split point significantly to the
1464 * right to try to optimize node fill and flag it. If we hit
1465 * that same leaf again our heuristic failed and we don't try
1466 * to optimize node fill (it could lead to a degenerate case).
1468 node = cursor->node;
1469 ondisk = node->ondisk;
1470 KKASSERT(ondisk->count > 4);
1471 if (cursor->index == ondisk->count &&
1472 (node->flags & HAMMER_NODE_NONLINEAR) == 0) {
1473 split = (ondisk->count + 1) * 3 / 4;
1474 node->flags |= HAMMER_NODE_NONLINEAR;
1477 * We are splitting but elms[split] will be promoted to
1478 * the parent, leaving the right hand node with one less
1479 * element. If the insertion point will be on the
1480 * left-hand side adjust the split point to give the
1481 * right hand side one additional node.
1483 split = (ondisk->count + 1) / 2;
1484 if (cursor->index <= split)
1489 * If we are at the root of the filesystem, create a new root node
1490 * with 1 element and split normally. Avoid making major
1491 * modifications until we know the whole operation will work.
1493 if (ondisk->parent == 0) {
1494 parent = hammer_alloc_btree(cursor->trans, 0, &error);
1497 hammer_lock_ex(&parent->lock);
1498 hammer_modify_node_noundo(cursor->trans, parent);
1499 ondisk = parent->ondisk;
1502 ondisk->mirror_tid = node->ondisk->mirror_tid;
1503 ondisk->signature = node->ondisk->signature;
1504 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1505 ondisk->elms[0].base = hmp->root_btree_beg;
1506 ondisk->elms[0].base.btype = node->ondisk->type;
1507 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1508 ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
1509 ondisk->elms[1].base = hmp->root_btree_end;
1510 hammer_modify_node_done(parent);
1512 parent_index = 0; /* index of current node in parent */
1515 parent = cursor->parent;
1516 parent_index = cursor->parent_index;
1520 * Split node into new_node at the split point.
1522 * B O O O P N N B <-- P = node->elms[split] (index 4)
1523 * 0 1 2 3 4 5 6 <-- subtree indices
1528 * B O O O B B N N B <--- inner boundary points are 'P'
1531 new_node = hammer_alloc_btree(cursor->trans, 0, &error);
1532 if (new_node == NULL) {
1534 hammer_unlock(&parent->lock);
1535 hammer_delete_node(cursor->trans, parent);
1536 hammer_rel_node(parent);
1540 hammer_lock_ex(&new_node->lock);
1543 * Create the new node. P becomes the left-hand boundary in the
1544 * new node. Copy the right-hand boundary as well.
1546 * elm is the new separator.
1548 hammer_modify_node_noundo(cursor->trans, new_node);
1549 hammer_modify_node_all(cursor->trans, node);
1550 ondisk = node->ondisk;
1551 elm = &ondisk->elms[split];
1552 bcopy(elm, &new_node->ondisk->elms[0],
1553 (ondisk->count - split + 1) * esize); /* +1 for boundary */
1554 new_node->ondisk->count = ondisk->count - split;
1555 new_node->ondisk->parent = parent->node_offset;
1556 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1557 new_node->ondisk->mirror_tid = ondisk->mirror_tid;
1558 KKASSERT(ondisk->type == new_node->ondisk->type);
1559 hammer_cursor_split_node(node, new_node, split);
1562 * Cleanup the original node. Elm (P) becomes the new boundary,
1563 * its subtree_offset was moved to the new node. If we had created
1564 * a new root its parent pointer may have changed.
1566 elm->internal.subtree_offset = 0;
1567 ondisk->count = split;
1570 * Insert the separator into the parent, fixup the parent's
1571 * reference to the original node, and reference the new node.
1572 * The separator is P.
1574 * Remember that base.count does not include the right-hand boundary.
1576 hammer_modify_node_all(cursor->trans, parent);
1577 ondisk = parent->ondisk;
1578 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1579 parent_elm = &ondisk->elms[parent_index+1];
1580 bcopy(parent_elm, parent_elm + 1,
1581 (ondisk->count - parent_index) * esize);
1584 * Why not use hammer_make_separator() here ?
1586 parent_elm->internal.base = elm->base; /* separator P */
1587 parent_elm->internal.base.btype = new_node->ondisk->type;
1588 parent_elm->internal.subtree_offset = new_node->node_offset;
1589 parent_elm->internal.mirror_tid = new_node->ondisk->mirror_tid;
1591 hammer_modify_node_done(parent);
1592 hammer_cursor_inserted_element(parent, parent_index + 1);
1595 * The children of new_node need their parent pointer set to new_node.
1596 * The children have already been locked by
1597 * hammer_btree_lock_children().
1599 for (i = 0; i < new_node->ondisk->count; ++i) {
1600 elm = &new_node->ondisk->elms[i];
1601 error = btree_set_parent(cursor->trans, new_node, elm);
1603 panic("btree_split_internal: btree-fixup problem");
1606 hammer_modify_node_done(new_node);
1609 * The filesystem's root B-Tree pointer may have to be updated.
1612 hammer_volume_t volume;
1614 volume = hammer_get_root_volume(hmp, &error);
1615 KKASSERT(error == 0);
1617 hammer_modify_volume_field(cursor->trans, volume,
1619 volume->ondisk->vol0_btree_root = parent->node_offset;
1620 hammer_modify_volume_done(volume);
1621 node->ondisk->parent = parent->node_offset;
1622 /* node->ondisk->signature = 0; */
1623 if (cursor->parent) {
1624 hammer_unlock(&cursor->parent->lock);
1625 hammer_rel_node(cursor->parent);
1627 cursor->parent = parent; /* lock'd and ref'd */
1628 hammer_rel_volume(volume, 0);
1630 hammer_modify_node_done(node);
1633 * Ok, now adjust the cursor depending on which element the original
1634 * index was pointing at. If we are >= the split point the push node
1635 * is now in the new node.
1637 * NOTE: If we are at the split point itself we cannot stay with the
1638 * original node because the push index will point at the right-hand
1639 * boundary, which is illegal.
1641 * NOTE: The cursor's parent or parent_index must be adjusted for
1642 * the case where a new parent (new root) was created, and the case
1643 * where the cursor is now pointing at the split node.
1645 if (cursor->index >= split) {
1646 cursor->parent_index = parent_index + 1;
1647 cursor->index -= split;
1648 hammer_unlock(&cursor->node->lock);
1649 hammer_rel_node(cursor->node);
1650 cursor->node = new_node; /* locked and ref'd */
1652 cursor->parent_index = parent_index;
1653 hammer_unlock(&new_node->lock);
1654 hammer_rel_node(new_node);
1658 * Fixup left and right bounds
1660 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1661 cursor->left_bound = &parent_elm[0].internal.base;
1662 cursor->right_bound = &parent_elm[1].internal.base;
1663 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1664 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1665 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1666 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1669 hammer_btree_unlock_children(cursor->trans->hmp, &lockroot, NULL);
1670 hammer_cursor_downgrade(cursor);
1675 * Same as the above, but splits a full leaf node.
1679 btree_split_leaf(hammer_cursor_t cursor)
1681 hammer_node_ondisk_t ondisk;
1682 hammer_node_t parent;
1685 hammer_node_t new_leaf;
1686 hammer_btree_elm_t elm;
1687 hammer_btree_elm_t parent_elm;
1688 hammer_base_elm_t mid_boundary;
1693 const size_t esize = sizeof(*elm);
1695 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1697 ++hammer_stats_btree_splits;
1699 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1700 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1701 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1702 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1705 * Calculate the split point. If the insertion point is at the
1706 * end of the leaf we adjust the split point significantly to the
1707 * right to try to optimize node fill and flag it. If we hit
1708 * that same leaf again our heuristic failed and we don't try
1709 * to optimize node fill (it could lead to a degenerate case).
1711 leaf = cursor->node;
1712 ondisk = leaf->ondisk;
1713 KKASSERT(ondisk->count > 4);
1714 if (cursor->index == ondisk->count &&
1715 (leaf->flags & HAMMER_NODE_NONLINEAR) == 0) {
1716 split = (ondisk->count + 1) * 3 / 4;
1717 leaf->flags |= HAMMER_NODE_NONLINEAR;
1719 split = (ondisk->count + 1) / 2;
1724 * If the insertion point is at the split point shift the
1725 * split point left so we don't have to worry about
1727 if (cursor->index == split)
1730 KKASSERT(split > 0 && split < ondisk->count);
1735 elm = &ondisk->elms[split];
1737 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1738 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1739 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1740 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1743 * If we are at the root of the tree, create a new root node with
1744 * 1 element and split normally. Avoid making major modifications
1745 * until we know the whole operation will work.
1747 if (ondisk->parent == 0) {
1748 parent = hammer_alloc_btree(cursor->trans, 0, &error);
1751 hammer_lock_ex(&parent->lock);
1752 hammer_modify_node_noundo(cursor->trans, parent);
1753 ondisk = parent->ondisk;
1756 ondisk->mirror_tid = leaf->ondisk->mirror_tid;
1757 ondisk->signature = leaf->ondisk->signature;
1758 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1759 ondisk->elms[0].base = hmp->root_btree_beg;
1760 ondisk->elms[0].base.btype = leaf->ondisk->type;
1761 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1762 ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
1763 ondisk->elms[1].base = hmp->root_btree_end;
1764 hammer_modify_node_done(parent);
1766 parent_index = 0; /* insertion point in parent */
1769 parent = cursor->parent;
1770 parent_index = cursor->parent_index;
1774 * Split leaf into new_leaf at the split point. Select a separator
1775 * value in-between the two leafs but with a bent towards the right
1776 * leaf since comparisons use an 'elm >= separator' inequality.
1785 new_leaf = hammer_alloc_btree(cursor->trans, 0, &error);
1786 if (new_leaf == NULL) {
1788 hammer_unlock(&parent->lock);
1789 hammer_delete_node(cursor->trans, parent);
1790 hammer_rel_node(parent);
1794 hammer_lock_ex(&new_leaf->lock);
1797 * Create the new node and copy the leaf elements from the split
1798 * point on to the new node.
1800 hammer_modify_node_all(cursor->trans, leaf);
1801 hammer_modify_node_noundo(cursor->trans, new_leaf);
1802 ondisk = leaf->ondisk;
1803 elm = &ondisk->elms[split];
1804 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1805 new_leaf->ondisk->count = ondisk->count - split;
1806 new_leaf->ondisk->parent = parent->node_offset;
1807 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1808 new_leaf->ondisk->mirror_tid = ondisk->mirror_tid;
1809 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1810 hammer_modify_node_done(new_leaf);
1811 hammer_cursor_split_node(leaf, new_leaf, split);
1814 * Cleanup the original node. Because this is a leaf node and
1815 * leaf nodes do not have a right-hand boundary, there
1816 * aren't any special edge cases to clean up. We just fixup the
1819 ondisk->count = split;
1822 * Insert the separator into the parent, fixup the parent's
1823 * reference to the original node, and reference the new node.
1824 * The separator is P.
1826 * Remember that base.count does not include the right-hand boundary.
1827 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1829 hammer_modify_node_all(cursor->trans, parent);
1830 ondisk = parent->ondisk;
1831 KKASSERT(split != 0);
1832 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1833 parent_elm = &ondisk->elms[parent_index+1];
1834 bcopy(parent_elm, parent_elm + 1,
1835 (ondisk->count - parent_index) * esize);
1838 * elm[-1] is the right-most elm in the original node.
1839 * elm[0] equals the left-most elm at index=0 in the new node.
1840 * parent_elm[-1] and parent_elm point to original and new node.
1841 * Update the parent_elm base to meet >elm[-1] and <=elm[0].
1843 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1844 parent_elm->internal.base.btype = new_leaf->ondisk->type;
1845 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1846 parent_elm->internal.mirror_tid = new_leaf->ondisk->mirror_tid;
1847 mid_boundary = &parent_elm->base;
1849 hammer_modify_node_done(parent);
1850 hammer_cursor_inserted_element(parent, parent_index + 1);
1853 * The filesystem's root B-Tree pointer may have to be updated.
1856 hammer_volume_t volume;
1858 volume = hammer_get_root_volume(hmp, &error);
1859 KKASSERT(error == 0);
1861 hammer_modify_volume_field(cursor->trans, volume,
1863 volume->ondisk->vol0_btree_root = parent->node_offset;
1864 hammer_modify_volume_done(volume);
1865 leaf->ondisk->parent = parent->node_offset;
1866 /* leaf->ondisk->signature = 0; */
1867 if (cursor->parent) {
1868 hammer_unlock(&cursor->parent->lock);
1869 hammer_rel_node(cursor->parent);
1871 cursor->parent = parent; /* lock'd and ref'd */
1872 hammer_rel_volume(volume, 0);
1874 hammer_modify_node_done(leaf);
1877 * Ok, now adjust the cursor depending on which element the original
1878 * index was pointing at. If we are >= the split point the push node
1879 * is now in the new node.
1881 * NOTE: If we are at the split point itself we need to select the
1882 * old or new node based on where key_beg's insertion point will be.
1883 * If we pick the wrong side the inserted element will wind up in
1884 * the wrong leaf node and outside that node's bounds.
1886 if (cursor->index > split ||
1887 (cursor->index == split &&
1888 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1889 cursor->parent_index = parent_index + 1;
1890 cursor->index -= split;
1891 hammer_unlock(&cursor->node->lock);
1892 hammer_rel_node(cursor->node);
1893 cursor->node = new_leaf;
1895 cursor->parent_index = parent_index;
1896 hammer_unlock(&new_leaf->lock);
1897 hammer_rel_node(new_leaf);
1901 * Fixup left and right bounds
1903 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1904 cursor->left_bound = &parent_elm[0].internal.base;
1905 cursor->right_bound = &parent_elm[1].internal.base;
1908 * Assert that the bounds are correct.
1910 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1911 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1912 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1913 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1914 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1915 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
1918 hammer_cursor_downgrade(cursor);
1925 * Recursively correct the right-hand boundary's create_tid to (tid) as
1926 * long as the rest of the key matches. We have to recurse upward in
1927 * the tree as well as down the left side of each parent's right node.
1929 * Return EDEADLK if we were only partially successful, forcing the caller
1930 * to try again. The original cursor is not modified. This routine can
1931 * also fail with EDEADLK if it is forced to throw away a portion of its
1934 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1937 TAILQ_ENTRY(hammer_rhb) entry;
1942 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1945 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1947 struct hammer_mount *hmp;
1948 struct hammer_rhb_list rhb_list;
1949 hammer_base_elm_t elm;
1950 hammer_node_t orig_node;
1951 struct hammer_rhb *rhb;
1955 TAILQ_INIT(&rhb_list);
1956 hmp = cursor->trans->hmp;
1959 * Save our position so we can restore it on return. This also
1960 * gives us a stable 'elm'.
1962 orig_node = cursor->node;
1963 hammer_ref_node(orig_node);
1964 hammer_lock_sh(&orig_node->lock);
1965 orig_index = cursor->index;
1966 elm = &orig_node->ondisk->elms[orig_index].base;
1969 * Now build a list of parents going up, allocating a rhb
1970 * structure for each one.
1972 while (cursor->parent) {
1974 * Stop if we no longer have any right-bounds to fix up
1976 if (elm->obj_id != cursor->right_bound->obj_id ||
1977 elm->rec_type != cursor->right_bound->rec_type ||
1978 elm->key != cursor->right_bound->key) {
1983 * Stop if the right-hand bound's create_tid does not
1984 * need to be corrected.
1986 if (cursor->right_bound->create_tid >= tid)
1989 rhb = kmalloc(sizeof(*rhb), hmp->m_misc, M_WAITOK|M_ZERO);
1990 rhb->node = cursor->parent;
1991 rhb->index = cursor->parent_index;
1992 hammer_ref_node(rhb->node);
1993 hammer_lock_sh(&rhb->node->lock);
1994 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1996 hammer_cursor_up(cursor);
2000 * now safely adjust the right hand bound for each rhb. This may
2001 * also require taking the right side of the tree and iterating down
2005 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2006 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
2009 TAILQ_REMOVE(&rhb_list, rhb, entry);
2010 hammer_unlock(&rhb->node->lock);
2011 hammer_rel_node(rhb->node);
2012 kfree(rhb, hmp->m_misc);
2014 switch (cursor->node->ondisk->type) {
2015 case HAMMER_BTREE_TYPE_INTERNAL:
2017 * Right-boundary for parent at internal node
2018 * is one element to the right of the element whos
2019 * right boundary needs adjusting. We must then
2020 * traverse down the left side correcting any left
2021 * bounds (which may now be too far to the left).
2024 error = hammer_btree_correct_lhb(cursor, tid);
2027 panic("hammer_btree_correct_rhb(): Bad node type");
2036 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2037 TAILQ_REMOVE(&rhb_list, rhb, entry);
2038 hammer_unlock(&rhb->node->lock);
2039 hammer_rel_node(rhb->node);
2040 kfree(rhb, hmp->m_misc);
2042 error = hammer_cursor_seek(cursor, orig_node, orig_index);
2043 hammer_unlock(&orig_node->lock);
2044 hammer_rel_node(orig_node);
2049 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
2050 * bound going downward starting at the current cursor position.
2052 * This function does not restore the cursor after use.
2055 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
2057 struct hammer_rhb_list rhb_list;
2058 hammer_base_elm_t elm;
2059 hammer_base_elm_t cmp;
2060 struct hammer_rhb *rhb;
2061 struct hammer_mount *hmp;
2064 TAILQ_INIT(&rhb_list);
2065 hmp = cursor->trans->hmp;
2067 cmp = &cursor->node->ondisk->elms[cursor->index].base;
2070 * Record the node and traverse down the left-hand side for all
2071 * matching records needing a boundary correction.
2075 rhb = kmalloc(sizeof(*rhb), hmp->m_misc, M_WAITOK|M_ZERO);
2076 rhb->node = cursor->node;
2077 rhb->index = cursor->index;
2078 hammer_ref_node(rhb->node);
2079 hammer_lock_sh(&rhb->node->lock);
2080 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
2082 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2084 * Nothing to traverse down if we are at the right
2085 * boundary of an internal node.
2087 if (cursor->index == cursor->node->ondisk->count)
2090 elm = &cursor->node->ondisk->elms[cursor->index].base;
2091 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
2093 panic("Illegal leaf record type %02x", elm->btype);
2095 error = hammer_cursor_down(cursor);
2099 elm = &cursor->node->ondisk->elms[cursor->index].base;
2100 if (elm->obj_id != cmp->obj_id ||
2101 elm->rec_type != cmp->rec_type ||
2102 elm->key != cmp->key) {
2105 if (elm->create_tid >= tid)
2111 * Now we can safely adjust the left-hand boundary from the bottom-up.
2112 * The last element we remove from the list is the caller's right hand
2113 * boundary, which must also be adjusted.
2115 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2116 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
2119 TAILQ_REMOVE(&rhb_list, rhb, entry);
2120 hammer_unlock(&rhb->node->lock);
2121 hammer_rel_node(rhb->node);
2122 kfree(rhb, hmp->m_misc);
2124 elm = &cursor->node->ondisk->elms[cursor->index].base;
2125 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2126 hammer_modify_node(cursor->trans, cursor->node,
2128 sizeof(elm->create_tid));
2129 elm->create_tid = tid;
2130 hammer_modify_node_done(cursor->node);
2132 panic("hammer_btree_correct_lhb(): Bad element type");
2139 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2140 TAILQ_REMOVE(&rhb_list, rhb, entry);
2141 hammer_unlock(&rhb->node->lock);
2142 hammer_rel_node(rhb->node);
2143 kfree(rhb, hmp->m_misc);
2151 * Attempt to remove the locked, empty or want-to-be-empty B-Tree node at
2152 * (cursor->node). Returns 0 on success, EDEADLK if we could not complete
2153 * the operation due to a deadlock, or some other error.
2155 * This routine is initially called with an empty leaf and may be
2156 * recursively called with single-element internal nodes.
2158 * It should also be noted that when removing empty leaves we must be sure
2159 * to test and update mirror_tid because another thread may have deadlocked
2160 * against us (or someone) trying to propagate it up and cannot retry once
2161 * the node has been deleted.
2163 * On return the cursor may end up pointing to an internal node, suitable
2164 * for further iteration but not for an immediate insertion or deletion.
2167 btree_remove(hammer_cursor_t cursor, int *ndelete)
2169 hammer_node_ondisk_t ondisk;
2170 hammer_btree_elm_t elm;
2172 hammer_node_t parent;
2173 const int esize = sizeof(*elm);
2176 node = cursor->node;
2179 * When deleting the root of the filesystem convert it to
2180 * an empty leaf node. Internal nodes cannot be empty.
2182 ondisk = node->ondisk;
2183 if (ondisk->parent == 0) {
2184 KKASSERT(cursor->parent == NULL);
2185 hammer_modify_node_all(cursor->trans, node);
2186 KKASSERT(ondisk == node->ondisk);
2187 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
2189 hammer_modify_node_done(node);
2194 parent = cursor->parent;
2197 * Attempt to remove the parent's reference to the child. If the
2198 * parent would become empty we have to recurse. If we fail we
2199 * leave the parent pointing to an empty leaf node.
2201 * We have to recurse successfully before we can delete the internal
2202 * node as it is illegal to have empty internal nodes. Even though
2203 * the operation may be aborted we must still fixup any unlocked
2204 * cursors as if we had deleted the element prior to recursing
2205 * (by calling hammer_cursor_deleted_element()) so those cursors
2206 * are properly forced up the chain by the recursion.
2208 if (parent->ondisk->count == 1) {
2210 * This special cursor_up_locked() call leaves the original
2211 * node exclusively locked and referenced, leaves the
2212 * original parent locked (as the new node), and locks the
2213 * new parent. It can return EDEADLK.
2215 * We cannot call hammer_cursor_removed_node() until we are
2216 * actually able to remove the node. If we did then tracked
2217 * cursors in the middle of iterations could be repointed
2218 * to a parent node. If this occurs they could end up
2219 * scanning newly inserted records into the node (that could
2220 * not be deleted) when they push down again.
2222 * Due to the way the recursion works the final parent is left
2223 * in cursor->parent after the recursion returns. Each
2224 * layer on the way back up is thus able to call
2225 * hammer_cursor_removed_node() and 'jump' the node up to
2226 * the (same) final parent.
2228 * NOTE! The local variable 'parent' is invalid after we
2229 * call hammer_cursor_up_locked().
2231 error = hammer_cursor_up_locked(cursor);
2235 hammer_cursor_deleted_element(cursor->node, 0);
2236 error = btree_remove(cursor, ndelete);
2238 KKASSERT(node != cursor->node);
2239 hammer_cursor_removed_node(
2240 node, cursor->node, cursor->index);
2241 hammer_modify_node_all(cursor->trans, node);
2242 ondisk = node->ondisk;
2243 ondisk->type = HAMMER_BTREE_TYPE_DELETED;
2245 hammer_modify_node_done(node);
2246 hammer_flush_node(node, 0);
2247 hammer_delete_node(cursor->trans, node);
2252 * Defer parent removal because we could not
2253 * get the lock, just let the leaf remain
2258 hammer_unlock(&node->lock);
2259 hammer_rel_node(node);
2262 * Defer parent removal because we could not
2263 * get the lock, just let the leaf remain
2269 KKASSERT(parent->ondisk->count > 1);
2271 hammer_modify_node_all(cursor->trans, parent);
2272 ondisk = parent->ondisk;
2273 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
2275 elm = &ondisk->elms[cursor->parent_index];
2276 KKASSERT(elm->internal.subtree_offset == node->node_offset);
2277 KKASSERT(ondisk->count > 0);
2280 * We must retain the highest mirror_tid. The deleted
2281 * range is now encompassed by the element to the left.
2282 * If we are already at the left edge the new left edge
2283 * inherits mirror_tid.
2285 * Note that bounds of the parent to our parent may create
2286 * a gap to the left of our left-most node or to the right
2287 * of our right-most node. The gap is silently included
2288 * in the mirror_tid's area of effect from the point of view
2291 if (cursor->parent_index) {
2292 if (elm[-1].internal.mirror_tid <
2293 elm[0].internal.mirror_tid) {
2294 elm[-1].internal.mirror_tid =
2295 elm[0].internal.mirror_tid;
2298 if (elm[1].internal.mirror_tid <
2299 elm[0].internal.mirror_tid) {
2300 elm[1].internal.mirror_tid =
2301 elm[0].internal.mirror_tid;
2306 * Delete the subtree reference in the parent. Include
2307 * boundary element at end.
2309 bcopy(&elm[1], &elm[0],
2310 (ondisk->count - cursor->parent_index) * esize);
2312 hammer_modify_node_done(parent);
2313 hammer_cursor_removed_node(node, parent, cursor->parent_index);
2314 hammer_cursor_deleted_element(parent, cursor->parent_index);
2315 hammer_flush_node(node, 0);
2316 hammer_delete_node(cursor->trans, node);
2319 * cursor->node is invalid, cursor up to make the cursor
2320 * valid again. We have to flag the condition in case
2321 * another thread wiggles an insertion in during an
2324 cursor->flags |= HAMMER_CURSOR_ITERATE_CHECK;
2325 error = hammer_cursor_up(cursor);
2333 * Propagate cursor->trans->tid up the B-Tree starting at the current
2334 * cursor position using pseudofs info gleaned from the passed inode.
2336 * The passed inode has no relationship to the cursor position other
2337 * then being in the same pseudofs as the insertion or deletion we
2338 * are propagating the mirror_tid for.
2340 * WARNING! Because we push and pop the passed cursor, it may be
2341 * modified by other B-Tree operations while it is unlocked
2342 * and things like the node & leaf pointers, and indexes might
2346 hammer_btree_do_propagation(hammer_cursor_t cursor,
2347 hammer_pseudofs_inmem_t pfsm,
2348 hammer_btree_leaf_elm_t leaf)
2350 hammer_cursor_t ncursor;
2351 hammer_tid_t mirror_tid;
2352 int error __debugvar;
2355 * We do not propagate a mirror_tid if the filesystem was mounted
2356 * in no-mirror mode.
2358 if (cursor->trans->hmp->master_id < 0)
2362 * This is a bit of a hack because we cannot deadlock or return
2363 * EDEADLK here. The related operation has already completed and
2364 * we must propagate the mirror_tid now regardless.
2366 * Generate a new cursor which inherits the original's locks and
2367 * unlock the original. Use the new cursor to propagate the
2368 * mirror_tid. Then clean up the new cursor and reacquire locks
2371 * hammer_dup_cursor() cannot dup locks. The dup inherits the
2372 * original's locks and the original is tracked and must be
2375 mirror_tid = cursor->node->ondisk->mirror_tid;
2376 KKASSERT(mirror_tid != 0);
2377 ncursor = hammer_push_cursor(cursor);
2378 error = hammer_btree_mirror_propagate(ncursor, mirror_tid);
2379 KKASSERT(error == 0);
2380 hammer_pop_cursor(cursor, ncursor);
2381 /* WARNING: cursor's leaf pointer may change after pop */
2386 * Propagate a mirror TID update upwards through the B-Tree to the root.
2388 * A locked internal node must be passed in. The node will remain locked
2391 * This function syncs mirror_tid at the specified internal node's element,
2392 * adjusts the node's aggregation mirror_tid, and then recurses upwards.
2395 hammer_btree_mirror_propagate(hammer_cursor_t cursor, hammer_tid_t mirror_tid)
2397 hammer_btree_internal_elm_t elm;
2402 error = hammer_cursor_up(cursor);
2404 error = hammer_cursor_upgrade(cursor);
2407 * We can ignore HAMMER_CURSOR_ITERATE_CHECK, the
2408 * cursor will still be properly positioned for
2409 * mirror propagation, just not for iterations.
2411 while (error == EDEADLK) {
2412 hammer_recover_cursor(cursor);
2413 error = hammer_cursor_upgrade(cursor);
2419 * If the cursor deadlocked it could end up at a leaf
2420 * after we lost the lock.
2422 node = cursor->node;
2423 if (node->ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
2427 * Adjust the node's element
2429 elm = &node->ondisk->elms[cursor->index].internal;
2430 if (elm->mirror_tid >= mirror_tid)
2432 hammer_modify_node(cursor->trans, node, &elm->mirror_tid,
2433 sizeof(elm->mirror_tid));
2434 elm->mirror_tid = mirror_tid;
2435 hammer_modify_node_done(node);
2436 if (hammer_debug_general & 0x0002) {
2437 kprintf("mirror_propagate: propagate "
2438 "%016llx @%016llx:%d\n",
2439 (long long)mirror_tid,
2440 (long long)node->node_offset,
2446 * Adjust the node's mirror_tid aggregator
2448 if (node->ondisk->mirror_tid >= mirror_tid)
2450 hammer_modify_node_field(cursor->trans, node, mirror_tid);
2451 node->ondisk->mirror_tid = mirror_tid;
2452 hammer_modify_node_done(node);
2453 if (hammer_debug_general & 0x0002) {
2454 kprintf("mirror_propagate: propagate "
2455 "%016llx @%016llx\n",
2456 (long long)mirror_tid,
2457 (long long)node->node_offset);
2460 if (error == ENOENT)
2466 * Return a pointer to node's parent. If there is no error,
2467 * *parent_index is set to an index of parent's elm that points
2471 hammer_btree_get_parent(hammer_transaction_t trans, hammer_node_t node,
2472 int *parent_indexp, int *errorp, int try_exclusive)
2474 hammer_node_t parent;
2475 hammer_btree_elm_t elm;
2481 parent = hammer_get_node(trans, node->ondisk->parent, 0, errorp);
2483 KKASSERT(parent == NULL);
2486 KKASSERT ((parent->flags & HAMMER_NODE_DELETED) == 0);
2491 if (try_exclusive) {
2492 if (hammer_lock_ex_try(&parent->lock)) {
2493 hammer_rel_node(parent);
2498 hammer_lock_sh(&parent->lock);
2502 * Figure out which element in the parent is pointing to the
2505 if (node->ondisk->count) {
2506 i = hammer_btree_search_node(&node->ondisk->elms[0].base,
2511 while (i < parent->ondisk->count) {
2512 elm = &parent->ondisk->elms[i];
2513 if (elm->internal.subtree_offset == node->node_offset)
2517 if (i == parent->ondisk->count) {
2518 hammer_unlock(&parent->lock);
2519 panic("Bad B-Tree link: parent %p node %p", parent, node);
2522 KKASSERT(*errorp == 0);
2527 * The element (elm) has been moved to a new internal node (node).
2529 * If the element represents a pointer to an internal node that node's
2530 * parent must be adjusted to the element's new location.
2532 * XXX deadlock potential here with our exclusive locks
2535 btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
2536 hammer_btree_elm_t elm)
2538 hammer_node_t child;
2543 if (hammer_is_internal_node_elm(elm)) {
2544 child = hammer_get_node(trans, elm->internal.subtree_offset,
2547 hammer_modify_node_field(trans, child, parent);
2548 child->ondisk->parent = node->node_offset;
2549 hammer_modify_node_done(child);
2550 hammer_rel_node(child);
2557 * Initialize the root of a recursive B-Tree node lock list structure.
2560 hammer_node_lock_init(hammer_node_lock_t parent, hammer_node_t node)
2562 TAILQ_INIT(&parent->list);
2563 parent->parent = NULL;
2564 parent->node = node;
2566 parent->count = node->ondisk->count;
2567 parent->copy = NULL;
2572 * Initialize a cache of hammer_node_lock's including space allocated
2575 * This is used by the rebalancing code to preallocate the copy space
2576 * for ~4096 B-Tree nodes (16MB of data) prior to acquiring any HAMMER
2577 * locks, otherwise we can blow out the pageout daemon's emergency
2578 * reserve and deadlock it.
2580 * NOTE: HAMMER_NODE_LOCK_LCACHE is not set on items cached in the lcache.
2581 * The flag is set when the item is pulled off the cache for use.
2584 hammer_btree_lcache_init(hammer_mount_t hmp, hammer_node_lock_t lcache,
2587 hammer_node_lock_t item;
2590 for (count = 1; depth; --depth)
2591 count *= HAMMER_BTREE_LEAF_ELMS;
2592 bzero(lcache, sizeof(*lcache));
2593 TAILQ_INIT(&lcache->list);
2595 item = kmalloc(sizeof(*item), hmp->m_misc, M_WAITOK|M_ZERO);
2596 item->copy = kmalloc(sizeof(*item->copy),
2597 hmp->m_misc, M_WAITOK);
2598 TAILQ_INIT(&item->list);
2599 TAILQ_INSERT_TAIL(&lcache->list, item, entry);
2605 hammer_btree_lcache_free(hammer_mount_t hmp, hammer_node_lock_t lcache)
2607 hammer_node_lock_t item;
2609 while ((item = TAILQ_FIRST(&lcache->list)) != NULL) {
2610 TAILQ_REMOVE(&lcache->list, item, entry);
2611 KKASSERT(item->copy);
2612 KKASSERT(TAILQ_EMPTY(&item->list));
2613 kfree(item->copy, hmp->m_misc);
2614 kfree(item, hmp->m_misc);
2616 KKASSERT(lcache->copy == NULL);
2620 * Exclusively lock all the children of node. This is used by the split
2621 * code to prevent anyone from accessing the children of a cursor node
2622 * while we fix-up its parent offset.
2624 * If we don't lock the children we can really mess up cursors which block
2625 * trying to cursor-up into our node.
2627 * On failure EDEADLK (or some other error) is returned. If a deadlock
2628 * error is returned the cursor is adjusted to block on termination.
2630 * The caller is responsible for managing parent->node, the root's node
2631 * is usually aliased from a cursor.
2634 hammer_btree_lock_children(hammer_cursor_t cursor, int depth,
2635 hammer_node_lock_t parent,
2636 hammer_node_lock_t lcache)
2639 hammer_node_lock_t item;
2640 hammer_node_ondisk_t ondisk;
2641 hammer_btree_elm_t elm;
2642 hammer_node_t child;
2643 struct hammer_mount *hmp;
2647 node = parent->node;
2648 ondisk = node->ondisk;
2650 hmp = cursor->trans->hmp;
2652 if (ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
2653 return(0); /* This could return non-zero */
2656 * We really do not want to block on I/O with exclusive locks held,
2657 * pre-get the children before trying to lock the mess. This is
2658 * only done one-level deep for now.
2660 for (i = 0; i < ondisk->count; ++i) {
2661 ++hammer_stats_btree_elements;
2662 elm = &ondisk->elms[i];
2663 child = hammer_get_node(cursor->trans,
2664 elm->internal.subtree_offset,
2667 hammer_rel_node(child);
2673 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2674 ++hammer_stats_btree_elements;
2675 elm = &ondisk->elms[i];
2677 KKASSERT(elm->internal.subtree_offset != 0);
2678 child = hammer_get_node(cursor->trans,
2679 elm->internal.subtree_offset,
2682 if (hammer_lock_ex_try(&child->lock) != 0) {
2683 if (cursor->deadlk_node == NULL) {
2684 cursor->deadlk_node = child;
2685 hammer_ref_node(cursor->deadlk_node);
2688 hammer_rel_node(child);
2691 item = TAILQ_FIRST(&lcache->list);
2692 KKASSERT(item != NULL);
2693 item->flags |= HAMMER_NODE_LOCK_LCACHE;
2694 TAILQ_REMOVE(&lcache->list, item, entry);
2696 item = kmalloc(sizeof(*item),
2699 TAILQ_INIT(&item->list);
2702 TAILQ_INSERT_TAIL(&parent->list, item, entry);
2703 item->parent = parent;
2706 item->count = child->ondisk->count;
2709 * Recurse (used by the rebalancing code)
2711 if (depth > 1 && elm->base.btype == HAMMER_BTREE_TYPE_INTERNAL) {
2712 error = hammer_btree_lock_children(
2722 hammer_btree_unlock_children(hmp, parent, lcache);
2727 * Create an in-memory copy of all B-Tree nodes listed, recursively,
2728 * including the parent.
2731 hammer_btree_lock_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
2733 hammer_mount_t hmp = cursor->trans->hmp;
2734 hammer_node_lock_t item;
2736 if (parent->copy == NULL) {
2737 KKASSERT((parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0);
2738 parent->copy = kmalloc(sizeof(*parent->copy),
2739 hmp->m_misc, M_WAITOK);
2741 KKASSERT((parent->flags & HAMMER_NODE_LOCK_UPDATED) == 0);
2742 *parent->copy = *parent->node->ondisk;
2743 TAILQ_FOREACH(item, &parent->list, entry) {
2744 hammer_btree_lock_copy(cursor, item);
2749 * Recursively sync modified copies to the media.
2752 hammer_btree_sync_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
2754 hammer_node_lock_t item;
2757 if (parent->flags & HAMMER_NODE_LOCK_UPDATED) {
2759 hammer_modify_node_all(cursor->trans, parent->node);
2760 *parent->node->ondisk = *parent->copy;
2761 hammer_modify_node_done(parent->node);
2762 if (parent->copy->type == HAMMER_BTREE_TYPE_DELETED) {
2763 hammer_flush_node(parent->node, 0);
2764 hammer_delete_node(cursor->trans, parent->node);
2767 TAILQ_FOREACH(item, &parent->list, entry) {
2768 count += hammer_btree_sync_copy(cursor, item);
2774 * Release previously obtained node locks. The caller is responsible for
2775 * cleaning up parent->node itself (its usually just aliased from a cursor),
2776 * but this function will take care of the copies.
2778 * NOTE: The root node is not placed in the lcache and node->copy is not
2779 * deallocated when lcache != NULL.
2782 hammer_btree_unlock_children(hammer_mount_t hmp, hammer_node_lock_t parent,
2783 hammer_node_lock_t lcache)
2785 hammer_node_lock_t item;
2786 hammer_node_ondisk_t copy;
2788 while ((item = TAILQ_FIRST(&parent->list)) != NULL) {
2789 TAILQ_REMOVE(&parent->list, item, entry);
2790 hammer_btree_unlock_children(hmp, item, lcache);
2791 hammer_unlock(&item->node->lock);
2792 hammer_rel_node(item->node);
2795 * NOTE: When placing the item back in the lcache
2796 * the flag is cleared by the bzero().
2797 * Remaining fields are cleared as a safety
2800 KKASSERT(item->flags & HAMMER_NODE_LOCK_LCACHE);
2801 KKASSERT(TAILQ_EMPTY(&item->list));
2803 bzero(item, sizeof(*item));
2804 TAILQ_INIT(&item->list);
2807 bzero(copy, sizeof(*copy));
2808 TAILQ_INSERT_TAIL(&lcache->list, item, entry);
2810 kfree(item, hmp->m_misc);
2813 if (parent->copy && (parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0) {
2814 kfree(parent->copy, hmp->m_misc);
2815 parent->copy = NULL; /* safety */
2819 /************************************************************************
2820 * MISCELLANIOUS SUPPORT *
2821 ************************************************************************/
2824 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2826 * Note that for this particular function a return value of -1, 0, or +1
2827 * can denote a match if create_tid is otherwise discounted. A create_tid
2828 * of zero is considered to be 'infinity' in comparisons.
2830 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2833 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2835 if (key1->localization < key2->localization)
2837 if (key1->localization > key2->localization)
2840 if (key1->obj_id < key2->obj_id)
2842 if (key1->obj_id > key2->obj_id)
2845 if (key1->rec_type < key2->rec_type)
2847 if (key1->rec_type > key2->rec_type)
2850 if (key1->key < key2->key)
2852 if (key1->key > key2->key)
2856 * A create_tid of zero indicates a record which is undeletable
2857 * and must be considered to have a value of positive infinity.
2859 if (key1->create_tid == 0) {
2860 if (key2->create_tid == 0)
2864 if (key2->create_tid == 0)
2866 if (key1->create_tid < key2->create_tid)
2868 if (key1->create_tid > key2->create_tid)
2874 * Test a timestamp against an element to determine whether the
2875 * element is visible. A timestamp of 0 means 'infinity'.
2878 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2881 if (base->delete_tid)
2885 if (asof < base->create_tid)
2887 if (base->delete_tid && asof >= base->delete_tid)
2893 * Create a separator half way inbetween key1 and key2. For fields just
2894 * one unit apart, the separator will match key2. key1 is on the left-hand
2895 * side and key2 is on the right-hand side.
2897 * key2 must be >= the separator. It is ok for the separator to match key2.
2899 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2902 * NOTE: It might be beneficial to just scrap this whole mess and just
2903 * set the separator to key2.
2905 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2906 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2909 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2910 hammer_base_elm_t dest)
2912 bzero(dest, sizeof(*dest));
2914 dest->rec_type = key2->rec_type;
2915 dest->key = key2->key;
2916 dest->obj_id = key2->obj_id;
2917 dest->create_tid = key2->create_tid;
2919 MAKE_SEPARATOR(key1, key2, dest, localization);
2920 if (key1->localization == key2->localization) {
2921 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2922 if (key1->obj_id == key2->obj_id) {
2923 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2924 if (key1->rec_type == key2->rec_type) {
2925 MAKE_SEPARATOR(key1, key2, dest, key);
2927 * Don't bother creating a separator for
2928 * create_tid, which also conveniently avoids
2929 * having to handle the create_tid == 0
2930 * (infinity) case. Just leave create_tid
2933 * Worst case, dest matches key2 exactly,
2934 * which is acceptable.
2941 #undef MAKE_SEPARATOR
2944 * Return whether a generic internal or leaf node is full
2948 btree_node_is_full(hammer_node_ondisk_t node)
2950 return(btree_max_elements(node->type) == node->count);
2955 btree_max_elements(u_int8_t type)
2959 n = hammer_node_max_elements(type);
2961 panic("btree_max_elements: bad type %d", type);
2966 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2970 kprintf("node %p count=%d parent=%016llx type=%c\n",
2971 ondisk, ondisk->count,
2972 (long long)ondisk->parent, ondisk->type);
2974 switch (ondisk->type) {
2975 case HAMMER_BTREE_TYPE_INTERNAL:
2976 n = ondisk->count + 1; /* count is NOT boundary inclusive */
2978 case HAMMER_BTREE_TYPE_LEAF:
2979 n = ondisk->count; /* there is no boundary */
2982 return; /* nothing to do */
2986 * Dump elements including boundary.
2988 for (i = 0; i < n; ++i) {
2990 hammer_print_btree_elm(&ondisk->elms[i]);
2995 hammer_print_btree_elm(hammer_btree_elm_t elm)
2997 kprintf("\tobj_id = %016llx\n", (long long)elm->base.obj_id);
2998 kprintf("\tkey = %016llx\n", (long long)elm->base.key);
2999 kprintf("\tcreate_tid = %016llx\n", (long long)elm->base.create_tid);
3000 kprintf("\tdelete_tid = %016llx\n", (long long)elm->base.delete_tid);
3001 kprintf("\trec_type = %04x\n", elm->base.rec_type);
3002 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
3003 kprintf("\tbtype = %02x (%c)\n", elm->base.btype,
3004 hammer_elm_btype(elm));
3005 kprintf("\tlocalization = %08x\n", elm->base.localization);
3007 if (hammer_is_internal_node_elm(elm)) {
3008 kprintf("\tsubtree_off = %016llx\n",
3009 (long long)elm->internal.subtree_offset);
3010 } else if (hammer_is_leaf_node_elm(elm)) {
3011 kprintf("\tdata_offset = %016llx\n",
3012 (long long)elm->leaf.data_offset);
3013 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
3014 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);
3020 hammer_debug_btree_elm(hammer_cursor_t cursor, hammer_btree_elm_t elm,
3021 const char *s, int res)
3023 kprintf("%-8s %016llx[%02d] %c "
3024 "lo=%08x obj=%016llx rec=%02x key=%016llx tid=%016llx td=%p "
3027 (long long)cursor->node->node_offset,
3029 hammer_elm_btype(elm),
3030 elm->base.localization,
3031 (long long)elm->base.obj_id,
3033 (long long)elm->base.key,
3034 (long long)elm->base.create_tid,
3041 hammer_debug_btree_parent(hammer_cursor_t cursor, const char *s)
3043 hammer_btree_elm_t elm =
3044 &cursor->parent->ondisk->elms[cursor->parent_index];
3046 kprintf("%-8s %016llx[%d] %c "
3047 "(%016llx/%016llx %016llx/%016llx) (%p/%p %p/%p)\n",
3049 (long long)cursor->parent->node_offset,
3050 cursor->parent_index,
3051 hammer_elm_btype(elm),
3052 (long long)cursor->left_bound->obj_id,
3053 (long long)elm->internal.base.obj_id,
3054 (long long)cursor->right_bound->obj_id,
3055 (long long)(elm + 1)->internal.base.obj_id,
3058 cursor->right_bound,