HAMMER utilities:
[dragonfly.git] / sys / vfs / hammer / hammer_btree.c
CommitLineData
427e5fc6
MD
1/*
2 * Copyright (c) 2007 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:
10 *
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.
20 *
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.
33 *
d5530d22 34 * $DragonFly: src/sys/vfs/hammer/hammer_btree.c,v 1.19 2008/01/16 01:15:36 dillon Exp $
427e5fc6
MD
35 */
36
37/*
8cd0a023 38 * HAMMER B-Tree index
427e5fc6
MD
39 *
40 * HAMMER implements a modified B+Tree. In documentation this will
9944ae54 41 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
427e5fc6
MD
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
8cd0a023 45 * otherwords, we have boundary elements at the two ends of a B-Tree node
427e5fc6
MD
46 * instead of sub-tree pointers.
47 *
8cd0a023 48 * A B-Tree internal node looks like this:
427e5fc6
MD
49 *
50 * B N N N N N N B <-- boundary and internal elements
51 * S S S S S S S <-- subtree pointers
52 *
8cd0a023 53 * A B-Tree leaf node basically looks like this:
427e5fc6
MD
54 *
55 * L L L L L L L L <-- leaf elemenets
56 *
8cd0a023
MD
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.
427e5fc6 59 *
8cd0a023
MD
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.
427e5fc6 67 *
8cd0a023
MD
68 * B-Trees also make the stacking of trees fairly straightforward.
69 *
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.
77 *
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
85 * lock.
86 */
87#include "hammer.h"
88#include <sys/buf.h>
89#include <sys/buf2.h>
66325755 90
8cd0a023
MD
91static int btree_search(hammer_cursor_t cursor, int flags);
92static int btree_split_internal(hammer_cursor_t cursor);
93static int btree_split_leaf(hammer_cursor_t cursor);
195c19a1 94static int btree_remove(hammer_cursor_t cursor);
7f7c1f84 95static int btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm);
8cd0a023
MD
96#if 0
97static int btree_rebalance(hammer_cursor_t cursor);
98static int btree_collapse(hammer_cursor_t cursor);
99#endif
9944ae54 100static int btree_node_is_almost_full(hammer_node_ondisk_t node);
8cd0a023
MD
101static void hammer_make_separator(hammer_base_elm_t key1,
102 hammer_base_elm_t key2, hammer_base_elm_t dest);
66325755
MD
103
104/*
8cd0a023
MD
105 * Iterate records after a search. The cursor is iterated forwards past
106 * the current record until a record matching the key-range requirements
107 * is found. ENOENT is returned if the iteration goes past the ending
108 * key.
66325755 109 *
d26d0ae9
MD
110 * The iteration is inclusive of key_beg and can be inclusive or exclusive
111 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
66325755 112 *
d5530d22
MD
113 * When doing an as-of search (cursor->asof != 0), key_beg.delete_tid
114 * may be modified by B-Tree functions.
115 *
8cd0a023 116 * cursor->key_beg may or may not be modified by this function during
d26d0ae9
MD
117 * the iteration. XXX future - in case of an inverted lock we may have
118 * to reinitiate the lookup and set key_beg to properly pick up where we
119 * left off.
66325755
MD
120 */
121int
8cd0a023 122hammer_btree_iterate(hammer_cursor_t cursor)
66325755 123{
8cd0a023
MD
124 hammer_node_ondisk_t node;
125 hammer_btree_elm_t elm;
66325755
MD
126 int error;
127 int r;
128 int s;
129
130 /*
8cd0a023 131 * Skip past the current record
66325755 132 */
8cd0a023 133 node = cursor->node->ondisk;
a89aec1b
MD
134 if (node == NULL)
135 return(ENOENT);
c0ade690
MD
136 if (cursor->index < node->count &&
137 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
66325755 138 ++cursor->index;
c0ade690 139 }
66325755 140
8cd0a023
MD
141 /*
142 * Loop until an element is found or we are done.
143 */
66325755
MD
144 for (;;) {
145 /*
8cd0a023
MD
146 * We iterate up the tree and then index over one element
147 * while we are at the last element in the current node.
148 *
149 * NOTE: This can pop us up to another cluster.
66325755 150 *
8cd0a023
MD
151 * If we are at the root of the root cluster, cursor_up
152 * returns ENOENT.
153 *
154 * NOTE: hammer_cursor_up() will adjust cursor->key_beg
155 * when told to re-search for the cluster tag.
66325755
MD
156 *
157 * XXX this could be optimized by storing the information in
158 * the parent reference.
195c19a1
MD
159 *
160 * XXX we can lose the node lock temporarily, this could mess
161 * up our scan.
66325755 162 */
8cd0a023 163 if (cursor->index == node->count) {
195c19a1 164 error = hammer_cursor_up(cursor, 0);
8cd0a023
MD
165 if (error)
166 break;
167 node = cursor->node->ondisk;
168 KKASSERT(cursor->index != node->count);
169 ++cursor->index;
170 continue;
66325755
MD
171 }
172
173 /*
d26d0ae9
MD
174 * Check internal or leaf element. Determine if the record
175 * at the cursor has gone beyond the end of our range.
66325755 176 *
d26d0ae9
MD
177 * Generally we recurse down through internal nodes. An
178 * internal node can only be returned if INCLUSTER is set
d5530d22 179 * and the node represents a cluster-push record.
66325755 180 */
8cd0a023
MD
181 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
182 elm = &node->elms[cursor->index];
d26d0ae9
MD
183 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
184 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
b3deaf57
MD
185 if (hammer_debug_btree) {
186 kprintf("BRACKETL %p:%d %016llx %02x %016llx %d\n",
187 cursor->node, cursor->index,
188 elm[0].internal.base.obj_id,
189 elm[0].internal.base.rec_type,
190 elm[0].internal.base.key,
191 r
192 );
193 kprintf("BRACKETR %p:%d %016llx %02x %016llx %d\n",
194 cursor->node, cursor->index + 1,
195 elm[1].internal.base.obj_id,
196 elm[1].internal.base.rec_type,
197 elm[1].internal.base.key,
198 s
199 );
200 }
201
d26d0ae9
MD
202 if (r < 0) {
203 error = ENOENT;
204 break;
66325755 205 }
d26d0ae9
MD
206 if (r == 0 && (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
207 error = ENOENT;
8cd0a023 208 break;
d26d0ae9
MD
209 }
210 KKASSERT(s <= 0);
211 if ((cursor->flags & HAMMER_CURSOR_INCLUSTER) == 0 ||
212 elm->internal.rec_offset == 0) {
213 error = hammer_cursor_down(cursor);
214 if (error)
215 break;
216 KKASSERT(cursor->index == 0);
217 node = cursor->node->ondisk;
218 continue;
219 }
220 } else {
221 elm = &node->elms[cursor->index];
222 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
b3deaf57
MD
223 if (hammer_debug_btree) {
224 kprintf("ELEMENT %p:%d %016llx %02x %016llx %d\n",
225 cursor->node, cursor->index,
226 elm[0].leaf.base.obj_id,
227 elm[0].leaf.base.rec_type,
228 elm[0].leaf.base.key,
229 r
230 );
231 }
d26d0ae9
MD
232 if (r < 0) {
233 error = ENOENT;
234 break;
235 }
236 if (r == 0 && (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
237 error = ENOENT;
238 break;
239 }
240 if ((cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0 &&
d5530d22 241 hammer_btree_chkts(cursor->asof, &elm->base) != 0) {
d26d0ae9
MD
242 ++cursor->index;
243 continue;
244 }
66325755
MD
245 }
246
247 /*
d26d0ae9 248 * Return entry
66325755 249 */
b3deaf57
MD
250 if (hammer_debug_btree) {
251 int i = cursor->index;
252 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
253 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
254 cursor->node, i,
255 elm->internal.base.obj_id,
256 elm->internal.base.rec_type,
257 elm->internal.base.key
258 );
259 }
d26d0ae9 260 return(0);
427e5fc6 261 }
66325755 262 return(error);
427e5fc6
MD
263}
264
265/*
8cd0a023
MD
266 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
267 * could not be found, and a fatal error otherwise.
268 *
269 * The cursor is suitably positioned for a deletion on success, and suitably
270 * positioned for an insertion on ENOENT.
427e5fc6 271 *
8cd0a023
MD
272 * The cursor may begin anywhere, the search will traverse clusters in
273 * either direction to locate the requested element.
427e5fc6
MD
274 */
275int
8cd0a023 276hammer_btree_lookup(hammer_cursor_t cursor)
427e5fc6 277{
66325755
MD
278 int error;
279
d5530d22
MD
280 if (cursor->flags & HAMMER_CURSOR_ASOF) {
281 cursor->key_beg.delete_tid = cursor->asof;
282 do {
283 error = btree_search(cursor, 0);
284 } while (error == EAGAIN);
285 } else {
286 error = btree_search(cursor, 0);
287 }
8cd0a023
MD
288 if (error == 0 && cursor->flags)
289 error = hammer_btree_extract(cursor, cursor->flags);
66325755
MD
290 return(error);
291}
292
d26d0ae9
MD
293/*
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.
297 */
298int
299hammer_btree_first(hammer_cursor_t cursor)
300{
301 int error;
302
303 error = hammer_btree_lookup(cursor);
304 if (error == ENOENT) {
305 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
306 error = hammer_btree_iterate(cursor);
307 }
308 cursor->flags |= HAMMER_CURSOR_ATEDISK;
309 return(error);
310}
311
8cd0a023
MD
312/*
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.
316 *
d26d0ae9
MD
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.
8cd0a023 320 */
66325755 321int
8cd0a023 322hammer_btree_extract(hammer_cursor_t cursor, int flags)
66325755 323{
8cd0a023
MD
324 hammer_node_ondisk_t node;
325 hammer_btree_elm_t elm;
326 hammer_cluster_t cluster;
c0ade690 327 u_int64_t buf_type;
427e5fc6 328 int32_t cloff;
d26d0ae9 329 int32_t roff;
427e5fc6 330 int error;
427e5fc6 331
8cd0a023 332 /*
427e5fc6 333 * A cluster record type has no data reference, the information
8cd0a023 334 * is stored directly in the record and B-Tree element.
427e5fc6
MD
335 *
336 * The case where the data reference resolves to the same buffer
337 * as the record reference must be handled.
338 */
8cd0a023 339 node = cursor->node->ondisk;
8cd0a023
MD
340 elm = &node->elms[cursor->index];
341 cluster = cursor->node->cluster;
d26d0ae9
MD
342 cursor->flags &= ~HAMMER_CURSOR_DATA_EMBEDDED;
343 cursor->data = NULL;
66325755
MD
344 error = 0;
345
d26d0ae9
MD
346 /*
347 * Internal elements can only be cluster pushes. A cluster push has
348 * no data reference.
349 */
350 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
9944ae54 351 cloff = elm->internal.rec_offset;
d26d0ae9
MD
352 KKASSERT(cloff != 0);
353 cursor->record = hammer_bread(cluster, cloff,
354 HAMMER_FSBUF_RECORDS, &error,
355 &cursor->record_buffer);
356 return(error);
357 }
358
359 /*
360 * Leaf element.
361 */
a89aec1b 362 if ((flags & HAMMER_CURSOR_GET_RECORD) && error == 0) {
8cd0a023
MD
363 cloff = elm->leaf.rec_offset;
364 cursor->record = hammer_bread(cluster, cloff,
365 HAMMER_FSBUF_RECORDS, &error,
366 &cursor->record_buffer);
427e5fc6
MD
367 } else {
368 cloff = 0;
369 }
a89aec1b 370 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
8cd0a023
MD
371 if ((cloff ^ elm->leaf.data_offset) & ~HAMMER_BUFMASK) {
372 /*
c0ade690
MD
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.
8cd0a023 377 */
c0ade690
MD
378 if ((elm->leaf.rec_offset ^ elm->leaf.data_offset) &
379 ~HAMMER_BUFMASK) {
380 if (elm->leaf.data_len & HAMMER_BUFMASK)
381 buf_type = HAMMER_FSBUF_DATA;
382 else
383 buf_type = 0; /* pure data buffer */
384 } else {
385 buf_type = HAMMER_FSBUF_RECORDS;
386 }
8cd0a023
MD
387 cursor->data = hammer_bread(cluster,
388 elm->leaf.data_offset,
c0ade690 389 buf_type, &error,
8cd0a023 390 &cursor->data_buffer);
427e5fc6 391 } else {
8cd0a023
MD
392 /*
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
397 * go back to it.
c0ade690 398 *
d26d0ae9
MD
399 * The data must be embedded in the record for this
400 * case to be hit.
401 *
c0ade690 402 * Just assume the buffer type is correct.
8cd0a023
MD
403 */
404 cursor->data = (void *)
405 ((char *)cursor->record_buffer->ondisk +
406 (elm->leaf.data_offset & HAMMER_BUFMASK));
d26d0ae9
MD
407 roff = (char *)cursor->data - (char *)cursor->record;
408 KKASSERT (roff >= 0 && roff < HAMMER_RECORD_SIZE);
409 cursor->flags |= HAMMER_CURSOR_DATA_EMBEDDED;
427e5fc6
MD
410 }
411 }
412 return(error);
413}
414
415
416/*
8cd0a023
MD
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.
420 *
a89aec1b 421 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
8cd0a023
MD
422 * flag set and that call must return ENOENT before this function can be
423 * called.
424 *
425 * ENOSPC is returned if there is no room to insert a new record.
427e5fc6
MD
426 */
427int
8cd0a023 428hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
427e5fc6 429{
8cd0a023
MD
430 hammer_node_ondisk_t parent;
431 hammer_node_ondisk_t node;
427e5fc6
MD
432 int i;
433
427e5fc6
MD
434 /*
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
8cd0a023 437 * the root of the B-Tree in the cluster is a leaf. It is also
427e5fc6
MD
438 * possible for the leaf to be empty.
439 *
440 * Remember that the right-hand boundary is not included in the
441 * count.
442 */
0b075555 443 hammer_modify_node(cursor->node);
8cd0a023 444 node = cursor->node->ondisk;
427e5fc6 445 i = cursor->index;
8cd0a023
MD
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));
451 }
452 node->elms[i] = *elm;
453 ++node->count;
427e5fc6 454
b3deaf57
MD
455 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
456 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
457 if (i)
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);
461
c0ade690
MD
462 /*
463 * Adjust the sub-tree count in the parent. note that the parent
464 * may be in a different cluster.
465 */
466 if (cursor->parent) {
0b075555 467 hammer_modify_node(cursor->parent);
c0ade690 468 parent = cursor->parent->ondisk;
427e5fc6 469 i = cursor->parent_index;
8cd0a023
MD
470 ++parent->elms[i].internal.subtree_count;
471 KKASSERT(parent->elms[i].internal.subtree_count <= node->count);
427e5fc6 472 }
427e5fc6
MD
473 return(0);
474}
475
9944ae54
MD
476/*
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.
479 *
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
482 * called.
483 *
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.
487 *
488 * ENOSPC is returned if there is no room to insert a new record.
489 */
490int
491hammer_btree_insert_cluster(hammer_cursor_t cursor, hammer_cluster_t ncluster,
492 int32_t rec_offset)
493{
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);
501 u_int8_t save;
502 int error = 0;
503 int pi, i;
504
505 kprintf("cursor %p ncluster %p\n", cursor, ncluster);
506 hammer_modify_node(cursor->node);
507 node = cursor->node->ondisk;
508 i = cursor->index;
509 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
510 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
511
512 /*
513 * Make sure the spike is legal or the B-Tree code will get really
514 * confused.
515 */
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);
523 }
524
525 /*
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
529 * modification.
530 */
531 ocluster = cursor->node->cluster;
532 if (cursor->parent == NULL) {
533 cursor->parent = hammer_alloc_btree(ocluster, &error);
534 if (error)
535 return(error);
536 hammer_lock_ex(&cursor->parent->lock);
537 hammer_modify_node(cursor->parent);
538 parent = cursor->parent->ondisk;
539 parent->count = 1;
540 parent->parent = 0;
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");
553 } else {
554 kprintf("has parent\n");
555 }
556
557
558 KKASSERT(cursor->parent->ondisk->count <= HAMMER_BTREE_INT_ELMS - 2);
559
560 hammer_modify_node(cursor->parent);
561 parent = cursor->parent->ondisk;
562 pi = cursor->parent_index;
563
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);
567
568 /*
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.
571 */
572 if (i != 0 && i != node->count) {
573 new_node = hammer_alloc_btree(cursor->node->cluster, &error);
574 if (error)
575 return(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;
582 node->count = i;
583 parent->elms[pi].internal.subtree_count = node->count;
584 } else {
585 new_node = NULL;
586 xnode = NULL;
587 }
588
589 /*
590 * Adjust the parent and set pi to point at the internal element
591 * which we intended to hold the spike.
592 */
593 if (new_node) {
594 /*
595 * Insert spike after parent index. Spike is at pi + 1.
596 * Also include room after the spike for new_node
597 */
598 ++pi;
599 bcopy(&parent->elms[pi], &parent->elms[pi+2],
600 (parent->count - pi + 1) * esize);
601 parent->count += 2;
602 } else if (i == 0) {
603 /*
604 * Insert spike before parent index. Spike is at pi.
605 *
606 * cursor->node's index in the parent (cursor->parent_index)
607 * has now shifted over by one.
608 */
609 bcopy(&parent->elms[pi], &parent->elms[pi+1],
610 (parent->count - pi + 1) * esize);
611 ++parent->count;
612 ++cursor->parent_index;
613 } else {
614 /*
615 * Insert spike after parent index. Spike is at pi + 1.
616 */
617 ++pi;
618 bcopy(&parent->elms[pi], &parent->elms[pi+1],
619 (parent->count - pi + 1) * esize);
620 ++parent->count;
621 }
622
623 /*
624 * Load the spike into the parent at (pi).
625 *
626 * WARNING: subtree_type is actually overloaded within base.
627 * WARNING: subtree_clu_no is overloaded on subtree_offset
628 */
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 */
636
637 /*
638 * Load the new node into parent at (pi+1) if non-NULL, and also
639 * set the right-hand boundary for the spike.
640 *
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.
643 *
644 * WARNING: subtree_type is actually overloaded within base.
645 * WARNING: subtree_clu_no is overloaded on subtree_offset
646 *
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.
650 */
651 if (new_node) {
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;
658 } else {
659 /*
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.
664 */
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;
668 }
669
670 /*
671 * The boundaries stored in the cursor for node are probably all
672 * messed up now, fix them.
673 */
674 cursor->left_bound = &parent->elms[cursor->parent_index].base;
675 cursor->right_bound = &parent->elms[cursor->parent_index+1].base;
676
677 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
678 &elm[1].internal.base) <= 0);
679
680
681 /*
682 * Adjust the target cluster's parent offset
683 */
684 hammer_modify_cluster(ncluster);
685 ncluster->ondisk->clu_btree_parent_offset = cursor->parent->node_offset;
686
687 if (new_node)
688 hammer_rel_node(new_node);
689
690 return(0);
691}
692
427e5fc6 693/*
8cd0a023
MD
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
696 * to be deleted.
697 *
195c19a1
MD
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.
8cd0a023 701 *
195c19a1
MD
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
705 * leaf).
427e5fc6
MD
706 */
707int
8cd0a023 708hammer_btree_delete(hammer_cursor_t cursor)
427e5fc6 709{
8cd0a023
MD
710 hammer_node_ondisk_t ondisk;
711 hammer_node_t node;
712 hammer_node_t parent;
713 hammer_btree_elm_t elm;
714 int error;
427e5fc6
MD
715 int i;
716
427e5fc6 717 /*
8cd0a023 718 * Delete the element from the leaf node.
427e5fc6 719 *
8cd0a023 720 * Remember that leaf nodes do not have boundaries.
427e5fc6 721 */
8cd0a023
MD
722 node = cursor->node;
723 ondisk = node->ondisk;
427e5fc6
MD
724 i = cursor->index;
725
8cd0a023 726 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
0b075555 727 hammer_modify_node(node);
8cd0a023
MD
728 if (i + 1 != ondisk->count) {
729 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
730 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
731 }
732 --ondisk->count;
733 if (cursor->parent != NULL) {
427e5fc6
MD
734 /*
735 * Adjust parent's notion of the leaf's count. subtree_count
8cd0a023 736 * is only approximate, it is allowed to be too small but
427e5fc6
MD
737 * never allowed to be too large. Make sure we don't drop
738 * the count below 0.
739 */
8cd0a023 740 parent = cursor->parent;
0b075555 741 hammer_modify_node(parent);
8cd0a023
MD
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);
427e5fc6 746 }
427e5fc6 747
8cd0a023 748 /*
195c19a1
MD
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.
8cd0a023 752 *
195c19a1
MD
753 * XXX rebalancing calls would go here too.
754 *
755 * This may reposition the cursor at one of the parent's of the
756 * current node.
8cd0a023 757 */
b3deaf57 758 KKASSERT(cursor->index <= ondisk->count);
8cd0a023 759 if (ondisk->count == 0) {
195c19a1
MD
760 error = btree_remove(cursor);
761 if (error == EAGAIN)
8cd0a023 762 error = 0;
8cd0a023 763 } else {
8cd0a023
MD
764 error = 0;
765 }
766 return(error);
767}
427e5fc6
MD
768
769/*
8cd0a023
MD
770 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
771 *
772 * Search a cluster's B-Tree for cursor->key_beg, return the matching node.
773 *
d26d0ae9
MD
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.
777 *
8cd0a023 778 * INSERTIONS: The search will split full nodes and leaves on its way down
d26d0ae9
MD
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.
427e5fc6 782 *
61aeeb33
MD
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.
787 *
d26d0ae9 788 * DELETIONS: The search will rebalance the tree on its way down. XXX
fbc6e32a
MD
789 *
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.
d26d0ae9
MD
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).
427e5fc6 795 */
8cd0a023 796static
427e5fc6 797int
8cd0a023 798btree_search(hammer_cursor_t cursor, int flags)
427e5fc6 799{
8cd0a023
MD
800 hammer_node_ondisk_t node;
801 hammer_cluster_t cluster;
61aeeb33 802 hammer_btree_elm_t elm;
8cd0a023 803 int error;
d26d0ae9 804 int enospc = 0;
8cd0a023
MD
805 int i;
806 int r;
807
808 flags |= cursor->flags;
809
b3deaf57 810 if (hammer_debug_btree) {
d5530d22 811 kprintf("SEARCH %p:%d %016llx %02x key=%016llx did=%016llx\n",
b3deaf57
MD
812 cursor->node, cursor->index,
813 cursor->key_beg.obj_id,
814 cursor->key_beg.rec_type,
d113fda1 815 cursor->key_beg.key,
d5530d22 816 cursor->key_beg.delete_tid
b3deaf57
MD
817 );
818 }
819
8cd0a023
MD
820 /*
821 * Move our cursor up the tree until we find a node whos range covers
822 * the key we are trying to locate. This may move us between
823 * clusters.
824 *
825 * The left bound is inclusive, the right bound is non-inclusive.
826 * It is ok to cursor up too far so when cursoring across a cluster
827 * boundary.
828 *
829 * First see if we can skip the whole cluster. hammer_cursor_up()
830 * handles both cases but this way we don't check the cluster
831 * bounds when going up the tree within a cluster.
d26d0ae9
MD
832 *
833 * NOTE: If INCLUSTER is set and we are at the root of the cluster,
834 * hammer_cursor_up() will return ENOENT.
8cd0a023
MD
835 */
836 cluster = cursor->node->cluster;
837 while (
838 hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_beg) < 0 ||
839 hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_end) >= 0) {
840 error = hammer_cursor_toroot(cursor);
841 if (error)
842 goto done;
9944ae54 843 KKASSERT(cursor->parent);
195c19a1 844 error = hammer_cursor_up(cursor, 0);
8cd0a023
MD
845 if (error)
846 goto done;
847 cluster = cursor->node->cluster;
427e5fc6
MD
848 }
849
850 /*
8cd0a023
MD
851 * Deal with normal cursoring within a cluster. The right bound
852 * is non-inclusive. That is, the bounds form a separator.
427e5fc6 853 */
8cd0a023
MD
854 while (hammer_btree_cmp(&cursor->key_beg, cursor->left_bound) < 0 ||
855 hammer_btree_cmp(&cursor->key_beg, cursor->right_bound) >= 0) {
9944ae54 856 KKASSERT(cursor->parent);
195c19a1 857 error = hammer_cursor_up(cursor, 0);
8cd0a023
MD
858 if (error)
859 goto done;
427e5fc6 860 }
427e5fc6 861
8cd0a023
MD
862 /*
863 * We better have ended up with a node somewhere, and our second
864 * while loop had better not have traversed up a cluster.
865 */
866 KKASSERT(cursor->node != NULL && cursor->node->cluster == cluster);
867
868 /*
869 * If we are inserting we can't start at a full node if the parent
870 * is also full (because there is no way to split the node),
871 * continue running up the tree until we hit the root of the
872 * root cluster or until the requirement is satisfied.
873 *
874 * NOTE: These cursor-up's CAN continue to cross cluster boundaries.
875 *
9944ae54
MD
876 * NOTE: We must guarantee at least two open spots in the parent
877 * to deal with hammer_btree_insert_cluster().
878 *
8cd0a023
MD
879 * XXX as an optimization it should be possible to unbalance the tree
880 * and stop at the root of the current cluster.
881 */
61aeeb33 882 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
9944ae54 883 if (btree_node_is_almost_full(cursor->node->ondisk) == 0)
8cd0a023
MD
884 break;
885 if (cursor->parent == NULL)
886 break;
887 if (cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS)
888 break;
195c19a1 889 error = hammer_cursor_up(cursor, 0);
8cd0a023
MD
890 /* cluster and node are now may become stale */
891 if (error)
892 goto done;
427e5fc6 893 }
8cd0a023 894 /* cluster = cursor->node->cluster; not needed until next cluster = */
427e5fc6 895
8cd0a023
MD
896#if 0
897 /*
898 * If we are deleting we can't start at an internal node with only
899 * one element unless it is root, because all of our code assumes
900 * that internal nodes will never be empty. Just do this generally
901 * for both leaf and internal nodes to get better balance.
902 *
903 * This handles the case where the cursor is sitting at a leaf and
904 * either the leaf or parent contain an insufficient number of
905 * elements.
906 *
907 * NOTE: These cursor-up's CAN continue to cross cluster boundaries.
a89aec1b
MD
908 *
909 * XXX NOTE: Iterations may not set this flag anyway.
8cd0a023 910 */
a89aec1b 911 while (flags & HAMMER_CURSOR_DELETE) {
8cd0a023
MD
912 if (cursor->node->ondisk->count > 1)
913 break;
914 if (cursor->parent == NULL)
915 break;
916 KKASSERT(cursor->node->ondisk->count != 0);
195c19a1 917 error = hammer_cursor_up(cursor, 0);
8cd0a023
MD
918 /* cluster and node are now may become stale */
919 if (error)
920 goto done;
921 }
922#endif
427e5fc6 923
8cd0a023
MD
924/*new_cluster:*/
925 /*
926 * Push down through internal nodes to locate the requested key.
927 */
928 cluster = cursor->node->cluster;
929 node = cursor->node->ondisk;
930 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
931#if 0
427e5fc6 932 /*
8cd0a023
MD
933 * If we are a the root node and deleting, try to collapse
934 * all of the root's children into the root. This is the
935 * only point where tree depth is reduced.
a89aec1b
MD
936 *
937 * XXX NOTE: Iterations may not set this flag anyway.
427e5fc6 938 */
a89aec1b 939 if ((flags & HAMMER_CURSOR_DELETE) && cursor->parent == NULL) {
8cd0a023
MD
940 error = btree_collapse(cursor);
941 /* node becomes stale after call */
d26d0ae9 942 /* XXX ENOSPC */
8cd0a023
MD
943 if (error)
944 goto done;
66325755 945 }
8cd0a023
MD
946 node = cursor->node->ondisk;
947#endif
8cd0a023
MD
948 /*
949 * Scan the node to find the subtree index to push down into.
fbc6e32a 950 * We go one-past, then back-up.
d113fda1 951 *
d5530d22
MD
952 * The left and right boundaries are included in the loop h
953 * in order to detect edge cases.
9944ae54 954 *
d5530d22
MD
955 * If the separator only differs by delete_tid (r == -1)
956 * we may end up going down a branch to the left of the
957 * one containing the desired key. Flag it.
8cd0a023 958 */
9944ae54 959 for (i = 0; i <= node->count; ++i) {
61aeeb33
MD
960 elm = &node->elms[i];
961 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
8cd0a023
MD
962 if (r < 0)
963 break;
964 }
8cd0a023
MD
965
966 /*
9944ae54
MD
967 * These cases occur when the parent's idea of the boundary
968 * is wider then the child's idea of the boundary, and
969 * require special handling. If not inserting we can
970 * terminate the search early for these cases but the
971 * child's boundaries cannot be unconditionally modified.
8cd0a023 972 */
fbc6e32a 973 if (i == 0) {
9944ae54
MD
974 /*
975 * If i == 0 the search terminated to the LEFT of the
976 * left_boundary but to the RIGHT of the parent's left
977 * boundary.
978 */
fbc6e32a 979 u_int8_t save;
d26d0ae9 980
fbc6e32a
MD
981 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
982 cursor->index = 0;
983 return(ENOENT);
984 }
9944ae54
MD
985 elm = &node->elms[0];
986
d5530d22
MD
987 /*
988 * Correct a left-hand boundary mismatch.
989 */
990 hammer_modify_node(cursor->node);
991 save = node->elms[0].base.subtree_type;
992 node->elms[0].base = *cursor->left_bound;
993 node->elms[0].base.subtree_type = save;
9944ae54 994 } else if (i == node->count + 1) {
d26d0ae9 995 /*
9944ae54
MD
996 * If i == node->count + 1 the search terminated to
997 * the RIGHT of the right boundary but to the LEFT
998 * of the parent's right boundary.
d113fda1 999 *
9944ae54
MD
1000 * Note that the last element in this case is
1001 * elms[i-2] prior to adjustments to 'i'.
d26d0ae9 1002 */
9944ae54 1003 --i;
d113fda1 1004 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
9944ae54
MD
1005 cursor->index = i;
1006 return(ENOENT);
d26d0ae9
MD
1007 }
1008
d5530d22
MD
1009 /*
1010 * Correct a right-hand boundary mismatch.
1011 * (actual push-down record is i-2 prior to
1012 * adjustments to i).
1013 */
9944ae54 1014 elm = &node->elms[i];
d5530d22
MD
1015 hammer_modify_node(cursor->node);
1016 elm->base = *cursor->right_bound;
1017 --i;
fbc6e32a
MD
1018 } else {
1019 /*
9944ae54
MD
1020 * The push-down index is now i - 1. If we had
1021 * terminated on the right boundary this will point
1022 * us at the last element.
fbc6e32a
MD
1023 */
1024 --i;
1025 }
8cd0a023
MD
1026 cursor->index = i;
1027
b3deaf57 1028 if (hammer_debug_btree) {
61aeeb33 1029 elm = &node->elms[i];
d5530d22 1030 kprintf("SEARCH-I %p:%d %016llx %02x key=%016llx did=%016llx\n",
b3deaf57
MD
1031 cursor->node, i,
1032 elm->internal.base.obj_id,
1033 elm->internal.base.rec_type,
d113fda1 1034 elm->internal.base.key,
d5530d22 1035 elm->internal.base.delete_tid
b3deaf57
MD
1036 );
1037 }
1038
8cd0a023
MD
1039 /*
1040 * Handle insertion and deletion requirements.
1041 *
1042 * If inserting split full nodes. The split code will
1043 * adjust cursor->node and cursor->index if the current
1044 * index winds up in the new node.
61aeeb33 1045 *
9944ae54
MD
1046 * If inserting and a left or right edge case was detected,
1047 * we cannot correct the left or right boundary and must
1048 * prepend and append an empty leaf node in order to make
1049 * the boundary correction.
1050 *
61aeeb33
MD
1051 * If we run out of space we set enospc and continue on
1052 * to a leaf to provide the spike code with a good point
1053 * of entry. Enospc is reset if we cross a cluster boundary.
8cd0a023 1054 */
61aeeb33 1055 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
9944ae54 1056 if (btree_node_is_almost_full(node)) {
8cd0a023 1057 error = btree_split_internal(cursor);
d26d0ae9
MD
1058 if (error) {
1059 if (error != ENOSPC)
1060 goto done;
1061 enospc = 1;
d26d0ae9 1062 }
8cd0a023
MD
1063 /*
1064 * reload stale pointers
1065 */
1066 i = cursor->index;
1067 node = cursor->node->ondisk;
1068 }
d5530d22 1069#if 0
9944ae54
MD
1070 if (edge != SEARCH_NONE && enospc == 0) {
1071 error = btree_edge_internal(cursor, edge);
1072 if (error) {
1073 if (error != ENOSPC)
1074 goto done;
1075 enospc = 1;
1076 }
1077 /*
1078 * reload stale pointers
1079 */
1080 i = cursor->index;
1081 node = cursor->node->ondisk;
1082 }
d5530d22 1083#endif
8cd0a023
MD
1084 }
1085
1086#if 0
427e5fc6 1087 /*
8cd0a023
MD
1088 * If deleting rebalance - do not allow the child to have
1089 * just one element or we will not be able to delete it.
1090 *
1091 * Neither internal or leaf nodes (except a root-leaf) are
1092 * allowed to drop to 0 elements. (XXX - well, leaf nodes
1093 * can at the moment).
1094 *
1095 * Our separators may have been reorganized after rebalancing,
1096 * so we have to pop back up and rescan.
1097 *
1098 * XXX test for subtree_count < maxelms / 2, minus 1 or 2
1099 * for hysteresis?
a89aec1b
MD
1100 *
1101 * XXX NOTE: Iterations may not set this flag anyway.
427e5fc6 1102 */
a89aec1b 1103 if (flags & HAMMER_CURSOR_DELETE) {
8cd0a023
MD
1104 if (node->elms[i].internal.subtree_count <= 1) {
1105 error = btree_rebalance(cursor);
1106 if (error)
1107 goto done;
1108 /* cursor->index is invalid after call */
1109 goto new_cluster;
1110 }
1111 }
1112#endif
d26d0ae9 1113 /*
61aeeb33
MD
1114 * A non-zero rec_offset specifies a cluster push.
1115 * If this is a cluster push we reset the enospc flag,
1116 * which reenables the insertion code in the new cluster.
1117 * This also ensures that if a spike occurs both its node
1118 * and its parent will be in the same cluster.
d26d0ae9 1119 *
61aeeb33
MD
1120 * If INCLUSTER is set we terminate at the cluster boundary.
1121 * In this case we must determine whether key_beg is within
1122 * the cluster's boundary or not. XXX
d26d0ae9 1123 */
61aeeb33
MD
1124 elm = &node->elms[i];
1125 if (elm->internal.rec_offset) {
9944ae54 1126 KKASSERT(elm->base.subtree_type ==
61aeeb33
MD
1127 HAMMER_BTREE_TYPE_CLUSTER);
1128 enospc = 0;
1129 if (flags & HAMMER_CURSOR_INCLUSTER) {
1130 KKASSERT((flags & HAMMER_CURSOR_INSERT) == 0);
1131 r = hammer_btree_cmp(&cursor->key_beg,
1132 &elm[1].base);
1133 error = (r < 0) ? 0 : ENOENT;
1134 goto done;
1135 }
d26d0ae9 1136 }
427e5fc6
MD
1137
1138 /*
8cd0a023 1139 * Push down (push into new node, existing node becomes
d26d0ae9 1140 * the parent) and continue the search.
427e5fc6 1141 */
8cd0a023
MD
1142 error = hammer_cursor_down(cursor);
1143 /* node and cluster become stale */
1144 if (error)
1145 goto done;
1146 node = cursor->node->ondisk;
1147 cluster = cursor->node->cluster;
427e5fc6 1148 }
427e5fc6 1149
8cd0a023
MD
1150 /*
1151 * We are at a leaf, do a linear search of the key array.
d26d0ae9
MD
1152 *
1153 * On success the index is set to the matching element and 0
1154 * is returned.
1155 *
1156 * On failure the index is set to the insertion point and ENOENT
1157 * is returned.
8cd0a023
MD
1158 *
1159 * Boundaries are not stored in leaf nodes, so the index can wind
1160 * up to the left of element 0 (index == 0) or past the end of
1161 * the array (index == node->count).
1162 */
1163 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1164
1165 for (i = 0; i < node->count; ++i) {
1166 r = hammer_btree_cmp(&cursor->key_beg, &node->elms[i].base);
427e5fc6 1167
d5530d22
MD
1168 if (hammer_debug_btree > 1)
1169 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1170
427e5fc6 1171 /*
d5530d22
MD
1172 * Stop if we've flipped past key_beg, not counting the
1173 * delete_tid test.
427e5fc6 1174 */
d5530d22
MD
1175 if (r < -1)
1176 goto failed;
1177 if (r > 0 && (cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0)
1178 continue;
427e5fc6 1179
66325755 1180 /*
d5530d22 1181 * Check our as-of timestamp against the element.
66325755 1182 */
d5530d22
MD
1183 if (r == -1) {
1184 if ((cursor->flags & HAMMER_CURSOR_ASOF) == 0)
1185 goto failed;
d113fda1 1186 if ((cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0 &&
d5530d22 1187 hammer_btree_chkts(cursor->asof,
d113fda1
MD
1188 &node->elms[i].base) != 0) {
1189 continue;
1190 }
66325755 1191 }
d5530d22
MD
1192 cursor->index = i;
1193 error = 0;
1194 if (hammer_debug_btree)
1195 kprintf("SEARCH-L %p:%d (SUCCESS)\n", cursor->node, i);
1196 goto done;
1197 }
1198
1199 /*
1200 * The search failed but due the way we handle delete_tid we may
1201 * have to iterate. Here is why: If a center separator differs
1202 * only by its delete_tid as shown below and we are looking for, say,
1203 * a record with an as-of TID of 12, we will traverse LEAF1. LEAF1
1204 * might contain element 11 and thus not match, and LEAF2 might
1205 * contain element 17 which we DO want to match (i.e. that record
1206 * will be visible to us).
1207 *
1208 * delete_tid: 10 15 20
1209 * L1 L2
1210 *
1211 *
1212 * Its easiest to adjust delete_tid and to tell the caller to
1213 * retry, because this may be an insertion search and require
1214 * more then just a simple iteration.
1215 */
1216 if ((flags & (HAMMER_CURSOR_INSERT|HAMMER_CURSOR_ASOF)) ==
1217 HAMMER_CURSOR_ASOF &&
1218 cursor->key_beg.obj_id == cursor->right_bound->obj_id &&
1219 cursor->key_beg.rec_type == cursor->right_bound->rec_type &&
1220 cursor->key_beg.key == cursor->right_bound->key &&
1221 (cursor->right_bound->delete_tid == 0 ||
1222 cursor->key_beg.delete_tid < cursor->right_bound->delete_tid)
1223 ) {
1224 kprintf("MUST ITERATE\n");
1225 cursor->key_beg.delete_tid = cursor->right_bound->delete_tid;
1226 return(EAGAIN);
427e5fc6 1227 }
8cd0a023 1228
d5530d22 1229failed:
b3deaf57
MD
1230 if (hammer_debug_btree) {
1231 kprintf("SEARCH-L %p:%d (FAILED)\n",
1232 cursor->node, i);
1233 }
1234
8cd0a023
MD
1235 /*
1236 * No exact match was found, i is now at the insertion point.
1237 *
1238 * If inserting split a full leaf before returning. This
1239 * may have the side effect of adjusting cursor->node and
1240 * cursor->index.
1241 */
1242 cursor->index = i;
9944ae54 1243 if ((flags & HAMMER_CURSOR_INSERT) && btree_node_is_almost_full(node)) {
8cd0a023 1244 error = btree_split_leaf(cursor);
d26d0ae9
MD
1245 if (error) {
1246 if (error != ENOSPC)
1247 goto done;
1248 enospc = 1;
1249 flags &= ~HAMMER_CURSOR_INSERT;
1250 }
1251 /*
1252 * reload stale pointers
1253 */
8cd0a023
MD
1254 /* NOT USED
1255 i = cursor->index;
1256 node = &cursor->node->internal;
1257 */
8cd0a023 1258 }
d26d0ae9
MD
1259
1260 /*
1261 * We reached a leaf but did not find the key we were looking for.
1262 * If this is an insert we will be properly positioned for an insert
1263 * (ENOENT) or spike (ENOSPC) operation.
1264 */
1265 error = enospc ? ENOSPC : ENOENT;
8cd0a023 1266done:
427e5fc6
MD
1267 return(error);
1268}
1269
8cd0a023 1270
427e5fc6 1271/************************************************************************
8cd0a023 1272 * SPLITTING AND MERGING *
427e5fc6
MD
1273 ************************************************************************
1274 *
1275 * These routines do all the dirty work required to split and merge nodes.
1276 */
1277
d5530d22 1278#if 0
9944ae54
MD
1279/*
1280 * This case occurs when we are trying to insert and have come across a
1281 * mismatched left or right boundary which could not be adjusted due to
1282 * being part of a spike. In order to be able to adjust the boundary
1283 * we have to prepend or append an empty leaf node.
1284 */
1285static
1286int
1287btree_edge_internal(hammer_cursor_t cursor, btree_search_edge_t edge)
1288{
1289 hammer_node_ondisk_t old_disk;
1290 hammer_node_ondisk_t new_disk;
1291 hammer_node_t new_node;
1292 hammer_btree_elm_t elm;
1293 int error;
1294 int n;
1295 const int esize = sizeof(*elm);
1296
1297 old_disk = cursor->node->ondisk;
1298 KKASSERT(old_disk->type == HAMMER_BTREE_TYPE_INTERNAL);
1299 KKASSERT(old_disk->count < HAMMER_BTREE_INT_ELMS);
1300
1301 /*
1302 * Allocate a new leaf node.
1303 */
1304 new_node = hammer_alloc_btree(cursor->node->cluster, &error);
1305 if (error)
1306 return(error);
1307
1308 hammer_lock_ex(&new_node->lock);
1309 hammer_modify_node(cursor->node);
1310 hammer_modify_node(new_node);
1311 new_disk = new_node->ondisk;
1312 n = old_disk->count;
1313
1314 /*
1315 * Prepend or append the leaf node and correct the boundary
1316 * mismatch.
1317 */
1318 switch(edge) {
1319 case SEARCH_LEFT_EDGE:
1320 KKASSERT(cursor->index == 0);
1321 elm = &old_disk->elms[0];
1322 bcopy(elm, elm + 1, (n + 1) * esize);
1323 elm->base = *cursor->left_bound;
1324 break;
1325 case SEARCH_RIGHT_EDGE:
1326 KKASSERT(cursor->index == old_disk->count);
1327 elm = &old_disk->elms[n];
1328 elm[1].base = *cursor->right_bound;
1329 break;
1330 default:
1331 panic("btree_edge_internal: bad edge");
1332 break;
1333 }
1334 ++old_disk->count;
1335 elm->base.subtree_type = HAMMER_BTREE_TYPE_LEAF;
1336 elm->internal.subtree_offset = new_node->node_offset;
1337 elm->internal.subtree_vol_no = -1;
1338 elm->internal.subtree_count = 0;
1339
1340 new_disk->count = 0;
1341 new_disk->parent = cursor->node->node_offset;
1342 new_disk->type = HAMMER_BTREE_TYPE_LEAF;
1343
1344 hammer_unlock(&new_node->lock);
1345 hammer_rel_node(new_node);
1346
1347 /*
1348 * Cursor->index remains unchanged. It now points to our new leaf
1349 * node and cursor->node's boundaries have been synchronized with
1350 * the parent.
1351 */
1352 return(0);
1353}
1354
d5530d22
MD
1355#endif
1356
427e5fc6 1357/*
8cd0a023 1358 * Split an internal node into two nodes and move the separator at the split
427e5fc6
MD
1359 * point to the parent. Note that the parent's parent's element pointing
1360 * to our parent will have an incorrect subtree_count (we don't update it).
1361 * It will be low, which is ok.
1362 *
8cd0a023
MD
1363 * (cursor->node, cursor->index) indicates the element the caller intends
1364 * to push into. We will adjust node and index if that element winds
427e5fc6 1365 * up in the split node.
8cd0a023
MD
1366 *
1367 * If we are at the root of a cluster a new root must be created with two
1368 * elements, one pointing to the original root and one pointing to the
1369 * newly allocated split node.
1370 *
1371 * NOTE! Being at the root of a cluster is different from being at the
1372 * root of the root cluster. cursor->parent will not be NULL and
1373 * cursor->node->ondisk.parent must be tested against 0. Theoretically
1374 * we could propogate the algorithm into the parent and deal with multiple
1375 * 'roots' in the cluster header, but it's easier not to.
427e5fc6
MD
1376 */
1377static
1378int
8cd0a023 1379btree_split_internal(hammer_cursor_t cursor)
427e5fc6 1380{
8cd0a023
MD
1381 hammer_node_ondisk_t ondisk;
1382 hammer_node_t node;
1383 hammer_node_t parent;
1384 hammer_node_t new_node;
1385 hammer_btree_elm_t elm;
1386 hammer_btree_elm_t parent_elm;
427e5fc6
MD
1387 int parent_index;
1388 int made_root;
1389 int split;
1390 int error;
7f7c1f84 1391 int i;
8cd0a023 1392 const int esize = sizeof(*elm);
427e5fc6
MD
1393
1394 /*
1395 * We are splitting but elms[split] will be promoted to the parent,
1396 * leaving the right hand node with one less element. If the
1397 * insertion point will be on the left-hand side adjust the split
1398 * point to give the right hand side one additional node.
1399 */
8cd0a023
MD
1400 node = cursor->node;
1401 ondisk = node->ondisk;
1402 split = (ondisk->count + 1) / 2;
427e5fc6
MD
1403 if (cursor->index <= split)
1404 --split;
1405 error = 0;
1406
1407 /*
8cd0a023 1408 * If we are at the root of the cluster, create a new root node with
427e5fc6
MD
1409 * 1 element and split normally. Avoid making major modifications
1410 * until we know the whole operation will work.
8cd0a023
MD
1411 *
1412 * The root of the cluster is different from the root of the root
1413 * cluster. Use the node's on-disk structure's parent offset to
1414 * detect the case.
427e5fc6 1415 */
8cd0a023
MD
1416 if (ondisk->parent == 0) {
1417 parent = hammer_alloc_btree(node->cluster, &error);
427e5fc6
MD
1418 if (parent == NULL)
1419 return(error);
8cd0a023 1420 hammer_lock_ex(&parent->lock);
0b075555 1421 hammer_modify_node(parent);
8cd0a023
MD
1422 ondisk = parent->ondisk;
1423 ondisk->count = 1;
1424 ondisk->parent = 0;
1425 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1426 ondisk->elms[0].base = node->cluster->clu_btree_beg;
9944ae54 1427 ondisk->elms[0].base.subtree_type = node->ondisk->type;
8cd0a023
MD
1428 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1429 ondisk->elms[1].base = node->cluster->clu_btree_end;
9944ae54 1430 /* ondisk->elms[1].base.subtree_Type - not used */
427e5fc6 1431 made_root = 1;
8cd0a023 1432 parent_index = 0; /* index of current node in parent */
427e5fc6
MD
1433 } else {
1434 made_root = 0;
8cd0a023
MD
1435 parent = cursor->parent;
1436 parent_index = cursor->parent_index;
195c19a1 1437 KKASSERT(parent->cluster == node->cluster);
427e5fc6 1438 }
427e5fc6
MD
1439
1440 /*
1441 * Split node into new_node at the split point.
1442 *
1443 * B O O O P N N B <-- P = node->elms[split]
1444 * 0 1 2 3 4 5 6 <-- subtree indices
1445 *
1446 * x x P x x
1447 * s S S s
1448 * / \
1449 * B O O O B B N N B <--- inner boundary points are 'P'
1450 * 0 1 2 3 4 5 6
1451 *
1452 */
8cd0a023 1453 new_node = hammer_alloc_btree(node->cluster, &error);
427e5fc6 1454 if (new_node == NULL) {
8cd0a023
MD
1455 if (made_root) {
1456 hammer_unlock(&parent->lock);
b3deaf57 1457 parent->flags |= HAMMER_NODE_DELETED;
8cd0a023
MD
1458 hammer_rel_node(parent);
1459 }
427e5fc6
MD
1460 return(error);
1461 }
8cd0a023 1462 hammer_lock_ex(&new_node->lock);
427e5fc6
MD
1463
1464 /*
8cd0a023 1465 * Create the new node. P becomes the left-hand boundary in the
427e5fc6
MD
1466 * new node. Copy the right-hand boundary as well.
1467 *
1468 * elm is the new separator.
1469 */
0b075555
MD
1470 hammer_modify_node(new_node);
1471 hammer_modify_node(node);
8cd0a023
MD
1472 ondisk = node->ondisk;
1473 elm = &ondisk->elms[split];
1474 bcopy(elm, &new_node->ondisk->elms[0],
1475 (ondisk->count - split + 1) * esize);
1476 new_node->ondisk->count = ondisk->count - split;
1477 new_node->ondisk->parent = parent->node_offset;
1478 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1479 KKASSERT(ondisk->type == new_node->ondisk->type);
427e5fc6
MD
1480
1481 /*
1482 * Cleanup the original node. P becomes the new boundary, its
1483 * subtree_offset was moved to the new node. If we had created
1484 * a new root its parent pointer may have changed.
1485 */
8cd0a023 1486 elm->internal.subtree_offset = 0;
0b075555 1487 elm->internal.rec_offset = 0;
c0ade690 1488 ondisk->count = split;
427e5fc6
MD
1489
1490 /*
1491 * Insert the separator into the parent, fixup the parent's
1492 * reference to the original node, and reference the new node.
1493 * The separator is P.
1494 *
1495 * Remember that base.count does not include the right-hand boundary.
1496 */
0b075555 1497 hammer_modify_node(parent);
8cd0a023 1498 ondisk = parent->ondisk;
d26d0ae9 1499 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
8cd0a023
MD
1500 ondisk->elms[parent_index].internal.subtree_count = split;
1501 parent_elm = &ondisk->elms[parent_index+1];
427e5fc6 1502 bcopy(parent_elm, parent_elm + 1,
8cd0a023
MD
1503 (ondisk->count - parent_index) * esize);
1504 parent_elm->internal.base = elm->base; /* separator P */
9944ae54 1505 parent_elm->internal.base.subtree_type = new_node->ondisk->type;
8cd0a023
MD
1506 parent_elm->internal.subtree_offset = new_node->node_offset;
1507 parent_elm->internal.subtree_count = new_node->ondisk->count;
0b075555
MD
1508 parent_elm->internal.subtree_vol_no = 0;
1509 parent_elm->internal.rec_offset = 0;
76376933 1510 ++ondisk->count;
427e5fc6 1511
7f7c1f84
MD
1512 /*
1513 * The children of new_node need their parent pointer set to new_node.
1514 */
1515 for (i = 0; i < new_node->ondisk->count; ++i) {
1516 elm = &new_node->ondisk->elms[i];
1517 error = btree_set_parent(new_node, elm);
1518 if (error) {
1519 panic("btree_split_internal: btree-fixup problem");
1520 }
1521 }
1522
427e5fc6
MD
1523 /*
1524 * The cluster's root pointer may have to be updated.
1525 */
1526 if (made_root) {
8cd0a023 1527 hammer_modify_cluster(node->cluster);
0b075555 1528 node->cluster->ondisk->clu_btree_root = parent->node_offset;
8cd0a023
MD
1529 node->ondisk->parent = parent->node_offset;
1530 if (cursor->parent) {
1531 hammer_unlock(&cursor->parent->lock);
1532 hammer_rel_node(cursor->parent);
1533 }
1534 cursor->parent = parent; /* lock'd and ref'd */
427e5fc6
MD
1535 }
1536
8cd0a023 1537
427e5fc6
MD
1538 /*
1539 * Ok, now adjust the cursor depending on which element the original
1540 * index was pointing at. If we are >= the split point the push node
1541 * is now in the new node.
1542 *
1543 * NOTE: If we are at the split point itself we cannot stay with the
1544 * original node because the push index will point at the right-hand
1545 * boundary, which is illegal.
8cd0a023
MD
1546 *
1547 * NOTE: The cursor's parent or parent_index must be adjusted for
1548 * the case where a new parent (new root) was created, and the case
1549 * where the cursor is now pointing at the split node.
427e5fc6
MD
1550 */
1551 if (cursor->index >= split) {
8cd0a023 1552 cursor->parent_index = parent_index + 1;
427e5fc6 1553 cursor->index -= split;
8cd0a023
MD
1554 hammer_unlock(&cursor->node->lock);
1555 hammer_rel_node(cursor->node);
1556 cursor->node = new_node; /* locked and ref'd */
1557 } else {
1558 cursor->parent_index = parent_index;
1559 hammer_unlock(&new_node->lock);
1560 hammer_rel_node(new_node);
427e5fc6 1561 }
76376933
MD
1562
1563 /*
1564 * Fixup left and right bounds
1565 */
1566 parent_elm = &parent->ondisk->elms[cursor->parent_index];
fbc6e32a
MD
1567 cursor->left_bound = &parent_elm[0].internal.base;
1568 cursor->right_bound = &parent_elm[1].internal.base;
b3deaf57
MD
1569 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1570 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1571 KKASSERT(hammer_btree_cmp(cursor->right_bound,
9944ae54 1572 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
76376933 1573
427e5fc6
MD
1574 return (0);
1575}
1576
1577/*
1578 * Same as the above, but splits a full leaf node.
1579 */
1580static
1581int
8cd0a023 1582btree_split_leaf(hammer_cursor_t cursor)
427e5fc6 1583{
8cd0a023
MD
1584 hammer_node_ondisk_t ondisk;
1585 hammer_node_t parent;
1586 hammer_node_t leaf;
1587 hammer_node_t new_leaf;
1588 hammer_btree_elm_t elm;
1589 hammer_btree_elm_t parent_elm;
b3deaf57 1590 hammer_base_elm_t mid_boundary;
427e5fc6
MD
1591 int parent_index;
1592 int made_root;
1593 int split;
1594 int error;
8cd0a023 1595 const size_t esize = sizeof(*elm);
427e5fc6
MD
1596
1597 /*
8cd0a023
MD
1598 * Calculate the split point. If the insertion point will be on
1599 * the left-hand side adjust the split point to give the right
1600 * hand side one additional node.
427e5fc6 1601 */
8cd0a023
MD
1602 leaf = cursor->node;
1603 ondisk = leaf->ondisk;
1604 split = (ondisk->count + 1) / 2;
427e5fc6
MD
1605 if (cursor->index <= split)
1606 --split;
1607 error = 0;
1608
1609 /*
1610 * If we are at the root of the tree, create a new root node with
1611 * 1 element and split normally. Avoid making major modifications
1612 * until we know the whole operation will work.
1613 */
8cd0a023
MD
1614 if (ondisk->parent == 0) {
1615 parent = hammer_alloc_btree(leaf->cluster, &error);
427e5fc6
MD
1616 if (parent == NULL)
1617 return(error);
8cd0a023 1618 hammer_lock_ex(&parent->lock);
0b075555 1619 hammer_modify_node(parent);
8cd0a023
MD
1620 ondisk = parent->ondisk;
1621 ondisk->count = 1;
1622 ondisk->parent = 0;
1623 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1624 ondisk->elms[0].base = leaf->cluster->clu_btree_beg;
9944ae54 1625 ondisk->elms[0].base.subtree_type = leaf->ondisk->type;
8cd0a023
MD
1626 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1627 ondisk->elms[1].base = leaf->cluster->clu_btree_end;
9944ae54 1628 /* ondisk->elms[1].base.subtree_type = not used */
427e5fc6 1629 made_root = 1;
8cd0a023 1630 parent_index = 0; /* insertion point in parent */
427e5fc6
MD
1631 } else {
1632 made_root = 0;
8cd0a023
MD
1633 parent = cursor->parent;
1634 parent_index = cursor->parent_index;
195c19a1 1635 KKASSERT(parent->cluster == leaf->cluster);
427e5fc6 1636 }
427e5fc6
MD
1637
1638 /*
1639 * Split leaf into new_leaf at the split point. Select a separator
1640 * value in-between the two leafs but with a bent towards the right
1641 * leaf since comparisons use an 'elm >= separator' inequality.
1642 *
1643 * L L L L L L L L
1644 *
1645 * x x P x x
1646 * s S S s
1647 * / \
1648 * L L L L L L L L
1649 */
8cd0a023 1650 new_leaf = hammer_alloc_btree(leaf->cluster, &error);
427e5fc6 1651 if (new_leaf == NULL) {
8cd0a023
MD
1652 if (made_root) {
1653 hammer_unlock(&parent->lock);
b3deaf57 1654 parent->flags |= HAMMER_NODE_DELETED;
8cd0a023
MD
1655 hammer_rel_node(parent);
1656 }
427e5fc6
MD
1657 return(error);
1658 }
8cd0a023 1659 hammer_lock_ex(&new_leaf->lock);
427e5fc6
MD
1660
1661 /*
1662 * Create the new node. P become the left-hand boundary in the
1663 * new node. Copy the right-hand boundary as well.
1664 */
0b075555
MD
1665 hammer_modify_node(leaf);
1666 hammer_modify_node(new_leaf);
8cd0a023
MD
1667 ondisk = leaf->ondisk;
1668 elm = &ondisk->elms[split];
1669 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1670 new_leaf->ondisk->count = ondisk->count - split;
1671 new_leaf->ondisk->parent = parent->node_offset;
1672 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1673 KKASSERT(ondisk->type == new_leaf->ondisk->type);
427e5fc6
MD
1674
1675 /*
8cd0a023
MD
1676 * Cleanup the original node. Because this is a leaf node and
1677 * leaf nodes do not have a right-hand boundary, there
c0ade690
MD
1678 * aren't any special edge cases to clean up. We just fixup the
1679 * count.
427e5fc6 1680 */
c0ade690 1681 ondisk->count = split;
427e5fc6
MD
1682
1683 /*
1684 * Insert the separator into the parent, fixup the parent's
1685 * reference to the original node, and reference the new node.
1686 * The separator is P.
1687 *
1688 * Remember that base.count does not include the right-hand boundary.
1689 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1690 */
0b075555 1691 hammer_modify_node(parent);
8cd0a023 1692 ondisk = parent->ondisk;
d26d0ae9 1693 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
8cd0a023
MD
1694 ondisk->elms[parent_index].internal.subtree_count = split;
1695 parent_elm = &ondisk->elms[parent_index+1];
d26d0ae9
MD
1696 bcopy(parent_elm, parent_elm + 1,
1697 (ondisk->count - parent_index) * esize);
427e5fc6 1698 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
9944ae54 1699 parent_elm->internal.base.subtree_type = new_leaf->ondisk->type;
8cd0a023
MD
1700 parent_elm->internal.subtree_offset = new_leaf->node_offset;
1701 parent_elm->internal.subtree_count = new_leaf->ondisk->count;
0b075555
MD
1702 parent_elm->internal.subtree_vol_no = 0;
1703 parent_elm->internal.rec_offset = 0;
b3deaf57 1704 mid_boundary = &parent_elm->base;
76376933 1705 ++ondisk->count;
427e5fc6
MD
1706
1707 /*
1708 * The cluster's root pointer may have to be updated.
1709 */
1710 if (made_root) {
8cd0a023 1711 hammer_modify_cluster(leaf->cluster);
0b075555 1712 leaf->cluster->ondisk->clu_btree_root = parent->node_offset;
8cd0a023
MD
1713 leaf->ondisk->parent = parent->node_offset;
1714 if (cursor->parent) {
1715 hammer_unlock(&cursor->parent->lock);
1716 hammer_rel_node(cursor->parent);
1717 }
1718 cursor->parent = parent; /* lock'd and ref'd */
427e5fc6 1719 }
8cd0a023 1720
427e5fc6
MD
1721 /*
1722 * Ok, now adjust the cursor depending on which element the original
1723 * index was pointing at. If we are >= the split point the push node
1724 * is now in the new node.
1725 *
b3deaf57
MD
1726 * NOTE: If we are at the split point itself we need to select the
1727 * old or new node based on where key_beg's insertion point will be.
1728 * If we pick the wrong side the inserted element will wind up in
1729 * the wrong leaf node and outside that node's bounds.
427e5fc6 1730 */
b3deaf57
MD
1731 if (cursor->index > split ||
1732 (cursor->index == split &&
1733 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
8cd0a023 1734 cursor->parent_index = parent_index + 1;
427e5fc6 1735 cursor->index -= split;
8cd0a023
MD
1736 hammer_unlock(&cursor->node->lock);
1737 hammer_rel_node(cursor->node);
1738 cursor->node = new_leaf;
1739 } else {
1740 cursor->parent_index = parent_index;
1741 hammer_unlock(&new_leaf->lock);
1742 hammer_rel_node(new_leaf);
427e5fc6 1743 }
76376933
MD
1744
1745 /*
1746 * Fixup left and right bounds
1747 */
1748 parent_elm = &parent->ondisk->elms[cursor->parent_index];
fbc6e32a
MD
1749 cursor->left_bound = &parent_elm[0].internal.base;
1750 cursor->right_bound = &parent_elm[1].internal.base;
b3deaf57
MD
1751 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1752 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1753 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1754 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
76376933 1755
427e5fc6
MD
1756 return (0);
1757}
1758
1759/*
195c19a1
MD
1760 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1761 * on success, EAGAIN if we could not acquire the necessary locks, or some
1762 * other error.
8cd0a023 1763 *
195c19a1 1764 * On return the cursor may end up pointing at an internal node, suitable
b3deaf57 1765 * for further iteration but not for an immediate insertion or deletion.
8cd0a023 1766 *
195c19a1 1767 * cursor->node may be an internal node or a leaf node.
b3deaf57
MD
1768 *
1769 * NOTE: If cursor->node has one element it is the parent trying to delete
1770 * that element, make sure cursor->index is properly adjusted on success.
8cd0a023
MD
1771 */
1772int
195c19a1 1773btree_remove(hammer_cursor_t cursor)
8cd0a023
MD
1774{
1775 hammer_node_ondisk_t ondisk;
195c19a1
MD
1776 hammer_btree_elm_t elm;
1777 hammer_node_t save;
1778 hammer_node_t node;
8cd0a023
MD
1779 hammer_node_t parent;
1780 int error;
195c19a1 1781 int i;
8cd0a023
MD
1782
1783 /*
195c19a1
MD
1784 * If we are at the root of the root cluster there is nothing to
1785 * remove, but an internal node at the root of a cluster is not
1786 * allowed to be empty so convert it to a leaf node.
8cd0a023 1787 */
195c19a1 1788 if (cursor->parent == NULL) {
0b075555 1789 hammer_modify_node(cursor->node);
195c19a1
MD
1790 ondisk = cursor->node->ondisk;
1791 KKASSERT(ondisk->parent == 0);
1792 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1793 ondisk->count = 0;
b3deaf57 1794 cursor->index = 0;
195c19a1 1795 kprintf("EMPTY ROOT OF ROOT CLUSTER -> LEAF\n");
8cd0a023
MD
1796 return(0);
1797 }
1798
1799 /*
195c19a1
MD
1800 * Retain a reference to cursor->node, ex-lock again (2 locks now)
1801 * so we do not lose the lock when we cursor around.
8cd0a023 1802 */
195c19a1
MD
1803 save = cursor->node;
1804 hammer_ref_node(save);
1805 hammer_lock_ex(&save->lock);
8cd0a023
MD
1806
1807 /*
195c19a1
MD
1808 * We need to be able to lock the parent of the parent. Do this
1809 * non-blocking and return EAGAIN if the lock cannot be acquired.
1810 * non-blocking is required in order to avoid a deadlock.
1811 *
1812 * After we cursor up, parent is moved to node and the new parent
1813 * is the parent of the parent.
8cd0a023 1814 */
195c19a1
MD
1815 error = hammer_cursor_up(cursor, 1);
1816 if (error) {
b3deaf57
MD
1817 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
1818 goto failure;
8cd0a023 1819 }
195c19a1
MD
1820
1821 /*
1822 * At this point we want to remove the element at (node, index),
1823 * which is now the (original) parent pointing to the saved node.
1824 * Removing the element allows us to then free the node it was
1825 * pointing to.
1826 *
1827 * However, an internal node is not allowed to have 0 elements, so
1828 * if the count would drop to 0 we have to recurse. It is possible
1829 * for the recursion to fail.
1830 *
1831 * NOTE: The cursor is in an indeterminant position after recursing,
1832 * but will still be suitable for an iteration.
1833 */
1834 node = cursor->node;
1835 KKASSERT(node->ondisk->count > 0);
1836 if (node->ondisk->count == 1) {
1837 error = btree_remove(cursor);
1838 if (error == 0) {
b3deaf57
MD
1839 /*kprintf("BTREE_REMOVE: Successful!\n");*/
1840 goto success;
195c19a1
MD
1841 } else {
1842 kprintf("BTREE_REMOVE: Recursion failed %d\n", error);
b3deaf57 1843 goto failure;
8cd0a023
MD
1844 }
1845 }
195c19a1
MD
1846
1847 /*
1848 * Remove the element at (node, index) and adjust the parent's
1849 * subtree_count.
fbc6e32a 1850 *
d26d0ae9
MD
1851 * NOTE! If removing element 0 an internal node's left-hand boundary
1852 * will no longer match its parent. If removing a mid-element the
1853 * boundary will no longer match a child's left hand or right hand
1854 * boundary.
1855 *
1856 * BxBxBxB remove a (x[0]): internal node's left-hand
1857 * | | | boundary no longer matches
1858 * a b c parent.
1859 *
1860 * remove b (x[1]): a's right hand boundary no
1861 * longer matches parent.
fbc6e32a 1862 *
d26d0ae9
MD
1863 * remove c (x[2]): b's right hand boundary no
1864 * longer matches parent.
1865 *
1866 * These cases are corrected in btree_search().
195c19a1 1867 */
fbc6e32a 1868#if 0
195c19a1 1869 kprintf("BTREE_REMOVE: Removing element %d\n", cursor->index);
fbc6e32a 1870#endif
b3deaf57
MD
1871 KKASSERT(node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1872 KKASSERT(cursor->index < node->ondisk->count);
0b075555 1873 hammer_modify_node(node);
195c19a1
MD
1874 ondisk = node->ondisk;
1875 i = cursor->index;
9944ae54
MD
1876
1877 /*
1878 * WARNING: For historical lookups to work properly we cannot
1879 * recalculate the mid-point or we might blow up historical searches
1880 * which depend on the mid-point matching the first right-hand element
1881 * XXX
1882 */
195c19a1
MD
1883 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
1884 (ondisk->count - i) * sizeof(ondisk->elms[0]));
1885 --ondisk->count;
195c19a1
MD
1886
1887 /*
1888 * Adjust the parent-parent's (now parent) reference to the parent
1889 * (now node).
1890 */
1891 if ((parent = cursor->parent) != NULL) {
1892 elm = &parent->ondisk->elms[cursor->parent_index];
1893 if (elm->internal.subtree_count != ondisk->count) {
195c19a1 1894 hammer_modify_node(parent);
0b075555 1895 elm->internal.subtree_count = ondisk->count;
195c19a1 1896 }
9944ae54
MD
1897 if (elm->base.subtree_type != HAMMER_BTREE_TYPE_CLUSTER &&
1898 elm->base.subtree_type != ondisk->type) {
195c19a1 1899 hammer_modify_node(parent);
9944ae54 1900 elm->base.subtree_type = ondisk->type;
8cd0a023
MD
1901 }
1902 }
b3deaf57
MD
1903
1904success:
195c19a1 1905 /*
b3deaf57
MD
1906 * Free the saved node. If the saved node was the root of a
1907 * cluster, free the entire cluster.
195c19a1
MD
1908 */
1909 hammer_flush_node(save);
b3deaf57
MD
1910 save->flags |= HAMMER_NODE_DELETED;
1911
1912 error = 0;
1913failure:
195c19a1
MD
1914 hammer_unlock(&save->lock);
1915 hammer_rel_node(save);
b3deaf57 1916 return(error);
8cd0a023
MD
1917}
1918
7f7c1f84
MD
1919/*
1920 * The child represented by the element in internal node node needs
1921 * to have its parent pointer adjusted.
1922 */
1923static
1924int
1925btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm)
1926{
1927 hammer_volume_t volume;
1928 hammer_cluster_t cluster;
1929 hammer_node_t child;
1930 int error;
1931
1932 error = 0;
1933
9944ae54 1934 switch(elm->internal.base.subtree_type) {
7f7c1f84
MD
1935 case HAMMER_BTREE_TYPE_LEAF:
1936 case HAMMER_BTREE_TYPE_INTERNAL:
1937 child = hammer_get_node(node->cluster,
1938 elm->internal.subtree_offset, &error);
1939 if (error == 0) {
0b075555 1940 hammer_modify_node(child);
7f7c1f84
MD
1941 hammer_lock_ex(&child->lock);
1942 child->ondisk->parent = node->node_offset;
7f7c1f84
MD
1943 hammer_unlock(&child->lock);
1944 hammer_rel_node(child);
1945 }
1946 break;
1947 case HAMMER_BTREE_TYPE_CLUSTER:
1948 volume = hammer_get_volume(node->cluster->volume->hmp,
d26d0ae9 1949 elm->internal.subtree_vol_no, &error);
7f7c1f84
MD
1950 if (error)
1951 break;
1952 cluster = hammer_get_cluster(volume,
d26d0ae9 1953 elm->internal.subtree_clu_no,
7f7c1f84
MD
1954 &error, 0);
1955 hammer_rel_volume(volume, 0);
1956 if (error)
1957 break;
0b075555 1958 hammer_modify_cluster(cluster);
7f7c1f84
MD
1959 hammer_lock_ex(&cluster->io.lock);
1960 cluster->ondisk->clu_btree_parent_offset = node->node_offset;
1961 hammer_unlock(&cluster->io.lock);
1962 KKASSERT(cluster->ondisk->clu_btree_parent_clu_no ==
1963 node->cluster->clu_no);
1964 KKASSERT(cluster->ondisk->clu_btree_parent_vol_no ==
1965 node->cluster->volume->vol_no);
7f7c1f84
MD
1966 hammer_rel_cluster(cluster, 0);
1967 break;
1968 default:
1969 hammer_print_btree_elm(elm, HAMMER_BTREE_TYPE_INTERNAL, -1);
1970 panic("btree_set_parent: bad subtree_type");
1971 break; /* NOT REACHED */
1972 }
1973 return(error);
1974}
1975
8cd0a023
MD
1976/************************************************************************
1977 * MISCELLANIOUS SUPPORT *
1978 ************************************************************************/
1979
1980/*
d26d0ae9 1981 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
8cd0a023 1982 *
d113fda1 1983 * Note that for this particular function a return value of -1, 0, or +1
d5530d22
MD
1984 * can denote a match if delete_tid is otherwise discounted. A delete_tid
1985 * of zero is considered to be 'infinity' in comparisons.
d113fda1 1986 *
8cd0a023 1987 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
8cd0a023
MD
1988 */
1989int
1990hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
1991{
d26d0ae9
MD
1992 if (key1->obj_id < key2->obj_id)
1993 return(-4);
1994 if (key1->obj_id > key2->obj_id)
1995 return(4);
8cd0a023 1996
d26d0ae9
MD
1997 if (key1->rec_type < key2->rec_type)
1998 return(-3);
1999 if (key1->rec_type > key2->rec_type)
2000 return(3);
8cd0a023 2001
8cd0a023
MD
2002 if (key1->key < key2->key)
2003 return(-2);
2004 if (key1->key > key2->key)
2005 return(2);
d113fda1 2006
d5530d22
MD
2007 /*
2008 * A delete_tid of zero indicates a record which has not been
2009 * deleted yet and must be considered to have a value of positive
2010 * infinity.
2011 */
2012 if (key1->delete_tid == 0) {
2013 if (key2->delete_tid == 0)
2014 return(0);
2015 return(1);
2016 }
2017 if (key2->delete_tid == 0)
2018 return(-1);
2019 if (key1->delete_tid < key2->delete_tid)
d113fda1 2020 return(-1);
d5530d22 2021 if (key1->delete_tid > key2->delete_tid)
d113fda1 2022 return(1);
8cd0a023
MD
2023 return(0);
2024}
2025
c0ade690 2026/*
d5530d22
MD
2027 * Test a timestamp against an element to determine whether the
2028 * element is visible. A timestamp of 0 means 'infinity'.
c0ade690
MD
2029 */
2030int
d5530d22 2031hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
c0ade690 2032{
d5530d22
MD
2033 if (asof == 0) {
2034 if (base->delete_tid)
2035 return(1);
2036 return(0);
2037 }
2038 if (asof < base->create_tid)
d26d0ae9 2039 return(-1);
d5530d22 2040 if (base->delete_tid && asof >= base->delete_tid)
d26d0ae9 2041 return(1);
c0ade690
MD
2042 return(0);
2043}
2044
8cd0a023
MD
2045/*
2046 * Create a separator half way inbetween key1 and key2. For fields just
d5530d22
MD
2047 * one unit apart, the separator will match key2. key1 is on the left-hand
2048 * side and key2 is on the right-hand side.
8cd0a023 2049 *
d5530d22
MD
2050 * delete_tid has to be special cased because a value of 0 represents
2051 * infinity, and records with a delete_tid of 0 can be replaced with
2052 * a non-zero delete_tid when deleted and must maintain their proper
2053 * (as in the same) position in the B-Tree.
8cd0a023
MD
2054 */
2055#define MAKE_SEPARATOR(key1, key2, dest, field) \
2056 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2057
2058static void
2059hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2060 hammer_base_elm_t dest)
2061{
2062 bzero(dest, sizeof(*dest));
2063 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2064 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2065 MAKE_SEPARATOR(key1, key2, dest, key);
d5530d22 2066
d113fda1
MD
2067 if (key1->obj_id == key2->obj_id &&
2068 key1->rec_type == key2->rec_type &&
2069 key1->key == key2->key) {
d5530d22
MD
2070 if (key1->delete_tid == 0) {
2071 /*
2072 * key1 cannot be on the left hand side if everything
2073 * matches but it has an infinite delete_tid!
2074 */
2075 panic("hammer_make_separator: illegal delete_tid");
2076 } else if (key2->delete_tid == 0) {
2077 dest->delete_tid = key1->delete_tid + 1;
2078 } else {
2079 MAKE_SEPARATOR(key1, key2, dest, delete_tid);
2080 }
d113fda1 2081 } else {
d5530d22 2082 dest->delete_tid = 0;
d113fda1 2083 }
8cd0a023
MD
2084}
2085
2086#undef MAKE_SEPARATOR
2087
9944ae54 2088#if 0
8cd0a023
MD
2089/*
2090 * Return whether a generic internal or leaf node is full
2091 */
2092static int
2093btree_node_is_full(hammer_node_ondisk_t node)
2094{
2095 switch(node->type) {
2096 case HAMMER_BTREE_TYPE_INTERNAL:
2097 if (node->count == HAMMER_BTREE_INT_ELMS)
2098 return(1);
2099 break;
2100 case HAMMER_BTREE_TYPE_LEAF:
2101 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2102 return(1);
2103 break;
2104 default:
2105 panic("illegal btree subtype");
2106 }
2107 return(0);
2108}
9944ae54
MD
2109#endif
2110
2111/*
2112 * Return whether a generic internal or leaf node is almost full. This
2113 * routine is used as a helper for search insertions to guarentee at
2114 * least 2 available slots in the internal node(s) leading up to a leaf,
2115 * so hammer_btree_insert_cluster() will function properly.
2116 */
2117static int
2118btree_node_is_almost_full(hammer_node_ondisk_t node)
2119{
2120 switch(node->type) {
2121 case HAMMER_BTREE_TYPE_INTERNAL:
2122 if (node->count > HAMMER_BTREE_INT_ELMS - 2)
2123 return(1);
2124 break;
2125 case HAMMER_BTREE_TYPE_LEAF:
2126 if (node->count > HAMMER_BTREE_LEAF_ELMS - 2)
2127 return(1);
2128 break;
2129 default:
2130 panic("illegal btree subtype");
2131 }
2132 return(0);
2133}
8cd0a023
MD
2134
2135#if 0
2136static int
2137btree_max_elements(u_int8_t type)
2138{
2139 if (type == HAMMER_BTREE_TYPE_LEAF)
2140 return(HAMMER_BTREE_LEAF_ELMS);
2141 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2142 return(HAMMER_BTREE_INT_ELMS);
2143 panic("btree_max_elements: bad type %d\n", type);
2144}
2145#endif
2146
c0ade690
MD
2147void
2148hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2149{
2150 hammer_btree_elm_t elm;
2151 int i;
2152
2153 kprintf("node %p count=%d parent=%d type=%c\n",
2154 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2155
2156 /*
2157 * Dump both boundary elements if an internal node
2158 */
2159 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2160 for (i = 0; i <= ondisk->count; ++i) {
2161 elm = &ondisk->elms[i];
2162 hammer_print_btree_elm(elm, ondisk->type, i);
2163 }
2164 } else {
2165 for (i = 0; i < ondisk->count; ++i) {
2166 elm = &ondisk->elms[i];
2167 hammer_print_btree_elm(elm, ondisk->type, i);
2168 }
2169 }
2170}
2171
2172void
2173hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2174{
2175 kprintf(" %2d", i);
2176 kprintf("\tobjid = %016llx\n", elm->base.obj_id);
2177 kprintf("\tkey = %016llx\n", elm->base.key);
2178 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2179 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2180 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2181 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
9944ae54 2182 kprintf("\tsubtree_type = %02x\n", elm->base.subtree_type);
c0ade690
MD
2183
2184 if (type == HAMMER_BTREE_TYPE_INTERNAL) {
2185 if (elm->internal.rec_offset) {
2186 kprintf("\tcluster_rec = %08x\n",
2187 elm->internal.rec_offset);
2188 kprintf("\tcluster_id = %08x\n",
d26d0ae9 2189 elm->internal.subtree_clu_no);
c0ade690 2190 kprintf("\tvolno = %08x\n",
d26d0ae9 2191 elm->internal.subtree_vol_no);
c0ade690
MD
2192 } else {
2193 kprintf("\tsubtree_off = %08x\n",
2194 elm->internal.subtree_offset);
2195 }
2196 kprintf("\tsubtree_count= %d\n", elm->internal.subtree_count);
2197 } else {
2198 kprintf("\trec_offset = %08x\n", elm->leaf.rec_offset);
2199 kprintf("\tdata_offset = %08x\n", elm->leaf.data_offset);
2200 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2201 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);
2202 }
2203}