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(uint8_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 hkprintf("BRACKETU %016jx[%d] -> %016jx[%d] td=%p\n",
178 (intmax_t)cursor->node->node_offset,
180 (intmax_t)(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 hdkprintf("DEBUG: Caught parent seek "
266 "in internal iteration\n");
269 error = hammer_cursor_down(cursor);
272 KKASSERT(cursor->index == 0);
273 /* reload stale pointer */
274 node = cursor->node->ondisk;
277 elm = &node->elms[cursor->index];
278 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
279 if (hammer_debug_btree) {
280 hammer_debug_btree_elm(cursor, elm, "ELEMENT", r);
288 * We support both end-inclusive and
289 * end-exclusive searches.
292 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
298 * If ITERATE_CHECK is set an unlocked cursor may
299 * have been moved to a parent and the iterate can
300 * happen upon elements that are not in the requested
303 if (cursor->flags & HAMMER_CURSOR_ITERATE_CHECK) {
304 s = hammer_btree_cmp(&cursor->key_beg,
307 hdkprintf("DEBUG: Caught parent seek "
308 "in leaf iteration\n");
313 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
318 switch(elm->leaf.base.btype) {
319 case HAMMER_BTREE_TYPE_RECORD:
320 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
321 hammer_btree_chkts(cursor->asof, &elm->base)) {
338 if (hammer_debug_btree) {
339 elm = &cursor->node->ondisk->elms[cursor->index];
340 hammer_debug_btree_elm(cursor, elm, "ITERATE", 0xffff);
348 * We hit an internal element that we could skip as part of a mirroring
349 * scan. Calculate the entire range being skipped.
351 * It is important to include any gaps between the parent's left_bound
352 * and the node's left_bound, and same goes for the right side.
355 hammer_cursor_mirror_filter(hammer_cursor_t cursor)
357 struct hammer_cmirror *cmirror;
358 hammer_node_ondisk_t ondisk;
359 hammer_btree_elm_t elm;
361 ondisk = cursor->node->ondisk;
362 cmirror = cursor->cmirror;
365 * Calculate the skipped range
367 elm = &ondisk->elms[cursor->index];
368 if (cursor->index == 0)
369 cmirror->skip_beg = *cursor->left_bound;
371 cmirror->skip_beg = elm->internal.base;
372 while (cursor->index < ondisk->count) {
373 if (elm->internal.mirror_tid >= cmirror->mirror_tid)
378 if (cursor->index == ondisk->count)
379 cmirror->skip_end = *cursor->right_bound;
381 cmirror->skip_end = elm->internal.base;
384 * clip the returned result.
386 if (hammer_btree_cmp(&cmirror->skip_beg, &cursor->key_beg) < 0)
387 cmirror->skip_beg = cursor->key_beg;
388 if (hammer_btree_cmp(&cmirror->skip_end, &cursor->key_end) > 0)
389 cmirror->skip_end = cursor->key_end;
393 * Iterate in the reverse direction. This is used by the pruning code to
394 * avoid overlapping records.
397 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
399 hammer_node_ondisk_t node;
400 hammer_btree_elm_t elm;
406 /* mirror filtering not supported for reverse iteration */
407 KKASSERT ((cursor->flags & HAMMER_CURSOR_MIRROR_FILTERED) == 0);
410 * Skip past the current record. For various reasons the cursor
411 * may end up set to -1 or set to point at the end of the current
412 * node. These cases must be addressed.
414 node = cursor->node->ondisk;
417 if (cursor->index != -1 &&
418 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
421 if (cursor->index == cursor->node->ondisk->count)
425 * HAMMER can wind up being cpu-bound.
427 hmp = cursor->trans->hmp;
428 if (++hmp->check_yield > hammer_yield_check) {
429 hmp->check_yield = 0;
434 * Loop until an element is found or we are done.
437 ++hammer_stats_btree_iterations;
438 hammer_flusher_clean_loose_ios(hmp);
441 * We iterate up the tree and then index over one element
442 * while we are at the last element in the current node.
444 if (cursor->index == -1) {
445 error = hammer_cursor_up(cursor);
447 cursor->index = 0; /* sanity */
450 /* reload stale pointer */
451 node = cursor->node->ondisk;
452 KKASSERT(cursor->index != node->count);
458 * Check internal or leaf element. Determine if the record
459 * at the cursor has gone beyond the end of our range.
461 * We recurse down through internal nodes.
463 KKASSERT(cursor->index != node->count);
464 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
465 elm = &node->elms[cursor->index];
467 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
468 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
469 if (hammer_debug_btree) {
470 hammer_debug_btree_elm(cursor, elm, "BRACKETL", r);
471 hammer_debug_btree_elm(cursor, elm + 1, "BRACKETR", s);
480 * It shouldn't be possible to be seeked past key_end,
481 * even if the cursor got moved to a parent.
488 KKASSERT(elm->internal.subtree_offset != 0);
490 error = hammer_cursor_down(cursor);
493 KKASSERT(cursor->index == 0);
494 /* reload stale pointer */
495 node = cursor->node->ondisk;
497 /* this can assign -1 if the leaf was empty */
498 cursor->index = node->count - 1;
501 elm = &node->elms[cursor->index];
502 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
503 if (hammer_debug_btree) {
504 hammer_debug_btree_elm(cursor, elm, "ELEMENTR", s);
512 * It shouldn't be possible to be seeked past key_end,
513 * even if the cursor got moved to a parent.
515 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
520 switch(elm->leaf.base.btype) {
521 case HAMMER_BTREE_TYPE_RECORD:
522 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
523 hammer_btree_chkts(cursor->asof, &elm->base)) {
540 if (hammer_debug_btree) {
541 elm = &cursor->node->ondisk->elms[cursor->index];
542 hammer_debug_btree_elm(cursor, elm, "ITERATER", 0xffff);
550 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
551 * could not be found, EDEADLK if inserting and a retry is needed, and a
552 * fatal error otherwise. When retrying, the caller must terminate the
553 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
555 * The cursor is suitably positioned for a deletion on success, and suitably
556 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
559 * The cursor may begin anywhere, the search will traverse the tree in
560 * either direction to locate the requested element.
562 * Most of the logic implementing historical searches is handled here. We
563 * do an initial lookup with create_tid set to the asof TID. Due to the
564 * way records are laid out, a backwards iteration may be required if
565 * ENOENT is returned to locate the historical record. Here's the
568 * create_tid: 10 15 20
572 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
573 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
574 * not visible and thus causes ENOENT to be returned. We really need
575 * to check record 11 in LEAF1. If it also fails then the search fails
576 * (e.g. it might represent the range 11-16 and thus still not match our
577 * AS-OF timestamp of 17). Note that LEAF1 could be empty, requiring
578 * further iterations.
580 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
581 * and the cursor->create_check TID if an iteration might be needed.
582 * In the above example create_check would be set to 14.
585 hammer_btree_lookup(hammer_cursor_t cursor)
589 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
590 KKASSERT ((cursor->flags & HAMMER_CURSOR_INSERT) == 0 ||
591 cursor->trans->sync_lock_refs > 0);
592 ++hammer_stats_btree_lookups;
593 if (cursor->flags & HAMMER_CURSOR_ASOF) {
594 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
595 cursor->key_beg.create_tid = cursor->asof;
597 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
598 error = btree_search(cursor, 0);
599 if (error != ENOENT ||
600 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
603 * Stop if error other then ENOENT.
604 * Stop if ENOENT and not special case.
608 if (hammer_debug_btree) {
609 hkprintf("CREATE_CHECK %016jx\n",
610 (intmax_t)cursor->create_check);
612 cursor->key_beg.create_tid = cursor->create_check;
616 error = btree_search(cursor, 0);
619 error = hammer_btree_extract(cursor, cursor->flags);
624 * Execute the logic required to start an iteration. The first record
625 * located within the specified range is returned and iteration control
626 * flags are adjusted for successive hammer_btree_iterate() calls.
628 * Set ATEDISK so a low-level caller can call btree_first/btree_iterate
629 * in a loop without worrying about it. Higher-level merged searches will
630 * adjust the flag appropriately.
633 hammer_btree_first(hammer_cursor_t cursor)
637 error = hammer_btree_lookup(cursor);
638 if (error == ENOENT) {
639 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
640 error = hammer_btree_iterate(cursor);
642 cursor->flags |= HAMMER_CURSOR_ATEDISK;
647 * Similarly but for an iteration in the reverse direction.
649 * Set ATEDISK when iterating backwards to skip the current entry,
650 * which after an ENOENT lookup will be pointing beyond our end point.
652 * Set ATEDISK so a low-level caller can call btree_last/btree_iterate_reverse
653 * in a loop without worrying about it. Higher-level merged searches will
654 * adjust the flag appropriately.
657 hammer_btree_last(hammer_cursor_t cursor)
659 struct hammer_base_elm save;
662 save = cursor->key_beg;
663 cursor->key_beg = cursor->key_end;
664 error = hammer_btree_lookup(cursor);
665 cursor->key_beg = save;
666 if (error == ENOENT ||
667 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
668 cursor->flags |= HAMMER_CURSOR_ATEDISK;
669 error = hammer_btree_iterate_reverse(cursor);
671 cursor->flags |= HAMMER_CURSOR_ATEDISK;
676 * Extract the record and/or data associated with the cursor's current
677 * position. Any prior record or data stored in the cursor is replaced.
679 * NOTE: All extractions occur at the leaf of the B-Tree.
682 hammer_btree_extract(hammer_cursor_t cursor, int flags)
684 hammer_node_ondisk_t node;
685 hammer_btree_elm_t elm;
686 hammer_off_t data_off;
692 * Certain types of corruption can result in a NULL node pointer.
694 if (cursor->node == NULL) {
695 hkprintf("NULL cursor->node, filesystem might "
696 "have gotten corrupted\n");
701 * The case where the data reference resolves to the same buffer
702 * as the record reference must be handled.
704 node = cursor->node->ondisk;
705 elm = &node->elms[cursor->index];
707 hmp = cursor->node->hmp;
710 * There is nothing to extract for an internal element.
712 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
716 * Only record types have data.
718 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
719 cursor->leaf = &elm->leaf;
722 * Returns here unless HAMMER_CURSOR_GET_DATA is set.
724 if ((flags & HAMMER_CURSOR_GET_DATA) == 0)
727 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
729 data_off = elm->leaf.data_offset;
730 data_len = elm->leaf.data_len;
737 KKASSERT(data_len >= 0 && data_len <= HAMMER_XBUFSIZE);
738 cursor->data = hammer_bread_ext(hmp, data_off, data_len,
739 &error, &cursor->data_buffer);
742 * Mark the data buffer as not being meta-data if it isn't
743 * meta-data (sometimes bulk data is accessed via a volume
747 switch(elm->leaf.base.rec_type) {
748 case HAMMER_RECTYPE_DATA:
749 case HAMMER_RECTYPE_DB:
750 if ((data_off & HAMMER_ZONE_LARGE_DATA) == 0)
752 if (hammer_double_buffer == 0 ||
753 (cursor->flags & HAMMER_CURSOR_NOSWAPCACHE)) {
754 hammer_io_notmeta(cursor->data_buffer);
763 * Deal with CRC errors on the extracted data.
766 hammer_crc_test_leaf(cursor->data, &elm->leaf) == 0) {
767 hdkprintf("CRC DATA @ %016jx/%d FAILED\n",
768 (intmax_t)elm->leaf.data_offset, elm->leaf.data_len);
769 if (hammer_debug_critical)
770 Debugger("CRC FAILED: DATA");
771 if (cursor->trans->flags & HAMMER_TRANSF_CRCDOM)
772 error = EDOM; /* less critical (mirroring) */
774 error = EIO; /* critical */
781 * Insert a leaf element into the B-Tree at the current cursor position.
782 * The cursor is positioned such that the element at and beyond the cursor
783 * are shifted to make room for the new record.
785 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
786 * flag set and that call must return ENOENT before this function can be
787 * called. ENOSPC is returned if there is no room to insert a new record.
789 * The caller may depend on the cursor's exclusive lock after return to
790 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
793 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_leaf_elm_t elm,
796 hammer_node_ondisk_t node;
801 if ((error = hammer_cursor_upgrade_node(cursor)) != 0)
803 ++hammer_stats_btree_inserts;
806 * Insert the element at the leaf node and update the count in the
807 * parent. It is possible for parent to be NULL, indicating that
808 * the filesystem's ROOT B-Tree node is a leaf itself, which is
809 * possible. The root inode can never be deleted so the leaf should
812 * Remember that leaf nodes do not have boundaries.
814 hammer_modify_node_all(cursor->trans, cursor->node);
815 node = cursor->node->ondisk;
817 KKASSERT(elm->base.btype != 0);
818 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
819 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
820 if (i != node->count) {
821 bcopy(&node->elms[i], &node->elms[i+1],
822 (node->count - i) * sizeof(*elm));
824 node->elms[i].leaf = *elm;
826 hammer_cursor_inserted_element(cursor->node, i);
829 * Update the leaf node's aggregate mirror_tid for mirroring
832 if (node->mirror_tid < elm->base.delete_tid) {
833 node->mirror_tid = elm->base.delete_tid;
836 if (node->mirror_tid < elm->base.create_tid) {
837 node->mirror_tid = elm->base.create_tid;
840 hammer_modify_node_done(cursor->node);
843 * Debugging sanity checks.
845 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->base) <= 0);
846 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->base) > 0);
848 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->base) < 0);
850 if (i != node->count - 1)
851 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->base) > 0);
857 * Delete a record from the B-Tree at the current cursor position.
858 * The cursor is positioned such that the current element is the one
861 * On return the cursor will be positioned after the deleted element and
862 * MAY point to an internal node. It will be suitable for the continuation
863 * of an iteration but not for an insertion or deletion.
865 * Deletions will attempt to partially rebalance the B-Tree in an upward
866 * direction, but will terminate rather then deadlock. Empty internal nodes
867 * are never allowed by a deletion which deadlocks may end up giving us an
868 * empty leaf. The pruner will clean up and rebalance the tree.
870 * This function can return EDEADLK, requiring the caller to retry the
871 * operation after clearing the deadlock.
873 * This function will store the number of deleted btree nodes in *ndelete
874 * if ndelete is not NULL.
877 hammer_btree_delete(hammer_cursor_t cursor, int *ndelete)
879 hammer_node_ondisk_t ondisk;
881 hammer_node_t parent __debugvar;
885 KKASSERT (cursor->trans->sync_lock_refs > 0);
888 if ((error = hammer_cursor_upgrade(cursor)) != 0)
890 ++hammer_stats_btree_deletes;
893 * Delete the element from the leaf node.
895 * Remember that leaf nodes do not have boundaries.
898 ondisk = node->ondisk;
901 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
902 KKASSERT(i >= 0 && i < ondisk->count);
903 hammer_modify_node_all(cursor->trans, node);
904 if (i + 1 != ondisk->count) {
905 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
906 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
909 hammer_modify_node_done(node);
910 hammer_cursor_deleted_element(node, i);
913 * Validate local parent
915 if (ondisk->parent) {
916 parent = cursor->parent;
918 KKASSERT(parent != NULL);
919 KKASSERT(parent->node_offset == ondisk->parent);
923 * If the leaf becomes empty it must be detached from the parent,
924 * potentially recursing through to the filesystem root.
926 * This may reposition the cursor at one of the parent's of the
929 * Ignore deadlock errors, that simply means that btree_remove
930 * was unable to recurse and had to leave us with an empty leaf.
932 KKASSERT(cursor->index <= ondisk->count);
933 if (ondisk->count == 0) {
934 error = btree_remove(cursor, ndelete);
935 if (error == EDEADLK)
940 KKASSERT(cursor->parent == NULL ||
941 cursor->parent_index < cursor->parent->ondisk->count);
946 * PRIMARY B-TREE SEARCH SUPPORT PROCEDURE
948 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
950 * The search can begin ANYWHERE in the B-Tree. As a first step the search
951 * iterates up the tree as necessary to properly position itself prior to
952 * actually doing the sarch.
954 * INSERTIONS: The search will split full nodes and leaves on its way down
955 * and guarentee that the leaf it ends up on is not full. If we run out
956 * of space the search continues to the leaf, but ENOSPC is returned.
958 * The search is only guarenteed to end up on a leaf if an error code of 0
959 * is returned, or if inserting and an error code of ENOENT is returned.
960 * Otherwise it can stop at an internal node. On success a search returns
963 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
964 * filesystem, and it is not simple code. Please note the following facts:
966 * - Internal node recursions have a boundary on the left AND right. The
967 * right boundary is non-inclusive. The create_tid is a generic part
968 * of the key for internal nodes.
970 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
971 * historical search. ASOF and INSERT are mutually exclusive. When
972 * doing an as-of lookup btree_search() checks for a right-edge boundary
973 * case. If while recursing down the left-edge differs from the key
974 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
975 * with cursor->create_check. This is used by btree_lookup() to iterate.
976 * The iteration backwards because as-of searches can wind up going
977 * down the wrong branch of the B-Tree.
981 btree_search(hammer_cursor_t cursor, int flags)
983 hammer_node_ondisk_t node;
984 hammer_btree_elm_t elm;
991 flags |= cursor->flags;
992 ++hammer_stats_btree_searches;
994 if (hammer_debug_btree) {
995 hammer_debug_btree_elm(cursor,
996 (hammer_btree_elm_t)&cursor->key_beg,
999 hammer_debug_btree_parent(cursor, "SEARCHP");
1003 * Move our cursor up the tree until we find a node whos range covers
1004 * the key we are trying to locate.
1006 * The left bound is inclusive, the right bound is non-inclusive.
1007 * It is ok to cursor up too far.
1010 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
1011 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
1012 if (r >= 0 && s < 0)
1014 KKASSERT(cursor->parent);
1015 ++hammer_stats_btree_iterations;
1016 error = hammer_cursor_up(cursor);
1022 * The delete-checks below are based on node, not parent. Set the
1023 * initial delete-check based on the parent.
1026 KKASSERT(cursor->left_bound->create_tid != 1);
1027 cursor->create_check = cursor->left_bound->create_tid - 1;
1028 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
1032 * We better have ended up with a node somewhere.
1034 KKASSERT(cursor->node != NULL);
1037 * If we are inserting we can't start at a full node if the parent
1038 * is also full (because there is no way to split the node),
1039 * continue running up the tree until the requirement is satisfied
1040 * or we hit the root of the filesystem.
1042 * (If inserting we aren't doing an as-of search so we don't have
1043 * to worry about create_check).
1045 while (flags & HAMMER_CURSOR_INSERT) {
1046 if (btree_node_is_full(cursor->node->ondisk) == 0)
1048 if (cursor->node->ondisk->parent == 0 ||
1049 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
1052 ++hammer_stats_btree_iterations;
1053 error = hammer_cursor_up(cursor);
1054 /* node may have become stale */
1060 * Push down through internal nodes to locate the requested key.
1062 node = cursor->node->ondisk;
1063 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
1065 * Scan the node to find the subtree index to push down into.
1066 * We go one-past, then back-up.
1068 * We must proactively remove deleted elements which may
1069 * have been left over from a deadlocked btree_remove().
1071 * The left and right boundaries are included in the loop
1072 * in order to detect edge cases.
1074 * If the separator only differs by create_tid (r == 1)
1075 * and we are doing an as-of search, we may end up going
1076 * down a branch to the left of the one containing the
1077 * desired key. This requires numerous special cases.
1079 ++hammer_stats_btree_iterations;
1080 if (hammer_debug_btree) {
1081 hkprintf("SEARCH-I %016jx count=%d\n",
1082 (intmax_t)cursor->node->node_offset,
1087 * Try to shortcut the search before dropping into the
1088 * linear loop. Locate the first node where r <= 1.
1090 i = hammer_btree_search_node(&cursor->key_beg, node);
1091 while (i <= node->count) {
1092 ++hammer_stats_btree_elements;
1093 elm = &node->elms[i];
1094 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
1095 if (hammer_debug_btree > 2) {
1096 hkprintf(" IELM %p [%d] r=%d\n",
1097 &node->elms[i], i, r);
1102 KKASSERT(elm->base.create_tid != 1);
1103 cursor->create_check = elm->base.create_tid - 1;
1104 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
1108 if (hammer_debug_btree) {
1109 hkprintf("SEARCH-I preI=%d/%d r=%d\n",
1114 * The first two cases (i == 0 or i == node->count + 1)
1115 * occur when the parent's idea of the boundary
1116 * is wider then the child's idea of the boundary, and
1117 * require special handling. If not inserting we can
1118 * terminate the search early for these cases but the
1119 * child's boundaries cannot be unconditionally modified.
1121 * The last case (neither of the above) fits in child's
1122 * idea of the boundary, so we can simply push down the
1127 * If i == 0 the search terminated to the LEFT of the
1128 * left_boundary but to the RIGHT of the parent's left
1133 elm = &node->elms[0];
1136 * If we aren't inserting we can stop here.
1138 if ((flags & (HAMMER_CURSOR_INSERT |
1139 HAMMER_CURSOR_PRUNING)) == 0) {
1145 * Correct a left-hand boundary mismatch.
1147 * We can only do this if we can upgrade the lock,
1148 * and synchronized as a background cursor (i.e.
1149 * inserting or pruning).
1151 * WARNING: We can only do this if inserting, i.e.
1152 * we are running on the backend.
1154 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1156 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1157 hammer_modify_node_field(cursor->trans, cursor->node,
1159 save = node->elms[0].base.btype;
1160 node->elms[0].base = *cursor->left_bound;
1161 node->elms[0].base.btype = save;
1162 hammer_modify_node_done(cursor->node);
1163 } else if (i == node->count + 1) {
1165 * If i == node->count + 1 the search terminated to
1166 * the RIGHT of the right boundary but to the LEFT
1167 * of the parent's right boundary. If we aren't
1168 * inserting we can stop here.
1170 * Note that the last element in this case is
1171 * elms[i-2] prior to adjustments to 'i'.
1174 if ((flags & (HAMMER_CURSOR_INSERT |
1175 HAMMER_CURSOR_PRUNING)) == 0) {
1181 * Correct a right-hand boundary mismatch.
1182 * (actual push-down record is i-2 prior to
1183 * adjustments to i).
1185 * We can only do this if we can upgrade the lock,
1186 * and synchronized as a background cursor (i.e.
1187 * inserting or pruning).
1189 * WARNING: We can only do this if inserting, i.e.
1190 * we are running on the backend.
1192 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1194 elm = &node->elms[i];
1195 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1196 hammer_modify_node(cursor->trans, cursor->node,
1197 &elm->base, sizeof(elm->base));
1198 elm->base = *cursor->right_bound;
1199 hammer_modify_node_done(cursor->node);
1203 * The push-down index is now i - 1. If we had
1204 * terminated on the right boundary this will point
1205 * us at the last element.
1210 elm = &node->elms[i];
1212 if (hammer_debug_btree) {
1213 hammer_debug_btree_elm(cursor, elm, "RESULT-I", 0xffff);
1217 * We better have a valid subtree offset.
1219 KKASSERT(elm->internal.subtree_offset != 0);
1222 * Handle insertion and deletion requirements.
1224 * If inserting split full nodes. The split code will
1225 * adjust cursor->node and cursor->index if the current
1226 * index winds up in the new node.
1228 * If inserting and a left or right edge case was detected,
1229 * we cannot correct the left or right boundary and must
1230 * prepend and append an empty leaf node in order to make
1231 * the boundary correction.
1233 * If we run out of space we set enospc but continue on
1236 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1237 if (btree_node_is_full(node)) {
1238 error = btree_split_internal(cursor);
1240 if (error != ENOSPC)
1245 * reload stale pointers
1248 node = cursor->node->ondisk;
1253 * Push down (push into new node, existing node becomes
1254 * the parent) and continue the search.
1256 error = hammer_cursor_down(cursor);
1257 /* node may have become stale */
1260 node = cursor->node->ondisk;
1264 * We are at a leaf, do a linear search of the key array.
1266 * On success the index is set to the matching element and 0
1269 * On failure the index is set to the insertion point and ENOENT
1272 * Boundaries are not stored in leaf nodes, so the index can wind
1273 * up to the left of element 0 (index == 0) or past the end of
1274 * the array (index == node->count). It is also possible that the
1275 * leaf might be empty.
1277 ++hammer_stats_btree_iterations;
1278 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1279 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1280 if (hammer_debug_btree) {
1281 hkprintf("SEARCH-L %016jx count=%d\n",
1282 (intmax_t)cursor->node->node_offset,
1287 * Try to shortcut the search before dropping into the
1288 * linear loop. Locate the first node where r <= 1.
1290 i = hammer_btree_search_node(&cursor->key_beg, node);
1291 while (i < node->count) {
1292 ++hammer_stats_btree_elements;
1293 elm = &node->elms[i];
1295 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1297 if (hammer_debug_btree > 1)
1298 hkprintf(" LELM %p [%d] r=%d\n", &node->elms[i], i, r);
1301 * We are at a record element. Stop if we've flipped past
1302 * key_beg, not counting the create_tid test. Allow the
1303 * r == 1 case (key_beg > element but differs only by its
1304 * create_tid) to fall through to the AS-OF check.
1306 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1316 * Check our as-of timestamp against the element.
1318 if (flags & HAMMER_CURSOR_ASOF) {
1319 if (hammer_btree_chkts(cursor->asof,
1320 &node->elms[i].base) != 0) {
1326 if (r > 0) { /* can only be +1 */
1334 if (hammer_debug_btree) {
1335 hkprintf("RESULT-L %016jx[%d] (SUCCESS)\n",
1336 (intmax_t)cursor->node->node_offset, i);
1342 * The search of the leaf node failed. i is the insertion point.
1345 if (hammer_debug_btree) {
1346 hkprintf("RESULT-L %016jx[%d] (FAILED)\n",
1347 (intmax_t)cursor->node->node_offset, i);
1351 * No exact match was found, i is now at the insertion point.
1353 * If inserting split a full leaf before returning. This
1354 * may have the side effect of adjusting cursor->node and
1358 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1359 btree_node_is_full(node)) {
1360 error = btree_split_leaf(cursor);
1362 if (error != ENOSPC)
1367 * reload stale pointers
1371 node = &cursor->node->internal;
1376 * We reached a leaf but did not find the key we were looking for.
1377 * If this is an insert we will be properly positioned for an insert
1378 * (ENOENT) or unable to insert (ENOSPC).
1380 error = enospc ? ENOSPC : ENOENT;
1386 * Heuristical search for the first element whos comparison is <= 1. May
1387 * return an index whos compare result is > 1 but may only return an index
1388 * whos compare result is <= 1 if it is the first element with that result.
1391 hammer_btree_search_node(hammer_base_elm_t elm, hammer_node_ondisk_t node)
1399 * Don't bother if the node does not have very many elements
1404 i = b + (s - b) / 2;
1405 ++hammer_stats_btree_elements;
1406 r = hammer_btree_cmp(elm, &node->elms[i].leaf.base);
1417 /************************************************************************
1418 * SPLITTING AND MERGING *
1419 ************************************************************************
1421 * These routines do all the dirty work required to split and merge nodes.
1425 * Split an internal node into two nodes and move the separator at the split
1426 * point to the parent.
1428 * (cursor->node, cursor->index) indicates the element the caller intends
1429 * to push into. We will adjust node and index if that element winds
1430 * up in the split node.
1432 * If we are at the root of the filesystem a new root must be created with
1433 * two elements, one pointing to the original root and one pointing to the
1434 * newly allocated split node.
1438 btree_split_internal(hammer_cursor_t cursor)
1440 hammer_node_ondisk_t ondisk;
1442 hammer_node_t parent;
1443 hammer_node_t new_node;
1444 hammer_btree_elm_t elm;
1445 hammer_btree_elm_t parent_elm;
1446 struct hammer_node_lock lockroot;
1447 hammer_mount_t hmp = cursor->trans->hmp;
1453 const int esize = sizeof(*elm);
1455 hammer_node_lock_init(&lockroot, cursor->node);
1456 error = hammer_btree_lock_children(cursor, 1, &lockroot, NULL);
1459 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1461 ++hammer_stats_btree_splits;
1464 * Calculate the split point. If the insertion point is at the
1465 * end of the leaf we adjust the split point significantly to the
1466 * right to try to optimize node fill and flag it. If we hit
1467 * that same leaf again our heuristic failed and we don't try
1468 * to optimize node fill (it could lead to a degenerate case).
1470 node = cursor->node;
1471 ondisk = node->ondisk;
1472 KKASSERT(ondisk->count > 4);
1473 if (cursor->index == ondisk->count &&
1474 (node->flags & HAMMER_NODE_NONLINEAR) == 0) {
1475 split = (ondisk->count + 1) * 3 / 4;
1476 node->flags |= HAMMER_NODE_NONLINEAR;
1479 * We are splitting but elms[split] will be promoted to
1480 * the parent, leaving the right hand node with one less
1481 * element. If the insertion point will be on the
1482 * left-hand side adjust the split point to give the
1483 * right hand side one additional node.
1485 split = (ondisk->count + 1) / 2;
1486 if (cursor->index <= split)
1491 * If we are at the root of the filesystem, create a new root node
1492 * with 1 element and split normally. Avoid making major
1493 * modifications until we know the whole operation will work.
1495 if (ondisk->parent == 0) {
1496 parent = hammer_alloc_btree(cursor->trans, 0, &error);
1499 hammer_lock_ex(&parent->lock);
1500 hammer_modify_node_noundo(cursor->trans, parent);
1501 ondisk = parent->ondisk;
1504 ondisk->mirror_tid = node->ondisk->mirror_tid;
1505 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1506 ondisk->elms[0].base = hmp->root_btree_beg;
1507 ondisk->elms[0].base.btype = node->ondisk->type;
1508 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1509 ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
1510 ondisk->elms[1].base = hmp->root_btree_end;
1511 hammer_modify_node_done(parent);
1513 parent_index = 0; /* index of current node in parent */
1516 parent = cursor->parent;
1517 parent_index = cursor->parent_index;
1521 * Split node into new_node at the split point.
1523 * B O O O P N N B <-- P = node->elms[split] (index 4)
1524 * 0 1 2 3 4 5 6 <-- subtree indices
1529 * B O O O B B N N B <--- inner boundary points are 'P'
1532 new_node = hammer_alloc_btree(cursor->trans, 0, &error);
1533 if (new_node == NULL) {
1535 hammer_unlock(&parent->lock);
1536 hammer_delete_node(cursor->trans, parent);
1537 hammer_rel_node(parent);
1541 hammer_lock_ex(&new_node->lock);
1544 * Create the new node. P becomes the left-hand boundary in the
1545 * new node. Copy the right-hand boundary as well.
1547 * elm is the new separator.
1549 hammer_modify_node_noundo(cursor->trans, new_node);
1550 hammer_modify_node_all(cursor->trans, node);
1551 ondisk = node->ondisk;
1552 elm = &ondisk->elms[split];
1553 bcopy(elm, &new_node->ondisk->elms[0],
1554 (ondisk->count - split + 1) * esize); /* +1 for boundary */
1555 new_node->ondisk->count = ondisk->count - split;
1556 new_node->ondisk->parent = parent->node_offset;
1557 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1558 new_node->ondisk->mirror_tid = ondisk->mirror_tid;
1559 KKASSERT(ondisk->type == new_node->ondisk->type);
1560 hammer_cursor_split_node(node, new_node, split);
1563 * Cleanup the original node. Elm (P) becomes the new boundary,
1564 * its subtree_offset was moved to the new node. If we had created
1565 * a new root its parent pointer may have changed.
1567 elm->base.btype = HAMMER_BTREE_TYPE_NONE;
1568 elm->internal.subtree_offset = 0;
1569 ondisk->count = split;
1572 * Insert the separator into the parent, fixup the parent's
1573 * reference to the original node, and reference the new node.
1574 * The separator is P.
1576 * Remember that ondisk->count does not include the right-hand boundary.
1578 hammer_modify_node_all(cursor->trans, parent);
1579 ondisk = parent->ondisk;
1580 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1581 parent_elm = &ondisk->elms[parent_index+1];
1582 bcopy(parent_elm, parent_elm + 1,
1583 (ondisk->count - parent_index) * esize);
1586 * Why not use hammer_make_separator() here ?
1588 parent_elm->internal.base = elm->base; /* separator P */
1589 parent_elm->internal.base.btype = new_node->ondisk->type;
1590 parent_elm->internal.subtree_offset = new_node->node_offset;
1591 parent_elm->internal.mirror_tid = new_node->ondisk->mirror_tid;
1593 hammer_modify_node_done(parent);
1594 hammer_cursor_inserted_element(parent, parent_index + 1);
1597 * The children of new_node need their parent pointer set to new_node.
1598 * The children have already been locked by
1599 * hammer_btree_lock_children().
1601 for (i = 0; i < new_node->ondisk->count; ++i) {
1602 elm = &new_node->ondisk->elms[i];
1603 error = btree_set_parent_of_child(cursor->trans, new_node, elm);
1605 hpanic("btree-fixup problem");
1608 hammer_modify_node_done(new_node);
1611 * The filesystem's root B-Tree pointer may have to be updated.
1614 hammer_volume_t volume;
1616 volume = hammer_get_root_volume(hmp, &error);
1617 KKASSERT(error == 0);
1619 hammer_modify_volume_field(cursor->trans, volume,
1621 volume->ondisk->vol0_btree_root = parent->node_offset;
1622 hammer_modify_volume_done(volume);
1623 node->ondisk->parent = parent->node_offset;
1624 if (cursor->parent) {
1625 hammer_unlock(&cursor->parent->lock);
1626 hammer_rel_node(cursor->parent);
1628 cursor->parent = parent; /* lock'd and ref'd */
1629 hammer_rel_volume(volume, 0);
1631 hammer_modify_node_done(node);
1634 * Ok, now adjust the cursor depending on which element the original
1635 * index was pointing at. If we are >= the split point the push node
1636 * is now in the new node.
1638 * NOTE: If we are at the split point itself we cannot stay with the
1639 * original node because the push index will point at the right-hand
1640 * boundary, which is illegal.
1642 * NOTE: The cursor's parent or parent_index must be adjusted for
1643 * the case where a new parent (new root) was created, and the case
1644 * where the cursor is now pointing at the split node.
1646 if (cursor->index >= split) {
1647 cursor->parent_index = parent_index + 1;
1648 cursor->index -= split;
1649 hammer_unlock(&cursor->node->lock);
1650 hammer_rel_node(cursor->node);
1651 cursor->node = new_node; /* locked and ref'd */
1653 cursor->parent_index = parent_index;
1654 hammer_unlock(&new_node->lock);
1655 hammer_rel_node(new_node);
1659 * Fixup left and right bounds
1661 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1662 cursor->left_bound = &parent_elm[0].internal.base;
1663 cursor->right_bound = &parent_elm[1].internal.base;
1664 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1665 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1666 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1667 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1670 hammer_btree_unlock_children(cursor->trans->hmp, &lockroot, NULL);
1671 hammer_cursor_downgrade(cursor);
1676 * Same as the above, but splits a full leaf node.
1680 btree_split_leaf(hammer_cursor_t cursor)
1682 hammer_node_ondisk_t ondisk;
1683 hammer_node_t parent;
1686 hammer_node_t new_leaf;
1687 hammer_btree_elm_t elm;
1688 hammer_btree_elm_t parent_elm;
1689 hammer_base_elm_t mid_boundary;
1694 const size_t esize = sizeof(*elm);
1696 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1698 ++hammer_stats_btree_splits;
1700 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1701 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1702 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1703 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1706 * Calculate the split point. If the insertion point is at the
1707 * end of the leaf we adjust the split point significantly to the
1708 * right to try to optimize node fill and flag it. If we hit
1709 * that same leaf again our heuristic failed and we don't try
1710 * to optimize node fill (it could lead to a degenerate case).
1712 leaf = cursor->node;
1713 ondisk = leaf->ondisk;
1714 KKASSERT(ondisk->count > 4);
1715 if (cursor->index == ondisk->count &&
1716 (leaf->flags & HAMMER_NODE_NONLINEAR) == 0) {
1717 split = (ondisk->count + 1) * 3 / 4;
1718 leaf->flags |= HAMMER_NODE_NONLINEAR;
1720 split = (ondisk->count + 1) / 2;
1725 * If the insertion point is at the split point shift the
1726 * split point left so we don't have to worry about
1728 if (cursor->index == split)
1731 KKASSERT(split > 0 && split < ondisk->count);
1736 elm = &ondisk->elms[split];
1738 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1739 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1740 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1741 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1744 * If we are at the root of the tree, create a new root node with
1745 * 1 element and split normally. Avoid making major modifications
1746 * until we know the whole operation will work.
1748 if (ondisk->parent == 0) {
1749 parent = hammer_alloc_btree(cursor->trans, 0, &error);
1752 hammer_lock_ex(&parent->lock);
1753 hammer_modify_node_noundo(cursor->trans, parent);
1754 ondisk = parent->ondisk;
1757 ondisk->mirror_tid = leaf->ondisk->mirror_tid;
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 ondisk->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 if (cursor->parent) {
1867 hammer_unlock(&cursor->parent->lock);
1868 hammer_rel_node(cursor->parent);
1870 cursor->parent = parent; /* lock'd and ref'd */
1871 hammer_rel_volume(volume, 0);
1873 hammer_modify_node_done(leaf);
1876 * Ok, now adjust the cursor depending on which element the original
1877 * index was pointing at. If we are >= the split point the push node
1878 * is now in the new node.
1880 * NOTE: If we are at the split point itself we need to select the
1881 * old or new node based on where key_beg's insertion point will be.
1882 * If we pick the wrong side the inserted element will wind up in
1883 * the wrong leaf node and outside that node's bounds.
1885 if (cursor->index > split ||
1886 (cursor->index == split &&
1887 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1888 cursor->parent_index = parent_index + 1;
1889 cursor->index -= split;
1890 hammer_unlock(&cursor->node->lock);
1891 hammer_rel_node(cursor->node);
1892 cursor->node = new_leaf;
1894 cursor->parent_index = parent_index;
1895 hammer_unlock(&new_leaf->lock);
1896 hammer_rel_node(new_leaf);
1900 * Fixup left and right bounds
1902 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1903 cursor->left_bound = &parent_elm[0].internal.base;
1904 cursor->right_bound = &parent_elm[1].internal.base;
1907 * Assert that the bounds are correct.
1909 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1910 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1911 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1912 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1913 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1914 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
1917 hammer_cursor_downgrade(cursor);
1924 * Recursively correct the right-hand boundary's create_tid to (tid) as
1925 * long as the rest of the key matches. We have to recurse upward in
1926 * the tree as well as down the left side of each parent's right node.
1928 * Return EDEADLK if we were only partially successful, forcing the caller
1929 * to try again. The original cursor is not modified. This routine can
1930 * also fail with EDEADLK if it is forced to throw away a portion of its
1933 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1936 TAILQ_ENTRY(hammer_rhb) entry;
1941 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1944 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1947 struct hammer_rhb_list rhb_list;
1948 hammer_base_elm_t elm;
1949 hammer_node_t orig_node;
1950 struct hammer_rhb *rhb;
1954 TAILQ_INIT(&rhb_list);
1955 hmp = cursor->trans->hmp;
1958 * Save our position so we can restore it on return. This also
1959 * gives us a stable 'elm'.
1961 orig_node = cursor->node;
1962 hammer_ref_node(orig_node);
1963 hammer_lock_sh(&orig_node->lock);
1964 orig_index = cursor->index;
1965 elm = &orig_node->ondisk->elms[orig_index].base;
1968 * Now build a list of parents going up, allocating a rhb
1969 * structure for each one.
1971 while (cursor->parent) {
1973 * Stop if we no longer have any right-bounds to fix up
1975 if (elm->obj_id != cursor->right_bound->obj_id ||
1976 elm->rec_type != cursor->right_bound->rec_type ||
1977 elm->key != cursor->right_bound->key) {
1982 * Stop if the right-hand bound's create_tid does not
1983 * need to be corrected.
1985 if (cursor->right_bound->create_tid >= tid)
1988 rhb = kmalloc(sizeof(*rhb), hmp->m_misc, M_WAITOK|M_ZERO);
1989 rhb->node = cursor->parent;
1990 rhb->index = cursor->parent_index;
1991 hammer_ref_node(rhb->node);
1992 hammer_lock_sh(&rhb->node->lock);
1993 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1995 hammer_cursor_up(cursor);
1999 * now safely adjust the right hand bound for each rhb. This may
2000 * also require taking the right side of the tree and iterating down
2004 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2005 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
2008 TAILQ_REMOVE(&rhb_list, rhb, entry);
2009 hammer_unlock(&rhb->node->lock);
2010 hammer_rel_node(rhb->node);
2011 kfree(rhb, hmp->m_misc);
2013 switch (cursor->node->ondisk->type) {
2014 case HAMMER_BTREE_TYPE_INTERNAL:
2016 * Right-boundary for parent at internal node
2017 * is one element to the right of the element whos
2018 * right boundary needs adjusting. We must then
2019 * traverse down the left side correcting any left
2020 * bounds (which may now be too far to the left).
2023 error = hammer_btree_correct_lhb(cursor, tid);
2026 hpanic("Bad node type");
2035 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2036 TAILQ_REMOVE(&rhb_list, rhb, entry);
2037 hammer_unlock(&rhb->node->lock);
2038 hammer_rel_node(rhb->node);
2039 kfree(rhb, hmp->m_misc);
2041 error = hammer_cursor_seek(cursor, orig_node, orig_index);
2042 hammer_unlock(&orig_node->lock);
2043 hammer_rel_node(orig_node);
2048 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
2049 * bound going downward starting at the current cursor position.
2051 * This function does not restore the cursor after use.
2054 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
2056 struct hammer_rhb_list rhb_list;
2057 hammer_base_elm_t elm;
2058 hammer_base_elm_t cmp;
2059 struct hammer_rhb *rhb;
2063 TAILQ_INIT(&rhb_list);
2064 hmp = cursor->trans->hmp;
2066 cmp = &cursor->node->ondisk->elms[cursor->index].base;
2069 * Record the node and traverse down the left-hand side for all
2070 * matching records needing a boundary correction.
2074 rhb = kmalloc(sizeof(*rhb), hmp->m_misc, M_WAITOK|M_ZERO);
2075 rhb->node = cursor->node;
2076 rhb->index = cursor->index;
2077 hammer_ref_node(rhb->node);
2078 hammer_lock_sh(&rhb->node->lock);
2079 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
2081 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2083 * Nothing to traverse down if we are at the right
2084 * boundary of an internal node.
2086 if (cursor->index == cursor->node->ondisk->count)
2089 elm = &cursor->node->ondisk->elms[cursor->index].base;
2090 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
2092 hpanic("Illegal leaf record type %02x", elm->btype);
2094 error = hammer_cursor_down(cursor);
2098 elm = &cursor->node->ondisk->elms[cursor->index].base;
2099 if (elm->obj_id != cmp->obj_id ||
2100 elm->rec_type != cmp->rec_type ||
2101 elm->key != cmp->key) {
2104 if (elm->create_tid >= tid)
2110 * Now we can safely adjust the left-hand boundary from the bottom-up.
2111 * The last element we remove from the list is the caller's right hand
2112 * boundary, which must also be adjusted.
2114 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2115 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
2118 TAILQ_REMOVE(&rhb_list, rhb, entry);
2119 hammer_unlock(&rhb->node->lock);
2120 hammer_rel_node(rhb->node);
2121 kfree(rhb, hmp->m_misc);
2123 elm = &cursor->node->ondisk->elms[cursor->index].base;
2124 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2125 hammer_modify_node(cursor->trans, cursor->node,
2127 sizeof(elm->create_tid));
2128 elm->create_tid = tid;
2129 hammer_modify_node_done(cursor->node);
2131 hpanic("Bad element type");
2138 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2139 TAILQ_REMOVE(&rhb_list, rhb, entry);
2140 hammer_unlock(&rhb->node->lock);
2141 hammer_rel_node(rhb->node);
2142 kfree(rhb, hmp->m_misc);
2150 * Attempt to remove the locked, empty or want-to-be-empty B-Tree node at
2151 * (cursor->node). Returns 0 on success, EDEADLK if we could not complete
2152 * the operation due to a deadlock, or some other error.
2154 * This routine is initially called with an empty leaf and may be
2155 * recursively called with single-element internal nodes.
2157 * It should also be noted that when removing empty leaves we must be sure
2158 * to test and update mirror_tid because another thread may have deadlocked
2159 * against us (or someone) trying to propagate it up and cannot retry once
2160 * the node has been deleted.
2162 * On return the cursor may end up pointing to an internal node, suitable
2163 * for further iteration but not for an immediate insertion or deletion.
2166 btree_remove(hammer_cursor_t cursor, int *ndelete)
2168 hammer_node_ondisk_t ondisk;
2169 hammer_btree_elm_t elm;
2171 hammer_node_t parent;
2172 const int esize = sizeof(*elm);
2175 node = cursor->node;
2178 * When deleting the root of the filesystem convert it to
2179 * an empty leaf node. Internal nodes cannot be empty.
2181 ondisk = node->ondisk;
2182 if (ondisk->parent == 0) {
2183 KKASSERT(cursor->parent == NULL);
2184 hammer_modify_node_all(cursor->trans, node);
2185 KKASSERT(ondisk == node->ondisk);
2186 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
2188 hammer_modify_node_done(node);
2193 parent = cursor->parent;
2196 * Attempt to remove the parent's reference to the child. If the
2197 * parent would become empty we have to recurse. If we fail we
2198 * leave the parent pointing to an empty leaf node.
2200 * We have to recurse successfully before we can delete the internal
2201 * node as it is illegal to have empty internal nodes. Even though
2202 * the operation may be aborted we must still fixup any unlocked
2203 * cursors as if we had deleted the element prior to recursing
2204 * (by calling hammer_cursor_deleted_element()) so those cursors
2205 * are properly forced up the chain by the recursion.
2207 if (parent->ondisk->count == 1) {
2209 * This special cursor_up_locked() call leaves the original
2210 * node exclusively locked and referenced, leaves the
2211 * original parent locked (as the new node), and locks the
2212 * new parent. It can return EDEADLK.
2214 * We cannot call hammer_cursor_removed_node() until we are
2215 * actually able to remove the node. If we did then tracked
2216 * cursors in the middle of iterations could be repointed
2217 * to a parent node. If this occurs they could end up
2218 * scanning newly inserted records into the node (that could
2219 * not be deleted) when they push down again.
2221 * Due to the way the recursion works the final parent is left
2222 * in cursor->parent after the recursion returns. Each
2223 * layer on the way back up is thus able to call
2224 * hammer_cursor_removed_node() and 'jump' the node up to
2225 * the (same) final parent.
2227 * NOTE! The local variable 'parent' is invalid after we
2228 * call hammer_cursor_up_locked().
2230 error = hammer_cursor_up_locked(cursor);
2234 hammer_cursor_deleted_element(cursor->node, 0);
2235 error = btree_remove(cursor, ndelete);
2237 KKASSERT(node != cursor->node);
2238 hammer_cursor_removed_node(
2239 node, cursor->node, cursor->index);
2240 hammer_modify_node_all(cursor->trans, node);
2241 ondisk = node->ondisk;
2242 ondisk->type = HAMMER_BTREE_TYPE_DELETED;
2244 hammer_modify_node_done(node);
2245 hammer_flush_node(node, 0);
2246 hammer_delete_node(cursor->trans, node);
2251 * Defer parent removal because we could not
2252 * get the lock, just let the leaf remain
2256 * hammer show doesn't consider this as an error.
2259 hammer_unlock(&node->lock);
2260 hammer_rel_node(node);
2263 * Defer parent removal because we could not
2264 * get the lock, just let the leaf remain
2268 * hammer show doesn't consider this as an error.
2272 KKASSERT(parent->ondisk->count > 1);
2274 hammer_modify_node_all(cursor->trans, parent);
2275 ondisk = parent->ondisk;
2276 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
2278 elm = &ondisk->elms[cursor->parent_index];
2279 KKASSERT(elm->internal.subtree_offset == node->node_offset);
2280 KKASSERT(ondisk->count > 0);
2283 * We must retain the highest mirror_tid. The deleted
2284 * range is now encompassed by the element to the left.
2285 * If we are already at the left edge the new left edge
2286 * inherits mirror_tid.
2288 * Note that bounds of the parent to our parent may create
2289 * a gap to the left of our left-most node or to the right
2290 * of our right-most node. The gap is silently included
2291 * in the mirror_tid's area of effect from the point of view
2294 if (cursor->parent_index) {
2295 if (elm[-1].internal.mirror_tid <
2296 elm[0].internal.mirror_tid) {
2297 elm[-1].internal.mirror_tid =
2298 elm[0].internal.mirror_tid;
2301 if (elm[1].internal.mirror_tid <
2302 elm[0].internal.mirror_tid) {
2303 elm[1].internal.mirror_tid =
2304 elm[0].internal.mirror_tid;
2309 * Delete the subtree reference in the parent. Include
2310 * boundary element at end.
2312 bcopy(&elm[1], &elm[0],
2313 (ondisk->count - cursor->parent_index) * esize);
2315 hammer_modify_node_done(parent);
2316 hammer_cursor_removed_node(node, parent, cursor->parent_index);
2317 hammer_cursor_deleted_element(parent, cursor->parent_index);
2318 hammer_flush_node(node, 0);
2319 hammer_delete_node(cursor->trans, node);
2322 * cursor->node is invalid, cursor up to make the cursor
2323 * valid again. We have to flag the condition in case
2324 * another thread wiggles an insertion in during an
2327 cursor->flags |= HAMMER_CURSOR_ITERATE_CHECK;
2328 error = hammer_cursor_up(cursor);
2336 * Propagate mirror_tid up the B-Tree starting at the current cursor.
2338 * WARNING! Because we push and pop the passed cursor, it may be
2339 * modified by other B-Tree operations while it is unlocked
2340 * and things like the node & leaf pointers, and indexes might
2344 hammer_btree_do_propagation(hammer_cursor_t cursor,
2345 hammer_btree_leaf_elm_t leaf)
2347 hammer_cursor_t ncursor;
2348 hammer_tid_t mirror_tid;
2349 int error __debugvar;
2352 * We do not propagate a mirror_tid if the filesystem was mounted
2353 * in no-mirror mode.
2355 if (cursor->trans->hmp->master_id < 0)
2359 * This is a bit of a hack because we cannot deadlock or return
2360 * EDEADLK here. The related operation has already completed and
2361 * we must propagate the mirror_tid now regardless.
2363 * Generate a new cursor which inherits the original's locks and
2364 * unlock the original. Use the new cursor to propagate the
2365 * mirror_tid. Then clean up the new cursor and reacquire locks
2368 * hammer_dup_cursor() cannot dup locks. The dup inherits the
2369 * original's locks and the original is tracked and must be
2372 mirror_tid = cursor->node->ondisk->mirror_tid;
2373 KKASSERT(mirror_tid != 0);
2374 ncursor = hammer_push_cursor(cursor);
2375 error = hammer_btree_mirror_propagate(ncursor, mirror_tid);
2376 KKASSERT(error == 0);
2377 hammer_pop_cursor(cursor, ncursor);
2378 /* WARNING: cursor's leaf pointer may change after pop */
2383 * Propagate a mirror TID update upwards through the B-Tree to the root.
2385 * A locked internal node must be passed in. The node will remain locked
2388 * This function syncs mirror_tid at the specified internal node's element,
2389 * adjusts the node's aggregation mirror_tid, and then recurses upwards.
2392 hammer_btree_mirror_propagate(hammer_cursor_t cursor, hammer_tid_t mirror_tid)
2394 hammer_btree_internal_elm_t elm;
2399 error = hammer_cursor_up(cursor);
2401 error = hammer_cursor_upgrade(cursor);
2404 * We can ignore HAMMER_CURSOR_ITERATE_CHECK, the
2405 * cursor will still be properly positioned for
2406 * mirror propagation, just not for iterations.
2408 while (error == EDEADLK) {
2409 hammer_recover_cursor(cursor);
2410 error = hammer_cursor_upgrade(cursor);
2416 * If the cursor deadlocked it could end up at a leaf
2417 * after we lost the lock.
2419 node = cursor->node;
2420 if (node->ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
2424 * Adjust the node's element
2426 elm = &node->ondisk->elms[cursor->index].internal;
2427 if (elm->mirror_tid >= mirror_tid)
2429 hammer_modify_node(cursor->trans, node, &elm->mirror_tid,
2430 sizeof(elm->mirror_tid));
2431 elm->mirror_tid = mirror_tid;
2432 hammer_modify_node_done(node);
2433 if (hammer_debug_general & 0x0002) {
2434 hdkprintf("propagate %016jx @%016jx:%d\n",
2435 (intmax_t)mirror_tid,
2436 (intmax_t)node->node_offset,
2442 * Adjust the node's mirror_tid aggregator
2444 if (node->ondisk->mirror_tid >= mirror_tid)
2446 hammer_modify_node_field(cursor->trans, node, mirror_tid);
2447 node->ondisk->mirror_tid = mirror_tid;
2448 hammer_modify_node_done(node);
2449 if (hammer_debug_general & 0x0002) {
2450 hdkprintf("propagate %016jx @%016jx\n",
2451 (intmax_t)mirror_tid,
2452 (intmax_t)node->node_offset);
2455 if (error == ENOENT)
2461 * Return a pointer to node's parent. If there is no error,
2462 * *parent_index is set to an index of parent's elm that points
2466 hammer_btree_get_parent(hammer_transaction_t trans, hammer_node_t node,
2467 int *parent_indexp, int *errorp, int try_exclusive)
2469 hammer_node_t parent;
2470 hammer_btree_elm_t elm;
2476 parent = hammer_get_node(trans, node->ondisk->parent, 0, errorp);
2478 KKASSERT(parent == NULL);
2481 KKASSERT ((parent->flags & HAMMER_NODE_DELETED) == 0);
2486 if (try_exclusive) {
2487 if (hammer_lock_ex_try(&parent->lock)) {
2488 hammer_rel_node(parent);
2493 hammer_lock_sh(&parent->lock);
2497 * Figure out which element in the parent is pointing to the
2500 if (node->ondisk->count) {
2501 i = hammer_btree_search_node(&node->ondisk->elms[0].base,
2506 while (i < parent->ondisk->count) {
2507 elm = &parent->ondisk->elms[i];
2508 if (elm->internal.subtree_offset == node->node_offset)
2512 if (i == parent->ondisk->count) {
2513 hammer_unlock(&parent->lock);
2514 hpanic("Bad B-Tree link: parent %p node %p", parent, node);
2517 KKASSERT(*errorp == 0);
2522 * The element (elm) has been moved to a new internal node (node).
2524 * If the element represents a pointer to an internal node that node's
2525 * parent must be adjusted to the element's new location.
2527 * XXX deadlock potential here with our exclusive locks
2530 btree_set_parent_of_child(hammer_transaction_t trans, hammer_node_t node,
2531 hammer_btree_elm_t elm)
2533 hammer_node_t child;
2538 if (hammer_is_internal_node_elm(elm)) {
2539 child = hammer_get_node(trans, elm->internal.subtree_offset,
2542 hammer_modify_node_field(trans, child, parent);
2543 child->ondisk->parent = node->node_offset;
2544 hammer_modify_node_done(child);
2545 hammer_rel_node(child);
2552 * Initialize the root of a recursive B-Tree node lock list structure.
2555 hammer_node_lock_init(hammer_node_lock_t parent, hammer_node_t node)
2557 TAILQ_INIT(&parent->list);
2558 parent->parent = NULL;
2559 parent->node = node;
2561 parent->count = node->ondisk->count;
2562 parent->copy = NULL;
2567 * Initialize a cache of hammer_node_lock's including space allocated
2570 * This is used by the rebalancing code to preallocate the copy space
2571 * for ~4096 B-Tree nodes (16MB of data) prior to acquiring any HAMMER
2572 * locks, otherwise we can blow out the pageout daemon's emergency
2573 * reserve and deadlock it.
2575 * NOTE: HAMMER_NODE_LOCK_LCACHE is not set on items cached in the lcache.
2576 * The flag is set when the item is pulled off the cache for use.
2579 hammer_btree_lcache_init(hammer_mount_t hmp, hammer_node_lock_t lcache,
2582 hammer_node_lock_t item;
2585 for (count = 1; depth; --depth)
2586 count *= HAMMER_BTREE_LEAF_ELMS;
2587 bzero(lcache, sizeof(*lcache));
2588 TAILQ_INIT(&lcache->list);
2590 item = kmalloc(sizeof(*item), hmp->m_misc, M_WAITOK|M_ZERO);
2591 item->copy = kmalloc(sizeof(*item->copy),
2592 hmp->m_misc, M_WAITOK);
2593 TAILQ_INIT(&item->list);
2594 TAILQ_INSERT_TAIL(&lcache->list, item, entry);
2600 hammer_btree_lcache_free(hammer_mount_t hmp, hammer_node_lock_t lcache)
2602 hammer_node_lock_t item;
2604 while ((item = TAILQ_FIRST(&lcache->list)) != NULL) {
2605 TAILQ_REMOVE(&lcache->list, item, entry);
2606 KKASSERT(item->copy);
2607 KKASSERT(TAILQ_EMPTY(&item->list));
2608 kfree(item->copy, hmp->m_misc);
2609 kfree(item, hmp->m_misc);
2611 KKASSERT(lcache->copy == NULL);
2615 * Exclusively lock all the children of node. This is used by the split
2616 * code to prevent anyone from accessing the children of a cursor node
2617 * while we fix-up its parent offset.
2619 * If we don't lock the children we can really mess up cursors which block
2620 * trying to cursor-up into our node.
2622 * On failure EDEADLK (or some other error) is returned. If a deadlock
2623 * error is returned the cursor is adjusted to block on termination.
2625 * The caller is responsible for managing parent->node, the root's node
2626 * is usually aliased from a cursor.
2629 hammer_btree_lock_children(hammer_cursor_t cursor, int depth,
2630 hammer_node_lock_t parent,
2631 hammer_node_lock_t lcache)
2634 hammer_node_lock_t item;
2635 hammer_node_ondisk_t ondisk;
2636 hammer_btree_elm_t elm;
2637 hammer_node_t child;
2642 node = parent->node;
2643 ondisk = node->ondisk;
2645 hmp = cursor->trans->hmp;
2647 if (ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
2648 return(0); /* This could return non-zero */
2651 * We really do not want to block on I/O with exclusive locks held,
2652 * pre-get the children before trying to lock the mess. This is
2653 * only done one-level deep for now.
2655 for (i = 0; i < ondisk->count; ++i) {
2656 ++hammer_stats_btree_elements;
2657 elm = &ondisk->elms[i];
2658 child = hammer_get_node(cursor->trans,
2659 elm->internal.subtree_offset,
2662 hammer_rel_node(child);
2668 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2669 ++hammer_stats_btree_elements;
2670 elm = &ondisk->elms[i];
2672 KKASSERT(elm->internal.subtree_offset != 0);
2673 child = hammer_get_node(cursor->trans,
2674 elm->internal.subtree_offset,
2677 if (hammer_lock_ex_try(&child->lock) != 0) {
2678 if (cursor->deadlk_node == NULL) {
2679 cursor->deadlk_node = child;
2680 hammer_ref_node(cursor->deadlk_node);
2683 hammer_rel_node(child);
2686 item = TAILQ_FIRST(&lcache->list);
2687 KKASSERT(item != NULL);
2688 item->flags |= HAMMER_NODE_LOCK_LCACHE;
2689 TAILQ_REMOVE(&lcache->list, item, entry);
2691 item = kmalloc(sizeof(*item),
2694 TAILQ_INIT(&item->list);
2697 TAILQ_INSERT_TAIL(&parent->list, item, entry);
2698 item->parent = parent;
2701 item->count = child->ondisk->count;
2704 * Recurse (used by the rebalancing code)
2706 if (depth > 1 && elm->base.btype == HAMMER_BTREE_TYPE_INTERNAL) {
2707 error = hammer_btree_lock_children(
2717 hammer_btree_unlock_children(hmp, parent, lcache);
2722 * Create an in-memory copy of all B-Tree nodes listed, recursively,
2723 * including the parent.
2726 hammer_btree_lock_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
2728 hammer_mount_t hmp = cursor->trans->hmp;
2729 hammer_node_lock_t item;
2731 if (parent->copy == NULL) {
2732 KKASSERT((parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0);
2733 parent->copy = kmalloc(sizeof(*parent->copy),
2734 hmp->m_misc, M_WAITOK);
2736 KKASSERT((parent->flags & HAMMER_NODE_LOCK_UPDATED) == 0);
2737 *parent->copy = *parent->node->ondisk;
2738 TAILQ_FOREACH(item, &parent->list, entry) {
2739 hammer_btree_lock_copy(cursor, item);
2744 * Recursively sync modified copies to the media.
2747 hammer_btree_sync_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
2749 hammer_node_lock_t item;
2752 if (parent->flags & HAMMER_NODE_LOCK_UPDATED) {
2754 hammer_modify_node_all(cursor->trans, parent->node);
2755 *parent->node->ondisk = *parent->copy;
2756 hammer_modify_node_done(parent->node);
2757 if (parent->copy->type == HAMMER_BTREE_TYPE_DELETED) {
2758 hammer_flush_node(parent->node, 0);
2759 hammer_delete_node(cursor->trans, parent->node);
2762 TAILQ_FOREACH(item, &parent->list, entry) {
2763 count += hammer_btree_sync_copy(cursor, item);
2769 * Release previously obtained node locks. The caller is responsible for
2770 * cleaning up parent->node itself (its usually just aliased from a cursor),
2771 * but this function will take care of the copies.
2773 * NOTE: The root node is not placed in the lcache and node->copy is not
2774 * deallocated when lcache != NULL.
2777 hammer_btree_unlock_children(hammer_mount_t hmp, hammer_node_lock_t parent,
2778 hammer_node_lock_t lcache)
2780 hammer_node_lock_t item;
2781 hammer_node_ondisk_t copy;
2783 while ((item = TAILQ_FIRST(&parent->list)) != NULL) {
2784 TAILQ_REMOVE(&parent->list, item, entry);
2785 hammer_btree_unlock_children(hmp, item, lcache);
2786 hammer_unlock(&item->node->lock);
2787 hammer_rel_node(item->node);
2790 * NOTE: When placing the item back in the lcache
2791 * the flag is cleared by the bzero().
2792 * Remaining fields are cleared as a safety
2795 KKASSERT(item->flags & HAMMER_NODE_LOCK_LCACHE);
2796 KKASSERT(TAILQ_EMPTY(&item->list));
2798 bzero(item, sizeof(*item));
2799 TAILQ_INIT(&item->list);
2802 bzero(copy, sizeof(*copy));
2803 TAILQ_INSERT_TAIL(&lcache->list, item, entry);
2805 kfree(item, hmp->m_misc);
2808 if (parent->copy && (parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0) {
2809 kfree(parent->copy, hmp->m_misc);
2810 parent->copy = NULL; /* safety */
2814 /************************************************************************
2815 * MISCELLANIOUS SUPPORT *
2816 ************************************************************************/
2819 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2821 * Note that for this particular function a return value of -1, 0, or +1
2822 * can denote a match if create_tid is otherwise discounted. A create_tid
2823 * of zero is considered to be 'infinity' in comparisons.
2825 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2828 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2830 if (key1->localization < key2->localization)
2832 if (key1->localization > key2->localization)
2835 if (key1->obj_id < key2->obj_id)
2837 if (key1->obj_id > key2->obj_id)
2840 if (key1->rec_type < key2->rec_type)
2842 if (key1->rec_type > key2->rec_type)
2845 if (key1->key < key2->key)
2847 if (key1->key > key2->key)
2851 * A create_tid of zero indicates a record which is undeletable
2852 * and must be considered to have a value of positive infinity.
2854 if (key1->create_tid == 0) {
2855 if (key2->create_tid == 0)
2859 if (key2->create_tid == 0)
2861 if (key1->create_tid < key2->create_tid)
2863 if (key1->create_tid > key2->create_tid)
2869 * Test a timestamp against an element to determine whether the
2870 * element is visible. A timestamp of 0 means 'infinity'.
2873 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2876 if (base->delete_tid)
2880 if (asof < base->create_tid)
2882 if (base->delete_tid && asof >= base->delete_tid)
2888 * Create a separator half way inbetween key1 and key2. For fields just
2889 * one unit apart, the separator will match key2. key1 is on the left-hand
2890 * side and key2 is on the right-hand side.
2892 * key2 must be >= the separator. It is ok for the separator to match key2.
2894 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2897 * NOTE: It might be beneficial to just scrap this whole mess and just
2898 * set the separator to key2.
2900 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2901 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2904 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2905 hammer_base_elm_t dest)
2907 bzero(dest, sizeof(*dest));
2909 dest->rec_type = key2->rec_type;
2910 dest->key = key2->key;
2911 dest->obj_id = key2->obj_id;
2912 dest->create_tid = key2->create_tid;
2914 MAKE_SEPARATOR(key1, key2, dest, localization);
2915 if (key1->localization == key2->localization) {
2916 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2917 if (key1->obj_id == key2->obj_id) {
2918 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2919 if (key1->rec_type == key2->rec_type) {
2920 MAKE_SEPARATOR(key1, key2, dest, key);
2922 * Don't bother creating a separator for
2923 * create_tid, which also conveniently avoids
2924 * having to handle the create_tid == 0
2925 * (infinity) case. Just leave create_tid
2928 * Worst case, dest matches key2 exactly,
2929 * which is acceptable.
2936 #undef MAKE_SEPARATOR
2939 * Return whether a generic internal or leaf node is full
2943 btree_node_is_full(hammer_node_ondisk_t node)
2945 return(btree_max_elements(node->type) == node->count);
2950 btree_max_elements(uint8_t type)
2954 n = hammer_node_max_elements(type);
2956 hpanic("bad type %d", type);
2961 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2965 kprintf("node %p count=%d parent=%016jx type=%c\n",
2966 ondisk, ondisk->count,
2967 (intmax_t)ondisk->parent, ondisk->type);
2969 switch (ondisk->type) {
2970 case HAMMER_BTREE_TYPE_INTERNAL:
2971 n = ondisk->count + 1; /* count is NOT boundary inclusive */
2973 case HAMMER_BTREE_TYPE_LEAF:
2974 n = ondisk->count; /* there is no boundary */
2977 return; /* nothing to do */
2981 * Dump elements including boundary.
2983 for (i = 0; i < n; ++i) {
2985 hammer_print_btree_elm(&ondisk->elms[i]);
2990 hammer_print_btree_elm(hammer_btree_elm_t elm)
2992 kprintf("\tobj_id = %016jx\n", (intmax_t)elm->base.obj_id);
2993 kprintf("\tkey = %016jx\n", (intmax_t)elm->base.key);
2994 kprintf("\tcreate_tid = %016jx\n", (intmax_t)elm->base.create_tid);
2995 kprintf("\tdelete_tid = %016jx\n", (intmax_t)elm->base.delete_tid);
2996 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2997 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2998 kprintf("\tbtype = %02x (%c)\n", elm->base.btype,
2999 hammer_elm_btype(elm));
3000 kprintf("\tlocalization = %08x\n", elm->base.localization);
3002 if (hammer_is_internal_node_elm(elm)) {
3003 kprintf("\tsubtree_off = %016jx\n",
3004 (intmax_t)elm->internal.subtree_offset);
3005 } else if (hammer_is_leaf_node_elm(elm)) {
3006 kprintf("\tdata_offset = %016jx\n",
3007 (intmax_t)elm->leaf.data_offset);
3008 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
3009 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);
3015 hammer_debug_btree_elm(hammer_cursor_t cursor, hammer_btree_elm_t elm,
3016 const char *s, int res)
3018 hkprintf("%-8s %016jx[%02d] %c "
3019 "lo=%08x obj=%016jx rec=%02x key=%016jx tid=%016jx td=%p "
3022 (intmax_t)cursor->node->node_offset,
3024 hammer_elm_btype(elm),
3025 elm->base.localization,
3026 (intmax_t)elm->base.obj_id,
3028 (intmax_t)elm->base.key,
3029 (intmax_t)elm->base.create_tid,
3036 hammer_debug_btree_parent(hammer_cursor_t cursor, const char *s)
3038 hammer_btree_elm_t elm =
3039 &cursor->parent->ondisk->elms[cursor->parent_index];
3041 hkprintf("%-8s %016jx[%d] %c "
3042 "(%016jx/%016jx %016jx/%016jx) (%p/%p %p/%p)\n",
3044 (intmax_t)cursor->parent->node_offset,
3045 cursor->parent_index,
3046 hammer_elm_btype(elm),
3047 (intmax_t)cursor->left_bound->obj_id,
3048 (intmax_t)elm->internal.base.obj_id,
3049 (intmax_t)cursor->right_bound->obj_id,
3050 (intmax_t)(elm + 1)->internal.base.obj_id,
3053 cursor->right_bound,