HAMMER 59I/Many: Stabilization pass
[dragonfly.git] / sys / vfs / hammer / hammer_btree.c
blob296d414c812a261a2d1a59b56f67d4de53039685
1 /*
2 * Copyright (c) 2007-2008 The DragonFly Project. All rights reserved.
3 *
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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
16 * distribution.
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
32 * SUCH DAMAGE.
34 * $DragonFly: src/sys/vfs/hammer/hammer_btree.c,v 1.60 2008/07/01 16:48:51 dillon Exp $
38 * HAMMER B-Tree index
40 * HAMMER implements a modified B+Tree. In documentation this will
41 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
42 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
43 * of the tree), but adds two additional boundary elements which describe
44 * the left-most and right-most element a node is able to represent. In
45 * otherwords, we have boundary elements at the two ends of a B-Tree node
46 * instead of sub-tree pointers.
48 * A B-Tree internal node looks like this:
50 * B N N N N N N B <-- boundary and internal elements
51 * S S S S S S S <-- subtree pointers
53 * A B-Tree leaf node basically looks like this:
55 * L L L L L L L L <-- leaf elemenets
57 * The radix for an internal node is 1 less then a leaf but we get a
58 * number of significant benefits for our troubles.
60 * The big benefit to using a B-Tree containing boundary information
61 * is that it is possible to cache pointers into the middle of the tree
62 * and not have to start searches, insertions, OR deletions at the root
63 * node. In particular, searches are able to progress in a definitive
64 * direction from any point in the tree without revisting nodes. This
65 * greatly improves the efficiency of many operations, most especially
66 * record appends.
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
73 * B-Tree.
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
79 * up the boundaries).
81 #include "hammer.h"
82 #include <sys/buf.h>
83 #include <sys/buf2.h>
85 static int btree_search(hammer_cursor_t cursor, int flags);
86 static int btree_split_internal(hammer_cursor_t cursor);
87 static int btree_split_leaf(hammer_cursor_t cursor);
88 static int btree_remove(hammer_cursor_t cursor);
89 static int btree_node_is_full(hammer_node_ondisk_t node);
90 static void hammer_make_separator(hammer_base_elm_t key1,
91 hammer_base_elm_t key2, hammer_base_elm_t dest);
94 * Iterate records after a search. The cursor is iterated forwards past
95 * the current record until a record matching the key-range requirements
96 * is found. ENOENT is returned if the iteration goes past the ending
97 * key.
99 * The iteration is inclusive of key_beg and can be inclusive or exclusive
100 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
102 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
103 * may be modified by B-Tree functions.
105 * cursor->key_beg may or may not be modified by this function during
106 * the iteration. XXX future - in case of an inverted lock we may have
107 * to reinitiate the lookup and set key_beg to properly pick up where we
108 * left off.
110 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
113 hammer_btree_iterate(hammer_cursor_t cursor)
115 hammer_node_ondisk_t node;
116 hammer_btree_elm_t elm;
117 int error;
118 int r;
119 int s;
122 * Skip past the current record
124 node = cursor->node->ondisk;
125 if (node == NULL)
126 return(ENOENT);
127 if (cursor->index < node->count &&
128 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
129 ++cursor->index;
133 * Loop until an element is found or we are done.
135 for (;;) {
137 * We iterate up the tree and then index over one element
138 * while we are at the last element in the current node.
140 * If we are at the root of the filesystem, cursor_up
141 * returns ENOENT.
143 * XXX this could be optimized by storing the information in
144 * the parent reference.
146 * XXX we can lose the node lock temporarily, this could mess
147 * up our scan.
149 ++hammer_stats_btree_iterations;
150 hammer_flusher_clean_loose_ios(cursor->trans->hmp);
152 if (cursor->index == node->count) {
153 if (hammer_debug_btree) {
154 kprintf("BRACKETU %016llx[%d] -> %016llx[%d] (td=%p)\n",
155 cursor->node->node_offset,
156 cursor->index,
157 (cursor->parent ? cursor->parent->node_offset : -1),
158 cursor->parent_index,
159 curthread);
161 KKASSERT(cursor->parent == NULL || cursor->parent->ondisk->elms[cursor->parent_index].internal.subtree_offset == cursor->node->node_offset);
162 error = hammer_cursor_up(cursor);
163 if (error)
164 break;
165 /* reload stale pointer */
166 node = cursor->node->ondisk;
167 KKASSERT(cursor->index != node->count);
170 * If we are reblocking we want to return internal
171 * nodes.
173 if (cursor->flags & HAMMER_CURSOR_REBLOCKING) {
174 cursor->flags |= HAMMER_CURSOR_ATEDISK;
175 return(0);
177 ++cursor->index;
178 continue;
182 * Check internal or leaf element. Determine if the record
183 * at the cursor has gone beyond the end of our range.
185 * We recurse down through internal nodes.
187 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
188 elm = &node->elms[cursor->index];
190 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
191 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
192 if (hammer_debug_btree) {
193 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx lo=%02x %d (td=%p)\n",
194 cursor->node->node_offset,
195 cursor->index,
196 elm[0].internal.base.obj_id,
197 elm[0].internal.base.rec_type,
198 elm[0].internal.base.key,
199 elm[0].internal.base.localization,
201 curthread
203 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx lo=%02x %d\n",
204 cursor->node->node_offset,
205 cursor->index + 1,
206 elm[1].internal.base.obj_id,
207 elm[1].internal.base.rec_type,
208 elm[1].internal.base.key,
209 elm[1].internal.base.localization,
214 if (r < 0) {
215 error = ENOENT;
216 break;
218 if (r == 0 && (cursor->flags &
219 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
220 error = ENOENT;
221 break;
223 KKASSERT(s <= 0);
226 * Better not be zero
228 KKASSERT(elm->internal.subtree_offset != 0);
231 * If running the mirror filter see if we can skip
232 * the entire sub-tree.
234 if (cursor->flags & HAMMER_CURSOR_MIRROR_FILTERED) {
235 if (elm->internal.mirror_tid <
236 cursor->mirror_tid) {
237 ++cursor->index;
238 continue;
242 error = hammer_cursor_down(cursor);
243 if (error)
244 break;
245 KKASSERT(cursor->index == 0);
246 /* reload stale pointer */
247 node = cursor->node->ondisk;
248 continue;
249 } else {
250 elm = &node->elms[cursor->index];
251 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
252 if (hammer_debug_btree) {
253 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx lo=%02x %d\n",
254 cursor->node->node_offset,
255 cursor->index,
256 (elm[0].leaf.base.btype ?
257 elm[0].leaf.base.btype : '?'),
258 elm[0].leaf.base.obj_id,
259 elm[0].leaf.base.rec_type,
260 elm[0].leaf.base.key,
261 elm[0].leaf.base.localization,
265 if (r < 0) {
266 error = ENOENT;
267 break;
271 * We support both end-inclusive and
272 * end-exclusive searches.
274 if (r == 0 &&
275 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
276 error = ENOENT;
277 break;
280 switch(elm->leaf.base.btype) {
281 case HAMMER_BTREE_TYPE_RECORD:
282 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
283 hammer_btree_chkts(cursor->asof, &elm->base)) {
284 ++cursor->index;
285 continue;
287 break;
288 default:
289 error = EINVAL;
290 break;
292 if (error)
293 break;
296 * node pointer invalid after loop
300 * Return entry
302 if (hammer_debug_btree) {
303 int i = cursor->index;
304 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
305 kprintf("ITERATE %p:%d %016llx %02x %016llx lo=%02x\n",
306 cursor->node, i,
307 elm->internal.base.obj_id,
308 elm->internal.base.rec_type,
309 elm->internal.base.key,
310 elm->internal.base.localization
313 return(0);
315 return(error);
319 * Iterate in the reverse direction. This is used by the pruning code to
320 * avoid overlapping records.
323 hammer_btree_iterate_reverse(hammer_cursor_t cursor)
325 hammer_node_ondisk_t node;
326 hammer_btree_elm_t elm;
327 int error;
328 int r;
329 int s;
332 * Skip past the current record. For various reasons the cursor
333 * may end up set to -1 or set to point at the end of the current
334 * node. These cases must be addressed.
336 node = cursor->node->ondisk;
337 if (node == NULL)
338 return(ENOENT);
339 if (cursor->index != -1 &&
340 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
341 --cursor->index;
343 if (cursor->index == cursor->node->ondisk->count)
344 --cursor->index;
347 * Loop until an element is found or we are done.
349 for (;;) {
350 ++hammer_stats_btree_iterations;
351 hammer_flusher_clean_loose_ios(cursor->trans->hmp);
354 * We iterate up the tree and then index over one element
355 * while we are at the last element in the current node.
357 if (cursor->index == -1) {
358 error = hammer_cursor_up(cursor);
359 if (error) {
360 cursor->index = 0; /* sanity */
361 break;
363 /* reload stale pointer */
364 node = cursor->node->ondisk;
365 KKASSERT(cursor->index != node->count);
366 --cursor->index;
367 continue;
371 * Check internal or leaf element. Determine if the record
372 * at the cursor has gone beyond the end of our range.
374 * We recurse down through internal nodes.
376 KKASSERT(cursor->index != node->count);
377 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
378 elm = &node->elms[cursor->index];
379 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
380 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
381 if (hammer_debug_btree) {
382 kprintf("BRACKETL %016llx[%d] %016llx %02x %016llx lo=%02x %d\n",
383 cursor->node->node_offset,
384 cursor->index,
385 elm[0].internal.base.obj_id,
386 elm[0].internal.base.rec_type,
387 elm[0].internal.base.key,
388 elm[0].internal.base.localization,
391 kprintf("BRACKETR %016llx[%d] %016llx %02x %016llx lo=%02x %d\n",
392 cursor->node->node_offset,
393 cursor->index + 1,
394 elm[1].internal.base.obj_id,
395 elm[1].internal.base.rec_type,
396 elm[1].internal.base.key,
397 elm[1].internal.base.localization,
402 if (s >= 0) {
403 error = ENOENT;
404 break;
406 KKASSERT(r >= 0);
409 * Better not be zero
411 KKASSERT(elm->internal.subtree_offset != 0);
413 error = hammer_cursor_down(cursor);
414 if (error)
415 break;
416 KKASSERT(cursor->index == 0);
417 /* reload stale pointer */
418 node = cursor->node->ondisk;
420 /* this can assign -1 if the leaf was empty */
421 cursor->index = node->count - 1;
422 continue;
423 } else {
424 elm = &node->elms[cursor->index];
425 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
426 if (hammer_debug_btree) {
427 kprintf("ELEMENT %016llx:%d %c %016llx %02x %016llx lo=%02x %d\n",
428 cursor->node->node_offset,
429 cursor->index,
430 (elm[0].leaf.base.btype ?
431 elm[0].leaf.base.btype : '?'),
432 elm[0].leaf.base.obj_id,
433 elm[0].leaf.base.rec_type,
434 elm[0].leaf.base.key,
435 elm[0].leaf.base.localization,
439 if (s > 0) {
440 error = ENOENT;
441 break;
444 switch(elm->leaf.base.btype) {
445 case HAMMER_BTREE_TYPE_RECORD:
446 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
447 hammer_btree_chkts(cursor->asof, &elm->base)) {
448 --cursor->index;
449 continue;
451 break;
452 default:
453 error = EINVAL;
454 break;
456 if (error)
457 break;
460 * node pointer invalid after loop
464 * Return entry
466 if (hammer_debug_btree) {
467 int i = cursor->index;
468 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
469 kprintf("ITERATE %p:%d %016llx %02x %016llx lo=%02x\n",
470 cursor->node, i,
471 elm->internal.base.obj_id,
472 elm->internal.base.rec_type,
473 elm->internal.base.key,
474 elm->internal.base.localization
477 return(0);
479 return(error);
483 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
484 * could not be found, EDEADLK if inserting and a retry is needed, and a
485 * fatal error otherwise. When retrying, the caller must terminate the
486 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
488 * The cursor is suitably positioned for a deletion on success, and suitably
489 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
490 * specified.
492 * The cursor may begin anywhere, the search will traverse the tree in
493 * either direction to locate the requested element.
495 * Most of the logic implementing historical searches is handled here. We
496 * do an initial lookup with create_tid set to the asof TID. Due to the
497 * way records are laid out, a backwards iteration may be required if
498 * ENOENT is returned to locate the historical record. Here's the
499 * problem:
501 * create_tid: 10 15 20
502 * LEAF1 LEAF2
503 * records: (11) (18)
505 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
506 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
507 * not visible and thus causes ENOENT to be returned. We really need
508 * to check record 11 in LEAF1. If it also fails then the search fails
509 * (e.g. it might represent the range 11-16 and thus still not match our
510 * AS-OF timestamp of 17). Note that LEAF1 could be empty, requiring
511 * further iterations.
513 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
514 * and the cursor->create_check TID if an iteration might be needed.
515 * In the above example create_check would be set to 14.
518 hammer_btree_lookup(hammer_cursor_t cursor)
520 int error;
522 ++hammer_stats_btree_lookups;
523 if (cursor->flags & HAMMER_CURSOR_ASOF) {
524 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
525 cursor->key_beg.create_tid = cursor->asof;
526 for (;;) {
527 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
528 error = btree_search(cursor, 0);
529 if (error != ENOENT ||
530 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
532 * Stop if no error.
533 * Stop if error other then ENOENT.
534 * Stop if ENOENT and not special case.
536 break;
538 if (hammer_debug_btree) {
539 kprintf("CREATE_CHECK %016llx\n",
540 cursor->create_check);
542 cursor->key_beg.create_tid = cursor->create_check;
543 /* loop */
545 } else {
546 error = btree_search(cursor, 0);
548 if (error == 0)
549 error = hammer_btree_extract(cursor, cursor->flags);
550 return(error);
554 * Execute the logic required to start an iteration. The first record
555 * located within the specified range is returned and iteration control
556 * flags are adjusted for successive hammer_btree_iterate() calls.
559 hammer_btree_first(hammer_cursor_t cursor)
561 int error;
563 error = hammer_btree_lookup(cursor);
564 if (error == ENOENT) {
565 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
566 error = hammer_btree_iterate(cursor);
568 cursor->flags |= HAMMER_CURSOR_ATEDISK;
569 return(error);
573 * Similarly but for an iteration in the reverse direction.
575 * Set ATEDISK when iterating backwards to skip the current entry,
576 * which after an ENOENT lookup will be pointing beyond our end point.
579 hammer_btree_last(hammer_cursor_t cursor)
581 struct hammer_base_elm save;
582 int error;
584 save = cursor->key_beg;
585 cursor->key_beg = cursor->key_end;
586 error = hammer_btree_lookup(cursor);
587 cursor->key_beg = save;
588 if (error == ENOENT ||
589 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
590 cursor->flags |= HAMMER_CURSOR_ATEDISK;
591 error = hammer_btree_iterate_reverse(cursor);
593 cursor->flags |= HAMMER_CURSOR_ATEDISK;
594 return(error);
598 * Extract the record and/or data associated with the cursor's current
599 * position. Any prior record or data stored in the cursor is replaced.
600 * The cursor must be positioned at a leaf node.
602 * NOTE: All extractions occur at the leaf of the B-Tree.
605 hammer_btree_extract(hammer_cursor_t cursor, int flags)
607 hammer_mount_t hmp;
608 hammer_node_ondisk_t node;
609 hammer_btree_elm_t elm;
610 hammer_off_t data_off;
611 int32_t data_len;
612 int error;
615 * The case where the data reference resolves to the same buffer
616 * as the record reference must be handled.
618 node = cursor->node->ondisk;
619 elm = &node->elms[cursor->index];
620 cursor->data = NULL;
621 hmp = cursor->node->hmp;
624 * There is nothing to extract for an internal element.
626 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
627 return(EINVAL);
630 * Only record types have data.
632 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
633 cursor->leaf = &elm->leaf;
635 if ((flags & HAMMER_CURSOR_GET_DATA) == 0)
636 return(0);
637 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
638 return(0);
639 data_off = elm->leaf.data_offset;
640 data_len = elm->leaf.data_len;
641 if (data_off == 0)
642 return(0);
645 * Load the data
647 KKASSERT(data_len >= 0 && data_len <= HAMMER_XBUFSIZE);
648 cursor->data = hammer_bread_ext(hmp, data_off, data_len,
649 &error, &cursor->data_buffer);
650 if (hammer_crc_test_leaf(cursor->data, &elm->leaf) == 0)
651 Debugger("CRC FAILED: DATA");
652 return(error);
657 * Insert a leaf element into the B-Tree at the current cursor position.
658 * The cursor is positioned such that the element at and beyond the cursor
659 * are shifted to make room for the new record.
661 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
662 * flag set and that call must return ENOENT before this function can be
663 * called.
665 * The caller may depend on the cursor's exclusive lock after return to
666 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
668 * ENOSPC is returned if there is no room to insert a new record.
671 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_leaf_elm_t elm)
673 hammer_node_ondisk_t node;
674 int i;
675 int error;
677 if ((error = hammer_cursor_upgrade_node(cursor)) != 0)
678 return(error);
679 ++hammer_stats_btree_inserts;
682 * Insert the element at the leaf node and update the count in the
683 * parent. It is possible for parent to be NULL, indicating that
684 * the filesystem's ROOT B-Tree node is a leaf itself, which is
685 * possible. The root inode can never be deleted so the leaf should
686 * never be empty.
688 * Remember that the right-hand boundary is not included in the
689 * count.
691 hammer_modify_node_all(cursor->trans, cursor->node);
692 node = cursor->node->ondisk;
693 i = cursor->index;
694 KKASSERT(elm->base.btype != 0);
695 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
696 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
697 if (i != node->count) {
698 bcopy(&node->elms[i], &node->elms[i+1],
699 (node->count - i) * sizeof(*elm));
701 node->elms[i].leaf = *elm;
702 ++node->count;
705 * Update the leaf node's aggregate mirror_tid for mirroring
706 * support.
708 if (node->mirror_tid < elm->base.delete_tid)
709 node->mirror_tid = elm->base.delete_tid;
710 if (node->mirror_tid < elm->base.create_tid)
711 node->mirror_tid = elm->base.create_tid;
712 hammer_modify_node_done(cursor->node);
715 * What we really want to do is propogate mirror_tid all the way
716 * up the parent chain to the B-Tree root. That would be
717 * ultra-expensive, though.
719 if (cursor->parent &&
720 (cursor->trans->hmp->hflags & (HMNT_MASTERID|HMNT_SLAVE))) {
721 hammer_btree_mirror_propagate(cursor->trans, cursor->parent,
722 cursor->parent_index,
723 node->mirror_tid);
727 * Debugging sanity checks.
729 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->base) <= 0);
730 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->base) > 0);
731 if (i) {
732 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->base) < 0);
734 if (i != node->count - 1)
735 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->base) > 0);
737 return(0);
741 * Delete a record from the B-Tree at the current cursor position.
742 * The cursor is positioned such that the current element is the one
743 * to be deleted.
745 * On return the cursor will be positioned after the deleted element and
746 * MAY point to an internal node. It will be suitable for the continuation
747 * of an iteration but not for an insertion or deletion.
749 * Deletions will attempt to partially rebalance the B-Tree in an upward
750 * direction, but will terminate rather then deadlock. Empty internal nodes
751 * are never allowed by a deletion which deadlocks may end up giving us an
752 * empty leaf. The pruner will clean up and rebalance the tree.
754 * This function can return EDEADLK, requiring the caller to retry the
755 * operation after clearing the deadlock.
758 hammer_btree_delete(hammer_cursor_t cursor)
760 hammer_node_ondisk_t ondisk;
761 hammer_node_t node;
762 hammer_node_t parent;
763 int error;
764 int i;
766 if ((error = hammer_cursor_upgrade(cursor)) != 0)
767 return(error);
768 ++hammer_stats_btree_deletes;
771 * Delete the element from the leaf node.
773 * Remember that leaf nodes do not have boundaries.
775 node = cursor->node;
776 ondisk = node->ondisk;
777 i = cursor->index;
779 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
780 KKASSERT(i >= 0 && i < ondisk->count);
781 hammer_modify_node_all(cursor->trans, node);
782 if (i + 1 != ondisk->count) {
783 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
784 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
786 --ondisk->count;
787 hammer_modify_node_done(node);
790 * Validate local parent
792 if (ondisk->parent) {
793 parent = cursor->parent;
795 KKASSERT(parent != NULL);
796 KKASSERT(parent->node_offset == ondisk->parent);
800 * If the leaf becomes empty it must be detached from the parent,
801 * potentially recursing through to the filesystem root.
803 * This may reposition the cursor at one of the parent's of the
804 * current node.
806 * Ignore deadlock errors, that simply means that btree_remove
807 * was unable to recurse and had to leave us with an empty leaf.
809 KKASSERT(cursor->index <= ondisk->count);
810 if (ondisk->count == 0) {
811 error = btree_remove(cursor);
812 if (error == EDEADLK)
813 error = 0;
814 } else {
815 error = 0;
817 KKASSERT(cursor->parent == NULL ||
818 cursor->parent_index < cursor->parent->ondisk->count);
819 return(error);
823 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
825 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
827 * The search can begin ANYWHERE in the B-Tree. As a first step the search
828 * iterates up the tree as necessary to properly position itself prior to
829 * actually doing the sarch.
831 * INSERTIONS: The search will split full nodes and leaves on its way down
832 * and guarentee that the leaf it ends up on is not full. If we run out
833 * of space the search continues to the leaf (to position the cursor for
834 * the spike), but ENOSPC is returned.
836 * The search is only guarenteed to end up on a leaf if an error code of 0
837 * is returned, or if inserting and an error code of ENOENT is returned.
838 * Otherwise it can stop at an internal node. On success a search returns
839 * a leaf node.
841 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
842 * filesystem, and it is not simple code. Please note the following facts:
844 * - Internal node recursions have a boundary on the left AND right. The
845 * right boundary is non-inclusive. The create_tid is a generic part
846 * of the key for internal nodes.
848 * - Leaf nodes contain terminal elements only now.
850 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
851 * historical search. ASOF and INSERT are mutually exclusive. When
852 * doing an as-of lookup btree_search() checks for a right-edge boundary
853 * case. If while recursing down the left-edge differs from the key
854 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
855 * with cursor->create_check. This is used by btree_lookup() to iterate.
856 * The iteration backwards because as-of searches can wind up going
857 * down the wrong branch of the B-Tree.
859 static
861 btree_search(hammer_cursor_t cursor, int flags)
863 hammer_node_ondisk_t node;
864 hammer_btree_elm_t elm;
865 int error;
866 int enospc = 0;
867 int i;
868 int r;
869 int s;
871 flags |= cursor->flags;
872 ++hammer_stats_btree_searches;
874 if (hammer_debug_btree) {
875 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx lo=%02x (td = %p)\n",
876 cursor->node->node_offset,
877 cursor->index,
878 cursor->key_beg.obj_id,
879 cursor->key_beg.rec_type,
880 cursor->key_beg.key,
881 cursor->key_beg.create_tid,
882 cursor->key_beg.localization,
883 curthread
885 if (cursor->parent)
886 kprintf("SEARCHP %016llx[%d] (%016llx/%016llx %016llx/%016llx) (%p/%p %p/%p)\n",
887 cursor->parent->node_offset, cursor->parent_index,
888 cursor->left_bound->obj_id,
889 cursor->parent->ondisk->elms[cursor->parent_index].internal.base.obj_id,
890 cursor->right_bound->obj_id,
891 cursor->parent->ondisk->elms[cursor->parent_index+1].internal.base.obj_id,
892 cursor->left_bound,
893 &cursor->parent->ondisk->elms[cursor->parent_index],
894 cursor->right_bound,
895 &cursor->parent->ondisk->elms[cursor->parent_index+1]
900 * Move our cursor up the tree until we find a node whos range covers
901 * the key we are trying to locate.
903 * The left bound is inclusive, the right bound is non-inclusive.
904 * It is ok to cursor up too far.
906 for (;;) {
907 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
908 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
909 if (r >= 0 && s < 0)
910 break;
911 KKASSERT(cursor->parent);
912 ++hammer_stats_btree_iterations;
913 error = hammer_cursor_up(cursor);
914 if (error)
915 goto done;
919 * The delete-checks below are based on node, not parent. Set the
920 * initial delete-check based on the parent.
922 if (r == 1) {
923 KKASSERT(cursor->left_bound->create_tid != 1);
924 cursor->create_check = cursor->left_bound->create_tid - 1;
925 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
929 * We better have ended up with a node somewhere.
931 KKASSERT(cursor->node != NULL);
934 * If we are inserting we can't start at a full node if the parent
935 * is also full (because there is no way to split the node),
936 * continue running up the tree until the requirement is satisfied
937 * or we hit the root of the filesystem.
939 * (If inserting we aren't doing an as-of search so we don't have
940 * to worry about create_check).
942 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
943 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
944 if (btree_node_is_full(cursor->node->ondisk) == 0)
945 break;
946 } else {
947 if (btree_node_is_full(cursor->node->ondisk) ==0)
948 break;
950 if (cursor->node->ondisk->parent == 0 ||
951 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
952 break;
954 ++hammer_stats_btree_iterations;
955 error = hammer_cursor_up(cursor);
956 /* node may have become stale */
957 if (error)
958 goto done;
962 * Push down through internal nodes to locate the requested key.
964 node = cursor->node->ondisk;
965 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
967 * Scan the node to find the subtree index to push down into.
968 * We go one-past, then back-up.
970 * We must proactively remove deleted elements which may
971 * have been left over from a deadlocked btree_remove().
973 * The left and right boundaries are included in the loop
974 * in order to detect edge cases.
976 * If the separator only differs by create_tid (r == 1)
977 * and we are doing an as-of search, we may end up going
978 * down a branch to the left of the one containing the
979 * desired key. This requires numerous special cases.
981 ++hammer_stats_btree_iterations;
982 if (hammer_debug_btree) {
983 kprintf("SEARCH-I %016llx count=%d\n",
984 cursor->node->node_offset,
985 node->count);
989 * Try to shortcut the search before dropping into the
990 * linear loop. Locate the first node where r <= 1.
992 i = hammer_btree_search_node(&cursor->key_beg, node);
993 while (i <= node->count) {
994 ++hammer_stats_btree_elements;
995 elm = &node->elms[i];
996 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
997 if (hammer_debug_btree > 2) {
998 kprintf(" IELM %p %d r=%d\n",
999 &node->elms[i], i, r);
1001 if (r < 0)
1002 break;
1003 if (r == 1) {
1004 KKASSERT(elm->base.create_tid != 1);
1005 cursor->create_check = elm->base.create_tid - 1;
1006 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
1008 ++i;
1010 if (hammer_debug_btree) {
1011 kprintf("SEARCH-I preI=%d/%d r=%d\n",
1012 i, node->count, r);
1016 * These cases occur when the parent's idea of the boundary
1017 * is wider then the child's idea of the boundary, and
1018 * require special handling. If not inserting we can
1019 * terminate the search early for these cases but the
1020 * child's boundaries cannot be unconditionally modified.
1022 if (i == 0) {
1024 * If i == 0 the search terminated to the LEFT of the
1025 * left_boundary but to the RIGHT of the parent's left
1026 * boundary.
1028 u_int8_t save;
1030 elm = &node->elms[0];
1033 * If we aren't inserting we can stop here.
1035 if ((flags & (HAMMER_CURSOR_INSERT |
1036 HAMMER_CURSOR_PRUNING)) == 0) {
1037 cursor->index = 0;
1038 return(ENOENT);
1042 * Correct a left-hand boundary mismatch.
1044 * We can only do this if we can upgrade the lock,
1045 * and synchronized as a background cursor (i.e.
1046 * inserting or pruning).
1048 * WARNING: We can only do this if inserting, i.e.
1049 * we are running on the backend.
1051 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1052 return(error);
1053 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1054 hammer_modify_node_field(cursor->trans, cursor->node,
1055 elms[0]);
1056 save = node->elms[0].base.btype;
1057 node->elms[0].base = *cursor->left_bound;
1058 node->elms[0].base.btype = save;
1059 hammer_modify_node_done(cursor->node);
1060 } else if (i == node->count + 1) {
1062 * If i == node->count + 1 the search terminated to
1063 * the RIGHT of the right boundary but to the LEFT
1064 * of the parent's right boundary. If we aren't
1065 * inserting we can stop here.
1067 * Note that the last element in this case is
1068 * elms[i-2] prior to adjustments to 'i'.
1070 --i;
1071 if ((flags & (HAMMER_CURSOR_INSERT |
1072 HAMMER_CURSOR_PRUNING)) == 0) {
1073 cursor->index = i;
1074 return (ENOENT);
1078 * Correct a right-hand boundary mismatch.
1079 * (actual push-down record is i-2 prior to
1080 * adjustments to i).
1082 * We can only do this if we can upgrade the lock,
1083 * and synchronized as a background cursor (i.e.
1084 * inserting or pruning).
1086 * WARNING: We can only do this if inserting, i.e.
1087 * we are running on the backend.
1089 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1090 return(error);
1091 elm = &node->elms[i];
1092 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
1093 hammer_modify_node(cursor->trans, cursor->node,
1094 &elm->base, sizeof(elm->base));
1095 elm->base = *cursor->right_bound;
1096 hammer_modify_node_done(cursor->node);
1097 --i;
1098 } else {
1100 * The push-down index is now i - 1. If we had
1101 * terminated on the right boundary this will point
1102 * us at the last element.
1104 --i;
1106 cursor->index = i;
1107 elm = &node->elms[i];
1109 if (hammer_debug_btree) {
1110 kprintf("RESULT-I %016llx[%d] %016llx %02x "
1111 "key=%016llx cre=%016llx lo=%02x\n",
1112 cursor->node->node_offset,
1114 elm->internal.base.obj_id,
1115 elm->internal.base.rec_type,
1116 elm->internal.base.key,
1117 elm->internal.base.create_tid,
1118 elm->internal.base.localization
1123 * We better have a valid subtree offset.
1125 KKASSERT(elm->internal.subtree_offset != 0);
1128 * Handle insertion and deletion requirements.
1130 * If inserting split full nodes. The split code will
1131 * adjust cursor->node and cursor->index if the current
1132 * index winds up in the new node.
1134 * If inserting and a left or right edge case was detected,
1135 * we cannot correct the left or right boundary and must
1136 * prepend and append an empty leaf node in order to make
1137 * the boundary correction.
1139 * If we run out of space we set enospc and continue on
1140 * to a leaf to provide the spike code with a good point
1141 * of entry.
1143 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1144 if (btree_node_is_full(node)) {
1145 error = btree_split_internal(cursor);
1146 if (error) {
1147 if (error != ENOSPC)
1148 goto done;
1149 enospc = 1;
1152 * reload stale pointers
1154 i = cursor->index;
1155 node = cursor->node->ondisk;
1160 * Push down (push into new node, existing node becomes
1161 * the parent) and continue the search.
1163 error = hammer_cursor_down(cursor);
1164 /* node may have become stale */
1165 if (error)
1166 goto done;
1167 node = cursor->node->ondisk;
1171 * We are at a leaf, do a linear search of the key array.
1173 * On success the index is set to the matching element and 0
1174 * is returned.
1176 * On failure the index is set to the insertion point and ENOENT
1177 * is returned.
1179 * Boundaries are not stored in leaf nodes, so the index can wind
1180 * up to the left of element 0 (index == 0) or past the end of
1181 * the array (index == node->count). It is also possible that the
1182 * leaf might be empty.
1184 ++hammer_stats_btree_iterations;
1185 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
1186 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1187 if (hammer_debug_btree) {
1188 kprintf("SEARCH-L %016llx count=%d\n",
1189 cursor->node->node_offset,
1190 node->count);
1194 * Try to shortcut the search before dropping into the
1195 * linear loop. Locate the first node where r <= 1.
1197 i = hammer_btree_search_node(&cursor->key_beg, node);
1198 while (i < node->count) {
1199 ++hammer_stats_btree_elements;
1200 elm = &node->elms[i];
1202 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
1204 if (hammer_debug_btree > 1)
1205 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1208 * We are at a record element. Stop if we've flipped past
1209 * key_beg, not counting the create_tid test. Allow the
1210 * r == 1 case (key_beg > element but differs only by its
1211 * create_tid) to fall through to the AS-OF check.
1213 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1215 if (r < 0)
1216 goto failed;
1217 if (r > 1) {
1218 ++i;
1219 continue;
1223 * Check our as-of timestamp against the element.
1225 if (flags & HAMMER_CURSOR_ASOF) {
1226 if (hammer_btree_chkts(cursor->asof,
1227 &node->elms[i].base) != 0) {
1228 ++i;
1229 continue;
1231 /* success */
1232 } else {
1233 if (r > 0) { /* can only be +1 */
1234 ++i;
1235 continue;
1237 /* success */
1239 cursor->index = i;
1240 error = 0;
1241 if (hammer_debug_btree) {
1242 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
1243 cursor->node->node_offset, i);
1245 goto done;
1249 * The search of the leaf node failed. i is the insertion point.
1251 failed:
1252 if (hammer_debug_btree) {
1253 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
1254 cursor->node->node_offset, i);
1258 * No exact match was found, i is now at the insertion point.
1260 * If inserting split a full leaf before returning. This
1261 * may have the side effect of adjusting cursor->node and
1262 * cursor->index.
1264 cursor->index = i;
1265 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1266 btree_node_is_full(node)) {
1267 error = btree_split_leaf(cursor);
1268 if (error) {
1269 if (error != ENOSPC)
1270 goto done;
1271 enospc = 1;
1274 * reload stale pointers
1276 /* NOT USED
1277 i = cursor->index;
1278 node = &cursor->node->internal;
1283 * We reached a leaf but did not find the key we were looking for.
1284 * If this is an insert we will be properly positioned for an insert
1285 * (ENOENT) or spike (ENOSPC) operation.
1287 error = enospc ? ENOSPC : ENOENT;
1288 done:
1289 return(error);
1293 * Heuristical search for the first element whos comparison is <= 1. May
1294 * return an index whos compare result is > 1 but may only return an index
1295 * whos compare result is <= 1 if it is the first element with that result.
1298 hammer_btree_search_node(hammer_base_elm_t elm, hammer_node_ondisk_t node)
1300 int b;
1301 int s;
1302 int i;
1303 int r;
1306 * Don't bother if the node does not have very many elements
1308 b = 0;
1309 s = node->count;
1310 while (s - b > 4) {
1311 i = b + (s - b) / 2;
1312 ++hammer_stats_btree_elements;
1313 r = hammer_btree_cmp(elm, &node->elms[i].leaf.base);
1314 if (r <= 1) {
1315 s = i;
1316 } else {
1317 b = i;
1320 return(b);
1324 /************************************************************************
1325 * SPLITTING AND MERGING *
1326 ************************************************************************
1328 * These routines do all the dirty work required to split and merge nodes.
1332 * Split an internal node into two nodes and move the separator at the split
1333 * point to the parent.
1335 * (cursor->node, cursor->index) indicates the element the caller intends
1336 * to push into. We will adjust node and index if that element winds
1337 * up in the split node.
1339 * If we are at the root of the filesystem a new root must be created with
1340 * two elements, one pointing to the original root and one pointing to the
1341 * newly allocated split node.
1343 static
1345 btree_split_internal(hammer_cursor_t cursor)
1347 hammer_node_ondisk_t ondisk;
1348 hammer_node_t node;
1349 hammer_node_t parent;
1350 hammer_node_t new_node;
1351 hammer_btree_elm_t elm;
1352 hammer_btree_elm_t parent_elm;
1353 hammer_node_locklist_t locklist = NULL;
1354 hammer_mount_t hmp = cursor->trans->hmp;
1355 int parent_index;
1356 int made_root;
1357 int split;
1358 int error;
1359 int i;
1360 const int esize = sizeof(*elm);
1362 error = hammer_btree_lock_children(cursor, &locklist);
1363 if (error)
1364 goto done;
1365 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1366 goto done;
1367 ++hammer_stats_btree_splits;
1370 * We are splitting but elms[split] will be promoted to the parent,
1371 * leaving the right hand node with one less element. If the
1372 * insertion point will be on the left-hand side adjust the split
1373 * point to give the right hand side one additional node.
1375 node = cursor->node;
1376 ondisk = node->ondisk;
1377 split = (ondisk->count + 1) / 2;
1378 if (cursor->index <= split)
1379 --split;
1382 * If we are at the root of the filesystem, create a new root node
1383 * with 1 element and split normally. Avoid making major
1384 * modifications until we know the whole operation will work.
1386 if (ondisk->parent == 0) {
1387 parent = hammer_alloc_btree(cursor->trans, &error);
1388 if (parent == NULL)
1389 goto done;
1390 hammer_lock_ex(&parent->lock);
1391 hammer_modify_node_noundo(cursor->trans, parent);
1392 ondisk = parent->ondisk;
1393 ondisk->count = 1;
1394 ondisk->parent = 0;
1395 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1396 ondisk->elms[0].base = hmp->root_btree_beg;
1397 ondisk->elms[0].base.btype = node->ondisk->type;
1398 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1399 ondisk->elms[1].base = hmp->root_btree_end;
1400 hammer_modify_node_done(parent);
1401 /* ondisk->elms[1].base.btype - not used */
1402 made_root = 1;
1403 parent_index = 0; /* index of current node in parent */
1404 } else {
1405 made_root = 0;
1406 parent = cursor->parent;
1407 parent_index = cursor->parent_index;
1411 * Split node into new_node at the split point.
1413 * B O O O P N N B <-- P = node->elms[split]
1414 * 0 1 2 3 4 5 6 <-- subtree indices
1416 * x x P x x
1417 * s S S s
1418 * / \
1419 * B O O O B B N N B <--- inner boundary points are 'P'
1420 * 0 1 2 3 4 5 6
1423 new_node = hammer_alloc_btree(cursor->trans, &error);
1424 if (new_node == NULL) {
1425 if (made_root) {
1426 hammer_unlock(&parent->lock);
1427 hammer_delete_node(cursor->trans, parent);
1428 hammer_rel_node(parent);
1430 goto done;
1432 hammer_lock_ex(&new_node->lock);
1435 * Create the new node. P becomes the left-hand boundary in the
1436 * new node. Copy the right-hand boundary as well.
1438 * elm is the new separator.
1440 hammer_modify_node_noundo(cursor->trans, new_node);
1441 hammer_modify_node_all(cursor->trans, node);
1442 ondisk = node->ondisk;
1443 elm = &ondisk->elms[split];
1444 bcopy(elm, &new_node->ondisk->elms[0],
1445 (ondisk->count - split + 1) * esize);
1446 new_node->ondisk->count = ondisk->count - split;
1447 new_node->ondisk->parent = parent->node_offset;
1448 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1449 KKASSERT(ondisk->type == new_node->ondisk->type);
1452 * Cleanup the original node. Elm (P) becomes the new boundary,
1453 * its subtree_offset was moved to the new node. If we had created
1454 * a new root its parent pointer may have changed.
1456 elm->internal.subtree_offset = 0;
1457 ondisk->count = split;
1460 * Insert the separator into the parent, fixup the parent's
1461 * reference to the original node, and reference the new node.
1462 * The separator is P.
1464 * Remember that base.count does not include the right-hand boundary.
1466 hammer_modify_node_all(cursor->trans, parent);
1467 ondisk = parent->ondisk;
1468 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1469 parent_elm = &ondisk->elms[parent_index+1];
1470 bcopy(parent_elm, parent_elm + 1,
1471 (ondisk->count - parent_index) * esize);
1472 parent_elm->internal.base = elm->base; /* separator P */
1473 parent_elm->internal.base.btype = new_node->ondisk->type;
1474 parent_elm->internal.subtree_offset = new_node->node_offset;
1475 ++ondisk->count;
1476 hammer_modify_node_done(parent);
1479 * The children of new_node need their parent pointer set to new_node.
1480 * The children have already been locked by
1481 * hammer_btree_lock_children().
1483 for (i = 0; i < new_node->ondisk->count; ++i) {
1484 elm = &new_node->ondisk->elms[i];
1485 error = btree_set_parent(cursor->trans, new_node, elm);
1486 if (error) {
1487 panic("btree_split_internal: btree-fixup problem");
1490 hammer_modify_node_done(new_node);
1493 * The filesystem's root B-Tree pointer may have to be updated.
1495 if (made_root) {
1496 hammer_volume_t volume;
1498 volume = hammer_get_root_volume(hmp, &error);
1499 KKASSERT(error == 0);
1501 hammer_modify_volume_field(cursor->trans, volume,
1502 vol0_btree_root);
1503 volume->ondisk->vol0_btree_root = parent->node_offset;
1504 hammer_modify_volume_done(volume);
1505 node->ondisk->parent = parent->node_offset;
1506 if (cursor->parent) {
1507 hammer_unlock(&cursor->parent->lock);
1508 hammer_rel_node(cursor->parent);
1510 cursor->parent = parent; /* lock'd and ref'd */
1511 hammer_rel_volume(volume, 0);
1513 hammer_modify_node_done(node);
1517 * Ok, now adjust the cursor depending on which element the original
1518 * index was pointing at. If we are >= the split point the push node
1519 * is now in the new node.
1521 * NOTE: If we are at the split point itself we cannot stay with the
1522 * original node because the push index will point at the right-hand
1523 * boundary, which is illegal.
1525 * NOTE: The cursor's parent or parent_index must be adjusted for
1526 * the case where a new parent (new root) was created, and the case
1527 * where the cursor is now pointing at the split node.
1529 if (cursor->index >= split) {
1530 cursor->parent_index = parent_index + 1;
1531 cursor->index -= split;
1532 hammer_unlock(&cursor->node->lock);
1533 hammer_rel_node(cursor->node);
1534 cursor->node = new_node; /* locked and ref'd */
1535 } else {
1536 cursor->parent_index = parent_index;
1537 hammer_unlock(&new_node->lock);
1538 hammer_rel_node(new_node);
1542 * Fixup left and right bounds
1544 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1545 cursor->left_bound = &parent_elm[0].internal.base;
1546 cursor->right_bound = &parent_elm[1].internal.base;
1547 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1548 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1549 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1550 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1552 done:
1553 hammer_btree_unlock_children(&locklist);
1554 hammer_cursor_downgrade(cursor);
1555 return (error);
1559 * Same as the above, but splits a full leaf node.
1561 * This function
1563 static
1565 btree_split_leaf(hammer_cursor_t cursor)
1567 hammer_node_ondisk_t ondisk;
1568 hammer_node_t parent;
1569 hammer_node_t leaf;
1570 hammer_mount_t hmp;
1571 hammer_node_t new_leaf;
1572 hammer_btree_elm_t elm;
1573 hammer_btree_elm_t parent_elm;
1574 hammer_base_elm_t mid_boundary;
1575 int parent_index;
1576 int made_root;
1577 int split;
1578 int error;
1579 const size_t esize = sizeof(*elm);
1581 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1582 return(error);
1583 ++hammer_stats_btree_splits;
1585 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1586 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1587 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1588 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1591 * Calculate the split point. If the insertion point will be on
1592 * the left-hand side adjust the split point to give the right
1593 * hand side one additional node.
1595 * Spikes are made up of two leaf elements which cannot be
1596 * safely split.
1598 leaf = cursor->node;
1599 ondisk = leaf->ondisk;
1600 split = (ondisk->count + 1) / 2;
1601 if (cursor->index <= split)
1602 --split;
1603 error = 0;
1604 hmp = leaf->hmp;
1606 elm = &ondisk->elms[split];
1608 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1609 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1610 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1611 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1614 * If we are at the root of the tree, create a new root node with
1615 * 1 element and split normally. Avoid making major modifications
1616 * until we know the whole operation will work.
1618 if (ondisk->parent == 0) {
1619 parent = hammer_alloc_btree(cursor->trans, &error);
1620 if (parent == NULL)
1621 goto done;
1622 hammer_lock_ex(&parent->lock);
1623 hammer_modify_node_noundo(cursor->trans, parent);
1624 ondisk = parent->ondisk;
1625 ondisk->count = 1;
1626 ondisk->parent = 0;
1627 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1628 ondisk->elms[0].base = hmp->root_btree_beg;
1629 ondisk->elms[0].base.btype = leaf->ondisk->type;
1630 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1631 ondisk->elms[1].base = hmp->root_btree_end;
1632 /* ondisk->elms[1].base.btype = not used */
1633 hammer_modify_node_done(parent);
1634 made_root = 1;
1635 parent_index = 0; /* insertion point in parent */
1636 } else {
1637 made_root = 0;
1638 parent = cursor->parent;
1639 parent_index = cursor->parent_index;
1643 * Split leaf into new_leaf at the split point. Select a separator
1644 * value in-between the two leafs but with a bent towards the right
1645 * leaf since comparisons use an 'elm >= separator' inequality.
1647 * L L L L L L L L
1649 * x x P x x
1650 * s S S s
1651 * / \
1652 * L L L L L L L L
1654 new_leaf = hammer_alloc_btree(cursor->trans, &error);
1655 if (new_leaf == NULL) {
1656 if (made_root) {
1657 hammer_unlock(&parent->lock);
1658 hammer_delete_node(cursor->trans, parent);
1659 hammer_rel_node(parent);
1661 goto done;
1663 hammer_lock_ex(&new_leaf->lock);
1666 * Create the new node and copy the leaf elements from the split
1667 * point on to the new node.
1669 hammer_modify_node_all(cursor->trans, leaf);
1670 hammer_modify_node_noundo(cursor->trans, new_leaf);
1671 ondisk = leaf->ondisk;
1672 elm = &ondisk->elms[split];
1673 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1674 new_leaf->ondisk->count = ondisk->count - split;
1675 new_leaf->ondisk->parent = parent->node_offset;
1676 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1677 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1678 hammer_modify_node_done(new_leaf);
1681 * Cleanup the original node. Because this is a leaf node and
1682 * leaf nodes do not have a right-hand boundary, there
1683 * aren't any special edge cases to clean up. We just fixup the
1684 * count.
1686 ondisk->count = split;
1689 * Insert the separator into the parent, fixup the parent's
1690 * reference to the original node, and reference the new node.
1691 * The separator is P.
1693 * Remember that base.count does not include the right-hand boundary.
1694 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1696 hammer_modify_node_all(cursor->trans, parent);
1697 ondisk = parent->ondisk;
1698 KKASSERT(split != 0);
1699 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1700 parent_elm = &ondisk->elms[parent_index+1];
1701 bcopy(parent_elm, parent_elm + 1,
1702 (ondisk->count - parent_index) * esize);
1704 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1705 parent_elm->internal.base.btype = new_leaf->ondisk->type;
1706 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1707 mid_boundary = &parent_elm->base;
1708 ++ondisk->count;
1709 hammer_modify_node_done(parent);
1712 * The filesystem's root B-Tree pointer may have to be updated.
1714 if (made_root) {
1715 hammer_volume_t volume;
1717 volume = hammer_get_root_volume(hmp, &error);
1718 KKASSERT(error == 0);
1720 hammer_modify_volume_field(cursor->trans, volume,
1721 vol0_btree_root);
1722 volume->ondisk->vol0_btree_root = parent->node_offset;
1723 hammer_modify_volume_done(volume);
1724 leaf->ondisk->parent = parent->node_offset;
1725 if (cursor->parent) {
1726 hammer_unlock(&cursor->parent->lock);
1727 hammer_rel_node(cursor->parent);
1729 cursor->parent = parent; /* lock'd and ref'd */
1730 hammer_rel_volume(volume, 0);
1732 hammer_modify_node_done(leaf);
1735 * Ok, now adjust the cursor depending on which element the original
1736 * index was pointing at. If we are >= the split point the push node
1737 * is now in the new node.
1739 * NOTE: If we are at the split point itself we need to select the
1740 * old or new node based on where key_beg's insertion point will be.
1741 * If we pick the wrong side the inserted element will wind up in
1742 * the wrong leaf node and outside that node's bounds.
1744 if (cursor->index > split ||
1745 (cursor->index == split &&
1746 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1747 cursor->parent_index = parent_index + 1;
1748 cursor->index -= split;
1749 hammer_unlock(&cursor->node->lock);
1750 hammer_rel_node(cursor->node);
1751 cursor->node = new_leaf;
1752 } else {
1753 cursor->parent_index = parent_index;
1754 hammer_unlock(&new_leaf->lock);
1755 hammer_rel_node(new_leaf);
1759 * Fixup left and right bounds
1761 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1762 cursor->left_bound = &parent_elm[0].internal.base;
1763 cursor->right_bound = &parent_elm[1].internal.base;
1766 * Assert that the bounds are correct.
1768 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1769 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1770 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1771 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1772 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1773 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
1775 done:
1776 hammer_cursor_downgrade(cursor);
1777 return (error);
1781 * Recursively correct the right-hand boundary's create_tid to (tid) as
1782 * long as the rest of the key matches. We have to recurse upward in
1783 * the tree as well as down the left side of each parent's right node.
1785 * Return EDEADLK if we were only partially successful, forcing the caller
1786 * to try again. The original cursor is not modified. This routine can
1787 * also fail with EDEADLK if it is forced to throw away a portion of its
1788 * record history.
1790 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
1792 struct hammer_rhb {
1793 TAILQ_ENTRY(hammer_rhb) entry;
1794 hammer_node_t node;
1795 int index;
1798 TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
1801 hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
1803 struct hammer_rhb_list rhb_list;
1804 hammer_base_elm_t elm;
1805 hammer_node_t orig_node;
1806 struct hammer_rhb *rhb;
1807 int orig_index;
1808 int error;
1810 TAILQ_INIT(&rhb_list);
1813 * Save our position so we can restore it on return. This also
1814 * gives us a stable 'elm'.
1816 orig_node = cursor->node;
1817 hammer_ref_node(orig_node);
1818 hammer_lock_sh(&orig_node->lock);
1819 orig_index = cursor->index;
1820 elm = &orig_node->ondisk->elms[orig_index].base;
1823 * Now build a list of parents going up, allocating a rhb
1824 * structure for each one.
1826 while (cursor->parent) {
1828 * Stop if we no longer have any right-bounds to fix up
1830 if (elm->obj_id != cursor->right_bound->obj_id ||
1831 elm->rec_type != cursor->right_bound->rec_type ||
1832 elm->key != cursor->right_bound->key) {
1833 break;
1837 * Stop if the right-hand bound's create_tid does not
1838 * need to be corrected.
1840 if (cursor->right_bound->create_tid >= tid)
1841 break;
1843 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1844 rhb->node = cursor->parent;
1845 rhb->index = cursor->parent_index;
1846 hammer_ref_node(rhb->node);
1847 hammer_lock_sh(&rhb->node->lock);
1848 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1850 hammer_cursor_up(cursor);
1854 * now safely adjust the right hand bound for each rhb. This may
1855 * also require taking the right side of the tree and iterating down
1856 * ITS left side.
1858 error = 0;
1859 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1860 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1861 if (error)
1862 break;
1863 TAILQ_REMOVE(&rhb_list, rhb, entry);
1864 hammer_unlock(&rhb->node->lock);
1865 hammer_rel_node(rhb->node);
1866 kfree(rhb, M_HAMMER);
1868 switch (cursor->node->ondisk->type) {
1869 case HAMMER_BTREE_TYPE_INTERNAL:
1871 * Right-boundary for parent at internal node
1872 * is one element to the right of the element whos
1873 * right boundary needs adjusting. We must then
1874 * traverse down the left side correcting any left
1875 * bounds (which may now be too far to the left).
1877 ++cursor->index;
1878 error = hammer_btree_correct_lhb(cursor, tid);
1879 break;
1880 default:
1881 panic("hammer_btree_correct_rhb(): Bad node type");
1882 error = EINVAL;
1883 break;
1888 * Cleanup
1890 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1891 TAILQ_REMOVE(&rhb_list, rhb, entry);
1892 hammer_unlock(&rhb->node->lock);
1893 hammer_rel_node(rhb->node);
1894 kfree(rhb, M_HAMMER);
1896 error = hammer_cursor_seek(cursor, orig_node, orig_index);
1897 hammer_unlock(&orig_node->lock);
1898 hammer_rel_node(orig_node);
1899 return (error);
1903 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
1904 * bound going downward starting at the current cursor position.
1906 * This function does not restore the cursor after use.
1909 hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
1911 struct hammer_rhb_list rhb_list;
1912 hammer_base_elm_t elm;
1913 hammer_base_elm_t cmp;
1914 struct hammer_rhb *rhb;
1915 int error;
1917 TAILQ_INIT(&rhb_list);
1919 cmp = &cursor->node->ondisk->elms[cursor->index].base;
1922 * Record the node and traverse down the left-hand side for all
1923 * matching records needing a boundary correction.
1925 error = 0;
1926 for (;;) {
1927 rhb = kmalloc(sizeof(*rhb), M_HAMMER, M_WAITOK|M_ZERO);
1928 rhb->node = cursor->node;
1929 rhb->index = cursor->index;
1930 hammer_ref_node(rhb->node);
1931 hammer_lock_sh(&rhb->node->lock);
1932 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
1934 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1936 * Nothing to traverse down if we are at the right
1937 * boundary of an internal node.
1939 if (cursor->index == cursor->node->ondisk->count)
1940 break;
1941 } else {
1942 elm = &cursor->node->ondisk->elms[cursor->index].base;
1943 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
1944 break;
1945 panic("Illegal leaf record type %02x", elm->btype);
1947 error = hammer_cursor_down(cursor);
1948 if (error)
1949 break;
1951 elm = &cursor->node->ondisk->elms[cursor->index].base;
1952 if (elm->obj_id != cmp->obj_id ||
1953 elm->rec_type != cmp->rec_type ||
1954 elm->key != cmp->key) {
1955 break;
1957 if (elm->create_tid >= tid)
1958 break;
1963 * Now we can safely adjust the left-hand boundary from the bottom-up.
1964 * The last element we remove from the list is the caller's right hand
1965 * boundary, which must also be adjusted.
1967 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1968 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
1969 if (error)
1970 break;
1971 TAILQ_REMOVE(&rhb_list, rhb, entry);
1972 hammer_unlock(&rhb->node->lock);
1973 hammer_rel_node(rhb->node);
1974 kfree(rhb, M_HAMMER);
1976 elm = &cursor->node->ondisk->elms[cursor->index].base;
1977 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
1978 hammer_modify_node(cursor->trans, cursor->node,
1979 &elm->create_tid,
1980 sizeof(elm->create_tid));
1981 elm->create_tid = tid;
1982 hammer_modify_node_done(cursor->node);
1983 } else {
1984 panic("hammer_btree_correct_lhb(): Bad element type");
1989 * Cleanup
1991 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
1992 TAILQ_REMOVE(&rhb_list, rhb, entry);
1993 hammer_unlock(&rhb->node->lock);
1994 hammer_rel_node(rhb->node);
1995 kfree(rhb, M_HAMMER);
1997 return (error);
2001 * Attempt to remove the locked, empty or want-to-be-empty B-Tree node at
2002 * (cursor->node). Returns 0 on success, EDEADLK if we could not complete
2003 * the operation due to a deadlock, or some other error.
2005 * This routine is always called with an empty, locked leaf but may recurse
2006 * into want-to-be-empty parents as part of its operation.
2008 * It should also be noted that when removing empty leaves we must be sure
2009 * to test and update mirror_tid because another thread may have deadlocked
2010 * against us (or someone) trying to propogate it up and cannot retry once
2011 * the node has been deleted.
2013 * On return the cursor may end up pointing to an internal node, suitable
2014 * for further iteration but not for an immediate insertion or deletion.
2016 static int
2017 btree_remove(hammer_cursor_t cursor)
2019 hammer_node_ondisk_t ondisk;
2020 hammer_btree_elm_t elm;
2021 hammer_node_t node;
2022 hammer_node_t parent;
2023 const int esize = sizeof(*elm);
2024 int error;
2026 node = cursor->node;
2029 * When deleting the root of the filesystem convert it to
2030 * an empty leaf node. Internal nodes cannot be empty.
2032 ondisk = node->ondisk;
2033 if (ondisk->parent == 0) {
2034 KKASSERT(cursor->parent == NULL);
2035 hammer_modify_node_all(cursor->trans, node);
2036 KKASSERT(ondisk == node->ondisk);
2037 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
2038 ondisk->count = 0;
2039 hammer_modify_node_done(node);
2040 cursor->index = 0;
2041 return(0);
2044 parent = cursor->parent;
2047 * If another thread deadlocked trying to propogate mirror_tid up
2048 * we have to finish the job before deleting node. XXX
2050 if (parent->ondisk->mirror_tid < node->ondisk->mirror_tid &&
2051 (cursor->trans->hmp->hflags & (HMNT_MASTERID|HMNT_SLAVE))) {
2052 hammer_btree_mirror_propagate(cursor->trans,
2053 parent,
2054 cursor->parent_index,
2055 node->ondisk->mirror_tid);
2060 * Attempt to remove the parent's reference to the child. If the
2061 * parent would become empty we have to recurse. If we fail we
2062 * leave the parent pointing to an empty leaf node.
2064 if (parent->ondisk->count == 1) {
2066 * This special cursor_up_locked() call leaves the original
2067 * node exclusively locked and referenced, leaves the
2068 * original parent locked (as the new node), and locks the
2069 * new parent. It can return EDEADLK.
2071 error = hammer_cursor_up_locked(cursor);
2072 if (error == 0) {
2073 error = btree_remove(cursor);
2074 if (error == 0) {
2075 hammer_modify_node_all(cursor->trans, node);
2076 ondisk = node->ondisk;
2077 ondisk->type = HAMMER_BTREE_TYPE_DELETED;
2078 ondisk->count = 0;
2079 hammer_modify_node_done(node);
2080 hammer_flush_node(node);
2081 hammer_delete_node(cursor->trans, node);
2082 } else {
2083 kprintf("Warning: BTREE_REMOVE: Defering "
2084 "parent removal1 @ %016llx, skipping\n",
2085 node->node_offset);
2087 hammer_unlock(&node->lock);
2088 hammer_rel_node(node);
2089 } else {
2090 kprintf("Warning: BTREE_REMOVE: Defering parent "
2091 "removal2 @ %016llx, skipping\n",
2092 node->node_offset);
2094 } else {
2095 KKASSERT(parent->ondisk->count > 1);
2098 * Delete the subtree reference in the parent
2100 hammer_modify_node_all(cursor->trans, parent);
2101 ondisk = parent->ondisk;
2102 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
2104 elm = &ondisk->elms[cursor->parent_index];
2105 KKASSERT(elm->internal.subtree_offset == node->node_offset);
2106 KKASSERT(ondisk->count > 0);
2107 bcopy(&elm[1], &elm[0],
2108 (ondisk->count - cursor->parent_index) * esize);
2109 --ondisk->count;
2110 hammer_modify_node_done(parent);
2111 hammer_flush_node(node);
2112 hammer_delete_node(cursor->trans, node);
2115 * cursor->node is invalid, cursor up to make the cursor
2116 * valid again.
2118 error = hammer_cursor_up(cursor);
2120 return (error);
2124 * Propagate a mirror TID update upwards through the B-Tree to the root.
2126 * A locked internal node must be passed in. The node will remain locked
2127 * on return.
2129 * This function syncs mirror_tid at the specified internal node's element,
2130 * adjusts the node's aggregation mirror_tid, and then recurses upwards.
2133 hammer_btree_mirror_propagate(hammer_transaction_t trans, hammer_node_t node,
2134 int index, hammer_tid_t mirror_tid)
2136 hammer_btree_internal_elm_t elm;
2137 hammer_node_t parent;
2138 int parent_index;
2139 int error;
2141 KKASSERT (node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
2144 * Adjust the node's element
2146 elm = &node->ondisk->elms[index].internal;
2147 if (elm->mirror_tid >= mirror_tid)
2148 return(0);
2149 hammer_modify_node(trans, node, &elm->mirror_tid,
2150 sizeof(elm->mirror_tid));
2151 elm->mirror_tid = mirror_tid;
2152 hammer_modify_node_done(node);
2155 * Adjust the node's mirror_tid aggragator
2157 if (node->ondisk->mirror_tid >= mirror_tid)
2158 return(0);
2159 hammer_modify_node_field(trans, node, mirror_tid);
2160 node->ondisk->mirror_tid = mirror_tid;
2161 hammer_modify_node_done(node);
2163 error = 0;
2164 error = 0;
2165 if (node->ondisk->parent &&
2166 (trans->hmp->hflags & (HMNT_MASTERID|HMNT_SLAVE))) {
2167 parent = hammer_btree_get_parent(node, &parent_index,
2168 &error, 1);
2169 if (parent) {
2170 hammer_btree_mirror_propagate(trans, parent,
2171 parent_index, mirror_tid);
2172 hammer_unlock(&parent->lock);
2173 hammer_rel_node(parent);
2176 return(error);
2179 hammer_node_t
2180 hammer_btree_get_parent(hammer_node_t node, int *parent_indexp, int *errorp,
2181 int try_exclusive)
2183 hammer_node_t parent;
2184 hammer_btree_elm_t elm;
2185 int i;
2188 * Get the node
2190 parent = hammer_get_node(node->hmp, node->ondisk->parent, 0, errorp);
2191 if (*errorp) {
2192 KKASSERT(parent == NULL);
2193 return(NULL);
2195 KKASSERT ((parent->flags & HAMMER_NODE_DELETED) == 0);
2198 * Lock the node
2200 if (try_exclusive) {
2201 if (hammer_lock_ex_try(&parent->lock)) {
2202 hammer_rel_node(parent);
2203 *errorp = EDEADLK;
2204 return(NULL);
2206 } else {
2207 hammer_lock_sh(&parent->lock);
2211 * Figure out which element in the parent is pointing to the
2212 * child.
2214 if (node->ondisk->count) {
2215 i = hammer_btree_search_node(&node->ondisk->elms[0].base,
2216 parent->ondisk);
2217 } else {
2218 i = 0;
2220 while (i < parent->ondisk->count) {
2221 elm = &parent->ondisk->elms[i];
2222 if (elm->internal.subtree_offset == node->node_offset)
2223 break;
2224 ++i;
2226 if (i == parent->ondisk->count) {
2227 hammer_unlock(&parent->lock);
2228 panic("Bad B-Tree link: parent %p node %p\n", parent, node);
2230 *parent_indexp = i;
2231 KKASSERT(*errorp == 0);
2232 return(parent);
2236 * The element (elm) has been moved to a new internal node (node).
2238 * If the element represents a pointer to an internal node that node's
2239 * parent must be adjusted to the element's new location.
2241 * XXX deadlock potential here with our exclusive locks
2244 btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
2245 hammer_btree_elm_t elm)
2247 hammer_node_t child;
2248 int error;
2250 error = 0;
2252 switch(elm->base.btype) {
2253 case HAMMER_BTREE_TYPE_INTERNAL:
2254 case HAMMER_BTREE_TYPE_LEAF:
2255 child = hammer_get_node(node->hmp, elm->internal.subtree_offset,
2256 0, &error);
2257 if (error == 0) {
2258 hammer_modify_node_field(trans, child, parent);
2259 child->ondisk->parent = node->node_offset;
2260 hammer_modify_node_done(child);
2261 hammer_rel_node(child);
2263 break;
2264 default:
2265 break;
2267 return(error);
2271 * Exclusively lock all the children of node. This is used by the split
2272 * code to prevent anyone from accessing the children of a cursor node
2273 * while we fix-up its parent offset.
2275 * If we don't lock the children we can really mess up cursors which block
2276 * trying to cursor-up into our node.
2278 * On failure EDEADLK (or some other error) is returned. If a deadlock
2279 * error is returned the cursor is adjusted to block on termination.
2282 hammer_btree_lock_children(hammer_cursor_t cursor,
2283 struct hammer_node_locklist **locklistp)
2285 hammer_node_t node;
2286 hammer_node_locklist_t item;
2287 hammer_node_ondisk_t ondisk;
2288 hammer_btree_elm_t elm;
2289 hammer_node_t child;
2290 int error;
2291 int i;
2293 node = cursor->node;
2294 ondisk = node->ondisk;
2295 error = 0;
2298 * We really do not want to block on I/O with exclusive locks held,
2299 * pre-get the children before trying to lock the mess.
2301 for (i = 0; i < ondisk->count; ++i) {
2302 ++hammer_stats_btree_elements;
2303 elm = &ondisk->elms[i];
2304 if (elm->base.btype != HAMMER_BTREE_TYPE_LEAF &&
2305 elm->base.btype != HAMMER_BTREE_TYPE_INTERNAL) {
2306 continue;
2308 child = hammer_get_node(node->hmp,
2309 elm->internal.subtree_offset,
2310 0, &error);
2311 if (child)
2312 hammer_rel_node(child);
2316 * Do it for real
2318 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2319 ++hammer_stats_btree_elements;
2320 elm = &ondisk->elms[i];
2322 switch(elm->base.btype) {
2323 case HAMMER_BTREE_TYPE_INTERNAL:
2324 case HAMMER_BTREE_TYPE_LEAF:
2325 KKASSERT(elm->internal.subtree_offset != 0);
2326 child = hammer_get_node(node->hmp,
2327 elm->internal.subtree_offset,
2328 0, &error);
2329 break;
2330 default:
2331 child = NULL;
2332 break;
2334 if (child) {
2335 if (hammer_lock_ex_try(&child->lock) != 0) {
2336 if (cursor->deadlk_node == NULL) {
2337 cursor->deadlk_node = child;
2338 hammer_ref_node(cursor->deadlk_node);
2340 error = EDEADLK;
2341 hammer_rel_node(child);
2342 } else {
2343 item = kmalloc(sizeof(*item),
2344 M_HAMMER, M_WAITOK);
2345 item->next = *locklistp;
2346 item->node = child;
2347 *locklistp = item;
2351 if (error)
2352 hammer_btree_unlock_children(locklistp);
2353 return(error);
2358 * Release previously obtained node locks.
2360 void
2361 hammer_btree_unlock_children(struct hammer_node_locklist **locklistp)
2363 hammer_node_locklist_t item;
2365 while ((item = *locklistp) != NULL) {
2366 *locklistp = item->next;
2367 hammer_unlock(&item->node->lock);
2368 hammer_rel_node(item->node);
2369 kfree(item, M_HAMMER);
2373 /************************************************************************
2374 * MISCELLANIOUS SUPPORT *
2375 ************************************************************************/
2378 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
2380 * Note that for this particular function a return value of -1, 0, or +1
2381 * can denote a match if create_tid is otherwise discounted. A create_tid
2382 * of zero is considered to be 'infinity' in comparisons.
2384 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
2387 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2389 if (key1->localization < key2->localization)
2390 return(-5);
2391 if (key1->localization > key2->localization)
2392 return(5);
2394 if (key1->obj_id < key2->obj_id)
2395 return(-4);
2396 if (key1->obj_id > key2->obj_id)
2397 return(4);
2399 if (key1->rec_type < key2->rec_type)
2400 return(-3);
2401 if (key1->rec_type > key2->rec_type)
2402 return(3);
2404 if (key1->key < key2->key)
2405 return(-2);
2406 if (key1->key > key2->key)
2407 return(2);
2410 * A create_tid of zero indicates a record which is undeletable
2411 * and must be considered to have a value of positive infinity.
2413 if (key1->create_tid == 0) {
2414 if (key2->create_tid == 0)
2415 return(0);
2416 return(1);
2418 if (key2->create_tid == 0)
2419 return(-1);
2420 if (key1->create_tid < key2->create_tid)
2421 return(-1);
2422 if (key1->create_tid > key2->create_tid)
2423 return(1);
2424 return(0);
2428 * Test a timestamp against an element to determine whether the
2429 * element is visible. A timestamp of 0 means 'infinity'.
2432 hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
2434 if (asof == 0) {
2435 if (base->delete_tid)
2436 return(1);
2437 return(0);
2439 if (asof < base->create_tid)
2440 return(-1);
2441 if (base->delete_tid && asof >= base->delete_tid)
2442 return(1);
2443 return(0);
2447 * Create a separator half way inbetween key1 and key2. For fields just
2448 * one unit apart, the separator will match key2. key1 is on the left-hand
2449 * side and key2 is on the right-hand side.
2451 * key2 must be >= the separator. It is ok for the separator to match key2.
2453 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2454 * key2.
2456 * NOTE: It might be beneficial to just scrap this whole mess and just
2457 * set the separator to key2.
2459 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2460 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2462 static void
2463 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2464 hammer_base_elm_t dest)
2466 bzero(dest, sizeof(*dest));
2468 dest->rec_type = key2->rec_type;
2469 dest->key = key2->key;
2470 dest->obj_id = key2->obj_id;
2471 dest->create_tid = key2->create_tid;
2473 MAKE_SEPARATOR(key1, key2, dest, localization);
2474 if (key1->localization == key2->localization) {
2475 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2476 if (key1->obj_id == key2->obj_id) {
2477 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2478 if (key1->rec_type == key2->rec_type) {
2479 MAKE_SEPARATOR(key1, key2, dest, key);
2481 * Don't bother creating a separator for
2482 * create_tid, which also conveniently avoids
2483 * having to handle the create_tid == 0
2484 * (infinity) case. Just leave create_tid
2485 * set to key2.
2487 * Worst case, dest matches key2 exactly,
2488 * which is acceptable.
2495 #undef MAKE_SEPARATOR
2498 * Return whether a generic internal or leaf node is full
2500 static int
2501 btree_node_is_full(hammer_node_ondisk_t node)
2503 switch(node->type) {
2504 case HAMMER_BTREE_TYPE_INTERNAL:
2505 if (node->count == HAMMER_BTREE_INT_ELMS)
2506 return(1);
2507 break;
2508 case HAMMER_BTREE_TYPE_LEAF:
2509 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2510 return(1);
2511 break;
2512 default:
2513 panic("illegal btree subtype");
2515 return(0);
2518 #if 0
2519 static int
2520 btree_max_elements(u_int8_t type)
2522 if (type == HAMMER_BTREE_TYPE_LEAF)
2523 return(HAMMER_BTREE_LEAF_ELMS);
2524 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2525 return(HAMMER_BTREE_INT_ELMS);
2526 panic("btree_max_elements: bad type %d\n", type);
2528 #endif
2530 void
2531 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2533 hammer_btree_elm_t elm;
2534 int i;
2536 kprintf("node %p count=%d parent=%016llx type=%c\n",
2537 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2540 * Dump both boundary elements if an internal node
2542 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2543 for (i = 0; i <= ondisk->count; ++i) {
2544 elm = &ondisk->elms[i];
2545 hammer_print_btree_elm(elm, ondisk->type, i);
2547 } else {
2548 for (i = 0; i < ondisk->count; ++i) {
2549 elm = &ondisk->elms[i];
2550 hammer_print_btree_elm(elm, ondisk->type, i);
2555 void
2556 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2558 kprintf(" %2d", i);
2559 kprintf("\tobj_id = %016llx\n", elm->base.obj_id);
2560 kprintf("\tkey = %016llx\n", elm->base.key);
2561 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2562 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2563 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2564 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2565 kprintf("\tbtype = %02x (%c)\n",
2566 elm->base.btype,
2567 (elm->base.btype ? elm->base.btype : '?'));
2568 kprintf("\tlocalization = %02x\n", elm->base.localization);
2570 switch(type) {
2571 case HAMMER_BTREE_TYPE_INTERNAL:
2572 kprintf("\tsubtree_off = %016llx\n",
2573 elm->internal.subtree_offset);
2574 break;
2575 case HAMMER_BTREE_TYPE_RECORD:
2576 kprintf("\tdata_offset = %016llx\n", elm->leaf.data_offset);
2577 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2578 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);
2579 break;