2 * Copyright (c) 2007 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * $DragonFly: src/sys/vfs/hammer/hammer_btree.c,v 1.18 2008/01/15 06:02:57 dillon Exp $
40 * HAMMER implements a modified B+Tree. In documentation this will
41 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
42 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
43 * of the tree), but adds two additional boundary elements which describe
44 * the left-most and right-most element a node is able to represent. In
45 * otherwords, we have boundary elements at the two ends of a B-Tree node
46 * instead of sub-tree pointers.
48 * A B-Tree internal node looks like this:
50 * B N N N N N N B <-- boundary and internal elements
51 * S S S S S S S <-- subtree pointers
53 * A B-Tree leaf node basically looks like this:
55 * L L L L L L L L <-- leaf elemenets
57 * The radix for an internal node is 1 less then a leaf but we get a
58 * number of significant benefits for our troubles.
60 * The big benefit to using a B-Tree containing boundary information
61 * is that it is possible to cache pointers into the middle of the tree
62 * and not have to start searches, insertions, OR deletions at the root
63 * node. In particular, searches are able to progress in a definitive
64 * direction from any point in the tree without revisting nodes. This
65 * greatly improves the efficiency of many operations, most especially
68 * B-Trees also make the stacking of trees fairly straightforward.
70 * INTER-CLUSTER ELEMENTS: An element of an internal node may reference
71 * the root of another cluster rather then a node in the current cluster.
72 * This is known as an inter-cluster references. Only B-Tree searches
73 * will cross cluster boundaries. The rebalancing and collapse code does
74 * not attempt to move children between clusters. A major effect of this
75 * is that we have to relax minimum element count requirements and allow
76 * trees to become somewhat unabalanced.
78 * INSERTIONS AND DELETIONS: When inserting we split full nodes on our
79 * way down as an optimization. I originally experimented with rebalancing
80 * nodes on the way down for deletions but it created a huge mess due to
81 * the way inter-cluster linkages work. Instead, now I simply allow
82 * the tree to become unbalanced and allow leaf nodes to become empty.
83 * The delete code will try to clean things up from the bottom-up but
84 * will stop if related elements are not in-core or if it cannot get a node
91 typedef enum btree_search_edge {
95 } btree_search_edge_t;
97 static int btree_search(hammer_cursor_t cursor, int flags);
98 static int btree_edge_internal(hammer_cursor_t cursor,
99 btree_search_edge_t edge);
100 static int btree_split_internal(hammer_cursor_t cursor);
101 static int btree_split_leaf(hammer_cursor_t cursor);
102 static int btree_remove(hammer_cursor_t cursor);
103 static int btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm);
105 static int btree_rebalance(hammer_cursor_t cursor);
106 static int btree_collapse(hammer_cursor_t cursor);
108 static int btree_node_is_almost_full(hammer_node_ondisk_t node);
109 static void hammer_make_separator(hammer_base_elm_t key1,
110 hammer_base_elm_t key2, hammer_base_elm_t dest);
113 * Iterate records after a search. The cursor is iterated forwards past
114 * the current record until a record matching the key-range requirements
115 * is found. ENOENT is returned if the iteration goes past the ending
118 * The iteration is inclusive of key_beg and can be inclusive or exclusive
119 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
121 * cursor->key_beg may or may not be modified by this function during
122 * the iteration. XXX future - in case of an inverted lock we may have
123 * to reinitiate the lookup and set key_beg to properly pick up where we
127 hammer_btree_iterate(hammer_cursor_t cursor)
129 hammer_node_ondisk_t node;
130 hammer_btree_elm_t elm;
136 * Skip past the current record
138 node = cursor->node->ondisk;
141 if (cursor->index < node->count &&
142 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
147 * Loop until an element is found or we are done.
151 * We iterate up the tree and then index over one element
152 * while we are at the last element in the current node.
154 * NOTE: This can pop us up to another cluster.
156 * If we are at the root of the root cluster, cursor_up
159 * NOTE: hammer_cursor_up() will adjust cursor->key_beg
160 * when told to re-search for the cluster tag.
162 * XXX this could be optimized by storing the information in
163 * the parent reference.
165 * XXX we can lose the node lock temporarily, this could mess
168 if (cursor->index == node->count) {
169 error = hammer_cursor_up(cursor, 0);
172 node = cursor->node->ondisk;
173 KKASSERT(cursor->index != node->count);
179 * Check internal or leaf element. Determine if the record
180 * at the cursor has gone beyond the end of our range.
182 * Generally we recurse down through internal nodes. An
183 * internal node can only be returned if INCLUSTER is set
184 * and the node represents a cluster-push record. Internal
185 * elements do not contain create_tid/delete_tid information.
187 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
188 elm = &node->elms[cursor->index];
189 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
190 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
191 if (hammer_debug_btree) {
192 kprintf("BRACKETL %p:%d %016llx %02x %016llx %d\n",
193 cursor->node, cursor->index,
194 elm[0].internal.base.obj_id,
195 elm[0].internal.base.rec_type,
196 elm[0].internal.base.key,
199 kprintf("BRACKETR %p:%d %016llx %02x %016llx %d\n",
200 cursor->node, cursor->index + 1,
201 elm[1].internal.base.obj_id,
202 elm[1].internal.base.rec_type,
203 elm[1].internal.base.key,
212 if (r == 0 && (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
217 if ((cursor->flags & HAMMER_CURSOR_INCLUSTER) == 0 ||
218 elm->internal.rec_offset == 0) {
219 error = hammer_cursor_down(cursor);
222 KKASSERT(cursor->index == 0);
223 node = cursor->node->ondisk;
227 elm = &node->elms[cursor->index];
228 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
229 if (hammer_debug_btree) {
230 kprintf("ELEMENT %p:%d %016llx %02x %016llx %d\n",
231 cursor->node, cursor->index,
232 elm[0].leaf.base.obj_id,
233 elm[0].leaf.base.rec_type,
234 elm[0].leaf.base.key,
242 if (r == 0 && (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
246 if ((cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0 &&
247 hammer_btree_chkts(cursor->key_beg.create_tid,
257 if (hammer_debug_btree) {
258 int i = cursor->index;
259 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
260 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
262 elm->internal.base.obj_id,
263 elm->internal.base.rec_type,
264 elm->internal.base.key
273 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
274 * could not be found, and a fatal error otherwise.
276 * The cursor is suitably positioned for a deletion on success, and suitably
277 * positioned for an insertion on ENOENT.
279 * The cursor may begin anywhere, the search will traverse clusters in
280 * either direction to locate the requested element.
283 hammer_btree_lookup(hammer_cursor_t cursor)
287 error = btree_search(cursor, 0);
288 if (error == 0 && cursor->flags)
289 error = hammer_btree_extract(cursor, cursor->flags);
294 * Execute the logic required to start an iteration. The first record
295 * located within the specified range is returned and iteration control
296 * flags are adjusted for successive hammer_btree_iterate() calls.
299 hammer_btree_first(hammer_cursor_t cursor)
303 error = hammer_btree_lookup(cursor);
304 if (error == ENOENT) {
305 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
306 error = hammer_btree_iterate(cursor);
308 cursor->flags |= HAMMER_CURSOR_ATEDISK;
313 * Extract the record and/or data associated with the cursor's current
314 * position. Any prior record or data stored in the cursor is replaced.
315 * The cursor must be positioned at a leaf node.
317 * NOTE: Most extractions occur at the leaf of the B-Tree. The only
318 * extraction allowed at an internal element is at a cluster-push.
319 * Cluster-push elements have records but no data.
322 hammer_btree_extract(hammer_cursor_t cursor, int flags)
324 hammer_node_ondisk_t node;
325 hammer_btree_elm_t elm;
326 hammer_cluster_t cluster;
333 * A cluster record type has no data reference, the information
334 * is stored directly in the record and B-Tree element.
336 * The case where the data reference resolves to the same buffer
337 * as the record reference must be handled.
339 node = cursor->node->ondisk;
340 elm = &node->elms[cursor->index];
341 cluster = cursor->node->cluster;
342 cursor->flags &= ~HAMMER_CURSOR_DATA_EMBEDDED;
347 * Internal elements can only be cluster pushes. A cluster push has
350 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
351 cloff = elm->internal.rec_offset;
352 KKASSERT(cloff != 0);
353 cursor->record = hammer_bread(cluster, cloff,
354 HAMMER_FSBUF_RECORDS, &error,
355 &cursor->record_buffer);
362 if ((flags & HAMMER_CURSOR_GET_RECORD) && error == 0) {
363 cloff = elm->leaf.rec_offset;
364 cursor->record = hammer_bread(cluster, cloff,
365 HAMMER_FSBUF_RECORDS, &error,
366 &cursor->record_buffer);
370 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
371 if ((cloff ^ elm->leaf.data_offset) & ~HAMMER_BUFMASK) {
373 * The data is not in the same buffer as the last
374 * record we cached, but it could still be embedded
375 * in a record. Note that we may not have loaded the
376 * record's buffer above, depending on flags.
378 if ((elm->leaf.rec_offset ^ elm->leaf.data_offset) &
380 if (elm->leaf.data_len & HAMMER_BUFMASK)
381 buf_type = HAMMER_FSBUF_DATA;
383 buf_type = 0; /* pure data buffer */
385 buf_type = HAMMER_FSBUF_RECORDS;
387 cursor->data = hammer_bread(cluster,
388 elm->leaf.data_offset,
390 &cursor->data_buffer);
393 * Data in same buffer as record. Note that we
394 * leave any existing data_buffer intact, even
395 * though we don't use it in this case, in case
396 * other records extracted during an iteration
399 * The data must be embedded in the record for this
402 * Just assume the buffer type is correct.
404 cursor->data = (void *)
405 ((char *)cursor->record_buffer->ondisk +
406 (elm->leaf.data_offset & HAMMER_BUFMASK));
407 roff = (char *)cursor->data - (char *)cursor->record;
408 KKASSERT (roff >= 0 && roff < HAMMER_RECORD_SIZE);
409 cursor->flags |= HAMMER_CURSOR_DATA_EMBEDDED;
417 * Insert a leaf element into the B-Tree at the current cursor position.
418 * The cursor is positioned such that the element at and beyond the cursor
419 * are shifted to make room for the new record.
421 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
422 * flag set and that call must return ENOENT before this function can be
425 * ENOSPC is returned if there is no room to insert a new record.
428 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
430 hammer_node_ondisk_t parent;
431 hammer_node_ondisk_t node;
435 * Insert the element at the leaf node and update the count in the
436 * parent. It is possible for parent to be NULL, indicating that
437 * the root of the B-Tree in the cluster is a leaf. It is also
438 * possible for the leaf to be empty.
440 * Remember that the right-hand boundary is not included in the
443 hammer_modify_node(cursor->node);
444 node = cursor->node->ondisk;
446 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
447 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
448 if (i != node->count) {
449 bcopy(&node->elms[i], &node->elms[i+1],
450 (node->count - i) * sizeof(*elm));
452 node->elms[i] = *elm;
455 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
456 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
458 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->leaf.base) < 0);
459 if (i != node->count - 1)
460 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->leaf.base) > 0);
463 * Adjust the sub-tree count in the parent. note that the parent
464 * may be in a different cluster.
466 if (cursor->parent) {
467 hammer_modify_node(cursor->parent);
468 parent = cursor->parent->ondisk;
469 i = cursor->parent_index;
470 ++parent->elms[i].internal.subtree_count;
471 KKASSERT(parent->elms[i].internal.subtree_count <= node->count);
477 * Insert a cluster push into the B-Tree at the current cursor position.
478 * The cursor is positioned at a leaf after a failed btree_lookup.
480 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
481 * flag set and that call must return ENOENT before this function can be
484 * This routine is used ONLY during a recovery pass while the originating
485 * cluster is serialized. The leaf is broken up into up to three pieces,
486 * causing up to an additional internal elements to be added to the parent.
488 * ENOSPC is returned if there is no room to insert a new record.
491 hammer_btree_insert_cluster(hammer_cursor_t cursor, hammer_cluster_t ncluster,
494 hammer_cluster_t ocluster;
495 hammer_node_ondisk_t parent;
496 hammer_node_ondisk_t node;
497 hammer_node_ondisk_t xnode; /* additional leaf node */
498 hammer_node_t new_node;
499 hammer_btree_elm_t elm;
500 const int esize = sizeof(*elm);
505 kprintf("cursor %p ncluster %p\n", cursor, ncluster);
506 hammer_modify_node(cursor->node);
507 node = cursor->node->ondisk;
509 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
510 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
513 * Make sure the spike is legal or the B-Tree code will get really
516 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_beg,
517 cursor->left_bound) >= 0);
518 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
519 cursor->right_bound) <= 0);
520 if (i != node->count) {
521 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
522 &node->elms[i].leaf.base) <= 0);
526 * If we are at the local root of the cluster a new root node
527 * must be created, because we need an internal node. The
528 * caller has already marked the source cluster as undergoing
531 ocluster = cursor->node->cluster;
532 if (cursor->parent == NULL) {
533 cursor->parent = hammer_alloc_btree(ocluster, &error);
536 hammer_lock_ex(&cursor->parent->lock);
537 hammer_modify_node(cursor->parent);
538 parent = cursor->parent->ondisk;
541 parent->type = HAMMER_BTREE_TYPE_INTERNAL;
542 parent->elms[0].base = ocluster->clu_btree_beg;
543 parent->elms[0].base.subtree_type = node->type;
544 parent->elms[0].internal.subtree_offset = cursor->node->node_offset;
545 parent->elms[0].internal.subtree_count = node->count;
546 parent->elms[1].base = ocluster->clu_btree_end;
547 cursor->parent_index = 0;
548 cursor->left_bound = &parent->elms[0].base;
549 cursor->right_bound = &parent->elms[1].base;
550 node->parent = cursor->parent->node_offset;
551 ocluster->ondisk->clu_btree_root = cursor->parent->node_offset;
552 kprintf("no parent\n");
554 kprintf("has parent\n");
558 KKASSERT(cursor->parent->ondisk->count <= HAMMER_BTREE_INT_ELMS - 2);
560 hammer_modify_node(cursor->parent);
561 parent = cursor->parent->ondisk;
562 pi = cursor->parent_index;
564 kprintf("%d node %d/%d (%c) offset=%d parent=%d\n",
565 cursor->node->cluster->clu_no,
566 i, node->count, node->type, cursor->node->node_offset, node->parent);
569 * If the insertion point bisects the node we will need to allocate
570 * a second leaf node to copy the right hand side into.
572 if (i != 0 && i != node->count) {
573 new_node = hammer_alloc_btree(cursor->node->cluster, &error);
576 xnode = new_node->ondisk;
577 bcopy(&node->elms[i], &xnode->elms[0],
578 (node->count - i) * esize);
579 xnode->count = node->count - i;
580 xnode->parent = cursor->parent->node_offset;
581 xnode->type = HAMMER_BTREE_TYPE_LEAF;
583 parent->elms[pi].internal.subtree_count = node->count;
590 * Adjust the parent and set pi to point at the internal element
591 * which we intended to hold the spike.
595 * Insert spike after parent index. Spike is at pi + 1.
596 * Also include room after the spike for new_node
599 bcopy(&parent->elms[pi], &parent->elms[pi+2],
600 (parent->count - pi + 1) * esize);
604 * Insert spike before parent index. Spike is at pi.
606 * cursor->node's index in the parent (cursor->parent_index)
607 * has now shifted over by one.
609 bcopy(&parent->elms[pi], &parent->elms[pi+1],
610 (parent->count - pi + 1) * esize);
612 ++cursor->parent_index;
615 * Insert spike after parent index. Spike is at pi + 1.
618 bcopy(&parent->elms[pi], &parent->elms[pi+1],
619 (parent->count - pi + 1) * esize);
624 * Load the spike into the parent at (pi).
626 * WARNING: subtree_type is actually overloaded within base.
627 * WARNING: subtree_clu_no is overloaded on subtree_offset
629 elm = &parent->elms[pi];
630 elm[0].internal.base = ncluster->ondisk->clu_btree_beg;
631 elm[0].internal.base.subtree_type = HAMMER_BTREE_TYPE_CLUSTER;
632 elm[0].internal.rec_offset = rec_offset;
633 elm[0].internal.subtree_clu_no = ncluster->clu_no;
634 elm[0].internal.subtree_vol_no = ncluster->volume->vol_no;
635 elm[0].internal.subtree_count = 0; /* XXX */
638 * Load the new node into parent at (pi+1) if non-NULL, and also
639 * set the right-hand boundary for the spike.
641 * Because new_node is a leaf its elements do not point to any
642 * nodes so we don't have to scan it to adjust parent pointers.
644 * WARNING: subtree_type is actually overloaded within base.
645 * WARNING: subtree_clu_no is overloaded on subtree_offset
647 * XXX right-boundary may not match clu_btree_end if spike is
648 * at the end of the internal node. For now the cursor search
649 * insertion code will deal with it.
652 elm[1].internal.base = ncluster->ondisk->clu_btree_end;
653 elm[1].internal.base.subtree_type = HAMMER_BTREE_TYPE_LEAF;
654 elm[1].internal.subtree_offset = new_node->node_offset;
655 elm[1].internal.subtree_count = xnode->count;
656 elm[1].internal.subtree_vol_no = -1;
657 elm[1].internal.rec_offset = 0;
660 * The right boundary is only the base part of elm[1].
661 * The rest belongs to elm[1]'s recursion. Note however
662 * that subtree_type is overloaded within base so we
663 * have to retain it as well.
665 save = elm[1].internal.base.subtree_type;
666 elm[1].internal.base = ncluster->ondisk->clu_btree_end;
667 elm[1].internal.base.subtree_type = save;
671 * The boundaries stored in the cursor for node are probably all
672 * messed up now, fix them.
674 cursor->left_bound = &parent->elms[cursor->parent_index].base;
675 cursor->right_bound = &parent->elms[cursor->parent_index+1].base;
677 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
678 &elm[1].internal.base) <= 0);
682 * Adjust the target cluster's parent offset
684 hammer_modify_cluster(ncluster);
685 ncluster->ondisk->clu_btree_parent_offset = cursor->parent->node_offset;
688 hammer_rel_node(new_node);
694 * Delete a record from the B-Tree's at the current cursor position.
695 * The cursor is positioned such that the current element is the one
698 * On return the cursor will be positioned after the deleted element and
699 * MAY point to an internal node. It will be suitable for the continuation
700 * of an iteration but not for an insertion or deletion.
702 * Deletions will attempt to partially rebalance the B-Tree in an upward
703 * direction. It is possible to end up with empty leafs. An empty internal
704 * node is impossible (worst case: it has one element pointing to an empty
708 hammer_btree_delete(hammer_cursor_t cursor)
710 hammer_node_ondisk_t ondisk;
712 hammer_node_t parent;
713 hammer_btree_elm_t elm;
718 * Delete the element from the leaf node.
720 * Remember that leaf nodes do not have boundaries.
723 ondisk = node->ondisk;
726 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
727 hammer_modify_node(node);
728 if (i + 1 != ondisk->count) {
729 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
730 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
733 if (cursor->parent != NULL) {
735 * Adjust parent's notion of the leaf's count. subtree_count
736 * is only approximate, it is allowed to be too small but
737 * never allowed to be too large. Make sure we don't drop
740 parent = cursor->parent;
741 hammer_modify_node(parent);
742 elm = &parent->ondisk->elms[cursor->parent_index];
743 if (elm->internal.subtree_count)
744 --elm->internal.subtree_count;
745 KKASSERT(elm->internal.subtree_count <= ondisk->count);
749 * It is possible, but not desireable, to stop here. If the element
750 * count drops to 0 (which is allowed for a leaf), try recursively
751 * remove the B-Tree node.
753 * XXX rebalancing calls would go here too.
755 * This may reposition the cursor at one of the parent's of the
758 KKASSERT(cursor->index <= ondisk->count);
759 if (ondisk->count == 0) {
760 error = btree_remove(cursor);
770 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
772 * Search a cluster's B-Tree for cursor->key_beg, return the matching node.
774 * The search can begin ANYWHERE in the B-Tree. As a first step the search
775 * iterates up the tree as necessary to properly position itself prior to
776 * actually doing the sarch.
778 * INSERTIONS: The search will split full nodes and leaves on its way down
779 * and guarentee that the leaf it ends up on is not full. If we run out
780 * of space the search continues to the leaf (to position the cursor for
781 * the spike), but ENOSPC is returned.
783 * XXX this isn't optimal - we really need to just locate the end point and
784 * insert space going up, and if we get a deadlock just release and retry
785 * the operation. Or something like that. The insertion code can transit
786 * multiple clusters and run splits in unnecessary clusters.
788 * DELETIONS: The search will rebalance the tree on its way down. XXX
790 * The search is only guarenteed to end up on a leaf if an error code of 0
791 * is returned, or if inserting and an error code of ENOENT is returned.
792 * Otherwise it can stop at an internal node. On success a search returns
793 * a leaf node unless INCLUSTER is set and the search located a cluster push
794 * node (which is an internal node).
798 btree_search(hammer_cursor_t cursor, int flags)
800 hammer_node_ondisk_t node;
801 hammer_cluster_t cluster;
802 hammer_btree_elm_t elm;
803 btree_search_edge_t edge;
809 flags |= cursor->flags;
811 if (hammer_debug_btree) {
812 kprintf("SEARCH %p:%d %016llx %02x key=%016llx tid=%016llx\n",
813 cursor->node, cursor->index,
814 cursor->key_beg.obj_id,
815 cursor->key_beg.rec_type,
817 cursor->key_beg.create_tid
822 * Move our cursor up the tree until we find a node whos range covers
823 * the key we are trying to locate. This may move us between
826 * The left bound is inclusive, the right bound is non-inclusive.
827 * It is ok to cursor up too far so when cursoring across a cluster
830 * First see if we can skip the whole cluster. hammer_cursor_up()
831 * handles both cases but this way we don't check the cluster
832 * bounds when going up the tree within a cluster.
834 * NOTE: If INCLUSTER is set and we are at the root of the cluster,
835 * hammer_cursor_up() will return ENOENT.
837 cluster = cursor->node->cluster;
839 hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_beg) < 0 ||
840 hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_end) >= 0) {
841 error = hammer_cursor_toroot(cursor);
844 KKASSERT(cursor->parent);
845 error = hammer_cursor_up(cursor, 0);
848 cluster = cursor->node->cluster;
852 * Deal with normal cursoring within a cluster. The right bound
853 * is non-inclusive. That is, the bounds form a separator.
855 while (hammer_btree_cmp(&cursor->key_beg, cursor->left_bound) < 0 ||
856 hammer_btree_cmp(&cursor->key_beg, cursor->right_bound) >= 0) {
857 KKASSERT(cursor->parent);
858 error = hammer_cursor_up(cursor, 0);
864 * We better have ended up with a node somewhere, and our second
865 * while loop had better not have traversed up a cluster.
867 KKASSERT(cursor->node != NULL && cursor->node->cluster == cluster);
870 * If we are inserting we can't start at a full node if the parent
871 * is also full (because there is no way to split the node),
872 * continue running up the tree until we hit the root of the
873 * root cluster or until the requirement is satisfied.
875 * NOTE: These cursor-up's CAN continue to cross cluster boundaries.
877 * NOTE: We must guarantee at least two open spots in the parent
878 * to deal with hammer_btree_insert_cluster().
880 * XXX as an optimization it should be possible to unbalance the tree
881 * and stop at the root of the current cluster.
883 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
884 if (btree_node_is_almost_full(cursor->node->ondisk) == 0)
886 if (cursor->parent == NULL)
888 if (cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS)
890 error = hammer_cursor_up(cursor, 0);
891 /* cluster and node are now may become stale */
895 /* cluster = cursor->node->cluster; not needed until next cluster = */
899 * If we are deleting we can't start at an internal node with only
900 * one element unless it is root, because all of our code assumes
901 * that internal nodes will never be empty. Just do this generally
902 * for both leaf and internal nodes to get better balance.
904 * This handles the case where the cursor is sitting at a leaf and
905 * either the leaf or parent contain an insufficient number of
908 * NOTE: These cursor-up's CAN continue to cross cluster boundaries.
910 * XXX NOTE: Iterations may not set this flag anyway.
912 while (flags & HAMMER_CURSOR_DELETE) {
913 if (cursor->node->ondisk->count > 1)
915 if (cursor->parent == NULL)
917 KKASSERT(cursor->node->ondisk->count != 0);
918 error = hammer_cursor_up(cursor, 0);
919 /* cluster and node are now may become stale */
927 * Push down through internal nodes to locate the requested key.
929 cluster = cursor->node->cluster;
930 node = cursor->node->ondisk;
931 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
934 * If we are a the root node and deleting, try to collapse
935 * all of the root's children into the root. This is the
936 * only point where tree depth is reduced.
938 * XXX NOTE: Iterations may not set this flag anyway.
940 if ((flags & HAMMER_CURSOR_DELETE) && cursor->parent == NULL) {
941 error = btree_collapse(cursor);
942 /* node becomes stale after call */
947 node = cursor->node->ondisk;
950 * Scan the node to find the subtree index to push down into.
951 * We go one-past, then back-up.
953 * We have a serious issue with the midpoints for internal
954 * nodes when the midpoint bisects two historical records
955 * (where only create_tid is different). Short of iterating
956 * through the record's entire history the only solution is
957 * to calculate a midpoint that isn't a midpoint in that
958 * case. Please see hammer_make_separator() for more
961 * The right boundary is included in the search.
963 for (i = 0; i <= node->count; ++i) {
964 elm = &node->elms[i];
965 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
971 * These cases occur when the parent's idea of the boundary
972 * is wider then the child's idea of the boundary, and
973 * require special handling. If not inserting we can
974 * terminate the search early for these cases but the
975 * child's boundaries cannot be unconditionally modified.
980 * If i == 0 the search terminated to the LEFT of the
981 * left_boundary but to the RIGHT of the parent's left
986 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
990 elm = &node->elms[0];
992 if (elm->base.subtree_type ==
993 HAMMER_BTREE_TYPE_CLUSTER) {
994 edge = SEARCH_LEFT_EDGE;
997 * Correct a left-hand boundary mismatch.
999 hammer_modify_node(cursor->node);
1000 save = node->elms[0].base.subtree_type;
1001 node->elms[0].base = *cursor->left_bound;
1002 node->elms[0].base.subtree_type = save;
1004 } else if (i == node->count + 1) {
1006 * If i == node->count + 1 the search terminated to
1007 * the RIGHT of the right boundary but to the LEFT
1008 * of the parent's right boundary.
1010 * Note that the last element in this case is
1011 * elms[i-2] prior to adjustments to 'i'.
1014 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1019 elm = &node->elms[i];
1020 if (elm[-1].base.subtree_type ==
1021 HAMMER_BTREE_TYPE_CLUSTER) {
1022 edge = SEARCH_RIGHT_EDGE;
1024 hammer_modify_node(cursor->node);
1025 elm->base = *cursor->right_bound;
1029 * The push-down index is now i - 1. If we had
1030 * terminated on the right boundary this will point
1031 * us at the last element.
1037 if (hammer_debug_btree) {
1038 elm = &node->elms[i];
1039 kprintf("SEARCH-I %p:%d %016llx %02x key=%016llx tid=%016llx\n",
1041 elm->internal.base.obj_id,
1042 elm->internal.base.rec_type,
1043 elm->internal.base.key,
1044 elm->internal.base.create_tid
1049 * Handle insertion and deletion requirements.
1051 * If inserting split full nodes. The split code will
1052 * adjust cursor->node and cursor->index if the current
1053 * index winds up in the new node.
1055 * If inserting and a left or right edge case was detected,
1056 * we cannot correct the left or right boundary and must
1057 * prepend and append an empty leaf node in order to make
1058 * the boundary correction.
1060 * If we run out of space we set enospc and continue on
1061 * to a leaf to provide the spike code with a good point
1062 * of entry. Enospc is reset if we cross a cluster boundary.
1064 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1065 if (btree_node_is_almost_full(node)) {
1066 error = btree_split_internal(cursor);
1068 if (error != ENOSPC)
1073 * reload stale pointers
1076 node = cursor->node->ondisk;
1078 if (edge != SEARCH_NONE && enospc == 0) {
1079 error = btree_edge_internal(cursor, edge);
1081 if (error != ENOSPC)
1086 * reload stale pointers
1089 node = cursor->node->ondisk;
1095 * If deleting rebalance - do not allow the child to have
1096 * just one element or we will not be able to delete it.
1098 * Neither internal or leaf nodes (except a root-leaf) are
1099 * allowed to drop to 0 elements. (XXX - well, leaf nodes
1100 * can at the moment).
1102 * Our separators may have been reorganized after rebalancing,
1103 * so we have to pop back up and rescan.
1105 * XXX test for subtree_count < maxelms / 2, minus 1 or 2
1108 * XXX NOTE: Iterations may not set this flag anyway.
1110 if (flags & HAMMER_CURSOR_DELETE) {
1111 if (node->elms[i].internal.subtree_count <= 1) {
1112 error = btree_rebalance(cursor);
1115 /* cursor->index is invalid after call */
1121 * A non-zero rec_offset specifies a cluster push.
1122 * If this is a cluster push we reset the enospc flag,
1123 * which reenables the insertion code in the new cluster.
1124 * This also ensures that if a spike occurs both its node
1125 * and its parent will be in the same cluster.
1127 * If INCLUSTER is set we terminate at the cluster boundary.
1128 * In this case we must determine whether key_beg is within
1129 * the cluster's boundary or not. XXX
1131 elm = &node->elms[i];
1132 if (elm->internal.rec_offset) {
1133 KKASSERT(elm->base.subtree_type ==
1134 HAMMER_BTREE_TYPE_CLUSTER);
1136 if (flags & HAMMER_CURSOR_INCLUSTER) {
1137 KKASSERT((flags & HAMMER_CURSOR_INSERT) == 0);
1138 r = hammer_btree_cmp(&cursor->key_beg,
1140 error = (r < 0) ? 0 : ENOENT;
1146 * Push down (push into new node, existing node becomes
1147 * the parent) and continue the search.
1149 error = hammer_cursor_down(cursor);
1150 /* node and cluster become stale */
1153 node = cursor->node->ondisk;
1154 cluster = cursor->node->cluster;
1158 * We are at a leaf, do a linear search of the key array.
1160 * On success the index is set to the matching element and 0
1163 * On failure the index is set to the insertion point and ENOENT
1166 * Boundaries are not stored in leaf nodes, so the index can wind
1167 * up to the left of element 0 (index == 0) or past the end of
1168 * the array (index == node->count).
1170 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1172 for (i = 0; i < node->count; ++i) {
1173 r = hammer_btree_cmp(&cursor->key_beg, &node->elms[i].base);
1176 * Stop if we've flipped past key_beg. This includes a
1177 * record whos create_tid is larger then our asof id.
1183 * Return an exact match. In this case we have to do special
1184 * checks if the only difference in the records is the
1185 * create_ts, in order to properly match against our as-of
1188 if (r >= 0 && r <= 1) {
1189 if ((cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0 &&
1190 hammer_btree_chkts(cursor->key_beg.create_tid,
1191 &node->elms[i].base) != 0) {
1196 if (hammer_debug_btree) {
1197 kprintf("SEARCH-L %p:%d (SUCCESS)\n",
1204 if (hammer_debug_btree) {
1205 kprintf("SEARCH-L %p:%d (FAILED)\n",
1210 * No exact match was found, i is now at the insertion point.
1212 * If inserting split a full leaf before returning. This
1213 * may have the side effect of adjusting cursor->node and
1217 if ((flags & HAMMER_CURSOR_INSERT) && btree_node_is_almost_full(node)) {
1218 error = btree_split_leaf(cursor);
1220 if (error != ENOSPC)
1223 flags &= ~HAMMER_CURSOR_INSERT;
1226 * reload stale pointers
1230 node = &cursor->node->internal;
1235 * We reached a leaf but did not find the key we were looking for.
1236 * If this is an insert we will be properly positioned for an insert
1237 * (ENOENT) or spike (ENOSPC) operation.
1239 error = enospc ? ENOSPC : ENOENT;
1245 /************************************************************************
1246 * SPLITTING AND MERGING *
1247 ************************************************************************
1249 * These routines do all the dirty work required to split and merge nodes.
1253 * This case occurs when we are trying to insert and have come across a
1254 * mismatched left or right boundary which could not be adjusted due to
1255 * being part of a spike. In order to be able to adjust the boundary
1256 * we have to prepend or append an empty leaf node.
1260 btree_edge_internal(hammer_cursor_t cursor, btree_search_edge_t edge)
1262 hammer_node_ondisk_t old_disk;
1263 hammer_node_ondisk_t new_disk;
1264 hammer_node_t new_node;
1265 hammer_btree_elm_t elm;
1268 const int esize = sizeof(*elm);
1270 old_disk = cursor->node->ondisk;
1271 KKASSERT(old_disk->type == HAMMER_BTREE_TYPE_INTERNAL);
1272 KKASSERT(old_disk->count < HAMMER_BTREE_INT_ELMS);
1275 * Allocate a new leaf node.
1277 new_node = hammer_alloc_btree(cursor->node->cluster, &error);
1281 hammer_lock_ex(&new_node->lock);
1282 hammer_modify_node(cursor->node);
1283 hammer_modify_node(new_node);
1284 new_disk = new_node->ondisk;
1285 n = old_disk->count;
1288 * Prepend or append the leaf node and correct the boundary
1292 case SEARCH_LEFT_EDGE:
1293 KKASSERT(cursor->index == 0);
1294 elm = &old_disk->elms[0];
1295 bcopy(elm, elm + 1, (n + 1) * esize);
1296 elm->base = *cursor->left_bound;
1298 case SEARCH_RIGHT_EDGE:
1299 KKASSERT(cursor->index == old_disk->count);
1300 elm = &old_disk->elms[n];
1301 elm[1].base = *cursor->right_bound;
1304 panic("btree_edge_internal: bad edge");
1308 elm->base.subtree_type = HAMMER_BTREE_TYPE_LEAF;
1309 elm->internal.subtree_offset = new_node->node_offset;
1310 elm->internal.subtree_vol_no = -1;
1311 elm->internal.subtree_count = 0;
1313 new_disk->count = 0;
1314 new_disk->parent = cursor->node->node_offset;
1315 new_disk->type = HAMMER_BTREE_TYPE_LEAF;
1317 hammer_unlock(&new_node->lock);
1318 hammer_rel_node(new_node);
1321 * Cursor->index remains unchanged. It now points to our new leaf
1322 * node and cursor->node's boundaries have been synchronized with
1329 * Split an internal node into two nodes and move the separator at the split
1330 * point to the parent. Note that the parent's parent's element pointing
1331 * to our parent will have an incorrect subtree_count (we don't update it).
1332 * It will be low, which is ok.
1334 * (cursor->node, cursor->index) indicates the element the caller intends
1335 * to push into. We will adjust node and index if that element winds
1336 * up in the split node.
1338 * If we are at the root of a cluster a new root must be created with two
1339 * elements, one pointing to the original root and one pointing to the
1340 * newly allocated split node.
1342 * NOTE! Being at the root of a cluster is different from being at the
1343 * root of the root cluster. cursor->parent will not be NULL and
1344 * cursor->node->ondisk.parent must be tested against 0. Theoretically
1345 * we could propogate the algorithm into the parent and deal with multiple
1346 * 'roots' in the cluster header, but it's easier not to.
1350 btree_split_internal(hammer_cursor_t cursor)
1352 hammer_node_ondisk_t ondisk;
1354 hammer_node_t parent;
1355 hammer_node_t new_node;
1356 hammer_btree_elm_t elm;
1357 hammer_btree_elm_t parent_elm;
1363 const int esize = sizeof(*elm);
1366 * We are splitting but elms[split] will be promoted to the parent,
1367 * leaving the right hand node with one less element. If the
1368 * insertion point will be on the left-hand side adjust the split
1369 * point to give the right hand side one additional node.
1371 node = cursor->node;
1372 ondisk = node->ondisk;
1373 split = (ondisk->count + 1) / 2;
1374 if (cursor->index <= split)
1379 * If we are at the root of the cluster, create a new root node with
1380 * 1 element and split normally. Avoid making major modifications
1381 * until we know the whole operation will work.
1383 * The root of the cluster is different from the root of the root
1384 * cluster. Use the node's on-disk structure's parent offset to
1387 if (ondisk->parent == 0) {
1388 parent = hammer_alloc_btree(node->cluster, &error);
1391 hammer_lock_ex(&parent->lock);
1392 hammer_modify_node(parent);
1393 ondisk = parent->ondisk;
1396 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1397 ondisk->elms[0].base = node->cluster->clu_btree_beg;
1398 ondisk->elms[0].base.subtree_type = node->ondisk->type;
1399 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1400 ondisk->elms[1].base = node->cluster->clu_btree_end;
1401 /* ondisk->elms[1].base.subtree_Type - not used */
1403 parent_index = 0; /* index of current node in parent */
1406 parent = cursor->parent;
1407 parent_index = cursor->parent_index;
1408 KKASSERT(parent->cluster == node->cluster);
1412 * Split node into new_node at the split point.
1414 * B O O O P N N B <-- P = node->elms[split]
1415 * 0 1 2 3 4 5 6 <-- subtree indices
1420 * B O O O B B N N B <--- inner boundary points are 'P'
1424 new_node = hammer_alloc_btree(node->cluster, &error);
1425 if (new_node == NULL) {
1427 hammer_unlock(&parent->lock);
1428 parent->flags |= HAMMER_NODE_DELETED;
1429 hammer_rel_node(parent);
1433 hammer_lock_ex(&new_node->lock);
1436 * Create the new node. P becomes the left-hand boundary in the
1437 * new node. Copy the right-hand boundary as well.
1439 * elm is the new separator.
1441 hammer_modify_node(new_node);
1442 hammer_modify_node(node);
1443 ondisk = node->ondisk;
1444 elm = &ondisk->elms[split];
1445 bcopy(elm, &new_node->ondisk->elms[0],
1446 (ondisk->count - split + 1) * esize);
1447 new_node->ondisk->count = ondisk->count - split;
1448 new_node->ondisk->parent = parent->node_offset;
1449 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1450 KKASSERT(ondisk->type == new_node->ondisk->type);
1453 * Cleanup the original node. P becomes the new boundary, its
1454 * subtree_offset was moved to the new node. If we had created
1455 * a new root its parent pointer may have changed.
1457 elm->internal.subtree_offset = 0;
1458 elm->internal.rec_offset = 0;
1459 ondisk->count = split;
1462 * Insert the separator into the parent, fixup the parent's
1463 * reference to the original node, and reference the new node.
1464 * The separator is P.
1466 * Remember that base.count does not include the right-hand boundary.
1468 hammer_modify_node(parent);
1469 ondisk = parent->ondisk;
1470 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1471 ondisk->elms[parent_index].internal.subtree_count = split;
1472 parent_elm = &ondisk->elms[parent_index+1];
1473 bcopy(parent_elm, parent_elm + 1,
1474 (ondisk->count - parent_index) * esize);
1475 parent_elm->internal.base = elm->base; /* separator P */
1476 parent_elm->internal.base.subtree_type = new_node->ondisk->type;
1477 parent_elm->internal.subtree_offset = new_node->node_offset;
1478 parent_elm->internal.subtree_count = new_node->ondisk->count;
1479 parent_elm->internal.subtree_vol_no = 0;
1480 parent_elm->internal.rec_offset = 0;
1484 * The children of new_node need their parent pointer set to new_node.
1486 for (i = 0; i < new_node->ondisk->count; ++i) {
1487 elm = &new_node->ondisk->elms[i];
1488 error = btree_set_parent(new_node, elm);
1490 panic("btree_split_internal: btree-fixup problem");
1495 * The cluster's root pointer may have to be updated.
1498 hammer_modify_cluster(node->cluster);
1499 node->cluster->ondisk->clu_btree_root = parent->node_offset;
1500 node->ondisk->parent = parent->node_offset;
1501 if (cursor->parent) {
1502 hammer_unlock(&cursor->parent->lock);
1503 hammer_rel_node(cursor->parent);
1505 cursor->parent = parent; /* lock'd and ref'd */
1510 * Ok, now adjust the cursor depending on which element the original
1511 * index was pointing at. If we are >= the split point the push node
1512 * is now in the new node.
1514 * NOTE: If we are at the split point itself we cannot stay with the
1515 * original node because the push index will point at the right-hand
1516 * boundary, which is illegal.
1518 * NOTE: The cursor's parent or parent_index must be adjusted for
1519 * the case where a new parent (new root) was created, and the case
1520 * where the cursor is now pointing at the split node.
1522 if (cursor->index >= split) {
1523 cursor->parent_index = parent_index + 1;
1524 cursor->index -= split;
1525 hammer_unlock(&cursor->node->lock);
1526 hammer_rel_node(cursor->node);
1527 cursor->node = new_node; /* locked and ref'd */
1529 cursor->parent_index = parent_index;
1530 hammer_unlock(&new_node->lock);
1531 hammer_rel_node(new_node);
1535 * Fixup left and right bounds
1537 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1538 cursor->left_bound = &parent_elm[0].internal.base;
1539 cursor->right_bound = &parent_elm[1].internal.base;
1540 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1541 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1542 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1543 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1549 * Same as the above, but splits a full leaf node.
1553 btree_split_leaf(hammer_cursor_t cursor)
1555 hammer_node_ondisk_t ondisk;
1556 hammer_node_t parent;
1558 hammer_node_t new_leaf;
1559 hammer_btree_elm_t elm;
1560 hammer_btree_elm_t parent_elm;
1561 hammer_base_elm_t mid_boundary;
1566 const size_t esize = sizeof(*elm);
1569 * Calculate the split point. If the insertion point will be on
1570 * the left-hand side adjust the split point to give the right
1571 * hand side one additional node.
1573 leaf = cursor->node;
1574 ondisk = leaf->ondisk;
1575 split = (ondisk->count + 1) / 2;
1576 if (cursor->index <= split)
1581 * If we are at the root of the tree, create a new root node with
1582 * 1 element and split normally. Avoid making major modifications
1583 * until we know the whole operation will work.
1585 if (ondisk->parent == 0) {
1586 parent = hammer_alloc_btree(leaf->cluster, &error);
1589 hammer_lock_ex(&parent->lock);
1590 hammer_modify_node(parent);
1591 ondisk = parent->ondisk;
1594 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1595 ondisk->elms[0].base = leaf->cluster->clu_btree_beg;
1596 ondisk->elms[0].base.subtree_type = leaf->ondisk->type;
1597 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1598 ondisk->elms[1].base = leaf->cluster->clu_btree_end;
1599 /* ondisk->elms[1].base.subtree_type = not used */
1601 parent_index = 0; /* insertion point in parent */
1604 parent = cursor->parent;
1605 parent_index = cursor->parent_index;
1606 KKASSERT(parent->cluster == leaf->cluster);
1610 * Split leaf into new_leaf at the split point. Select a separator
1611 * value in-between the two leafs but with a bent towards the right
1612 * leaf since comparisons use an 'elm >= separator' inequality.
1621 new_leaf = hammer_alloc_btree(leaf->cluster, &error);
1622 if (new_leaf == NULL) {
1624 hammer_unlock(&parent->lock);
1625 parent->flags |= HAMMER_NODE_DELETED;
1626 hammer_rel_node(parent);
1630 hammer_lock_ex(&new_leaf->lock);
1633 * Create the new node. P become the left-hand boundary in the
1634 * new node. Copy the right-hand boundary as well.
1636 hammer_modify_node(leaf);
1637 hammer_modify_node(new_leaf);
1638 ondisk = leaf->ondisk;
1639 elm = &ondisk->elms[split];
1640 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1641 new_leaf->ondisk->count = ondisk->count - split;
1642 new_leaf->ondisk->parent = parent->node_offset;
1643 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1644 KKASSERT(ondisk->type == new_leaf->ondisk->type);
1647 * Cleanup the original node. Because this is a leaf node and
1648 * leaf nodes do not have a right-hand boundary, there
1649 * aren't any special edge cases to clean up. We just fixup the
1652 ondisk->count = split;
1655 * Insert the separator into the parent, fixup the parent's
1656 * reference to the original node, and reference the new node.
1657 * The separator is P.
1659 * Remember that base.count does not include the right-hand boundary.
1660 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1662 hammer_modify_node(parent);
1663 ondisk = parent->ondisk;
1664 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1665 ondisk->elms[parent_index].internal.subtree_count = split;
1666 parent_elm = &ondisk->elms[parent_index+1];
1667 bcopy(parent_elm, parent_elm + 1,
1668 (ondisk->count - parent_index) * esize);
1669 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1670 parent_elm->internal.base.subtree_type = new_leaf->ondisk->type;
1671 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1672 parent_elm->internal.subtree_count = new_leaf->ondisk->count;
1673 parent_elm->internal.subtree_vol_no = 0;
1674 parent_elm->internal.rec_offset = 0;
1675 mid_boundary = &parent_elm->base;
1679 * The cluster's root pointer may have to be updated.
1682 hammer_modify_cluster(leaf->cluster);
1683 leaf->cluster->ondisk->clu_btree_root = parent->node_offset;
1684 leaf->ondisk->parent = parent->node_offset;
1685 if (cursor->parent) {
1686 hammer_unlock(&cursor->parent->lock);
1687 hammer_rel_node(cursor->parent);
1689 cursor->parent = parent; /* lock'd and ref'd */
1693 * Ok, now adjust the cursor depending on which element the original
1694 * index was pointing at. If we are >= the split point the push node
1695 * is now in the new node.
1697 * NOTE: If we are at the split point itself we need to select the
1698 * old or new node based on where key_beg's insertion point will be.
1699 * If we pick the wrong side the inserted element will wind up in
1700 * the wrong leaf node and outside that node's bounds.
1702 if (cursor->index > split ||
1703 (cursor->index == split &&
1704 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1705 cursor->parent_index = parent_index + 1;
1706 cursor->index -= split;
1707 hammer_unlock(&cursor->node->lock);
1708 hammer_rel_node(cursor->node);
1709 cursor->node = new_leaf;
1711 cursor->parent_index = parent_index;
1712 hammer_unlock(&new_leaf->lock);
1713 hammer_rel_node(new_leaf);
1717 * Fixup left and right bounds
1719 parent_elm = &parent->ondisk->elms[cursor->parent_index];
1720 cursor->left_bound = &parent_elm[0].internal.base;
1721 cursor->right_bound = &parent_elm[1].internal.base;
1722 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1723 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1724 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1725 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1731 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1732 * on success, EAGAIN if we could not acquire the necessary locks, or some
1735 * On return the cursor may end up pointing at an internal node, suitable
1736 * for further iteration but not for an immediate insertion or deletion.
1738 * cursor->node may be an internal node or a leaf node.
1740 * NOTE: If cursor->node has one element it is the parent trying to delete
1741 * that element, make sure cursor->index is properly adjusted on success.
1744 btree_remove(hammer_cursor_t cursor)
1746 hammer_node_ondisk_t ondisk;
1747 hammer_btree_elm_t elm;
1750 hammer_node_t parent;
1755 * If we are at the root of the root cluster there is nothing to
1756 * remove, but an internal node at the root of a cluster is not
1757 * allowed to be empty so convert it to a leaf node.
1759 if (cursor->parent == NULL) {
1760 hammer_modify_node(cursor->node);
1761 ondisk = cursor->node->ondisk;
1762 KKASSERT(ondisk->parent == 0);
1763 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1766 kprintf("EMPTY ROOT OF ROOT CLUSTER -> LEAF\n");
1771 * Retain a reference to cursor->node, ex-lock again (2 locks now)
1772 * so we do not lose the lock when we cursor around.
1774 save = cursor->node;
1775 hammer_ref_node(save);
1776 hammer_lock_ex(&save->lock);
1779 * We need to be able to lock the parent of the parent. Do this
1780 * non-blocking and return EAGAIN if the lock cannot be acquired.
1781 * non-blocking is required in order to avoid a deadlock.
1783 * After we cursor up, parent is moved to node and the new parent
1784 * is the parent of the parent.
1786 error = hammer_cursor_up(cursor, 1);
1788 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
1793 * At this point we want to remove the element at (node, index),
1794 * which is now the (original) parent pointing to the saved node.
1795 * Removing the element allows us to then free the node it was
1798 * However, an internal node is not allowed to have 0 elements, so
1799 * if the count would drop to 0 we have to recurse. It is possible
1800 * for the recursion to fail.
1802 * NOTE: The cursor is in an indeterminant position after recursing,
1803 * but will still be suitable for an iteration.
1805 node = cursor->node;
1806 KKASSERT(node->ondisk->count > 0);
1807 if (node->ondisk->count == 1) {
1808 error = btree_remove(cursor);
1810 /*kprintf("BTREE_REMOVE: Successful!\n");*/
1813 kprintf("BTREE_REMOVE: Recursion failed %d\n", error);
1819 * Remove the element at (node, index) and adjust the parent's
1822 * NOTE! If removing element 0 an internal node's left-hand boundary
1823 * will no longer match its parent. If removing a mid-element the
1824 * boundary will no longer match a child's left hand or right hand
1827 * BxBxBxB remove a (x[0]): internal node's left-hand
1828 * | | | boundary no longer matches
1831 * remove b (x[1]): a's right hand boundary no
1832 * longer matches parent.
1834 * remove c (x[2]): b's right hand boundary no
1835 * longer matches parent.
1837 * These cases are corrected in btree_search().
1840 kprintf("BTREE_REMOVE: Removing element %d\n", cursor->index);
1842 KKASSERT(node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1843 KKASSERT(cursor->index < node->ondisk->count);
1844 hammer_modify_node(node);
1845 ondisk = node->ondisk;
1849 * WARNING: For historical lookups to work properly we cannot
1850 * recalculate the mid-point or we might blow up historical searches
1851 * which depend on the mid-point matching the first right-hand element
1854 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
1855 (ondisk->count - i) * sizeof(ondisk->elms[0]));
1859 * Adjust the parent-parent's (now parent) reference to the parent
1862 if ((parent = cursor->parent) != NULL) {
1863 elm = &parent->ondisk->elms[cursor->parent_index];
1864 if (elm->internal.subtree_count != ondisk->count) {
1865 hammer_modify_node(parent);
1866 elm->internal.subtree_count = ondisk->count;
1868 if (elm->base.subtree_type != HAMMER_BTREE_TYPE_CLUSTER &&
1869 elm->base.subtree_type != ondisk->type) {
1870 hammer_modify_node(parent);
1871 elm->base.subtree_type = ondisk->type;
1877 * Free the saved node. If the saved node was the root of a
1878 * cluster, free the entire cluster.
1880 hammer_flush_node(save);
1881 save->flags |= HAMMER_NODE_DELETED;
1885 hammer_unlock(&save->lock);
1886 hammer_rel_node(save);
1891 * The child represented by the element in internal node node needs
1892 * to have its parent pointer adjusted.
1896 btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm)
1898 hammer_volume_t volume;
1899 hammer_cluster_t cluster;
1900 hammer_node_t child;
1905 switch(elm->internal.base.subtree_type) {
1906 case HAMMER_BTREE_TYPE_LEAF:
1907 case HAMMER_BTREE_TYPE_INTERNAL:
1908 child = hammer_get_node(node->cluster,
1909 elm->internal.subtree_offset, &error);
1911 hammer_modify_node(child);
1912 hammer_lock_ex(&child->lock);
1913 child->ondisk->parent = node->node_offset;
1914 hammer_unlock(&child->lock);
1915 hammer_rel_node(child);
1918 case HAMMER_BTREE_TYPE_CLUSTER:
1919 volume = hammer_get_volume(node->cluster->volume->hmp,
1920 elm->internal.subtree_vol_no, &error);
1923 cluster = hammer_get_cluster(volume,
1924 elm->internal.subtree_clu_no,
1926 hammer_rel_volume(volume, 0);
1929 hammer_modify_cluster(cluster);
1930 hammer_lock_ex(&cluster->io.lock);
1931 cluster->ondisk->clu_btree_parent_offset = node->node_offset;
1932 hammer_unlock(&cluster->io.lock);
1933 KKASSERT(cluster->ondisk->clu_btree_parent_clu_no ==
1934 node->cluster->clu_no);
1935 KKASSERT(cluster->ondisk->clu_btree_parent_vol_no ==
1936 node->cluster->volume->vol_no);
1937 hammer_rel_cluster(cluster, 0);
1940 hammer_print_btree_elm(elm, HAMMER_BTREE_TYPE_INTERNAL, -1);
1941 panic("btree_set_parent: bad subtree_type");
1942 break; /* NOT REACHED */
1947 /************************************************************************
1948 * MISCELLANIOUS SUPPORT *
1949 ************************************************************************/
1952 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
1954 * Note that for this particular function a return value of -1, 0, or +1
1955 * can denote a match if create_tid is otherwise discounted.
1957 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
1960 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
1962 if (key1->obj_id < key2->obj_id)
1964 if (key1->obj_id > key2->obj_id)
1967 if (key1->rec_type < key2->rec_type)
1969 if (key1->rec_type > key2->rec_type)
1972 if (key1->key < key2->key)
1974 if (key1->key > key2->key)
1977 if (key1->create_tid < key2->create_tid)
1979 if (key1->create_tid > key2->create_tid)
1985 * Test a non-zero timestamp against an element to determine whether the
1986 * element is visible.
1989 hammer_btree_chkts(hammer_tid_t create_tid, hammer_base_elm_t base)
1991 if (create_tid < base->create_tid)
1993 if (base->delete_tid && create_tid >= base->delete_tid)
1999 * Create a separator half way inbetween key1 and key2. For fields just
2000 * one unit apart, the separator will match key2.
2002 * At the moment require that the separator never match key2 exactly.
2004 * We have to special case the separator between two historical keys,
2005 * where all elements except create_tid match. In this case our B-Tree
2006 * searches can't figure out which branch of an internal node to go down
2007 * unless the mid point's create_tid is exactly key2.
2008 * (see btree_search()'s scan code on HAMMER_BTREE_TYPE_INTERNAL).
2010 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2011 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2014 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2015 hammer_base_elm_t dest)
2017 bzero(dest, sizeof(*dest));
2018 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2019 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2020 MAKE_SEPARATOR(key1, key2, dest, key);
2021 if (key1->obj_id == key2->obj_id &&
2022 key1->rec_type == key2->rec_type &&
2023 key1->key == key2->key) {
2024 dest->create_tid = key2->create_tid;
2026 dest->create_tid = 0;
2030 #undef MAKE_SEPARATOR
2034 * Return whether a generic internal or leaf node is full
2037 btree_node_is_full(hammer_node_ondisk_t node)
2039 switch(node->type) {
2040 case HAMMER_BTREE_TYPE_INTERNAL:
2041 if (node->count == HAMMER_BTREE_INT_ELMS)
2044 case HAMMER_BTREE_TYPE_LEAF:
2045 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2049 panic("illegal btree subtype");
2056 * Return whether a generic internal or leaf node is almost full. This
2057 * routine is used as a helper for search insertions to guarentee at
2058 * least 2 available slots in the internal node(s) leading up to a leaf,
2059 * so hammer_btree_insert_cluster() will function properly.
2062 btree_node_is_almost_full(hammer_node_ondisk_t node)
2064 switch(node->type) {
2065 case HAMMER_BTREE_TYPE_INTERNAL:
2066 if (node->count > HAMMER_BTREE_INT_ELMS - 2)
2069 case HAMMER_BTREE_TYPE_LEAF:
2070 if (node->count > HAMMER_BTREE_LEAF_ELMS - 2)
2074 panic("illegal btree subtype");
2081 btree_max_elements(u_int8_t type)
2083 if (type == HAMMER_BTREE_TYPE_LEAF)
2084 return(HAMMER_BTREE_LEAF_ELMS);
2085 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2086 return(HAMMER_BTREE_INT_ELMS);
2087 panic("btree_max_elements: bad type %d\n", type);
2092 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2094 hammer_btree_elm_t elm;
2097 kprintf("node %p count=%d parent=%d type=%c\n",
2098 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2101 * Dump both boundary elements if an internal node
2103 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2104 for (i = 0; i <= ondisk->count; ++i) {
2105 elm = &ondisk->elms[i];
2106 hammer_print_btree_elm(elm, ondisk->type, i);
2109 for (i = 0; i < ondisk->count; ++i) {
2110 elm = &ondisk->elms[i];
2111 hammer_print_btree_elm(elm, ondisk->type, i);
2117 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2120 kprintf("\tobjid = %016llx\n", elm->base.obj_id);
2121 kprintf("\tkey = %016llx\n", elm->base.key);
2122 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2123 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2124 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2125 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
2126 kprintf("\tsubtree_type = %02x\n", elm->base.subtree_type);
2128 if (type == HAMMER_BTREE_TYPE_INTERNAL) {
2129 if (elm->internal.rec_offset) {
2130 kprintf("\tcluster_rec = %08x\n",
2131 elm->internal.rec_offset);
2132 kprintf("\tcluster_id = %08x\n",
2133 elm->internal.subtree_clu_no);
2134 kprintf("\tvolno = %08x\n",
2135 elm->internal.subtree_vol_no);
2137 kprintf("\tsubtree_off = %08x\n",
2138 elm->internal.subtree_offset);
2140 kprintf("\tsubtree_count= %d\n", elm->internal.subtree_count);
2142 kprintf("\trec_offset = %08x\n", elm->leaf.rec_offset);
2143 kprintf("\tdata_offset = %08x\n", elm->leaf.data_offset);
2144 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2145 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);