- It does not make sense to use "for (;cond;)", use "while (cond)" instead
[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 *
d5ef456e 34 * $DragonFly: src/sys/vfs/hammer/hammer_btree.c,v 1.25 2008/01/25 10:36:03 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 *
eaeff70d
MD
70 * SPIKES: Two leaf elements denoting a sub-range of keys may represent
71 * a spike, or a recursion into another cluster. Most standard B-Tree
b33e2cc0
MD
72 * searches traverse spikes. The ending spike element is range-inclusive
73 * and does not operate quite like a right-bound.
8cd0a023 74 *
fe7678ee
MD
75 * INSERTIONS: A search performed with the intention of doing
76 * an insert will guarantee that the terminal leaf node is not full by
77 * splitting full nodes. Splits occur top-down during the dive down the
78 * B-Tree.
79 *
80 * DELETIONS: A deletion makes no attempt to proactively balance the
81 * tree and will recursively remove nodes that become empty. Empty
82 * nodes are not allowed and a deletion may recurse upwards from the leaf.
83 * Rather then allow a deadlock a deletion may terminate early by setting
84 * an internal node's element's subtree_offset to 0. The deletion will
85 * then be resumed the next time a search encounters the element.
8cd0a023
MD
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);
46fe7ae1 94static int btree_remove(hammer_cursor_t cursor);
6a37e7e4 95static int btree_remove_deleted_element(hammer_cursor_t cursor);
7f7c1f84 96static int btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm);
9944ae54 97static int btree_node_is_almost_full(hammer_node_ondisk_t node);
fe7678ee 98static int btree_node_is_full(hammer_node_ondisk_t node);
8cd0a023
MD
99static void hammer_make_separator(hammer_base_elm_t key1,
100 hammer_base_elm_t key2, hammer_base_elm_t dest);
66325755
MD
101
102/*
8cd0a023
MD
103 * Iterate records after a search. The cursor is iterated forwards past
104 * the current record until a record matching the key-range requirements
105 * is found. ENOENT is returned if the iteration goes past the ending
6a37e7e4 106 * key.
66325755 107 *
d26d0ae9
MD
108 * The iteration is inclusive of key_beg and can be inclusive or exclusive
109 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
66325755 110 *
eaeff70d
MD
111 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
112 * and key_beg.delete_tid may be modified by B-Tree functions.
d5530d22 113 *
8cd0a023 114 * cursor->key_beg may or may not be modified by this function during
d26d0ae9
MD
115 * the iteration. XXX future - in case of an inverted lock we may have
116 * to reinitiate the lookup and set key_beg to properly pick up where we
117 * left off.
6a37e7e4
MD
118 *
119 * NOTE! EDEADLK *CANNOT* be returned by this procedure.
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) {
6a37e7e4 164 error = hammer_cursor_up(cursor);
8cd0a023
MD
165 if (error)
166 break;
46fe7ae1 167 /* reload stale pointer */
8cd0a023
MD
168 node = cursor->node->ondisk;
169 KKASSERT(cursor->index != node->count);
170 ++cursor->index;
171 continue;
66325755
MD
172 }
173
174 /*
d26d0ae9
MD
175 * Check internal or leaf element. Determine if the record
176 * at the cursor has gone beyond the end of our range.
66325755 177 *
d26d0ae9
MD
178 * Generally we recurse down through internal nodes. An
179 * internal node can only be returned if INCLUSTER is set
d5530d22 180 * and the node represents a cluster-push record.
66325755 181 */
8cd0a023
MD
182 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
183 elm = &node->elms[cursor->index];
d26d0ae9
MD
184 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
185 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
b3deaf57 186 if (hammer_debug_btree) {
eaeff70d
MD
187 kprintf("BRACKETL %d:%d:%08x[%d] %016llx %02x %016llx %d\n",
188 cursor->node->cluster->volume->vol_no,
189 cursor->node->cluster->clu_no,
190 cursor->node->node_offset,
191 cursor->index,
b3deaf57
MD
192 elm[0].internal.base.obj_id,
193 elm[0].internal.base.rec_type,
194 elm[0].internal.base.key,
195 r
196 );
eaeff70d
MD
197 kprintf("BRACKETR %d:%d:%08x[%d] %016llx %02x %016llx %d\n",
198 cursor->node->cluster->volume->vol_no,
199 cursor->node->cluster->clu_no,
200 cursor->node->node_offset,
201 cursor->index + 1,
b3deaf57
MD
202 elm[1].internal.base.obj_id,
203 elm[1].internal.base.rec_type,
204 elm[1].internal.base.key,
205 s
206 );
207 }
208
d26d0ae9
MD
209 if (r < 0) {
210 error = ENOENT;
211 break;
66325755 212 }
fe7678ee
MD
213 if (r == 0 && (cursor->flags &
214 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
d26d0ae9 215 error = ENOENT;
8cd0a023 216 break;
d26d0ae9
MD
217 }
218 KKASSERT(s <= 0);
6a37e7e4
MD
219
220 /*
221 * When iterating try to clean up any deleted
222 * internal elements left over from btree_remove()
223 * deadlocks, but it is ok if we can't.
224 */
46fe7ae1 225 if (elm->internal.subtree_offset == 0) {
6a37e7e4 226 btree_remove_deleted_element(cursor);
46fe7ae1
MD
227 /* note: elm also invalid */
228 } else if (elm->internal.subtree_offset != 0) {
6a37e7e4
MD
229 error = hammer_cursor_down(cursor);
230 if (error)
231 break;
232 KKASSERT(cursor->index == 0);
6a37e7e4 233 }
46fe7ae1
MD
234 /* reload stale pointer */
235 node = cursor->node->ondisk;
fe7678ee 236 continue;
d26d0ae9
MD
237 } else {
238 elm = &node->elms[cursor->index];
239 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
b3deaf57 240 if (hammer_debug_btree) {
eaeff70d
MD
241 kprintf("ELEMENT %d:%d:%08x:%d %c %016llx %02x %016llx %d\n",
242 cursor->node->cluster->volume->vol_no,
243 cursor->node->cluster->clu_no,
244 cursor->node->node_offset,
245 cursor->index,
246 (elm[0].leaf.base.btype ?
247 elm[0].leaf.base.btype : '?'),
b3deaf57
MD
248 elm[0].leaf.base.obj_id,
249 elm[0].leaf.base.rec_type,
250 elm[0].leaf.base.key,
251 r
252 );
253 }
d26d0ae9
MD
254 if (r < 0) {
255 error = ENOENT;
256 break;
257 }
b33e2cc0
MD
258
259 /*
260 * We support both end-inclusive and
261 * end-exclusive searches.
262 */
263 if (r == 0 &&
264 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
265 error = ENOENT;
266 break;
267 }
268
fe7678ee
MD
269 switch(elm->leaf.base.btype) {
270 case HAMMER_BTREE_TYPE_RECORD:
271 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
272 hammer_btree_chkts(cursor->asof, &elm->base)) {
273 ++cursor->index;
274 continue;
275 }
276 break;
277 case HAMMER_BTREE_TYPE_SPIKE_BEG:
eaeff70d 278 /*
eaeff70d
MD
279 * NOTE: This code assumes that the spike
280 * ending element immediately follows the
281 * spike beginning element.
282 */
fe7678ee
MD
283 /*
284 * We must cursor-down via the SPIKE_END
285 * element, otherwise cursor->parent will
286 * not be set correctly for deletions.
eaeff70d
MD
287 *
288 * fall-through to avoid an improper
289 * termination from the conditional above.
fe7678ee
MD
290 */
291 KKASSERT(cursor->index + 1 < node->count);
eaeff70d
MD
292 ++elm;
293 KKASSERT(elm->leaf.base.btype ==
294 HAMMER_BTREE_TYPE_SPIKE_END);
d26d0ae9 295 ++cursor->index;
fe7678ee
MD
296 /* fall through */
297 case HAMMER_BTREE_TYPE_SPIKE_END:
eaeff70d 298 /*
b33e2cc0
MD
299 * The SPIKE_END element is inclusive, NOT
300 * like a boundary, so be careful with the
301 * match check.
302 *
303 * This code assumes that a preceding SPIKE_BEG
304 * has already been checked.
eaeff70d 305 */
fe7678ee
MD
306 if (cursor->flags & HAMMER_CURSOR_INCLUSTER)
307 break;
308 error = hammer_cursor_down(cursor);
309 if (error)
310 break;
311 KKASSERT(cursor->index == 0);
46fe7ae1 312 /* reload stale pointer */
fe7678ee 313 node = cursor->node->ondisk;
46fe7ae1
MD
314
315 /*
316 * If the cluster root is empty it and its
317 * related spike can be deleted. Ignore
318 * errors. Cursor
319 */
320 if (node->count == 0) {
321 error = hammer_cursor_upgrade(cursor);
322 if (error == 0)
323 error = btree_remove(cursor);
324 hammer_cursor_downgrade(cursor);
325 error = 0;
326 /* reload stale pointer */
327 node = cursor->node->ondisk;
328 }
d26d0ae9 329 continue;
fe7678ee
MD
330 default:
331 error = EINVAL;
332 break;
d26d0ae9 333 }
fe7678ee
MD
334 if (error)
335 break;
66325755 336 }
46fe7ae1
MD
337 /*
338 * node pointer invalid after loop
339 */
66325755
MD
340
341 /*
d26d0ae9 342 * Return entry
66325755 343 */
b3deaf57
MD
344 if (hammer_debug_btree) {
345 int i = cursor->index;
346 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
347 kprintf("ITERATE %p:%d %016llx %02x %016llx\n",
348 cursor->node, i,
349 elm->internal.base.obj_id,
350 elm->internal.base.rec_type,
351 elm->internal.base.key
352 );
353 }
d26d0ae9 354 return(0);
427e5fc6 355 }
66325755 356 return(error);
427e5fc6
MD
357}
358
359/*
8cd0a023 360 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
6a37e7e4
MD
361 * could not be found, EDEADLK if inserting and a retry is needed, and a
362 * fatal error otherwise. When retrying, the caller must terminate the
eaeff70d 363 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
8cd0a023
MD
364 *
365 * The cursor is suitably positioned for a deletion on success, and suitably
eaeff70d
MD
366 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
367 * specified.
427e5fc6 368 *
8cd0a023
MD
369 * The cursor may begin anywhere, the search will traverse clusters in
370 * either direction to locate the requested element.
eaeff70d
MD
371 *
372 * Most of the logic implementing historical searches is handled here. We
373 * do an initial lookup with delete_tid set to the asof TID. Due to the
374 * way records are laid out, a forwards iteration may be required if
375 * ENOENT is returned to locate the historical record. Here's the
376 * problem:
377 *
378 * delete_tid: 10 15 20
379 * LEAF1 LEAF2
380 * records: (11) (18)
381 *
382 * Lets say we want to do a lookup AS-OF timestamp 12. We will traverse
383 * LEAF1 but the only record in LEAF1 has a termination (delete_tid) of 11,
384 * thus causing ENOENT to be returned. We really need to check record 18
385 * in LEAF2. If it also fails then the search fails (e.g. it might represent
386 * the range 14-18 and thus still not match our AS-OF timestamp of 12).
b33e2cc0
MD
387 *
388 * btree_search() will set HAMMER_CURSOR_DELETE_CHECK and the
389 * cursor->delete_check TID if an iteration might be needed. In the above
390 * example delete_check would be set to 15.
427e5fc6
MD
391 */
392int
8cd0a023 393hammer_btree_lookup(hammer_cursor_t cursor)
427e5fc6 394{
66325755
MD
395 int error;
396
d5530d22 397 if (cursor->flags & HAMMER_CURSOR_ASOF) {
eaeff70d 398 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
d5530d22 399 cursor->key_beg.delete_tid = cursor->asof;
eaeff70d 400 for (;;) {
b33e2cc0 401 cursor->flags &= ~HAMMER_CURSOR_DELETE_CHECK;
d5530d22 402 error = btree_search(cursor, 0);
b33e2cc0
MD
403 if (error != ENOENT ||
404 (cursor->flags & HAMMER_CURSOR_DELETE_CHECK) == 0) {
405 /*
406 * Stop if no error.
407 * Stop if error other then ENOENT.
408 * Stop if ENOENT and not special case.
409 */
eaeff70d
MD
410 break;
411 }
b33e2cc0 412 cursor->key_beg.delete_tid = cursor->delete_check;
eaeff70d
MD
413 /* loop */
414 }
d5530d22
MD
415 } else {
416 error = btree_search(cursor, 0);
417 }
8cd0a023
MD
418 if (error == 0 && cursor->flags)
419 error = hammer_btree_extract(cursor, cursor->flags);
66325755
MD
420 return(error);
421}
422
d26d0ae9
MD
423/*
424 * Execute the logic required to start an iteration. The first record
425 * located within the specified range is returned and iteration control
426 * flags are adjusted for successive hammer_btree_iterate() calls.
427 */
428int
429hammer_btree_first(hammer_cursor_t cursor)
430{
431 int error;
432
433 error = hammer_btree_lookup(cursor);
434 if (error == ENOENT) {
435 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
436 error = hammer_btree_iterate(cursor);
437 }
438 cursor->flags |= HAMMER_CURSOR_ATEDISK;
439 return(error);
440}
441
8cd0a023
MD
442/*
443 * Extract the record and/or data associated with the cursor's current
444 * position. Any prior record or data stored in the cursor is replaced.
445 * The cursor must be positioned at a leaf node.
446 *
d26d0ae9
MD
447 * NOTE: Most extractions occur at the leaf of the B-Tree. The only
448 * extraction allowed at an internal element is at a cluster-push.
449 * Cluster-push elements have records but no data.
8cd0a023 450 */
66325755 451int
8cd0a023 452hammer_btree_extract(hammer_cursor_t cursor, int flags)
66325755 453{
8cd0a023
MD
454 hammer_node_ondisk_t node;
455 hammer_btree_elm_t elm;
456 hammer_cluster_t cluster;
c0ade690 457 u_int64_t buf_type;
427e5fc6 458 int32_t cloff;
d26d0ae9 459 int32_t roff;
427e5fc6 460 int error;
427e5fc6 461
8cd0a023 462 /*
427e5fc6 463 * A cluster record type has no data reference, the information
8cd0a023 464 * is stored directly in the record and B-Tree element.
427e5fc6
MD
465 *
466 * The case where the data reference resolves to the same buffer
467 * as the record reference must be handled.
468 */
8cd0a023 469 node = cursor->node->ondisk;
8cd0a023
MD
470 elm = &node->elms[cursor->index];
471 cluster = cursor->node->cluster;
d26d0ae9
MD
472 cursor->flags &= ~HAMMER_CURSOR_DATA_EMBEDDED;
473 cursor->data = NULL;
66325755 474
d26d0ae9 475 /*
fe7678ee 476 * There is nothing to extract for an internal element.
d26d0ae9 477 */
fe7678ee
MD
478 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
479 return(EINVAL);
480
481 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
d26d0ae9
MD
482
483 /*
484 * Leaf element.
485 */
fe7678ee 486 if ((flags & HAMMER_CURSOR_GET_RECORD)) {
8cd0a023
MD
487 cloff = elm->leaf.rec_offset;
488 cursor->record = hammer_bread(cluster, cloff,
489 HAMMER_FSBUF_RECORDS, &error,
490 &cursor->record_buffer);
427e5fc6
MD
491 } else {
492 cloff = 0;
fe7678ee 493 error = 0;
427e5fc6 494 }
a89aec1b 495 if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
fe7678ee
MD
496 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD) {
497 /*
498 * Only records have data references. Spike elements
499 * do not.
500 */
501 cursor->data = NULL;
502 } else if ((cloff ^ elm->leaf.data_offset) & ~HAMMER_BUFMASK) {
8cd0a023 503 /*
c0ade690
MD
504 * The data is not in the same buffer as the last
505 * record we cached, but it could still be embedded
506 * in a record. Note that we may not have loaded the
507 * record's buffer above, depending on flags.
8cd0a023 508 */
c0ade690
MD
509 if ((elm->leaf.rec_offset ^ elm->leaf.data_offset) &
510 ~HAMMER_BUFMASK) {
511 if (elm->leaf.data_len & HAMMER_BUFMASK)
512 buf_type = HAMMER_FSBUF_DATA;
513 else
514 buf_type = 0; /* pure data buffer */
515 } else {
516 buf_type = HAMMER_FSBUF_RECORDS;
517 }
8cd0a023
MD
518 cursor->data = hammer_bread(cluster,
519 elm->leaf.data_offset,
c0ade690 520 buf_type, &error,
8cd0a023 521 &cursor->data_buffer);
427e5fc6 522 } else {
8cd0a023
MD
523 /*
524 * Data in same buffer as record. Note that we
525 * leave any existing data_buffer intact, even
526 * though we don't use it in this case, in case
527 * other records extracted during an iteration
528 * go back to it.
c0ade690 529 *
d26d0ae9
MD
530 * The data must be embedded in the record for this
531 * case to be hit.
532 *
c0ade690 533 * Just assume the buffer type is correct.
8cd0a023
MD
534 */
535 cursor->data = (void *)
536 ((char *)cursor->record_buffer->ondisk +
537 (elm->leaf.data_offset & HAMMER_BUFMASK));
d26d0ae9
MD
538 roff = (char *)cursor->data - (char *)cursor->record;
539 KKASSERT (roff >= 0 && roff < HAMMER_RECORD_SIZE);
540 cursor->flags |= HAMMER_CURSOR_DATA_EMBEDDED;
427e5fc6
MD
541 }
542 }
543 return(error);
544}
545
546
547/*
8cd0a023
MD
548 * Insert a leaf element into the B-Tree at the current cursor position.
549 * The cursor is positioned such that the element at and beyond the cursor
550 * are shifted to make room for the new record.
551 *
a89aec1b 552 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
8cd0a023
MD
553 * flag set and that call must return ENOENT before this function can be
554 * called.
555 *
556 * ENOSPC is returned if there is no room to insert a new record.
427e5fc6
MD
557 */
558int
8cd0a023 559hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
427e5fc6 560{
8cd0a023 561 hammer_node_ondisk_t node;
427e5fc6 562 int i;
6a37e7e4
MD
563 int error;
564
565 if ((error = hammer_cursor_upgrade(cursor)) != 0)
566 return(error);
427e5fc6 567
427e5fc6
MD
568 /*
569 * Insert the element at the leaf node and update the count in the
570 * parent. It is possible for parent to be NULL, indicating that
8cd0a023 571 * the root of the B-Tree in the cluster is a leaf. It is also
427e5fc6
MD
572 * possible for the leaf to be empty.
573 *
574 * Remember that the right-hand boundary is not included in the
575 * count.
576 */
0b075555 577 hammer_modify_node(cursor->node);
8cd0a023 578 node = cursor->node->ondisk;
427e5fc6 579 i = cursor->index;
fe7678ee 580 KKASSERT(elm->base.btype != 0);
8cd0a023
MD
581 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
582 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
583 if (i != node->count) {
584 bcopy(&node->elms[i], &node->elms[i+1],
585 (node->count - i) * sizeof(*elm));
586 }
587 node->elms[i] = *elm;
588 ++node->count;
427e5fc6 589
eaeff70d
MD
590 /*
591 * Debugging sanity checks. Note that the element to the left
592 * can match the element we are inserting if it is a SPIKE_END,
593 * because spike-end's represent a non-inclusive end to a range.
594 */
b3deaf57
MD
595 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
596 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
eaeff70d 597 if (i) {
b33e2cc0 598 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->leaf.base) < 0);
eaeff70d 599 }
b3deaf57
MD
600 if (i != node->count - 1)
601 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->leaf.base) > 0);
602
427e5fc6
MD
603 return(0);
604}
605
9944ae54 606/*
eaeff70d
MD
607 * Insert a cluster spike into the B-Tree at the current cursor position.
608 * The caller pre-positions the insertion cursor at ncluster's
609 * left bound in the originating cluster. Both the originating cluster
610 * and the target cluster must be serialized, EDEADLK is fatal.
9944ae54 611 *
eaeff70d
MD
612 * Basically we have to lay down the two spike elements and assert that
613 * the leaf's right bound does not bisect the ending element. The ending
b33e2cc0
MD
614 * spike element is non-inclusive, just like a boundary. The target cluster's
615 * clu_btree_parent_offset may have to adjusted.
9944ae54 616 *
eaeff70d
MD
617 * NOTE: Serialization is usually accoplished by virtue of being the
618 * initial accessor of a cluster.
9944ae54
MD
619 */
620int
621hammer_btree_insert_cluster(hammer_cursor_t cursor, hammer_cluster_t ncluster,
622 int32_t rec_offset)
623{
9944ae54 624 hammer_node_ondisk_t node;
9944ae54 625 hammer_btree_elm_t elm;
b33e2cc0 626 hammer_cluster_t ocluster;
9944ae54 627 const int esize = sizeof(*elm);
6a37e7e4 628 int error;
eaeff70d 629 int i;
b33e2cc0 630 int32_t node_offset;
9944ae54 631
6a37e7e4
MD
632 if ((error = hammer_cursor_upgrade(cursor)) != 0)
633 return(error);
9944ae54
MD
634 hammer_modify_node(cursor->node);
635 node = cursor->node->ondisk;
b33e2cc0 636 node_offset = cursor->node->node_offset;
9944ae54 637 i = cursor->index;
eaeff70d 638
9944ae54 639 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
eaeff70d
MD
640 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS - 2);
641 KKASSERT(i >= 0 && i <= node->count);
9944ae54
MD
642
643 /*
644 * Make sure the spike is legal or the B-Tree code will get really
645 * confused.
eaeff70d
MD
646 *
647 * XXX the right bound my bisect the two spike elements. We
648 * need code here to 'fix' the right bound going up the tree
649 * instead of an assertion.
9944ae54
MD
650 */
651 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_beg,
652 cursor->left_bound) >= 0);
653 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
654 cursor->right_bound) <= 0);
655 if (i != node->count) {
656 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
657 &node->elms[i].leaf.base) <= 0);
658 }
659
eaeff70d
MD
660 elm = &node->elms[i];
661 bcopy(elm, elm + 2, (node->count - i) * esize);
662 bzero(elm, 2 * esize);
663 node->count += 2;
9944ae54 664
eaeff70d
MD
665 elm[0].leaf.base = ncluster->ondisk->clu_btree_beg;
666 elm[0].leaf.base.btype = HAMMER_BTREE_TYPE_SPIKE_BEG;
b33e2cc0 667 elm[0].leaf.rec_offset = rec_offset;
eaeff70d
MD
668 elm[0].leaf.spike_clu_no = ncluster->clu_no;
669 elm[0].leaf.spike_vol_no = ncluster->volume->vol_no;
9944ae54 670
eaeff70d
MD
671 elm[1].leaf.base = ncluster->ondisk->clu_btree_end;
672 elm[1].leaf.base.btype = HAMMER_BTREE_TYPE_SPIKE_END;
b33e2cc0 673 elm[1].leaf.rec_offset = rec_offset;
eaeff70d
MD
674 elm[1].leaf.spike_clu_no = ncluster->clu_no;
675 elm[1].leaf.spike_vol_no = ncluster->volume->vol_no;
b33e2cc0
MD
676
677 /*
678 * SPIKE_END must be inclusive, not exclusive.
679 */
680 KKASSERT(elm[1].leaf.base.delete_tid != 1);
681 --elm[1].leaf.base.delete_tid;
682
683 /*
684 * The target cluster's parent offset may have to be updated.
685 *
686 * NOTE: Modifying a cluster header does not mark it open, and
687 * flushing it will only clear an existing open flag if the cluster
688 * has been validated.
689 */
d5ef456e
MD
690 if (hammer_debug_general & 0x40) {
691 kprintf("INSERT CLUSTER %d:%d -> %d:%d ",
692 ncluster->ondisk->clu_btree_parent_vol_no,
693 ncluster->ondisk->clu_btree_parent_clu_no,
694 ncluster->volume->vol_no,
695 ncluster->clu_no);
696 }
b33e2cc0
MD
697
698 ocluster = cursor->node->cluster;
699 if (ncluster->ondisk->clu_btree_parent_offset != node_offset ||
700 ncluster->ondisk->clu_btree_parent_clu_no != ocluster->clu_no ||
701 ncluster->ondisk->clu_btree_parent_vol_no != ocluster->volume->vol_no) {
702 hammer_modify_cluster(ncluster);
703 ncluster->ondisk->clu_btree_parent_offset = node_offset;
704 ncluster->ondisk->clu_btree_parent_clu_no = ocluster->clu_no;
705 ncluster->ondisk->clu_btree_parent_vol_no = ocluster->volume->vol_no;
d5ef456e
MD
706 if (hammer_debug_general & 0x40)
707 kprintf("(offset fixup)\n");
b33e2cc0 708 } else {
d5ef456e
MD
709 if (hammer_debug_general & 0x40)
710 kprintf("(offset unchanged)\n");
b33e2cc0
MD
711 }
712
9944ae54
MD
713 return(0);
714}
715
427e5fc6 716/*
fe7678ee 717 * Delete a record from the B-Tree at the current cursor position.
8cd0a023
MD
718 * The cursor is positioned such that the current element is the one
719 * to be deleted.
720 *
195c19a1
MD
721 * On return the cursor will be positioned after the deleted element and
722 * MAY point to an internal node. It will be suitable for the continuation
723 * of an iteration but not for an insertion or deletion.
8cd0a023 724 *
195c19a1 725 * Deletions will attempt to partially rebalance the B-Tree in an upward
fe7678ee
MD
726 * direction, but will terminate rather then deadlock. Empty leaves are
727 * not allowed except at the root node of a cluster. An early termination
728 * will leave an internal node with an element whos subtree_offset is 0,
729 * a case detected and handled by btree_search().
46fe7ae1
MD
730 *
731 * This function can return EDEADLK, requiring the caller to retry the
732 * operation after clearing the deadlock.
427e5fc6
MD
733 */
734int
8cd0a023 735hammer_btree_delete(hammer_cursor_t cursor)
427e5fc6 736{
8cd0a023
MD
737 hammer_node_ondisk_t ondisk;
738 hammer_node_t node;
739 hammer_node_t parent;
8cd0a023 740 int error;
427e5fc6
MD
741 int i;
742
6a37e7e4
MD
743 if ((error = hammer_cursor_upgrade(cursor)) != 0)
744 return(error);
745
427e5fc6 746 /*
8cd0a023 747 * Delete the element from the leaf node.
427e5fc6 748 *
8cd0a023 749 * Remember that leaf nodes do not have boundaries.
427e5fc6 750 */
8cd0a023
MD
751 node = cursor->node;
752 ondisk = node->ondisk;
427e5fc6
MD
753 i = cursor->index;
754
8cd0a023 755 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
fe7678ee 756 KKASSERT(i >= 0 && i < ondisk->count);
0b075555 757 hammer_modify_node(node);
8cd0a023
MD
758 if (i + 1 != ondisk->count) {
759 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
760 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
761 }
762 --ondisk->count;
fe7678ee
MD
763
764 /*
765 * Validate local parent
766 */
767 if (ondisk->parent) {
8cd0a023 768 parent = cursor->parent;
fe7678ee
MD
769
770 KKASSERT(parent != NULL);
771 KKASSERT(parent->node_offset == ondisk->parent);
772 KKASSERT(parent->cluster == node->cluster);
427e5fc6 773 }
427e5fc6 774
8cd0a023 775 /*
fe7678ee
MD
776 * If the leaf becomes empty it must be detached from the parent,
777 * potentially recursing through to the cluster root.
195c19a1
MD
778 *
779 * This may reposition the cursor at one of the parent's of the
780 * current node.
6a37e7e4
MD
781 *
782 * Ignore deadlock errors, that simply means that btree_remove
783 * was unable to recurse and had to leave the subtree_offset
784 * in the parent set to 0.
8cd0a023 785 */
b3deaf57 786 KKASSERT(cursor->index <= ondisk->count);
8cd0a023 787 if (ondisk->count == 0) {
fe7678ee 788 do {
46fe7ae1 789 error = btree_remove(cursor);
fe7678ee 790 } while (error == EAGAIN);
6a37e7e4
MD
791 if (error == EDEADLK)
792 error = 0;
8cd0a023 793 } else {
8cd0a023
MD
794 error = 0;
795 }
eaeff70d
MD
796 KKASSERT(cursor->parent == NULL ||
797 cursor->parent_index < cursor->parent->ondisk->count);
8cd0a023
MD
798 return(error);
799}
427e5fc6
MD
800
801/*
8cd0a023
MD
802 * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
803 *
804 * Search a cluster's B-Tree for cursor->key_beg, return the matching node.
805 *
d26d0ae9
MD
806 * The search can begin ANYWHERE in the B-Tree. As a first step the search
807 * iterates up the tree as necessary to properly position itself prior to
808 * actually doing the sarch.
809 *
8cd0a023 810 * INSERTIONS: The search will split full nodes and leaves on its way down
d26d0ae9
MD
811 * and guarentee that the leaf it ends up on is not full. If we run out
812 * of space the search continues to the leaf (to position the cursor for
813 * the spike), but ENOSPC is returned.
427e5fc6 814 *
fbc6e32a
MD
815 * The search is only guarenteed to end up on a leaf if an error code of 0
816 * is returned, or if inserting and an error code of ENOENT is returned.
d26d0ae9
MD
817 * Otherwise it can stop at an internal node. On success a search returns
818 * a leaf node unless INCLUSTER is set and the search located a cluster push
819 * node (which is an internal node).
eaeff70d
MD
820 *
821 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
822 * filesystem, and it is not simple code. Please note the following facts:
823 *
824 * - Internal node recursions have a boundary on the left AND right. The
825 * right boundary is non-inclusive. The delete_tid is a generic part
826 * of the key for internal nodes.
827 *
828 * - Leaf nodes contain terminal elements AND spikes. A spike recurses into
829 * another cluster and contains two leaf elements.. a beginning and an
830 * ending element. The SPIKE_END element is RANGE-EXCLUSIVE, just like a
831 * boundary. This means that it is possible to have two elements
832 * (a spike ending element and a record) side by side with the same key.
833 *
b33e2cc0 834 * - Because the SPIKE_END element is range inclusive, it cannot match the
eaeff70d
MD
835 * right boundary of the parent node. SPIKE_BEG and SPIKE_END elements
836 * always come in pairs, and always exist side by side in the same leaf.
837 *
838 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
b33e2cc0
MD
839 * historical search. ASOF and INSERT are mutually exclusive. When
840 * doing an as-of lookup btree_search() checks for a right-edge boundary
841 * case. If while recursing down the right-edge differs from the key
842 * by ONLY its delete_tid, HAMMER_CURSOR_DELETE_CHECK is set along
843 * with cursor->delete_check. This is used by btree_lookup() to iterate.
844 * The iteration is necessary because as-of searches can wind up going
845 * down the wrong branch of the B-Tree.
427e5fc6 846 */
8cd0a023 847static
427e5fc6 848int
8cd0a023 849btree_search(hammer_cursor_t cursor, int flags)
427e5fc6 850{
8cd0a023
MD
851 hammer_node_ondisk_t node;
852 hammer_cluster_t cluster;
61aeeb33 853 hammer_btree_elm_t elm;
8cd0a023 854 int error;
d26d0ae9 855 int enospc = 0;
8cd0a023
MD
856 int i;
857 int r;
b33e2cc0 858 int s;
8cd0a023
MD
859
860 flags |= cursor->flags;
861
b3deaf57 862 if (hammer_debug_btree) {
eaeff70d
MD
863 kprintf("SEARCH %d:%d:%08x[%d] %016llx %02x key=%016llx did=%016llx\n",
864 cursor->node->cluster->volume->vol_no,
865 cursor->node->cluster->clu_no,
866 cursor->node->node_offset,
867 cursor->index,
b3deaf57
MD
868 cursor->key_beg.obj_id,
869 cursor->key_beg.rec_type,
d113fda1 870 cursor->key_beg.key,
d5530d22 871 cursor->key_beg.delete_tid
b3deaf57
MD
872 );
873 }
874
8cd0a023
MD
875 /*
876 * Move our cursor up the tree until we find a node whos range covers
877 * the key we are trying to locate. This may move us between
878 * clusters.
879 *
880 * The left bound is inclusive, the right bound is non-inclusive.
881 * It is ok to cursor up too far so when cursoring across a cluster
882 * boundary.
883 *
884 * First see if we can skip the whole cluster. hammer_cursor_up()
885 * handles both cases but this way we don't check the cluster
886 * bounds when going up the tree within a cluster.
d26d0ae9
MD
887 *
888 * NOTE: If INCLUSTER is set and we are at the root of the cluster,
889 * hammer_cursor_up() will return ENOENT.
8cd0a023
MD
890 */
891 cluster = cursor->node->cluster;
b33e2cc0
MD
892 for (;;) {
893 r = hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_beg);
894 s = hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_end);
895
896 if (r >= 0 && s < 0)
897 break;
8cd0a023
MD
898 error = hammer_cursor_toroot(cursor);
899 if (error)
900 goto done;
9944ae54 901 KKASSERT(cursor->parent);
6a37e7e4 902 error = hammer_cursor_up(cursor);
8cd0a023
MD
903 if (error)
904 goto done;
905 cluster = cursor->node->cluster;
427e5fc6 906 }
b33e2cc0
MD
907 for (;;) {
908 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
909 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
910 if (r >= 0 && s < 0)
911 break;
9944ae54 912 KKASSERT(cursor->parent);
6a37e7e4 913 error = hammer_cursor_up(cursor);
8cd0a023
MD
914 if (error)
915 goto done;
427e5fc6 916 }
427e5fc6 917
b33e2cc0
MD
918 /*
919 * The delete-checks below are based on node, not parent. Set the
920 * initial delete-check based on the parent.
921 */
922 if (s == -1) {
923 cursor->delete_check = cursor->right_bound->delete_tid;
924 cursor->flags |= HAMMER_CURSOR_DELETE_CHECK;
925 }
926
8cd0a023
MD
927 /*
928 * We better have ended up with a node somewhere, and our second
929 * while loop had better not have traversed up a cluster.
930 */
931 KKASSERT(cursor->node != NULL && cursor->node->cluster == cluster);
932
933 /*
934 * If we are inserting we can't start at a full node if the parent
935 * is also full (because there is no way to split the node),
b33e2cc0
MD
936 * continue running up the tree until the requirement is satisfied
937 * or we hit the root of the current cluster.
8cd0a023 938 */
61aeeb33 939 while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
eaeff70d
MD
940 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
941 if (btree_node_is_full(cursor->node->ondisk) == 0)
942 break;
943 } else {
944 if (btree_node_is_almost_full(cursor->node->ondisk) ==0)
945 break;
946 }
b33e2cc0
MD
947 if (cursor->node->ondisk->parent == 0 ||
948 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
8cd0a023 949 break;
b33e2cc0 950 }
6a37e7e4 951 error = hammer_cursor_up(cursor);
8cd0a023
MD
952 /* cluster and node are now may become stale */
953 if (error)
954 goto done;
427e5fc6 955 }
8cd0a023 956 /* cluster = cursor->node->cluster; not needed until next cluster = */
427e5fc6 957
fe7678ee 958new_cluster:
8cd0a023
MD
959 /*
960 * Push down through internal nodes to locate the requested key.
961 */
962 cluster = cursor->node->cluster;
963 node = cursor->node->ondisk;
964 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
8cd0a023
MD
965 /*
966 * Scan the node to find the subtree index to push down into.
fbc6e32a 967 * We go one-past, then back-up.
d113fda1 968 *
fe7678ee
MD
969 * We must proactively remove deleted elements which may
970 * have been left over from a deadlocked btree_remove().
971 *
eaeff70d 972 * The left and right boundaries are included in the loop
d5530d22 973 * in order to detect edge cases.
9944ae54 974 *
d5530d22 975 * If the separator only differs by delete_tid (r == -1)
eaeff70d
MD
976 * and we are doing an as-of search, we may end up going
977 * down a branch to the left of the one containing the
978 * desired key. This requires numerous special cases.
8cd0a023 979 */
46fe7ae1
MD
980 if (hammer_debug_btree) {
981 kprintf("SEARCH-I %d:%d:%08x count=%d\n",
982 cursor->node->cluster->volume->vol_no,
983 cursor->node->cluster->clu_no,
984 cursor->node->node_offset,
985 node->count);
986 }
9944ae54 987 for (i = 0; i <= node->count; ++i) {
61aeeb33
MD
988 elm = &node->elms[i];
989 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
b33e2cc0
MD
990 if (hammer_debug_btree > 2) {
991 kprintf(" IELM %p %d r=%d\n",
992 &node->elms[i], i, r);
993 }
994 if (r < 0) {
995 if (r == -1) {
996 cursor->delete_check =
997 elm->base.delete_tid;
998 cursor->flags |=
999 HAMMER_CURSOR_DELETE_CHECK;
1000 }
8cd0a023 1001 break;
b33e2cc0 1002 }
8cd0a023 1003 }
eaeff70d 1004 if (hammer_debug_btree) {
46fe7ae1
MD
1005 kprintf("SEARCH-I preI=%d/%d r=%d\n",
1006 i, node->count, r);
eaeff70d 1007 }
8cd0a023
MD
1008
1009 /*
9944ae54
MD
1010 * These cases occur when the parent's idea of the boundary
1011 * is wider then the child's idea of the boundary, and
1012 * require special handling. If not inserting we can
1013 * terminate the search early for these cases but the
1014 * child's boundaries cannot be unconditionally modified.
8cd0a023 1015 */
fbc6e32a 1016 if (i == 0) {
9944ae54
MD
1017 /*
1018 * If i == 0 the search terminated to the LEFT of the
1019 * left_boundary but to the RIGHT of the parent's left
1020 * boundary.
1021 */
fbc6e32a 1022 u_int8_t save;
d26d0ae9 1023
eaeff70d
MD
1024 elm = &node->elms[0];
1025
1026 /*
1027 * If we aren't inserting we can stop here.
1028 */
fbc6e32a
MD
1029 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1030 cursor->index = 0;
1031 return(ENOENT);
1032 }
9944ae54 1033
d5530d22
MD
1034 /*
1035 * Correct a left-hand boundary mismatch.
6a37e7e4 1036 *
eaeff70d 1037 * We can only do this if we can upgrade the lock.
d5530d22 1038 */
eaeff70d
MD
1039 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1040 return(error);
d5530d22 1041 hammer_modify_node(cursor->node);
fe7678ee 1042 save = node->elms[0].base.btype;
d5530d22 1043 node->elms[0].base = *cursor->left_bound;
fe7678ee 1044 node->elms[0].base.btype = save;
9944ae54 1045 } else if (i == node->count + 1) {
d26d0ae9 1046 /*
9944ae54
MD
1047 * If i == node->count + 1 the search terminated to
1048 * the RIGHT of the right boundary but to the LEFT
eaeff70d
MD
1049 * of the parent's right boundary. If we aren't
1050 * inserting we can stop here.
d113fda1 1051 *
9944ae54
MD
1052 * Note that the last element in this case is
1053 * elms[i-2] prior to adjustments to 'i'.
d26d0ae9 1054 */
9944ae54 1055 --i;
d113fda1 1056 if ((flags & HAMMER_CURSOR_INSERT) == 0) {
9944ae54 1057 cursor->index = i;
eaeff70d 1058 return (ENOENT);
d26d0ae9
MD
1059 }
1060
d5530d22
MD
1061 /*
1062 * Correct a right-hand boundary mismatch.
1063 * (actual push-down record is i-2 prior to
1064 * adjustments to i).
6a37e7e4 1065 *
eaeff70d 1066 * We can only do this if we can upgrade the lock.
d5530d22 1067 */
eaeff70d
MD
1068 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1069 return(error);
9944ae54 1070 elm = &node->elms[i];
d5530d22
MD
1071 hammer_modify_node(cursor->node);
1072 elm->base = *cursor->right_bound;
1073 --i;
fbc6e32a
MD
1074 } else {
1075 /*
9944ae54
MD
1076 * The push-down index is now i - 1. If we had
1077 * terminated on the right boundary this will point
1078 * us at the last element.
fbc6e32a
MD
1079 */
1080 --i;
1081 }
8cd0a023 1082 cursor->index = i;
6a37e7e4 1083 elm = &node->elms[i];
8cd0a023 1084
b3deaf57 1085 if (hammer_debug_btree) {
46fe7ae1
MD
1086 kprintf("RESULT-I %d:%d:%08x[%d] %016llx %02x "
1087 "key=%016llx did=%016llx\n",
eaeff70d
MD
1088 cursor->node->cluster->volume->vol_no,
1089 cursor->node->cluster->clu_no,
1090 cursor->node->node_offset,
1091 i,
b3deaf57
MD
1092 elm->internal.base.obj_id,
1093 elm->internal.base.rec_type,
d113fda1 1094 elm->internal.base.key,
d5530d22 1095 elm->internal.base.delete_tid
b3deaf57
MD
1096 );
1097 }
1098
6a37e7e4
MD
1099 /*
1100 * When searching try to clean up any deleted
1101 * internal elements left over from btree_remove()
1102 * deadlocks.
1103 *
1104 * If we fail and we are doing an insertion lookup,
1105 * we have to return EDEADLK, because an insertion lookup
1106 * must terminate at a leaf.
1107 */
1108 if (elm->internal.subtree_offset == 0) {
1109 error = btree_remove_deleted_element(cursor);
1110 if (error == 0)
1111 goto new_cluster;
eaeff70d
MD
1112 if (error == EDEADLK &&
1113 (flags & HAMMER_CURSOR_INSERT) == 0) {
1114 error = ENOENT;
1115 }
1116 return(error);
6a37e7e4
MD
1117 }
1118
1119
8cd0a023
MD
1120 /*
1121 * Handle insertion and deletion requirements.
1122 *
1123 * If inserting split full nodes. The split code will
1124 * adjust cursor->node and cursor->index if the current
1125 * index winds up in the new node.
61aeeb33 1126 *
9944ae54
MD
1127 * If inserting and a left or right edge case was detected,
1128 * we cannot correct the left or right boundary and must
1129 * prepend and append an empty leaf node in order to make
1130 * the boundary correction.
1131 *
61aeeb33
MD
1132 * If we run out of space we set enospc and continue on
1133 * to a leaf to provide the spike code with a good point
1134 * of entry. Enospc is reset if we cross a cluster boundary.
8cd0a023 1135 */
61aeeb33 1136 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
fe7678ee 1137 if (btree_node_is_full(node)) {
8cd0a023 1138 error = btree_split_internal(cursor);
d26d0ae9
MD
1139 if (error) {
1140 if (error != ENOSPC)
1141 goto done;
1142 enospc = 1;
d26d0ae9 1143 }
8cd0a023
MD
1144 /*
1145 * reload stale pointers
1146 */
1147 i = cursor->index;
1148 node = cursor->node->ondisk;
1149 }
d26d0ae9 1150 }
427e5fc6
MD
1151
1152 /*
8cd0a023 1153 * Push down (push into new node, existing node becomes
d26d0ae9 1154 * the parent) and continue the search.
427e5fc6 1155 */
8cd0a023
MD
1156 error = hammer_cursor_down(cursor);
1157 /* node and cluster become stale */
1158 if (error)
1159 goto done;
1160 node = cursor->node->ondisk;
1161 cluster = cursor->node->cluster;
427e5fc6 1162 }
427e5fc6 1163
8cd0a023
MD
1164 /*
1165 * We are at a leaf, do a linear search of the key array.
d26d0ae9 1166 *
fe7678ee 1167 * If we encounter a spike element type within the necessary
eaeff70d
MD
1168 * range we push into it. Note that SPIKE_END is non-inclusive
1169 * of the spike range.
fe7678ee 1170 *
d26d0ae9
MD
1171 * On success the index is set to the matching element and 0
1172 * is returned.
1173 *
1174 * On failure the index is set to the insertion point and ENOENT
1175 * is returned.
8cd0a023
MD
1176 *
1177 * Boundaries are not stored in leaf nodes, so the index can wind
1178 * up to the left of element 0 (index == 0) or past the end of
1179 * the array (index == node->count).
1180 */
fe7678ee 1181 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
8cd0a023 1182 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
46fe7ae1
MD
1183 if (hammer_debug_btree) {
1184 kprintf("SEARCH-L %d:%d:%08x count=%d\n",
1185 cursor->node->cluster->volume->vol_no,
1186 cursor->node->cluster->clu_no,
1187 cursor->node->node_offset,
1188 node->count);
1189 }
8cd0a023
MD
1190
1191 for (i = 0; i < node->count; ++i) {
fe7678ee
MD
1192 elm = &node->elms[i];
1193
1194 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
427e5fc6 1195
d5530d22
MD
1196 if (hammer_debug_btree > 1)
1197 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1198
fe7678ee
MD
1199 if (elm->leaf.base.btype == HAMMER_BTREE_TYPE_SPIKE_BEG) {
1200 /*
1201 * SPIKE_BEG. Stop if we are to the left of the
1202 * spike begin element.
1203 *
1204 * If we are not the last element in the leaf continue
1205 * the loop looking for the SPIKE_END. If we are
1206 * the last element, however, then push into the
1207 * spike.
1208 *
eaeff70d
MD
1209 * If doing an as-of search a Spike demark on a
1210 * delete_tid boundary must be pushed into and an
1211 * iteration will be forced if it turned out to be
1212 * the wrong choice.
1213 *
1214 * If not doing an as-of search exact comparisons
1215 * must be used.
fe7678ee
MD
1216 *
1217 * enospc must be reset because we have crossed a
1218 * cluster boundary.
1219 */
b33e2cc0
MD
1220 if (r < 0) {
1221 /*
1222 * Set the delete check if the stop element
1223 * only differs by its delete_tid.
1224 */
1225 if (r == -1) {
1226 cursor->delete_check =
1227 elm->base.delete_tid;
1228 cursor->flags |=
1229 HAMMER_CURSOR_DELETE_CHECK;
1230 }
fe7678ee 1231 goto failed;
b33e2cc0 1232 }
fe7678ee
MD
1233 if (i != node->count - 1)
1234 continue;
1235 panic("btree_search: illegal spike, no SPIKE_END "
1236 "in leaf node! %p\n", cursor->node);
eaeff70d 1237#if 0
fe7678ee
MD
1238 /*
1239 * XXX This is not currently legal, you can only
1240 * cursor_down() from a SPIKE_END element, otherwise
1241 * the cursor parent is pointing at the wrong element
1242 * for deletions.
1243 */
eaeff70d 1244 if (flags & HAMMER_CURSOR_INCLUSTER)
fe7678ee
MD
1245 goto success;
1246 cursor->index = i;
1247 error = hammer_cursor_down(cursor);
1248 enospc = 0;
1249 if (error)
1250 goto done;
1251 goto new_cluster;
eaeff70d 1252#endif
fe7678ee
MD
1253 }
1254 if (elm->leaf.base.btype == HAMMER_BTREE_TYPE_SPIKE_END) {
1255 /*
1256 * SPIKE_END. We can only hit this case if we are
1257 * greater or equal to SPIKE_BEG.
1258 *
b33e2cc0 1259 * If we are <= SPIKE_END we must push into
eaeff70d 1260 * it, otherwise continue the search. The SPIKE_END
b33e2cc0 1261 * element is range-inclusive.
fe7678ee
MD
1262 *
1263 * enospc must be reset because we have crossed a
1264 * cluster boundary.
1265 */
b33e2cc0 1266 if (r > 0)
fe7678ee 1267 continue;
b33e2cc0
MD
1268
1269 /*
1270 * We're trying to recurse, set the delete check
1271 * if the right boundary only differs by its
1272 * delete_tid and delete_tid is not 0. Remember
1273 * the spike_end is inclusive, so we have to set
1274 * delete_check one past. A delete_tid of 0
1275 * represents infinity and cannot be incremented.
46fe7ae1
MD
1276 *
1277 * We also have to set it for an exact match,
1278 * because the SPIKE_END is still an (inclusive)
1279 * boundary, not a match.
b33e2cc0 1280 */
46fe7ae1 1281 if ((r == 0 || r == -1) && elm->base.delete_tid != 0) {
b33e2cc0
MD
1282 cursor->delete_check = elm->base.delete_tid + 1;
1283 cursor->flags |= HAMMER_CURSOR_DELETE_CHECK;
1284 }
eaeff70d 1285 if (flags & HAMMER_CURSOR_INCLUSTER)
fe7678ee
MD
1286 goto success;
1287 cursor->index = i;
1288 error = hammer_cursor_down(cursor);
1289 enospc = 0;
1290 if (error)
1291 goto done;
1292 goto new_cluster;
1293 }
1294
427e5fc6 1295 /*
fe7678ee
MD
1296 * We are at a record element. Stop if we've flipped past
1297 * key_beg, not counting the delete_tid test.
427e5fc6 1298 */
fe7678ee
MD
1299 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1300
d5530d22
MD
1301 if (r < -1)
1302 goto failed;
fe7678ee 1303 if (r > 0)
d5530d22 1304 continue;
427e5fc6 1305
66325755 1306 /*
eaeff70d
MD
1307 * Check our as-of timestamp against the element. A
1308 * delete_tid that matches exactly in an as-of search
1309 * is actually a no-match (the record was deleted as-of
1310 * our timestamp so it isn't visible).
66325755 1311 */
eaeff70d 1312 if (flags & HAMMER_CURSOR_ASOF) {
fe7678ee 1313 if (hammer_btree_chkts(cursor->asof,
d113fda1
MD
1314 &node->elms[i].base) != 0) {
1315 continue;
1316 }
eaeff70d
MD
1317 /* success */
1318 } else {
1319 if (r < 0) /* can only be -1 */
1320 goto failed;
1321 /* success */
66325755 1322 }
fe7678ee 1323success:
d5530d22
MD
1324 cursor->index = i;
1325 error = 0;
eaeff70d 1326 if (hammer_debug_btree) {
46fe7ae1 1327 kprintf("RESULT-L %d:%d:%08x[%d] (SUCCESS)\n",
eaeff70d
MD
1328 cursor->node->cluster->volume->vol_no,
1329 cursor->node->cluster->clu_no,
1330 cursor->node->node_offset,
1331 i);
1332 }
d5530d22
MD
1333 goto done;
1334 }
1335
1336 /*
eaeff70d 1337 * The search of the leaf node failed. i is the insertion point.
d5530d22 1338 */
d5530d22 1339failed:
b3deaf57 1340 if (hammer_debug_btree) {
46fe7ae1 1341 kprintf("RESULT-L %d:%d:%08x[%d] (FAILED)\n",
eaeff70d
MD
1342 cursor->node->cluster->volume->vol_no,
1343 cursor->node->cluster->clu_no,
1344 cursor->node->node_offset,
1345 i);
b3deaf57
MD
1346 }
1347
8cd0a023
MD
1348 /*
1349 * No exact match was found, i is now at the insertion point.
1350 *
1351 * If inserting split a full leaf before returning. This
1352 * may have the side effect of adjusting cursor->node and
1353 * cursor->index.
eaeff70d
MD
1354 *
1355 * For now the leaf must have at least 2 free elements to accomodate
1356 * the insertion of a spike during recovery. See the
1357 * hammer_btree_insert_cluster() function.
8cd0a023
MD
1358 */
1359 cursor->index = i;
eaeff70d
MD
1360 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
1361 btree_node_is_almost_full(node)) {
8cd0a023 1362 error = btree_split_leaf(cursor);
d26d0ae9
MD
1363 if (error) {
1364 if (error != ENOSPC)
1365 goto done;
1366 enospc = 1;
d26d0ae9
MD
1367 }
1368 /*
1369 * reload stale pointers
1370 */
8cd0a023
MD
1371 /* NOT USED
1372 i = cursor->index;
1373 node = &cursor->node->internal;
1374 */
8cd0a023 1375 }
d26d0ae9
MD
1376
1377 /*
1378 * We reached a leaf but did not find the key we were looking for.
1379 * If this is an insert we will be properly positioned for an insert
1380 * (ENOENT) or spike (ENOSPC) operation.
1381 */
1382 error = enospc ? ENOSPC : ENOENT;
8cd0a023 1383done:
427e5fc6
MD
1384 return(error);
1385}
1386
8cd0a023 1387
427e5fc6 1388/************************************************************************
8cd0a023 1389 * SPLITTING AND MERGING *
427e5fc6
MD
1390 ************************************************************************
1391 *
1392 * These routines do all the dirty work required to split and merge nodes.
1393 */
1394
1395/*
8cd0a023 1396 * Split an internal node into two nodes and move the separator at the split
fe7678ee 1397 * point to the parent.
427e5fc6 1398 *
8cd0a023
MD
1399 * (cursor->node, cursor->index) indicates the element the caller intends
1400 * to push into. We will adjust node and index if that element winds
427e5fc6 1401 * up in the split node.
8cd0a023
MD
1402 *
1403 * If we are at the root of a cluster a new root must be created with two
1404 * elements, one pointing to the original root and one pointing to the
1405 * newly allocated split node.
1406 *
1407 * NOTE! Being at the root of a cluster is different from being at the
1408 * root of the root cluster. cursor->parent will not be NULL and
1409 * cursor->node->ondisk.parent must be tested against 0. Theoretically
1410 * we could propogate the algorithm into the parent and deal with multiple
1411 * 'roots' in the cluster header, but it's easier not to.
427e5fc6
MD
1412 */
1413static
1414int
8cd0a023 1415btree_split_internal(hammer_cursor_t cursor)
427e5fc6 1416{
8cd0a023
MD
1417 hammer_node_ondisk_t ondisk;
1418 hammer_node_t node;
1419 hammer_node_t parent;
1420 hammer_node_t new_node;
1421 hammer_btree_elm_t elm;
1422 hammer_btree_elm_t parent_elm;
b33e2cc0 1423 hammer_node_locklist_t locklist = NULL;
427e5fc6
MD
1424 int parent_index;
1425 int made_root;
1426 int split;
1427 int error;
7f7c1f84 1428 int i;
8cd0a023 1429 const int esize = sizeof(*elm);
427e5fc6 1430
6a37e7e4
MD
1431 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1432 return(error);
b33e2cc0
MD
1433 if ((cursor->flags & HAMMER_CURSOR_RECOVER) == 0) {
1434 error = hammer_btree_lock_children(cursor, &locklist);
1435 if (error)
1436 goto done;
1437 }
6a37e7e4 1438
427e5fc6
MD
1439 /*
1440 * We are splitting but elms[split] will be promoted to the parent,
1441 * leaving the right hand node with one less element. If the
1442 * insertion point will be on the left-hand side adjust the split
1443 * point to give the right hand side one additional node.
1444 */
8cd0a023
MD
1445 node = cursor->node;
1446 ondisk = node->ondisk;
1447 split = (ondisk->count + 1) / 2;
427e5fc6
MD
1448 if (cursor->index <= split)
1449 --split;
427e5fc6
MD
1450
1451 /*
8cd0a023 1452 * If we are at the root of the cluster, create a new root node with
427e5fc6
MD
1453 * 1 element and split normally. Avoid making major modifications
1454 * until we know the whole operation will work.
8cd0a023
MD
1455 *
1456 * The root of the cluster is different from the root of the root
1457 * cluster. Use the node's on-disk structure's parent offset to
1458 * detect the case.
427e5fc6 1459 */
8cd0a023
MD
1460 if (ondisk->parent == 0) {
1461 parent = hammer_alloc_btree(node->cluster, &error);
427e5fc6 1462 if (parent == NULL)
6a37e7e4 1463 goto done;
8cd0a023 1464 hammer_lock_ex(&parent->lock);
0b075555 1465 hammer_modify_node(parent);
8cd0a023
MD
1466 ondisk = parent->ondisk;
1467 ondisk->count = 1;
1468 ondisk->parent = 0;
1469 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1470 ondisk->elms[0].base = node->cluster->clu_btree_beg;
fe7678ee 1471 ondisk->elms[0].base.btype = node->ondisk->type;
8cd0a023
MD
1472 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1473 ondisk->elms[1].base = node->cluster->clu_btree_end;
fe7678ee 1474 /* ondisk->elms[1].base.btype - not used */
427e5fc6 1475 made_root = 1;
8cd0a023 1476 parent_index = 0; /* index of current node in parent */
427e5fc6
MD
1477 } else {
1478 made_root = 0;
8cd0a023
MD
1479 parent = cursor->parent;
1480 parent_index = cursor->parent_index;
195c19a1 1481 KKASSERT(parent->cluster == node->cluster);
427e5fc6 1482 }
427e5fc6
MD
1483
1484 /*
1485 * Split node into new_node at the split point.
1486 *
1487 * B O O O P N N B <-- P = node->elms[split]
1488 * 0 1 2 3 4 5 6 <-- subtree indices
1489 *
1490 * x x P x x
1491 * s S S s
1492 * / \
1493 * B O O O B B N N B <--- inner boundary points are 'P'
1494 * 0 1 2 3 4 5 6
1495 *
1496 */
8cd0a023 1497 new_node = hammer_alloc_btree(node->cluster, &error);
427e5fc6 1498 if (new_node == NULL) {
8cd0a023
MD
1499 if (made_root) {
1500 hammer_unlock(&parent->lock);
b3deaf57 1501 parent->flags |= HAMMER_NODE_DELETED;
8cd0a023
MD
1502 hammer_rel_node(parent);
1503 }
6a37e7e4 1504 goto done;
427e5fc6 1505 }
8cd0a023 1506 hammer_lock_ex(&new_node->lock);
427e5fc6
MD
1507
1508 /*
8cd0a023 1509 * Create the new node. P becomes the left-hand boundary in the
427e5fc6
MD
1510 * new node. Copy the right-hand boundary as well.
1511 *
1512 * elm is the new separator.
1513 */
0b075555
MD
1514 hammer_modify_node(new_node);
1515 hammer_modify_node(node);
8cd0a023
MD
1516 ondisk = node->ondisk;
1517 elm = &ondisk->elms[split];
1518 bcopy(elm, &new_node->ondisk->elms[0],
1519 (ondisk->count - split + 1) * esize);
1520 new_node->ondisk->count = ondisk->count - split;
1521 new_node->ondisk->parent = parent->node_offset;
1522 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1523 KKASSERT(ondisk->type == new_node->ondisk->type);
427e5fc6
MD
1524
1525 /*
fe7678ee
MD
1526 * Cleanup the original node. Elm (P) becomes the new boundary,
1527 * its subtree_offset was moved to the new node. If we had created
427e5fc6
MD
1528 * a new root its parent pointer may have changed.
1529 */
8cd0a023 1530 elm->internal.subtree_offset = 0;
c0ade690 1531 ondisk->count = split;
427e5fc6
MD
1532
1533 /*
1534 * Insert the separator into the parent, fixup the parent's
1535 * reference to the original node, and reference the new node.
1536 * The separator is P.
1537 *
1538 * Remember that base.count does not include the right-hand boundary.
1539 */
0b075555 1540 hammer_modify_node(parent);
8cd0a023 1541 ondisk = parent->ondisk;
d26d0ae9 1542 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
8cd0a023 1543 parent_elm = &ondisk->elms[parent_index+1];
427e5fc6 1544 bcopy(parent_elm, parent_elm + 1,
8cd0a023
MD
1545 (ondisk->count - parent_index) * esize);
1546 parent_elm->internal.base = elm->base; /* separator P */
fe7678ee 1547 parent_elm->internal.base.btype = new_node->ondisk->type;
8cd0a023 1548 parent_elm->internal.subtree_offset = new_node->node_offset;
76376933 1549 ++ondisk->count;
427e5fc6 1550
7f7c1f84
MD
1551 /*
1552 * The children of new_node need their parent pointer set to new_node.
b33e2cc0
MD
1553 * The children have already been locked by
1554 * hammer_btree_lock_children().
7f7c1f84
MD
1555 */
1556 for (i = 0; i < new_node->ondisk->count; ++i) {
1557 elm = &new_node->ondisk->elms[i];
1558 error = btree_set_parent(new_node, elm);
1559 if (error) {
1560 panic("btree_split_internal: btree-fixup problem");
1561 }
1562 }
1563
427e5fc6
MD
1564 /*
1565 * The cluster's root pointer may have to be updated.
1566 */
1567 if (made_root) {
8cd0a023 1568 hammer_modify_cluster(node->cluster);
0b075555 1569 node->cluster->ondisk->clu_btree_root = parent->node_offset;
8cd0a023
MD
1570 node->ondisk->parent = parent->node_offset;
1571 if (cursor->parent) {
1572 hammer_unlock(&cursor->parent->lock);
1573 hammer_rel_node(cursor->parent);
1574 }
1575 cursor->parent = parent; /* lock'd and ref'd */
427e5fc6
MD
1576 }
1577
8cd0a023 1578
427e5fc6
MD
1579 /*
1580 * Ok, now adjust the cursor depending on which element the original
1581 * index was pointing at. If we are >= the split point the push node
1582 * is now in the new node.
1583 *
1584 * NOTE: If we are at the split point itself we cannot stay with the
1585 * original node because the push index will point at the right-hand
1586 * boundary, which is illegal.
8cd0a023
MD
1587 *
1588 * NOTE: The cursor's parent or parent_index must be adjusted for
1589 * the case where a new parent (new root) was created, and the case
1590 * where the cursor is now pointing at the split node.
427e5fc6
MD
1591 */
1592 if (cursor->index >= split) {
8cd0a023 1593 cursor->parent_index = parent_index + 1;
427e5fc6 1594 cursor->index -= split;
8cd0a023
MD
1595 hammer_unlock(&cursor->node->lock);
1596 hammer_rel_node(cursor->node);
1597 cursor->node = new_node; /* locked and ref'd */
1598 } else {
1599 cursor->parent_index = parent_index;
1600 hammer_unlock(&new_node->lock);
1601 hammer_rel_node(new_node);
427e5fc6 1602 }
76376933
MD
1603
1604 /*
1605 * Fixup left and right bounds
1606 */
1607 parent_elm = &parent->ondisk->elms[cursor->parent_index];
fbc6e32a
MD
1608 cursor->left_bound = &parent_elm[0].internal.base;
1609 cursor->right_bound = &parent_elm[1].internal.base;
b3deaf57
MD
1610 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1611 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1612 KKASSERT(hammer_btree_cmp(cursor->right_bound,
9944ae54 1613 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
76376933 1614
6a37e7e4 1615done:
b33e2cc0 1616 hammer_btree_unlock_children(&locklist);
6a37e7e4
MD
1617 hammer_cursor_downgrade(cursor);
1618 return (error);
427e5fc6
MD
1619}
1620
1621/*
1622 * Same as the above, but splits a full leaf node.
6a37e7e4
MD
1623 *
1624 * This function
427e5fc6
MD
1625 */
1626static
1627int
8cd0a023 1628btree_split_leaf(hammer_cursor_t cursor)
427e5fc6 1629{
8cd0a023
MD
1630 hammer_node_ondisk_t ondisk;
1631 hammer_node_t parent;
1632 hammer_node_t leaf;
1633 hammer_node_t new_leaf;
1634 hammer_btree_elm_t elm;
1635 hammer_btree_elm_t parent_elm;
b3deaf57 1636 hammer_base_elm_t mid_boundary;
b33e2cc0 1637 hammer_node_locklist_t locklist = NULL;
427e5fc6
MD
1638 int parent_index;
1639 int made_root;
1640 int split;
1641 int error;
fe7678ee 1642 int i;
8cd0a023 1643 const size_t esize = sizeof(*elm);
427e5fc6 1644
6a37e7e4
MD
1645 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1646 return(error);
b33e2cc0
MD
1647 if ((cursor->flags & HAMMER_CURSOR_RECOVER) == 0) {
1648 error = hammer_btree_lock_children(cursor, &locklist);
1649 if (error)
1650 goto done;
1651 }
6a37e7e4 1652
427e5fc6 1653 /*
8cd0a023
MD
1654 * Calculate the split point. If the insertion point will be on
1655 * the left-hand side adjust the split point to give the right
1656 * hand side one additional node.
fe7678ee
MD
1657 *
1658 * Spikes are made up of two leaf elements which cannot be
1659 * safely split.
427e5fc6 1660 */
8cd0a023
MD
1661 leaf = cursor->node;
1662 ondisk = leaf->ondisk;
1663 split = (ondisk->count + 1) / 2;
427e5fc6
MD
1664 if (cursor->index <= split)
1665 --split;
1666 error = 0;
1667
fe7678ee
MD
1668 elm = &ondisk->elms[split];
1669 if (elm->leaf.base.btype == HAMMER_BTREE_TYPE_SPIKE_END) {
1670 KKASSERT(split &&
1671 elm[-1].leaf.base.btype == HAMMER_BTREE_TYPE_SPIKE_BEG);
1672 --split;
1673 }
1674
427e5fc6
MD
1675 /*
1676 * If we are at the root of the tree, create a new root node with
1677 * 1 element and split normally. Avoid making major modifications
1678 * until we know the whole operation will work.
1679 */
8cd0a023
MD
1680 if (ondisk->parent == 0) {
1681 parent = hammer_alloc_btree(leaf->cluster, &error);
427e5fc6 1682 if (parent == NULL)
6a37e7e4 1683 goto done;
8cd0a023 1684 hammer_lock_ex(&parent->lock);
0b075555 1685 hammer_modify_node(parent);
8cd0a023
MD
1686 ondisk = parent->ondisk;
1687 ondisk->count = 1;
1688 ondisk->parent = 0;
1689 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1690 ondisk->elms[0].base = leaf->cluster->clu_btree_beg;
fe7678ee 1691 ondisk->elms[0].base.btype = leaf->ondisk->type;
8cd0a023
MD
1692 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1693 ondisk->elms[1].base = leaf->cluster->clu_btree_end;
fe7678ee 1694 /* ondisk->elms[1].base.btype = not used */
427e5fc6 1695 made_root = 1;
8cd0a023 1696 parent_index = 0; /* insertion point in parent */
427e5fc6
MD
1697 } else {
1698 made_root = 0;
8cd0a023
MD
1699 parent = cursor->parent;
1700 parent_index = cursor->parent_index;
195c19a1 1701 KKASSERT(parent->cluster == leaf->cluster);
427e5fc6 1702 }
427e5fc6
MD
1703
1704 /*
1705 * Split leaf into new_leaf at the split point. Select a separator
1706 * value in-between the two leafs but with a bent towards the right
1707 * leaf since comparisons use an 'elm >= separator' inequality.
1708 *
1709 * L L L L L L L L
1710 *
1711 * x x P x x
1712 * s S S s
1713 * / \
1714 * L L L L L L L L
1715 */
8cd0a023 1716 new_leaf = hammer_alloc_btree(leaf->cluster, &error);
427e5fc6 1717 if (new_leaf == NULL) {
8cd0a023
MD
1718 if (made_root) {
1719 hammer_unlock(&parent->lock);
b3deaf57 1720 parent->flags |= HAMMER_NODE_DELETED;
8cd0a023
MD
1721 hammer_rel_node(parent);
1722 }
6a37e7e4 1723 goto done;
427e5fc6 1724 }
8cd0a023 1725 hammer_lock_ex(&new_leaf->lock);
427e5fc6
MD
1726
1727 /*
eaeff70d 1728 * Create the new node. P (elm) become the left-hand boundary in the
427e5fc6
MD
1729 * new node. Copy the right-hand boundary as well.
1730 */
0b075555
MD
1731 hammer_modify_node(leaf);
1732 hammer_modify_node(new_leaf);
8cd0a023
MD
1733 ondisk = leaf->ondisk;
1734 elm = &ondisk->elms[split];
1735 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1736 new_leaf->ondisk->count = ondisk->count - split;
1737 new_leaf->ondisk->parent = parent->node_offset;
1738 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1739 KKASSERT(ondisk->type == new_leaf->ondisk->type);
427e5fc6
MD
1740
1741 /*
8cd0a023
MD
1742 * Cleanup the original node. Because this is a leaf node and
1743 * leaf nodes do not have a right-hand boundary, there
c0ade690
MD
1744 * aren't any special edge cases to clean up. We just fixup the
1745 * count.
427e5fc6 1746 */
c0ade690 1747 ondisk->count = split;
427e5fc6
MD
1748
1749 /*
1750 * Insert the separator into the parent, fixup the parent's
1751 * reference to the original node, and reference the new node.
1752 * The separator is P.
1753 *
1754 * Remember that base.count does not include the right-hand boundary.
1755 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1756 */
0b075555 1757 hammer_modify_node(parent);
8cd0a023 1758 ondisk = parent->ondisk;
d26d0ae9 1759 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
8cd0a023 1760 parent_elm = &ondisk->elms[parent_index+1];
d26d0ae9
MD
1761 bcopy(parent_elm, parent_elm + 1,
1762 (ondisk->count - parent_index) * esize);
eaeff70d
MD
1763
1764 /*
1765 * Create the separator. XXX At the moment use exactly the
1766 * right-hand element if this is a recovery operation in order
1767 * to guarantee that it does not bisect the spike elements in a
1768 * later call to hammer_btree_insert_cluster().
1769 */
1770 if (cursor->flags & HAMMER_CURSOR_RECOVER) {
1771 parent_elm->base = elm[0].base;
1772 } else {
1773 hammer_make_separator(&elm[-1].base, &elm[0].base,
1774 &parent_elm->base);
1775 }
fe7678ee 1776 parent_elm->internal.base.btype = new_leaf->ondisk->type;
8cd0a023 1777 parent_elm->internal.subtree_offset = new_leaf->node_offset;
b3deaf57 1778 mid_boundary = &parent_elm->base;
76376933 1779 ++ondisk->count;
427e5fc6 1780
fe7678ee
MD
1781 /*
1782 * The children of new_leaf need their parent pointer set to new_leaf.
b33e2cc0 1783 * The children have already been locked by btree_lock_children().
fe7678ee
MD
1784 *
1785 * The leaf's elements are either TYPE_RECORD or TYPE_SPIKE_*. Only
1786 * elements of BTREE_TYPE_SPIKE_END really requires any action.
1787 */
1788 for (i = 0; i < new_leaf->ondisk->count; ++i) {
1789 elm = &new_leaf->ondisk->elms[i];
1790 error = btree_set_parent(new_leaf, elm);
1791 if (error) {
1792 panic("btree_split_internal: btree-fixup problem");
1793 }
1794 }
1795
427e5fc6
MD
1796 /*
1797 * The cluster's root pointer may have to be updated.
1798 */
1799 if (made_root) {
8cd0a023 1800 hammer_modify_cluster(leaf->cluster);
0b075555 1801 leaf->cluster->ondisk->clu_btree_root = parent->node_offset;
8cd0a023
MD
1802 leaf->ondisk->parent = parent->node_offset;
1803 if (cursor->parent) {
1804 hammer_unlock(&cursor->parent->lock);
1805 hammer_rel_node(cursor->parent);
1806 }
1807 cursor->parent = parent; /* lock'd and ref'd */
427e5fc6 1808 }
8cd0a023 1809
427e5fc6
MD
1810 /*
1811 * Ok, now adjust the cursor depending on which element the original
1812 * index was pointing at. If we are >= the split point the push node
1813 * is now in the new node.
1814 *
b3deaf57
MD
1815 * NOTE: If we are at the split point itself we need to select the
1816 * old or new node based on where key_beg's insertion point will be.
1817 * If we pick the wrong side the inserted element will wind up in
1818 * the wrong leaf node and outside that node's bounds.
427e5fc6 1819 */
b3deaf57
MD
1820 if (cursor->index > split ||
1821 (cursor->index == split &&
1822 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
8cd0a023 1823 cursor->parent_index = parent_index + 1;
427e5fc6 1824 cursor->index -= split;
8cd0a023
MD
1825 hammer_unlock(&cursor->node->lock);
1826 hammer_rel_node(cursor->node);
1827 cursor->node = new_leaf;
1828 } else {
1829 cursor->parent_index = parent_index;
1830 hammer_unlock(&new_leaf->lock);
1831 hammer_rel_node(new_leaf);
427e5fc6 1832 }
76376933
MD
1833
1834 /*
1835 * Fixup left and right bounds
1836 */
1837 parent_elm = &parent->ondisk->elms[cursor->parent_index];
fbc6e32a
MD
1838 cursor->left_bound = &parent_elm[0].internal.base;
1839 cursor->right_bound = &parent_elm[1].internal.base;
eaeff70d
MD
1840
1841 /*
1842 * Note: The right assertion is typically > 0, but if the last element
1843 * is a SPIKE_END it can be == 0 because the spike-end is non-inclusive
1844 * of the range being spiked.
1845 *
1846 * This may seem a bit odd but it works.
1847 */
b3deaf57
MD
1848 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1849 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1850 KKASSERT(hammer_btree_cmp(cursor->right_bound,
eaeff70d 1851 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) >= 0);
76376933 1852
6a37e7e4 1853done:
b33e2cc0 1854 hammer_btree_unlock_children(&locklist);
6a37e7e4
MD
1855 hammer_cursor_downgrade(cursor);
1856 return (error);
427e5fc6
MD
1857}
1858
1859/*
195c19a1
MD
1860 * Attempt to remove the empty B-Tree node at (cursor->node). Returns 0
1861 * on success, EAGAIN if we could not acquire the necessary locks, or some
fe7678ee 1862 * other error. This node can be a leaf node or an internal node.
8cd0a023 1863 *
195c19a1 1864 * On return the cursor may end up pointing at an internal node, suitable
b3deaf57 1865 * for further iteration but not for an immediate insertion or deletion.
8cd0a023 1866 *
195c19a1 1867 * cursor->node may be an internal node or a leaf node.
b3deaf57
MD
1868 *
1869 * NOTE: If cursor->node has one element it is the parent trying to delete
1870 * that element, make sure cursor->index is properly adjusted on success.
8cd0a023
MD
1871 */
1872int
46fe7ae1 1873btree_remove(hammer_cursor_t cursor)
8cd0a023
MD
1874{
1875 hammer_node_ondisk_t ondisk;
195c19a1 1876 hammer_btree_elm_t elm;
195c19a1 1877 hammer_node_t node;
fe7678ee 1878 hammer_node_t save;
8cd0a023 1879 hammer_node_t parent;
fe7678ee 1880 const int esize = sizeof(*elm);
8cd0a023 1881 int error;
8cd0a023
MD
1882
1883 /*
fe7678ee
MD
1884 * If we are at the root of the cluster we must be able to
1885 * successfully delete the HAMMER_BTREE_SPIKE_* leaf elements in
1886 * the parent in order to be able to destroy the cluster.
8cd0a023 1887 */
fe7678ee
MD
1888 node = cursor->node;
1889
1890 if (node->ondisk->parent == 0) {
1891 hammer_modify_node(node);
1892 ondisk = node->ondisk;
195c19a1
MD
1893 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1894 ondisk->count = 0;
b3deaf57 1895 cursor->index = 0;
fe7678ee
MD
1896 error = 0;
1897
1898 /*
6a37e7e4
MD
1899 * When trying to delete a cluster we need to exclusively
1900 * lock the cluster root, its parent (leaf in parent cluster),
1901 * AND the parent of that leaf if it's going to be empty,
1902 * because we can't leave around an empty leaf.
1903 *
1904 * XXX this is messy due to potentially recursive locks.
1905 * downgrade the cursor, get a second shared lock on the
1906 * node that cannot deadlock because we only own shared locks
1907 * then, cursor-up, and re-upgrade everything. If the
1908 * upgrades EDEADLK then don't try to remove the cluster
1909 * at this time.
fe7678ee
MD
1910 */
1911 if ((parent = cursor->parent) != NULL) {
6a37e7e4 1912 hammer_cursor_downgrade(cursor);
fe7678ee
MD
1913 save = node;
1914 hammer_ref_node(save);
6a37e7e4
MD
1915 hammer_lock_sh(&save->lock);
1916
46fe7ae1
MD
1917 /*
1918 * After the cursor up save has the empty root node
1919 * of the target cluster to be deleted, cursor->node
1920 * is at the leaf containing the spikes, and
1921 * cursor->parent is the parent of that leaf.
1922 *
1923 * cursor->node and cursor->parent are both in the
1924 * parent cluster of the cluster being deleted.
1925 */
6a37e7e4 1926 error = hammer_cursor_up(cursor);
46fe7ae1 1927
6a37e7e4
MD
1928 if (error == 0)
1929 error = hammer_cursor_upgrade(cursor);
1930 if (error == 0)
1931 error = hammer_lock_upgrade(&save->lock);
1932
fe7678ee 1933 if (error) {
6a37e7e4 1934 /* may be EDEADLK */
fe7678ee
MD
1935 kprintf("BTREE_REMOVE: Cannot delete cluster\n");
1936 Debugger("BTREE_REMOVE");
fe7678ee
MD
1937 } else {
1938 /*
1939 * cursor->node is now the leaf in the parent
1940 * cluster containing the spike elements.
1941 *
1942 * The cursor should be pointing at the
1943 * SPIKE_END element.
1944 *
1945 * Remove the spike elements and recurse
1946 * if the leaf becomes empty.
1947 */
1948 node = cursor->node;
1949 hammer_modify_node(node);
1950 ondisk = node->ondisk;
1951 KKASSERT(cursor->index > 0);
1952 --cursor->index;
1953 elm = &ondisk->elms[cursor->index];
1954 KKASSERT(elm[0].leaf.base.btype ==
1955 HAMMER_BTREE_TYPE_SPIKE_BEG);
1956 KKASSERT(elm[1].leaf.base.btype ==
1957 HAMMER_BTREE_TYPE_SPIKE_END);
b33e2cc0
MD
1958
1959 /*
1960 * Ok, remove it and the underlying record.
1961 */
1962 hammer_free_record(node->cluster,
1963 elm->leaf.rec_offset,
1964 HAMMER_RECTYPE_CLUSTER);
fe7678ee
MD
1965 bcopy(elm + 2, elm, (ondisk->count -
1966 cursor->index - 2) * esize);
1967 ondisk->count -= 2;
fe7678ee 1968 save->flags |= HAMMER_NODE_DELETED;
46fe7ae1
MD
1969 save->cluster->flags |= HAMMER_CLUSTER_DELETED;
1970 hammer_flush_node(save);
1971 hammer_unlock(&save->lock);
1972 hammer_rel_node(save);
1973 if (ondisk->count == 0)
1974 error = EAGAIN;
fe7678ee 1975 }
fe7678ee
MD
1976 }
1977 return(error);
8cd0a023
MD
1978 }
1979
1980 /*
fe7678ee
MD
1981 * Zero-out the parent's reference to the child and flag the
1982 * child for destruction. This ensures that the child is not
1983 * reused while other references to it exist.
8cd0a023 1984 */
fe7678ee
MD
1985 parent = cursor->parent;
1986 hammer_modify_node(parent);
1987 ondisk = parent->ondisk;
1988 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1989 elm = &ondisk->elms[cursor->parent_index];
1990 KKASSERT(elm->internal.subtree_offset == node->node_offset);
1991 elm->internal.subtree_offset = 0;
1992
1993 hammer_flush_node(node);
1994 node->flags |= HAMMER_NODE_DELETED;
8cd0a023
MD
1995
1996 /*
fe7678ee
MD
1997 * If the parent would otherwise not become empty we can physically
1998 * remove the zero'd element. Note however that in order to
1999 * guarentee a valid cursor we still need to be able to cursor up
2000 * because we no longer have a node.
2001 *
2002 * This collapse will change the parent's boundary elements, making
2003 * them wider. The new boundaries are recursively corrected in
2004 * btree_search().
195c19a1 2005 *
fe7678ee
MD
2006 * XXX we can theoretically recalculate the midpoint but there isn't
2007 * much of a reason to do it.
8cd0a023 2008 */
6a37e7e4
MD
2009 error = hammer_cursor_up(cursor);
2010 if (error == 0)
2011 error = hammer_cursor_upgrade(cursor);
2012
195c19a1 2013 if (error) {
b3deaf57 2014 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
fe7678ee
MD
2015 Debugger("BTREE_REMOVE");
2016 return (0);
8cd0a023 2017 }
195c19a1
MD
2018
2019 /*
fe7678ee
MD
2020 * Remove the internal element from the parent. The bcopy must
2021 * include the right boundary element.
9944ae54 2022 */
fe7678ee
MD
2023 KKASSERT(parent == cursor->node && ondisk == parent->ondisk);
2024 node = parent;
2025 parent = NULL;
2026 /* ondisk is node's ondisk */
2027 /* elm is node's element */
2028
6a37e7e4
MD
2029 /*
2030 * Remove the internal element that we zero'd out. Tell the caller
2031 * to loop if it hits zero (to try to avoid eating up precious kernel
2032 * stack).
2033 */
fe7678ee
MD
2034 KKASSERT(ondisk->count > 0);
2035 bcopy(&elm[1], &elm[0], (ondisk->count - cursor->index) * esize);
195c19a1 2036 --ondisk->count;
fe7678ee
MD
2037 if (ondisk->count == 0)
2038 error = EAGAIN;
b3deaf57 2039 return(error);
8cd0a023
MD
2040}
2041
6a37e7e4
MD
2042/*
2043 * Attempt to remove the deleted internal element at the current cursor
2044 * position. If we are unable to remove the element we return EDEADLK.
2045 *
2046 * If the current internal node becomes empty we delete it in the parent
2047 * and cursor up, looping until we finish or we deadlock.
2048 *
2049 * On return, if successful, the cursor will be pointing at the next
2050 * iterative position in the B-Tree. If unsuccessful the cursor will be
2051 * pointing at the last deleted internal element that could not be
2052 * removed.
2053 */
2054static
2055int
2056btree_remove_deleted_element(hammer_cursor_t cursor)
2057{
2058 hammer_node_t node;
2059 hammer_btree_elm_t elm;
2060 int error;
2061
2062 if ((error = hammer_cursor_upgrade(cursor)) != 0)
2063 return(error);
2064 node = cursor->node;
2065 elm = &node->ondisk->elms[cursor->index];
2066 if (elm->internal.subtree_offset == 0) {
2067 do {
46fe7ae1 2068 error = btree_remove(cursor);
6a37e7e4
MD
2069 kprintf("BTREE REMOVE DELETED ELEMENT %d\n", error);
2070 } while (error == EAGAIN);
2071 }
2072 return(error);
2073}
2074
7f7c1f84 2075/*
fe7678ee
MD
2076 * The element (elm) has been moved to a new internal node (node).
2077 *
2078 * If the element represents a pointer to an internal node that node's
2079 * parent must be adjusted to the element's new location.
2080 *
2081 * If the element represents a spike the target cluster's header must
2082 * be adjusted to point to the element's new location. This only
b33e2cc0
MD
2083 * applies to HAMMER_SPIKE_END.
2084 *
2085 * GET_CLUSTER_NORECOVER must be used to avoid a recovery recursion during
2086 * the rebuild of the recovery cluster's B-Tree, which can blow the kernel
2087 * stack.
6a37e7e4
MD
2088 *
2089 * XXX deadlock potential here with our exclusive locks
7f7c1f84
MD
2090 */
2091static
2092int
2093btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm)
2094{
2095 hammer_volume_t volume;
2096 hammer_cluster_t cluster;
2097 hammer_node_t child;
2098 int error;
2099
2100 error = 0;
2101
fe7678ee 2102 switch(elm->base.btype) {
7f7c1f84 2103 case HAMMER_BTREE_TYPE_INTERNAL:
fe7678ee 2104 case HAMMER_BTREE_TYPE_LEAF:
7f7c1f84
MD
2105 child = hammer_get_node(node->cluster,
2106 elm->internal.subtree_offset, &error);
2107 if (error == 0) {
0b075555 2108 hammer_modify_node(child);
7f7c1f84 2109 child->ondisk->parent = node->node_offset;
7f7c1f84
MD
2110 hammer_rel_node(child);
2111 }
2112 break;
fe7678ee 2113 case HAMMER_BTREE_TYPE_SPIKE_END:
7f7c1f84 2114 volume = hammer_get_volume(node->cluster->volume->hmp,
fe7678ee 2115 elm->leaf.spike_vol_no, &error);
7f7c1f84
MD
2116 if (error)
2117 break;
fe7678ee 2118 cluster = hammer_get_cluster(volume, elm->leaf.spike_clu_no,
b33e2cc0 2119 &error, GET_CLUSTER_NORECOVER);
7f7c1f84
MD
2120 hammer_rel_volume(volume, 0);
2121 if (error)
2122 break;
0b075555 2123 hammer_modify_cluster(cluster);
7f7c1f84 2124 cluster->ondisk->clu_btree_parent_offset = node->node_offset;
7f7c1f84
MD
2125 KKASSERT(cluster->ondisk->clu_btree_parent_clu_no ==
2126 node->cluster->clu_no);
2127 KKASSERT(cluster->ondisk->clu_btree_parent_vol_no ==
2128 node->cluster->volume->vol_no);
7f7c1f84
MD
2129 hammer_rel_cluster(cluster, 0);
2130 break;
2131 default:
fe7678ee 2132 break;
7f7c1f84
MD
2133 }
2134 return(error);
2135}
2136
b33e2cc0
MD
2137/*
2138 * Exclusively lock all the children of node. This is used by the split
2139 * code to prevent anyone from accessing the children of a cursor node
2140 * while we fix-up its parent offset.
2141 *
2142 * If we don't lock the children we can really mess up cursors which block
2143 * trying to cursor-up into our node.
2144 *
2145 * WARNING: Cannot be used when doing B-tree operations on a recovery
2146 * cluster because the target cluster may require recovery, resulting
2147 * in a deep recursion which blows the kernel stack.
2148 *
2149 * On failure EDEADLK (or some other error) is returned. If a deadlock
2150 * error is returned the cursor is adjusted to block on termination.
2151 */
2152int
2153hammer_btree_lock_children(hammer_cursor_t cursor,
2154 struct hammer_node_locklist **locklistp)
2155{
2156 hammer_node_t node;
2157 hammer_node_locklist_t item;
2158 hammer_node_ondisk_t ondisk;
2159 hammer_btree_elm_t elm;
2160 hammer_volume_t volume;
2161 hammer_cluster_t cluster;
2162 hammer_node_t child;
2163 int error;
2164 int i;
2165
2166 node = cursor->node;
2167 ondisk = node->ondisk;
2168 error = 0;
2169 for (i = 0; error == 0 && i < ondisk->count; ++i) {
2170 elm = &ondisk->elms[i];
2171
2172 child = NULL;
2173 switch(elm->base.btype) {
2174 case HAMMER_BTREE_TYPE_INTERNAL:
2175 case HAMMER_BTREE_TYPE_LEAF:
2176 child = hammer_get_node(node->cluster,
2177 elm->internal.subtree_offset,
2178 &error);
2179 break;
2180 case HAMMER_BTREE_TYPE_SPIKE_END:
2181 volume = hammer_get_volume(node->cluster->volume->hmp,
2182 elm->leaf.spike_vol_no,
2183 &error);
2184 if (error)
2185 break;
2186 cluster = hammer_get_cluster(volume,
2187 elm->leaf.spike_clu_no,
2188 &error,
2189 0);
2190 hammer_rel_volume(volume, 0);
2191 if (error)
2192 break;
2193 KKASSERT(cluster->ondisk->clu_btree_root != 0);
2194 child = hammer_get_node(cluster,
2195 cluster->ondisk->clu_btree_root,
2196 &error);
2197 hammer_rel_cluster(cluster, 0);
2198 break;
2199 default:
2200 break;
2201 }
2202 if (child) {
2203 if (hammer_lock_ex_try(&child->lock) != 0) {
2204 if (cursor->deadlk_node == NULL) {
2205 cursor->deadlk_node = node;
2206 hammer_ref_node(cursor->deadlk_node);
2207 }
2208 error = EDEADLK;
2209 } else {
2210 item = kmalloc(sizeof(*item),
2211 M_HAMMER, M_WAITOK);
2212 item->next = *locklistp;
2213 item->node = child;
2214 *locklistp = item;
2215 }
2216 }
2217 }
2218 if (error)
2219 hammer_btree_unlock_children(locklistp);
2220 return(error);
2221}
2222
2223
2224/*
2225 * Release previously obtained node locks.
2226 */
2227void
2228hammer_btree_unlock_children(struct hammer_node_locklist **locklistp)
2229{
2230 hammer_node_locklist_t item;
2231
2232 while ((item = *locklistp) != NULL) {
2233 *locklistp = item->next;
2234 hammer_unlock(&item->node->lock);
2235 hammer_rel_node(item->node);
2236 kfree(item, M_HAMMER);
2237 }
2238}
2239
8cd0a023
MD
2240/************************************************************************
2241 * MISCELLANIOUS SUPPORT *
2242 ************************************************************************/
2243
2244/*
d26d0ae9 2245 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
8cd0a023 2246 *
d113fda1 2247 * Note that for this particular function a return value of -1, 0, or +1
d5530d22
MD
2248 * can denote a match if delete_tid is otherwise discounted. A delete_tid
2249 * of zero is considered to be 'infinity' in comparisons.
d113fda1 2250 *
8cd0a023 2251 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
8cd0a023
MD
2252 */
2253int
2254hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2255{
d26d0ae9
MD
2256 if (key1->obj_id < key2->obj_id)
2257 return(-4);
2258 if (key1->obj_id > key2->obj_id)
2259 return(4);
8cd0a023 2260
d26d0ae9
MD
2261 if (key1->rec_type < key2->rec_type)
2262 return(-3);
2263 if (key1->rec_type > key2->rec_type)
2264 return(3);
8cd0a023 2265
8cd0a023
MD
2266 if (key1->key < key2->key)
2267 return(-2);
2268 if (key1->key > key2->key)
2269 return(2);
d113fda1 2270
d5530d22
MD
2271 /*
2272 * A delete_tid of zero indicates a record which has not been
2273 * deleted yet and must be considered to have a value of positive
2274 * infinity.
2275 */
2276 if (key1->delete_tid == 0) {
2277 if (key2->delete_tid == 0)
2278 return(0);
2279 return(1);
2280 }
2281 if (key2->delete_tid == 0)
2282 return(-1);
2283 if (key1->delete_tid < key2->delete_tid)
d113fda1 2284 return(-1);
d5530d22 2285 if (key1->delete_tid > key2->delete_tid)
d113fda1 2286 return(1);
8cd0a023
MD
2287 return(0);
2288}
2289
c0ade690 2290/*
d5530d22
MD
2291 * Test a timestamp against an element to determine whether the
2292 * element is visible. A timestamp of 0 means 'infinity'.
c0ade690
MD
2293 */
2294int
d5530d22 2295hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
c0ade690 2296{
d5530d22
MD
2297 if (asof == 0) {
2298 if (base->delete_tid)
2299 return(1);
2300 return(0);
2301 }
2302 if (asof < base->create_tid)
d26d0ae9 2303 return(-1);
d5530d22 2304 if (base->delete_tid && asof >= base->delete_tid)
d26d0ae9 2305 return(1);
c0ade690
MD
2306 return(0);
2307}
2308
8cd0a023
MD
2309/*
2310 * Create a separator half way inbetween key1 and key2. For fields just
d5530d22
MD
2311 * one unit apart, the separator will match key2. key1 is on the left-hand
2312 * side and key2 is on the right-hand side.
8cd0a023 2313 *
d5530d22
MD
2314 * delete_tid has to be special cased because a value of 0 represents
2315 * infinity, and records with a delete_tid of 0 can be replaced with
2316 * a non-zero delete_tid when deleted and must maintain their proper
2317 * (as in the same) position in the B-Tree.
8cd0a023
MD
2318 */
2319#define MAKE_SEPARATOR(key1, key2, dest, field) \
2320 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2321
2322static void
2323hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2324 hammer_base_elm_t dest)
2325{
2326 bzero(dest, sizeof(*dest));
2327 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2328 MAKE_SEPARATOR(key1, key2, dest, rec_type);
2329 MAKE_SEPARATOR(key1, key2, dest, key);
d5530d22 2330
d113fda1
MD
2331 if (key1->obj_id == key2->obj_id &&
2332 key1->rec_type == key2->rec_type &&
2333 key1->key == key2->key) {
d5530d22 2334 if (key1->delete_tid == 0) {
b33e2cc0
MD
2335 /*
2336 * Oops, a delete_tid of 0 means 'infinity', so
2337 * if everything matches this just isn't legal.
d5530d22 2338 */
b33e2cc0
MD
2339 panic("key1->delete_tid of 0 is impossible here");
2340#if 0
2341 KKASSERT(key1->btype == HAMMER_BTREE_TYPE_SPIKE_END);
2342 dest->delete_tid = key1->delete_tid;
2343#endif
d5530d22
MD
2344 } else if (key2->delete_tid == 0) {
2345 dest->delete_tid = key1->delete_tid + 1;
2346 } else {
2347 MAKE_SEPARATOR(key1, key2, dest, delete_tid);
2348 }
d113fda1 2349 } else {
d5530d22 2350 dest->delete_tid = 0;
d113fda1 2351 }
8cd0a023
MD
2352}
2353
2354#undef MAKE_SEPARATOR
2355
2356/*
2357 * Return whether a generic internal or leaf node is full
2358 */
2359static int
2360btree_node_is_full(hammer_node_ondisk_t node)
2361{
2362 switch(node->type) {
2363 case HAMMER_BTREE_TYPE_INTERNAL:
2364 if (node->count == HAMMER_BTREE_INT_ELMS)
2365 return(1);
2366 break;
2367 case HAMMER_BTREE_TYPE_LEAF:
2368 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2369 return(1);
2370 break;
2371 default:
2372 panic("illegal btree subtype");
2373 }
2374 return(0);
2375}
9944ae54
MD
2376
2377/*
2378 * Return whether a generic internal or leaf node is almost full. This
2379 * routine is used as a helper for search insertions to guarentee at
2380 * least 2 available slots in the internal node(s) leading up to a leaf,
2381 * so hammer_btree_insert_cluster() will function properly.
2382 */
2383static int
2384btree_node_is_almost_full(hammer_node_ondisk_t node)
2385{
2386 switch(node->type) {
2387 case HAMMER_BTREE_TYPE_INTERNAL:
2388 if (node->count > HAMMER_BTREE_INT_ELMS - 2)
2389 return(1);
2390 break;
2391 case HAMMER_BTREE_TYPE_LEAF:
2392 if (node->count > HAMMER_BTREE_LEAF_ELMS - 2)
2393 return(1);
2394 break;
2395 default:
2396 panic("illegal btree subtype");
2397 }
2398 return(0);
2399}
8cd0a023
MD
2400
2401#if 0
2402static int
2403btree_max_elements(u_int8_t type)
2404{
2405 if (type == HAMMER_BTREE_TYPE_LEAF)
2406 return(HAMMER_BTREE_LEAF_ELMS);
2407 if (type == HAMMER_BTREE_TYPE_INTERNAL)
2408 return(HAMMER_BTREE_INT_ELMS);
2409 panic("btree_max_elements: bad type %d\n", type);
2410}
2411#endif
2412
c0ade690
MD
2413void
2414hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2415{
2416 hammer_btree_elm_t elm;
2417 int i;
2418
2419 kprintf("node %p count=%d parent=%d type=%c\n",
2420 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2421
2422 /*
2423 * Dump both boundary elements if an internal node
2424 */
2425 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2426 for (i = 0; i <= ondisk->count; ++i) {
2427 elm = &ondisk->elms[i];
2428 hammer_print_btree_elm(elm, ondisk->type, i);
2429 }
2430 } else {
2431 for (i = 0; i < ondisk->count; ++i) {
2432 elm = &ondisk->elms[i];
2433 hammer_print_btree_elm(elm, ondisk->type, i);
2434 }
2435 }
2436}
2437
2438void
2439hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2440{
2441 kprintf(" %2d", i);
2442 kprintf("\tobjid = %016llx\n", elm->base.obj_id);
2443 kprintf("\tkey = %016llx\n", elm->base.key);
2444 kprintf("\tcreate_tid = %016llx\n", elm->base.create_tid);
2445 kprintf("\tdelete_tid = %016llx\n", elm->base.delete_tid);
2446 kprintf("\trec_type = %04x\n", elm->base.rec_type);
2447 kprintf("\tobj_type = %02x\n", elm->base.obj_type);
fe7678ee
MD
2448 kprintf("\tbtype = %02x (%c)\n",
2449 elm->base.btype,
2450 (elm->base.btype ? elm->base.btype : '?'));
2451
2452 switch(type) {
2453 case HAMMER_BTREE_TYPE_INTERNAL:
2454 kprintf("\tsubtree_off = %08x\n",
2455 elm->internal.subtree_offset);
2456 break;
2457 case HAMMER_BTREE_TYPE_SPIKE_BEG:
2458 case HAMMER_BTREE_TYPE_SPIKE_END:
2459 kprintf("\tspike_clu_no = %d\n", elm->leaf.spike_clu_no);
2460 kprintf("\tspike_vol_no = %d\n", elm->leaf.spike_vol_no);
2461 break;
2462 case HAMMER_BTREE_TYPE_RECORD:
c0ade690
MD
2463 kprintf("\trec_offset = %08x\n", elm->leaf.rec_offset);
2464 kprintf("\tdata_offset = %08x\n", elm->leaf.data_offset);
2465 kprintf("\tdata_len = %08x\n", elm->leaf.data_len);
2466 kprintf("\tdata_crc = %08x\n", elm->leaf.data_crc);
fe7678ee 2467 break;
c0ade690
MD
2468 }
2469}