sys/vfs/hammer: Properly set mirror_tid on root node split
[dragonfly.git] / sys / vfs / hammer / hammer_btree.c
CommitLineData
427e5fc6 1/*
b84de5af 2 * Copyright (c) 2007-2008 The DragonFly Project. All rights reserved.
427e5fc6
MD
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.
427e5fc6
MD
33 */
34
35/*
8cd0a023 36 * HAMMER B-Tree index
427e5fc6
MD
37 *
38 * HAMMER implements a modified B+Tree. In documentation this will
9944ae54 39 * simply be refered to as the HAMMER B-Tree. Basically a HAMMER B-Tree
427e5fc6
MD
40 * looks like a B+Tree (A B-Tree which stores its records only at the leafs
41 * of the tree), but adds two additional boundary elements which describe
42 * the left-most and right-most element a node is able to represent. In
8cd0a023 43 * otherwords, we have boundary elements at the two ends of a B-Tree node
106ccd08 44 * with no valid sub-tree pointer for the right-most element.
427e5fc6 45 *
8cd0a023 46 * A B-Tree internal node looks like this:
427e5fc6
MD
47 *
48 * B N N N N N N B <-- boundary and internal elements
49 * S S S S S S S <-- subtree pointers
50 *
8cd0a023 51 * A B-Tree leaf node basically looks like this:
427e5fc6
MD
52 *
53 * L L L L L L L L <-- leaf elemenets
54 *
8cd0a023
MD
55 * The radix for an internal node is 1 less then a leaf but we get a
56 * number of significant benefits for our troubles.
106ccd08
TK
57 * The left-hand boundary (B in the left) is integrated into the first
58 * element so it doesn't require 2 elements to accomodate boundaries.
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 *
fe7678ee
MD
70 * INSERTIONS: A search performed with the intention of doing
71 * an insert will guarantee that the terminal leaf node is not full by
72 * splitting full nodes. Splits occur top-down during the dive down the
73 * B-Tree.
74 *
75 * DELETIONS: A deletion makes no attempt to proactively balance the
f36a9737
MD
76 * tree and will recursively remove nodes that become empty. If a
77 * deadlock occurs a deletion may not be able to remove an empty leaf.
78 * Deletions never allow internal nodes to become empty (that would blow
79 * up the boundaries).
8cd0a023
MD
80 */
81#include "hammer.h"
82#include <sys/buf.h>
83#include <sys/buf2.h>
66325755 84
8cd0a023
MD
85static int btree_search(hammer_cursor_t cursor, int flags);
86static int btree_split_internal(hammer_cursor_t cursor);
87static int btree_split_leaf(hammer_cursor_t cursor);
46fe7ae1 88static int btree_remove(hammer_cursor_t cursor);
fe7678ee 89static int btree_node_is_full(hammer_node_ondisk_t node);
adf01747
MD
90static int hammer_btree_mirror_propagate(hammer_cursor_t cursor,
91 hammer_tid_t mirror_tid);
8cd0a023
MD
92static void hammer_make_separator(hammer_base_elm_t key1,
93 hammer_base_elm_t key2, hammer_base_elm_t dest);
4c038e17 94static void hammer_cursor_mirror_filter(hammer_cursor_t cursor);
66325755
MD
95
96/*
8cd0a023
MD
97 * Iterate records after a search. The cursor is iterated forwards past
98 * the current record until a record matching the key-range requirements
99 * is found. ENOENT is returned if the iteration goes past the ending
6a37e7e4 100 * key.
66325755 101 *
d26d0ae9
MD
102 * The iteration is inclusive of key_beg and can be inclusive or exclusive
103 * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
66325755 104 *
eaeff70d 105 * When doing an as-of search (cursor->asof != 0), key_beg.create_tid
9582c7da 106 * may be modified by B-Tree functions.
d5530d22 107 *
8cd0a023 108 * cursor->key_beg may or may not be modified by this function during
d26d0ae9
MD
109 * the iteration. XXX future - in case of an inverted lock we may have
110 * to reinitiate the lookup and set key_beg to properly pick up where we
111 * left off.
6a37e7e4 112 *
6dc17446
MD
113 * If HAMMER_CURSOR_ITERATE_CHECK is set it is possible that the cursor
114 * was reverse indexed due to being moved to a parent while unlocked,
115 * and something else might have inserted an element outside the iteration
116 * range. When this case occurs the iterator just keeps iterating until
117 * it gets back into the iteration range (instead of asserting).
118 *
6a37e7e4 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;
3e583440 126 hammer_mount_t hmp;
1d4077f7 127 int error = 0;
66325755
MD
128 int r;
129 int s;
130
131 /*
8cd0a023 132 * Skip past the current record
66325755 133 */
3e583440 134 hmp = cursor->trans->hmp;
8cd0a023 135 node = cursor->node->ondisk;
a89aec1b
MD
136 if (node == NULL)
137 return(ENOENT);
c0ade690
MD
138 if (cursor->index < node->count &&
139 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
66325755 140 ++cursor->index;
c0ade690 141 }
66325755 142
3e583440
MD
143 /*
144 * HAMMER can wind up being cpu-bound.
145 */
146 if (++hmp->check_yield > hammer_yield_check) {
147 hmp->check_yield = 0;
148 lwkt_user_yield();
149 }
150
151
8cd0a023
MD
152 /*
153 * Loop until an element is found or we are done.
154 */
66325755
MD
155 for (;;) {
156 /*
8cd0a023
MD
157 * We iterate up the tree and then index over one element
158 * while we are at the last element in the current node.
159 *
47197d71 160 * If we are at the root of the filesystem, cursor_up
8cd0a023
MD
161 * returns ENOENT.
162 *
66325755
MD
163 * XXX this could be optimized by storing the information in
164 * the parent reference.
195c19a1
MD
165 *
166 * XXX we can lose the node lock temporarily, this could mess
167 * up our scan.
66325755 168 */
47637bff 169 ++hammer_stats_btree_iterations;
3e583440 170 hammer_flusher_clean_loose_ios(hmp);
77fec802 171
8cd0a023 172 if (cursor->index == node->count) {
a84a197d
MD
173 if (hammer_debug_btree) {
174 kprintf("BRACKETU %016llx[%d] -> %016llx[%d] (td=%p)\n",
973c11b9 175 (long long)cursor->node->node_offset,
a84a197d 176 cursor->index,
973c11b9 177 (long long)(cursor->parent ? cursor->parent->node_offset : -1),
a84a197d
MD
178 cursor->parent_index,
179 curthread);
180 }
181 KKASSERT(cursor->parent == NULL || cursor->parent->ondisk->elms[cursor->parent_index].internal.subtree_offset == cursor->node->node_offset);
6a37e7e4 182 error = hammer_cursor_up(cursor);
8cd0a023
MD
183 if (error)
184 break;
46fe7ae1 185 /* reload stale pointer */
8cd0a023
MD
186 node = cursor->node->ondisk;
187 KKASSERT(cursor->index != node->count);
2f85fa4d
MD
188
189 /*
190 * If we are reblocking we want to return internal
1775b6a0
MD
191 * nodes. Note that the internal node will be
192 * returned multiple times, on each upward recursion
193 * from its children. The caller selects which
194 * revisit it cares about (usually first or last only).
2f85fa4d
MD
195 */
196 if (cursor->flags & HAMMER_CURSOR_REBLOCKING) {
197 cursor->flags |= HAMMER_CURSOR_ATEDISK;
198 return(0);
199 }
8cd0a023
MD
200 ++cursor->index;
201 continue;
66325755
MD
202 }
203
204 /*
d26d0ae9
MD
205 * Check internal or leaf element. Determine if the record
206 * at the cursor has gone beyond the end of our range.
66325755 207 *
47197d71 208 * We recurse down through internal nodes.
66325755 209 */
8cd0a023
MD
210 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
211 elm = &node->elms[cursor->index];
c82af904 212
d26d0ae9
MD
213 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
214 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
b3deaf57 215 if (hammer_debug_btree) {
f9b843c4
TK
216 kprintf("BRACKETL %016llx[%d] %016llx %02x "
217 "key=%016llx lo=%02x %d (td=%p)\n",
973c11b9 218 (long long)cursor->node->node_offset,
eaeff70d 219 cursor->index,
973c11b9 220 (long long)elm[0].internal.base.obj_id,
b3deaf57 221 elm[0].internal.base.rec_type,
973c11b9 222 (long long)elm[0].internal.base.key,
2f85fa4d 223 elm[0].internal.base.localization,
a84a197d
MD
224 r,
225 curthread
b3deaf57 226 );
f9b843c4
TK
227 kprintf("BRACKETR %016llx[%d] %016llx %02x "
228 "key=%016llx lo=%02x %d\n",
973c11b9 229 (long long)cursor->node->node_offset,
eaeff70d 230 cursor->index + 1,
973c11b9 231 (long long)elm[1].internal.base.obj_id,
b3deaf57 232 elm[1].internal.base.rec_type,
973c11b9 233 (long long)elm[1].internal.base.key,
2f85fa4d 234 elm[1].internal.base.localization,
b3deaf57
MD
235 s
236 );
237 }
238
d26d0ae9
MD
239 if (r < 0) {
240 error = ENOENT;
241 break;
66325755 242 }
fe7678ee
MD
243 if (r == 0 && (cursor->flags &
244 HAMMER_CURSOR_END_INCLUSIVE) == 0) {
d26d0ae9 245 error = ENOENT;
8cd0a023 246 break;
d26d0ae9 247 }
6a37e7e4
MD
248
249 /*
f36a9737 250 * Better not be zero
6a37e7e4 251 */
f36a9737
MD
252 KKASSERT(elm->internal.subtree_offset != 0);
253
6dc17446
MD
254 if (s <= 0) {
255 /*
256 * If running the mirror filter see if we
257 * can skip one or more entire sub-trees.
258 * If we can we return the internal node
259 * and the caller processes the skipped
260 * range (see mirror_read).
261 */
262 if (cursor->flags &
263 HAMMER_CURSOR_MIRROR_FILTERED) {
264 if (elm->internal.mirror_tid <
265 cursor->cmirror->mirror_tid) {
266 hammer_cursor_mirror_filter(cursor);
267 return(0);
268 }
c82af904 269 }
6dc17446
MD
270 } else {
271 /*
272 * Normally it would be impossible for the
273 * cursor to have gotten back-indexed,
274 * but it can happen if a node is deleted
275 * and the cursor is moved to its parent
276 * internal node. ITERATE_CHECK will be set.
277 */
278 KKASSERT(cursor->flags &
279 HAMMER_CURSOR_ITERATE_CHECK);
280 kprintf("hammer_btree_iterate: "
281 "DEBUG: Caught parent seek "
282 "in internal iteration\n");
c82af904
MD
283 }
284
f36a9737
MD
285 error = hammer_cursor_down(cursor);
286 if (error)
287 break;
288 KKASSERT(cursor->index == 0);
46fe7ae1
MD
289 /* reload stale pointer */
290 node = cursor->node->ondisk;
fe7678ee 291 continue;
d26d0ae9
MD
292 } else {
293 elm = &node->elms[cursor->index];
294 r = hammer_btree_cmp(&cursor->key_end, &elm->base);
b3deaf57 295 if (hammer_debug_btree) {
f9b843c4
TK
296 kprintf("ELEMENT %016llx:%d %c %016llx %02x "
297 "key=%016llx lo=%02x %d\n",
973c11b9 298 (long long)cursor->node->node_offset,
eaeff70d
MD
299 cursor->index,
300 (elm[0].leaf.base.btype ?
301 elm[0].leaf.base.btype : '?'),
973c11b9 302 (long long)elm[0].leaf.base.obj_id,
b3deaf57 303 elm[0].leaf.base.rec_type,
973c11b9 304 (long long)elm[0].leaf.base.key,
2f85fa4d 305 elm[0].leaf.base.localization,
b3deaf57
MD
306 r
307 );
308 }
d26d0ae9
MD
309 if (r < 0) {
310 error = ENOENT;
311 break;
312 }
b33e2cc0
MD
313
314 /*
315 * We support both end-inclusive and
316 * end-exclusive searches.
317 */
318 if (r == 0 &&
319 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
320 error = ENOENT;
321 break;
322 }
323
6dc17446
MD
324 /*
325 * If ITERATE_CHECK is set an unlocked cursor may
326 * have been moved to a parent and the iterate can
327 * happen upon elements that are not in the requested
328 * range.
329 */
330 if (cursor->flags & HAMMER_CURSOR_ITERATE_CHECK) {
331 s = hammer_btree_cmp(&cursor->key_beg,
332 &elm->base);
333 if (s > 0) {
334 kprintf("hammer_btree_iterate: "
335 "DEBUG: Caught parent seek "
336 "in leaf iteration\n");
337 ++cursor->index;
338 continue;
339 }
340 }
341 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
342
343 /*
344 * Return the element
345 */
fe7678ee
MD
346 switch(elm->leaf.base.btype) {
347 case HAMMER_BTREE_TYPE_RECORD:
348 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
349 hammer_btree_chkts(cursor->asof, &elm->base)) {
350 ++cursor->index;
351 continue;
352 }
1d4077f7 353 error = 0;
fe7678ee 354 break;
fe7678ee
MD
355 default:
356 error = EINVAL;
357 break;
d26d0ae9 358 }
fe7678ee
MD
359 if (error)
360 break;
66325755
MD
361 }
362
363 /*
d26d0ae9 364 * Return entry
66325755 365 */
b3deaf57
MD
366 if (hammer_debug_btree) {
367 int i = cursor->index;
368 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
f9b843c4
TK
369 kprintf("ITERATE %p:%d %016llx %02x "
370 "key=%016llx lo=%02x\n",
b3deaf57 371 cursor->node, i,
973c11b9 372 (long long)elm->internal.base.obj_id,
b3deaf57 373 elm->internal.base.rec_type,
973c11b9 374 (long long)elm->internal.base.key,
2f85fa4d 375 elm->internal.base.localization
b3deaf57
MD
376 );
377 }
d26d0ae9 378 return(0);
427e5fc6 379 }
66325755 380 return(error);
427e5fc6
MD
381}
382
4c038e17
MD
383/*
384 * We hit an internal element that we could skip as part of a mirroring
385 * scan. Calculate the entire range being skipped.
386 *
387 * It is important to include any gaps between the parent's left_bound
388 * and the node's left_bound, and same goes for the right side.
389 */
390static void
391hammer_cursor_mirror_filter(hammer_cursor_t cursor)
392{
393 struct hammer_cmirror *cmirror;
394 hammer_node_ondisk_t ondisk;
395 hammer_btree_elm_t elm;
396
397 ondisk = cursor->node->ondisk;
398 cmirror = cursor->cmirror;
399
400 /*
401 * Calculate the skipped range
402 */
403 elm = &ondisk->elms[cursor->index];
404 if (cursor->index == 0)
405 cmirror->skip_beg = *cursor->left_bound;
406 else
407 cmirror->skip_beg = elm->internal.base;
408 while (cursor->index < ondisk->count) {
409 if (elm->internal.mirror_tid >= cmirror->mirror_tid)
410 break;
411 ++cursor->index;
412 ++elm;
413 }
414 if (cursor->index == ondisk->count)
415 cmirror->skip_end = *cursor->right_bound;
416 else
417 cmirror->skip_end = elm->internal.base;
418
419 /*
420 * clip the returned result.
421 */
422 if (hammer_btree_cmp(&cmirror->skip_beg, &cursor->key_beg) < 0)
423 cmirror->skip_beg = cursor->key_beg;
424 if (hammer_btree_cmp(&cmirror->skip_end, &cursor->key_end) > 0)
425 cmirror->skip_end = cursor->key_end;
426}
427
32c90105
MD
428/*
429 * Iterate in the reverse direction. This is used by the pruning code to
430 * avoid overlapping records.
431 */
432int
433hammer_btree_iterate_reverse(hammer_cursor_t cursor)
434{
435 hammer_node_ondisk_t node;
436 hammer_btree_elm_t elm;
bb5add8c 437 hammer_mount_t hmp;
f75df937 438 int error = 0;
32c90105
MD
439 int r;
440 int s;
441
4c038e17
MD
442 /* mirror filtering not supported for reverse iteration */
443 KKASSERT ((cursor->flags & HAMMER_CURSOR_MIRROR_FILTERED) == 0);
444
32c90105
MD
445 /*
446 * Skip past the current record. For various reasons the cursor
447 * may end up set to -1 or set to point at the end of the current
448 * node. These cases must be addressed.
449 */
450 node = cursor->node->ondisk;
451 if (node == NULL)
452 return(ENOENT);
453 if (cursor->index != -1 &&
454 (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
455 --cursor->index;
456 }
457 if (cursor->index == cursor->node->ondisk->count)
458 --cursor->index;
459
bb5add8c
MD
460 /*
461 * HAMMER can wind up being cpu-bound.
462 */
463 hmp = cursor->trans->hmp;
464 if (++hmp->check_yield > hammer_yield_check) {
465 hmp->check_yield = 0;
466 lwkt_user_yield();
467 }
468
32c90105
MD
469 /*
470 * Loop until an element is found or we are done.
471 */
472 for (;;) {
77fec802 473 ++hammer_stats_btree_iterations;
bb5add8c 474 hammer_flusher_clean_loose_ios(hmp);
77fec802 475
32c90105
MD
476 /*
477 * We iterate up the tree and then index over one element
478 * while we are at the last element in the current node.
32c90105
MD
479 */
480 if (cursor->index == -1) {
481 error = hammer_cursor_up(cursor);
482 if (error) {
483 cursor->index = 0; /* sanity */
484 break;
485 }
486 /* reload stale pointer */
487 node = cursor->node->ondisk;
488 KKASSERT(cursor->index != node->count);
489 --cursor->index;
490 continue;
491 }
492
493 /*
494 * Check internal or leaf element. Determine if the record
495 * at the cursor has gone beyond the end of our range.
496 *
47197d71 497 * We recurse down through internal nodes.
32c90105
MD
498 */
499 KKASSERT(cursor->index != node->count);
500 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
501 elm = &node->elms[cursor->index];
7c682412 502
32c90105
MD
503 r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
504 s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
505 if (hammer_debug_btree) {
f9b843c4 506 kprintf("BRACKETL %016llx[%d] %016llx %02x "
7c682412 507 "key=%016llx lo=%02x %d (td=%p)\n",
973c11b9 508 (long long)cursor->node->node_offset,
32c90105 509 cursor->index,
973c11b9 510 (long long)elm[0].internal.base.obj_id,
32c90105 511 elm[0].internal.base.rec_type,
973c11b9 512 (long long)elm[0].internal.base.key,
2f85fa4d 513 elm[0].internal.base.localization,
7c682412
TK
514 r,
515 curthread
32c90105 516 );
f9b843c4
TK
517 kprintf("BRACKETR %016llx[%d] %016llx %02x "
518 "key=%016llx lo=%02x %d\n",
973c11b9 519 (long long)cursor->node->node_offset,
32c90105 520 cursor->index + 1,
973c11b9 521 (long long)elm[1].internal.base.obj_id,
32c90105 522 elm[1].internal.base.rec_type,
973c11b9 523 (long long)elm[1].internal.base.key,
2f85fa4d 524 elm[1].internal.base.localization,
32c90105
MD
525 s
526 );
527 }
528
529 if (s >= 0) {
530 error = ENOENT;
531 break;
532 }
6dc17446
MD
533
534 /*
535 * It shouldn't be possible to be seeked past key_end,
536 * even if the cursor got moved to a parent.
537 */
32c90105
MD
538 KKASSERT(r >= 0);
539
540 /*
f36a9737 541 * Better not be zero
32c90105 542 */
f36a9737
MD
543 KKASSERT(elm->internal.subtree_offset != 0);
544
545 error = hammer_cursor_down(cursor);
546 if (error)
547 break;
548 KKASSERT(cursor->index == 0);
32c90105
MD
549 /* reload stale pointer */
550 node = cursor->node->ondisk;
f36a9737
MD
551
552 /* this can assign -1 if the leaf was empty */
553 cursor->index = node->count - 1;
32c90105
MD
554 continue;
555 } else {
556 elm = &node->elms[cursor->index];
557 s = hammer_btree_cmp(&cursor->key_beg, &elm->base);
558 if (hammer_debug_btree) {
7c682412 559 kprintf("ELEMENTR %016llx:%d %c %016llx %02x "
f9b843c4 560 "key=%016llx lo=%02x %d\n",
973c11b9 561 (long long)cursor->node->node_offset,
32c90105
MD
562 cursor->index,
563 (elm[0].leaf.base.btype ?
564 elm[0].leaf.base.btype : '?'),
973c11b9 565 (long long)elm[0].leaf.base.obj_id,
32c90105 566 elm[0].leaf.base.rec_type,
973c11b9 567 (long long)elm[0].leaf.base.key,
2f85fa4d 568 elm[0].leaf.base.localization,
32c90105
MD
569 s
570 );
571 }
572 if (s > 0) {
573 error = ENOENT;
574 break;
575 }
576
6dc17446
MD
577 /*
578 * It shouldn't be possible to be seeked past key_end,
579 * even if the cursor got moved to a parent.
580 */
581 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
582
583 /*
584 * Return the element
585 */
32c90105
MD
586 switch(elm->leaf.base.btype) {
587 case HAMMER_BTREE_TYPE_RECORD:
588 if ((cursor->flags & HAMMER_CURSOR_ASOF) &&
589 hammer_btree_chkts(cursor->asof, &elm->base)) {
590 --cursor->index;
591 continue;
592 }
f75df937 593 error = 0;
32c90105 594 break;
32c90105
MD
595 default:
596 error = EINVAL;
597 break;
598 }
599 if (error)
600 break;
601 }
32c90105
MD
602
603 /*
604 * Return entry
605 */
606 if (hammer_debug_btree) {
607 int i = cursor->index;
608 hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
7c682412 609 kprintf("ITERATER %p:%d %016llx %02x "
f9b843c4 610 "key=%016llx lo=%02x\n",
32c90105 611 cursor->node, i,
973c11b9 612 (long long)elm->internal.base.obj_id,
32c90105 613 elm->internal.base.rec_type,
973c11b9 614 (long long)elm->internal.base.key,
2f85fa4d 615 elm->internal.base.localization
32c90105
MD
616 );
617 }
618 return(0);
619 }
620 return(error);
621}
622
427e5fc6 623/*
8cd0a023 624 * Lookup cursor->key_beg. 0 is returned on success, ENOENT if the entry
6a37e7e4
MD
625 * could not be found, EDEADLK if inserting and a retry is needed, and a
626 * fatal error otherwise. When retrying, the caller must terminate the
eaeff70d 627 * cursor and reinitialize it. EDEADLK cannot be returned if not inserting.
8cd0a023
MD
628 *
629 * The cursor is suitably positioned for a deletion on success, and suitably
eaeff70d
MD
630 * positioned for an insertion on ENOENT if HAMMER_CURSOR_INSERT was
631 * specified.
427e5fc6 632 *
47197d71 633 * The cursor may begin anywhere, the search will traverse the tree in
8cd0a023 634 * either direction to locate the requested element.
eaeff70d
MD
635 *
636 * Most of the logic implementing historical searches is handled here. We
9582c7da
MD
637 * do an initial lookup with create_tid set to the asof TID. Due to the
638 * way records are laid out, a backwards iteration may be required if
eaeff70d
MD
639 * ENOENT is returned to locate the historical record. Here's the
640 * problem:
641 *
9582c7da 642 * create_tid: 10 15 20
eaeff70d
MD
643 * LEAF1 LEAF2
644 * records: (11) (18)
645 *
9582c7da
MD
646 * Lets say we want to do a lookup AS-OF timestamp 17. We will traverse
647 * LEAF2 but the only record in LEAF2 has a create_tid of 18, which is
648 * not visible and thus causes ENOENT to be returned. We really need
649 * to check record 11 in LEAF1. If it also fails then the search fails
650 * (e.g. it might represent the range 11-16 and thus still not match our
f36a9737
MD
651 * AS-OF timestamp of 17). Note that LEAF1 could be empty, requiring
652 * further iterations.
b33e2cc0 653 *
9582c7da
MD
654 * If this case occurs btree_search() will set HAMMER_CURSOR_CREATE_CHECK
655 * and the cursor->create_check TID if an iteration might be needed.
656 * In the above example create_check would be set to 14.
427e5fc6
MD
657 */
658int
8cd0a023 659hammer_btree_lookup(hammer_cursor_t cursor)
427e5fc6 660{
66325755
MD
661 int error;
662
6dc17446 663 cursor->flags &= ~HAMMER_CURSOR_ITERATE_CHECK;
98da6d8c
MD
664 KKASSERT ((cursor->flags & HAMMER_CURSOR_INSERT) == 0 ||
665 cursor->trans->sync_lock_refs > 0);
cb51be26 666 ++hammer_stats_btree_lookups;
d5530d22 667 if (cursor->flags & HAMMER_CURSOR_ASOF) {
eaeff70d 668 KKASSERT((cursor->flags & HAMMER_CURSOR_INSERT) == 0);
9582c7da 669 cursor->key_beg.create_tid = cursor->asof;
eaeff70d 670 for (;;) {
9582c7da 671 cursor->flags &= ~HAMMER_CURSOR_CREATE_CHECK;
d5530d22 672 error = btree_search(cursor, 0);
b33e2cc0 673 if (error != ENOENT ||
9582c7da 674 (cursor->flags & HAMMER_CURSOR_CREATE_CHECK) == 0) {
b33e2cc0
MD
675 /*
676 * Stop if no error.
677 * Stop if error other then ENOENT.
678 * Stop if ENOENT and not special case.
679 */
eaeff70d
MD
680 break;
681 }
32c90105
MD
682 if (hammer_debug_btree) {
683 kprintf("CREATE_CHECK %016llx\n",
973c11b9 684 (long long)cursor->create_check);
32c90105 685 }
9582c7da 686 cursor->key_beg.create_tid = cursor->create_check;
eaeff70d
MD
687 /* loop */
688 }
d5530d22
MD
689 } else {
690 error = btree_search(cursor, 0);
691 }
bf3b416b 692 if (error == 0)
8cd0a023 693 error = hammer_btree_extract(cursor, cursor->flags);
66325755
MD
694 return(error);
695}
696
d26d0ae9
MD
697/*
698 * Execute the logic required to start an iteration. The first record
699 * located within the specified range is returned and iteration control
700 * flags are adjusted for successive hammer_btree_iterate() calls.
3214ade6
MD
701 *
702 * Set ATEDISK so a low-level caller can call btree_first/btree_iterate
703 * in a loop without worrying about it. Higher-level merged searches will
704 * adjust the flag appropriately.
d26d0ae9
MD
705 */
706int
707hammer_btree_first(hammer_cursor_t cursor)
708{
709 int error;
710
711 error = hammer_btree_lookup(cursor);
712 if (error == ENOENT) {
713 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
714 error = hammer_btree_iterate(cursor);
715 }
716 cursor->flags |= HAMMER_CURSOR_ATEDISK;
717 return(error);
718}
719
32c90105
MD
720/*
721 * Similarly but for an iteration in the reverse direction.
814387f6
MD
722 *
723 * Set ATEDISK when iterating backwards to skip the current entry,
724 * which after an ENOENT lookup will be pointing beyond our end point.
3214ade6
MD
725 *
726 * Set ATEDISK so a low-level caller can call btree_last/btree_iterate_reverse
727 * in a loop without worrying about it. Higher-level merged searches will
728 * adjust the flag appropriately.
32c90105
MD
729 */
730int
731hammer_btree_last(hammer_cursor_t cursor)
732{
733 struct hammer_base_elm save;
734 int error;
735
736 save = cursor->key_beg;
737 cursor->key_beg = cursor->key_end;
738 error = hammer_btree_lookup(cursor);
739 cursor->key_beg = save;
740 if (error == ENOENT ||
741 (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
814387f6 742 cursor->flags |= HAMMER_CURSOR_ATEDISK;
32c90105
MD
743 error = hammer_btree_iterate_reverse(cursor);
744 }
745 cursor->flags |= HAMMER_CURSOR_ATEDISK;
746 return(error);
747}
748
8cd0a023
MD
749/*
750 * Extract the record and/or data associated with the cursor's current
751 * position. Any prior record or data stored in the cursor is replaced.
8cd0a023 752 *
47197d71 753 * NOTE: All extractions occur at the leaf of the B-Tree.
8cd0a023 754 */
66325755 755int
8cd0a023 756hammer_btree_extract(hammer_cursor_t cursor, int flags)
66325755 757{
8cd0a023
MD
758 hammer_node_ondisk_t node;
759 hammer_btree_elm_t elm;
47197d71 760 hammer_off_t data_off;
bac808fe 761 hammer_mount_t hmp;
19619882 762 int32_t data_len;
427e5fc6 763 int error;
427e5fc6 764
8cd0a023 765 /*
427e5fc6
MD
766 * The case where the data reference resolves to the same buffer
767 * as the record reference must be handled.
768 */
8cd0a023 769 node = cursor->node->ondisk;
8cd0a023 770 elm = &node->elms[cursor->index];
40043e7f
MD
771 cursor->data = NULL;
772 hmp = cursor->node->hmp;
66325755 773
d26d0ae9 774 /*
fe7678ee 775 * There is nothing to extract for an internal element.
d26d0ae9 776 */
fe7678ee
MD
777 if (node->type == HAMMER_BTREE_TYPE_INTERNAL)
778 return(EINVAL);
779
47197d71
MD
780 /*
781 * Only record types have data.
782 */
fe7678ee 783 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
11ad5ade 784 cursor->leaf = &elm->leaf;
4a2796f3
MD
785
786 if ((flags & HAMMER_CURSOR_GET_DATA) == 0)
787 return(0);
47197d71 788 if (elm->leaf.base.btype != HAMMER_BTREE_TYPE_RECORD)
4a2796f3 789 return(0);
47197d71 790 data_off = elm->leaf.data_offset;
19619882 791 data_len = elm->leaf.data_len;
47197d71 792 if (data_off == 0)
4a2796f3 793 return(0);
d26d0ae9 794
4a2796f3
MD
795 /*
796 * Load the data
797 */
798 KKASSERT(data_len >= 0 && data_len <= HAMMER_XBUFSIZE);
799 cursor->data = hammer_bread_ext(hmp, data_off, data_len,
800 &error, &cursor->data_buffer);
b8a41159
MD
801
802 /*
803 * Mark the data buffer as not being meta-data if it isn't
804 * meta-data (sometimes bulk data is accessed via a volume
805 * block device).
806 */
807 if (error == 0) {
808 switch(elm->leaf.base.rec_type) {
809 case HAMMER_RECTYPE_DATA:
810 case HAMMER_RECTYPE_DB:
18bee4a2
MD
811 if ((data_off & HAMMER_ZONE_LARGE_DATA) == 0)
812 break;
813 if (hammer_double_buffer == 0 ||
814 (cursor->flags & HAMMER_CURSOR_NOSWAPCACHE)) {
815 hammer_io_notmeta(cursor->data_buffer);
816 }
b8a41159
MD
817 break;
818 default:
819 break;
820 }
821 }
822
823 /*
824 * Deal with CRC errors on the extracted data.
825 */
2faf0737
MD
826 if (error == 0 &&
827 hammer_crc_test_leaf(cursor->data, &elm->leaf) == 0) {
e469566b 828 kprintf("CRC DATA @ %016llx/%d FAILED\n",
973c11b9 829 (long long)elm->leaf.data_offset, elm->leaf.data_len);
fc73edd8 830 if (hammer_debug_critical)
4c286c36
MD
831 Debugger("CRC FAILED: DATA");
832 if (cursor->trans->flags & HAMMER_TRANSF_CRCDOM)
833 error = EDOM; /* less critical (mirroring) */
834 else
835 error = EIO; /* critical */
e469566b 836 }
427e5fc6
MD
837 return(error);
838}
839
840
841/*
8cd0a023
MD
842 * Insert a leaf element into the B-Tree at the current cursor position.
843 * The cursor is positioned such that the element at and beyond the cursor
844 * are shifted to make room for the new record.
845 *
a89aec1b 846 * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
8cd0a023 847 * flag set and that call must return ENOENT before this function can be
2f49d4c5 848 * called. ENOSPC is returned if there is no room to insert a new record.
8cd0a023 849 *
d36ec43b 850 * The caller may depend on the cursor's exclusive lock after return to
1f07f686 851 * interlock frontend visibility (see HAMMER_RECF_CONVERT_DELETE).
427e5fc6
MD
852 */
853int
602c6cb8
MD
854hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_leaf_elm_t elm,
855 int *doprop)
427e5fc6 856{
8cd0a023 857 hammer_node_ondisk_t node;
427e5fc6 858 int i;
6a37e7e4
MD
859 int error;
860
602c6cb8 861 *doprop = 0;
7bc5b8c2 862 if ((error = hammer_cursor_upgrade_node(cursor)) != 0)
6a37e7e4 863 return(error);
cb51be26 864 ++hammer_stats_btree_inserts;
427e5fc6 865
427e5fc6
MD
866 /*
867 * Insert the element at the leaf node and update the count in the
868 * parent. It is possible for parent to be NULL, indicating that
47197d71
MD
869 * the filesystem's ROOT B-Tree node is a leaf itself, which is
870 * possible. The root inode can never be deleted so the leaf should
871 * never be empty.
427e5fc6 872 *
2f49d4c5 873 * Remember that leaf nodes do not have boundaries.
427e5fc6 874 */
36f82b23 875 hammer_modify_node_all(cursor->trans, cursor->node);
8cd0a023 876 node = cursor->node->ondisk;
427e5fc6 877 i = cursor->index;
fe7678ee 878 KKASSERT(elm->base.btype != 0);
8cd0a023
MD
879 KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
880 KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
881 if (i != node->count) {
882 bcopy(&node->elms[i], &node->elms[i+1],
883 (node->count - i) * sizeof(*elm));
884 }
11ad5ade 885 node->elms[i].leaf = *elm;
8cd0a023 886 ++node->count;
e4a5ff06 887 hammer_cursor_inserted_element(cursor->node, i);
c82af904
MD
888
889 /*
890 * Update the leaf node's aggregate mirror_tid for mirroring
891 * support.
892 */
602c6cb8 893 if (node->mirror_tid < elm->base.delete_tid) {
c82af904 894 node->mirror_tid = elm->base.delete_tid;
602c6cb8
MD
895 *doprop = 1;
896 }
897 if (node->mirror_tid < elm->base.create_tid) {
c82af904 898 node->mirror_tid = elm->base.create_tid;
602c6cb8 899 *doprop = 1;
c82af904 900 }
602c6cb8 901 hammer_modify_node_done(cursor->node);
c82af904 902
eaeff70d 903 /*
47197d71 904 * Debugging sanity checks.
eaeff70d 905 */
11ad5ade
MD
906 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->base) <= 0);
907 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->base) > 0);
eaeff70d 908 if (i) {
11ad5ade 909 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->base) < 0);
eaeff70d 910 }
b3deaf57 911 if (i != node->count - 1)
11ad5ade 912 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->base) > 0);
b3deaf57 913
427e5fc6
MD
914 return(0);
915}
916
917/*
fe7678ee 918 * Delete a record from the B-Tree at the current cursor position.
8cd0a023
MD
919 * The cursor is positioned such that the current element is the one
920 * to be deleted.
921 *
195c19a1
MD
922 * On return the cursor will be positioned after the deleted element and
923 * MAY point to an internal node. It will be suitable for the continuation
924 * of an iteration but not for an insertion or deletion.
8cd0a023 925 *
195c19a1 926 * Deletions will attempt to partially rebalance the B-Tree in an upward
f36a9737
MD
927 * direction, but will terminate rather then deadlock. Empty internal nodes
928 * are never allowed by a deletion which deadlocks may end up giving us an
929 * empty leaf. The pruner will clean up and rebalance the tree.
46fe7ae1
MD
930 *
931 * This function can return EDEADLK, requiring the caller to retry the
932 * operation after clearing the deadlock.
427e5fc6
MD
933 */
934int
8cd0a023 935hammer_btree_delete(hammer_cursor_t cursor)
427e5fc6 936{
8cd0a023
MD
937 hammer_node_ondisk_t ondisk;
938 hammer_node_t node;
f31f6d84 939 hammer_node_t parent __debugvar;
8cd0a023 940 int error;
427e5fc6
MD
941 int i;
942
98da6d8c 943 KKASSERT (cursor->trans->sync_lock_refs > 0);
6a37e7e4
MD
944 if ((error = hammer_cursor_upgrade(cursor)) != 0)
945 return(error);
cb51be26 946 ++hammer_stats_btree_deletes;
6a37e7e4 947
427e5fc6 948 /*
8cd0a023 949 * Delete the element from the leaf node.
427e5fc6 950 *
8cd0a023 951 * Remember that leaf nodes do not have boundaries.
427e5fc6 952 */
8cd0a023
MD
953 node = cursor->node;
954 ondisk = node->ondisk;
427e5fc6
MD
955 i = cursor->index;
956
8cd0a023 957 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
fe7678ee 958 KKASSERT(i >= 0 && i < ondisk->count);
36f82b23 959 hammer_modify_node_all(cursor->trans, node);
8cd0a023
MD
960 if (i + 1 != ondisk->count) {
961 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
962 (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
963 }
964 --ondisk->count;
10a5d1ba 965 hammer_modify_node_done(node);
b3bad96f 966 hammer_cursor_deleted_element(node, i);
fe7678ee
MD
967
968 /*
969 * Validate local parent
970 */
971 if (ondisk->parent) {
8cd0a023 972 parent = cursor->parent;
fe7678ee
MD
973
974 KKASSERT(parent != NULL);
975 KKASSERT(parent->node_offset == ondisk->parent);
427e5fc6 976 }
427e5fc6 977
8cd0a023 978 /*
fe7678ee 979 * If the leaf becomes empty it must be detached from the parent,
47197d71 980 * potentially recursing through to the filesystem root.
195c19a1
MD
981 *
982 * This may reposition the cursor at one of the parent's of the
983 * current node.
6a37e7e4
MD
984 *
985 * Ignore deadlock errors, that simply means that btree_remove
f36a9737 986 * was unable to recurse and had to leave us with an empty leaf.
8cd0a023 987 */
b3deaf57 988 KKASSERT(cursor->index <= ondisk->count);
8cd0a023 989 if (ondisk->count == 0) {
f36a9737 990 error = btree_remove(cursor);
6a37e7e4
MD
991 if (error == EDEADLK)
992 error = 0;
8cd0a023 993 } else {
8cd0a023
MD
994 error = 0;
995 }
eaeff70d
MD
996 KKASSERT(cursor->parent == NULL ||
997 cursor->parent_index < cursor->parent->ondisk->count);
8cd0a023
MD
998 return(error);
999}
427e5fc6
MD
1000
1001/*
2f49d4c5 1002 * PRIMARY B-TREE SEARCH SUPPORT PROCEDURE
8cd0a023 1003 *
47197d71 1004 * Search the filesystem B-Tree for cursor->key_beg, return the matching node.
8cd0a023 1005 *
d26d0ae9
MD
1006 * The search can begin ANYWHERE in the B-Tree. As a first step the search
1007 * iterates up the tree as necessary to properly position itself prior to
1008 * actually doing the sarch.
1009 *
8cd0a023 1010 * INSERTIONS: The search will split full nodes and leaves on its way down
d26d0ae9 1011 * and guarentee that the leaf it ends up on is not full. If we run out
fd1fcc1a 1012 * of space the search continues to the leaf, but ENOSPC is returned.
427e5fc6 1013 *
fbc6e32a
MD
1014 * The search is only guarenteed to end up on a leaf if an error code of 0
1015 * is returned, or if inserting and an error code of ENOENT is returned.
d26d0ae9 1016 * Otherwise it can stop at an internal node. On success a search returns
47197d71 1017 * a leaf node.
eaeff70d
MD
1018 *
1019 * COMPLEXITY WARNING! This is the core B-Tree search code for the entire
1020 * filesystem, and it is not simple code. Please note the following facts:
1021 *
1022 * - Internal node recursions have a boundary on the left AND right. The
9582c7da 1023 * right boundary is non-inclusive. The create_tid is a generic part
eaeff70d
MD
1024 * of the key for internal nodes.
1025 *
47197d71 1026 * - Leaf nodes contain terminal elements only now.
eaeff70d
MD
1027 *
1028 * - Filesystem lookups typically set HAMMER_CURSOR_ASOF, indicating a
b33e2cc0
MD
1029 * historical search. ASOF and INSERT are mutually exclusive. When
1030 * doing an as-of lookup btree_search() checks for a right-edge boundary
9582c7da
MD
1031 * case. If while recursing down the left-edge differs from the key
1032 * by ONLY its create_tid, HAMMER_CURSOR_CREATE_CHECK is set along
1033 * with cursor->create_check. This is used by btree_lookup() to iterate.
1034 * The iteration backwards because as-of searches can wind up going
b33e2cc0 1035 * down the wrong branch of the B-Tree.
427e5fc6 1036 */
8cd0a023 1037static
427e5fc6 1038int
8cd0a023 1039btree_search(hammer_cursor_t cursor, int flags)
427e5fc6 1040{
8cd0a023 1041 hammer_node_ondisk_t node;
61aeeb33 1042 hammer_btree_elm_t elm;
8cd0a023 1043 int error;
d26d0ae9 1044 int enospc = 0;
8cd0a023
MD
1045 int i;
1046 int r;
b33e2cc0 1047 int s;
8cd0a023
MD
1048
1049 flags |= cursor->flags;
cb51be26 1050 ++hammer_stats_btree_searches;
8cd0a023 1051
b3deaf57 1052 if (hammer_debug_btree) {
7c682412 1053 kprintf("SEARCH %016llx[%d] %016llx %02x key=%016llx cre=%016llx lo=%02x (td=%p)\n",
973c11b9 1054 (long long)cursor->node->node_offset,
eaeff70d 1055 cursor->index,
973c11b9 1056 (long long)cursor->key_beg.obj_id,
b3deaf57 1057 cursor->key_beg.rec_type,
973c11b9
MD
1058 (long long)cursor->key_beg.key,
1059 (long long)cursor->key_beg.create_tid,
2f85fa4d 1060 cursor->key_beg.localization,
a84a197d 1061 curthread
b3deaf57 1062 );
a84a197d 1063 if (cursor->parent)
7c682412 1064 kprintf("SEARCHP %016llx[%d] (%016llx/%016llx %016llx/%016llx) (%p/%p %p/%p)\n",
973c11b9
MD
1065 (long long)cursor->parent->node_offset,
1066 cursor->parent_index,
1067 (long long)cursor->left_bound->obj_id,
1068 (long long)cursor->parent->ondisk->elms[cursor->parent_index].internal.base.obj_id,
1069 (long long)cursor->right_bound->obj_id,
1070 (long long)cursor->parent->ondisk->elms[cursor->parent_index+1].internal.base.obj_id,
a84a197d
MD
1071 cursor->left_bound,
1072 &cursor->parent->ondisk->elms[cursor->parent_index],
1073 cursor->right_bound,
1074 &cursor->parent->ondisk->elms[cursor->parent_index+1]
1075 );
b3deaf57
MD
1076 }
1077
8cd0a023
MD
1078 /*
1079 * Move our cursor up the tree until we find a node whos range covers
47197d71 1080 * the key we are trying to locate.
8cd0a023
MD
1081 *
1082 * The left bound is inclusive, the right bound is non-inclusive.
47197d71 1083 * It is ok to cursor up too far.
8cd0a023 1084 */
b33e2cc0
MD
1085 for (;;) {
1086 r = hammer_btree_cmp(&cursor->key_beg, cursor->left_bound);
1087 s = hammer_btree_cmp(&cursor->key_beg, cursor->right_bound);
1088 if (r >= 0 && s < 0)
1089 break;
9944ae54 1090 KKASSERT(cursor->parent);
cb51be26 1091 ++hammer_stats_btree_iterations;
6a37e7e4 1092 error = hammer_cursor_up(cursor);
8cd0a023
MD
1093 if (error)
1094 goto done;
427e5fc6 1095 }
427e5fc6 1096
b33e2cc0
MD
1097 /*
1098 * The delete-checks below are based on node, not parent. Set the
1099 * initial delete-check based on the parent.
1100 */
9582c7da
MD
1101 if (r == 1) {
1102 KKASSERT(cursor->left_bound->create_tid != 1);
1103 cursor->create_check = cursor->left_bound->create_tid - 1;
1104 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
b33e2cc0
MD
1105 }
1106
8cd0a023 1107 /*
47197d71 1108 * We better have ended up with a node somewhere.
8cd0a023 1109 */
47197d71 1110 KKASSERT(cursor->node != NULL);
8cd0a023
MD
1111
1112 /*
1113 * If we are inserting we can't start at a full node if the parent
1114 * is also full (because there is no way to split the node),
b33e2cc0 1115 * continue running up the tree until the requirement is satisfied
47197d71 1116 * or we hit the root of the filesystem.
9582c7da
MD
1117 *
1118 * (If inserting we aren't doing an as-of search so we don't have
1119 * to worry about create_check).
8cd0a023 1120 */
a9fd59b8
TK
1121 while (flags & HAMMER_CURSOR_INSERT) {
1122 if (btree_node_is_full(cursor->node->ondisk) == 0)
1123 break;
b33e2cc0
MD
1124 if (cursor->node->ondisk->parent == 0 ||
1125 cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS) {
8cd0a023 1126 break;
b33e2cc0 1127 }
cb51be26 1128 ++hammer_stats_btree_iterations;
6a37e7e4 1129 error = hammer_cursor_up(cursor);
47197d71 1130 /* node may have become stale */
8cd0a023
MD
1131 if (error)
1132 goto done;
427e5fc6 1133 }
427e5fc6 1134
8cd0a023
MD
1135 /*
1136 * Push down through internal nodes to locate the requested key.
1137 */
8cd0a023
MD
1138 node = cursor->node->ondisk;
1139 while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
8cd0a023
MD
1140 /*
1141 * Scan the node to find the subtree index to push down into.
fbc6e32a 1142 * We go one-past, then back-up.
d113fda1 1143 *
fe7678ee
MD
1144 * We must proactively remove deleted elements which may
1145 * have been left over from a deadlocked btree_remove().
1146 *
eaeff70d 1147 * The left and right boundaries are included in the loop
d5530d22 1148 * in order to detect edge cases.
9944ae54 1149 *
9582c7da 1150 * If the separator only differs by create_tid (r == 1)
eaeff70d
MD
1151 * and we are doing an as-of search, we may end up going
1152 * down a branch to the left of the one containing the
1153 * desired key. This requires numerous special cases.
8cd0a023 1154 */
47637bff 1155 ++hammer_stats_btree_iterations;
46fe7ae1 1156 if (hammer_debug_btree) {
47197d71 1157 kprintf("SEARCH-I %016llx count=%d\n",
973c11b9 1158 (long long)cursor->node->node_offset,
46fe7ae1
MD
1159 node->count);
1160 }
af209b0f
MD
1161
1162 /*
1163 * Try to shortcut the search before dropping into the
1164 * linear loop. Locate the first node where r <= 1.
1165 */
1166 i = hammer_btree_search_node(&cursor->key_beg, node);
1167 while (i <= node->count) {
cb51be26 1168 ++hammer_stats_btree_elements;
61aeeb33
MD
1169 elm = &node->elms[i];
1170 r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
b33e2cc0
MD
1171 if (hammer_debug_btree > 2) {
1172 kprintf(" IELM %p %d r=%d\n",
1173 &node->elms[i], i, r);
1174 }
9582c7da 1175 if (r < 0)
8cd0a023 1176 break;
9582c7da
MD
1177 if (r == 1) {
1178 KKASSERT(elm->base.create_tid != 1);
1179 cursor->create_check = elm->base.create_tid - 1;
1180 cursor->flags |= HAMMER_CURSOR_CREATE_CHECK;
b33e2cc0 1181 }
af209b0f 1182 ++i;
8cd0a023 1183 }
eaeff70d 1184 if (hammer_debug_btree) {
46fe7ae1
MD
1185 kprintf("SEARCH-I preI=%d/%d r=%d\n",
1186 i, node->count, r);
eaeff70d 1187 }
8cd0a023
MD
1188
1189 /*
9944ae54
MD
1190 * These cases occur when the parent's idea of the boundary
1191 * is wider then the child's idea of the boundary, and
1192 * require special handling. If not inserting we can
1193 * terminate the search early for these cases but the
1194 * child's boundaries cannot be unconditionally modified.
8cd0a023 1195 */
fbc6e32a 1196 if (i == 0) {
9944ae54
MD
1197 /*
1198 * If i == 0 the search terminated to the LEFT of the
1199 * left_boundary but to the RIGHT of the parent's left
1200 * boundary.
1201 */
fbc6e32a 1202 u_int8_t save;
d26d0ae9 1203
eaeff70d
MD
1204 elm = &node->elms[0];
1205
1206 /*
1207 * If we aren't inserting we can stop here.
1208 */
11ad5ade
MD
1209 if ((flags & (HAMMER_CURSOR_INSERT |
1210 HAMMER_CURSOR_PRUNING)) == 0) {
fbc6e32a
MD
1211 cursor->index = 0;
1212 return(ENOENT);
1213 }
9944ae54 1214
d5530d22
MD
1215 /*
1216 * Correct a left-hand boundary mismatch.
6a37e7e4 1217 *
f36a9737
MD
1218 * We can only do this if we can upgrade the lock,
1219 * and synchronized as a background cursor (i.e.
1220 * inserting or pruning).
10a5d1ba
MD
1221 *
1222 * WARNING: We can only do this if inserting, i.e.
1223 * we are running on the backend.
d5530d22 1224 */
eaeff70d
MD
1225 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1226 return(error);
10a5d1ba 1227 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
c9b9e29d
MD
1228 hammer_modify_node_field(cursor->trans, cursor->node,
1229 elms[0]);
fe7678ee 1230 save = node->elms[0].base.btype;
d5530d22 1231 node->elms[0].base = *cursor->left_bound;
fe7678ee 1232 node->elms[0].base.btype = save;
10a5d1ba 1233 hammer_modify_node_done(cursor->node);
9944ae54 1234 } else if (i == node->count + 1) {
d26d0ae9 1235 /*
9944ae54
MD
1236 * If i == node->count + 1 the search terminated to
1237 * the RIGHT of the right boundary but to the LEFT
eaeff70d
MD
1238 * of the parent's right boundary. If we aren't
1239 * inserting we can stop here.
d113fda1 1240 *
9944ae54
MD
1241 * Note that the last element in this case is
1242 * elms[i-2] prior to adjustments to 'i'.
d26d0ae9 1243 */
9944ae54 1244 --i;
11ad5ade
MD
1245 if ((flags & (HAMMER_CURSOR_INSERT |
1246 HAMMER_CURSOR_PRUNING)) == 0) {
9944ae54 1247 cursor->index = i;
eaeff70d 1248 return (ENOENT);
d26d0ae9
MD
1249 }
1250
d5530d22
MD
1251 /*
1252 * Correct a right-hand boundary mismatch.
1253 * (actual push-down record is i-2 prior to
1254 * adjustments to i).
6a37e7e4 1255 *
f36a9737
MD
1256 * We can only do this if we can upgrade the lock,
1257 * and synchronized as a background cursor (i.e.
1258 * inserting or pruning).
10a5d1ba
MD
1259 *
1260 * WARNING: We can only do this if inserting, i.e.
1261 * we are running on the backend.
d5530d22 1262 */
eaeff70d
MD
1263 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1264 return(error);
9944ae54 1265 elm = &node->elms[i];
10a5d1ba 1266 KKASSERT(cursor->flags & HAMMER_CURSOR_BACKEND);
36f82b23
MD
1267 hammer_modify_node(cursor->trans, cursor->node,
1268 &elm->base, sizeof(elm->base));
d5530d22 1269 elm->base = *cursor->right_bound;
10a5d1ba 1270 hammer_modify_node_done(cursor->node);
d5530d22 1271 --i;
fbc6e32a
MD
1272 } else {
1273 /*
9944ae54
MD
1274 * The push-down index is now i - 1. If we had
1275 * terminated on the right boundary this will point
1276 * us at the last element.
fbc6e32a
MD
1277 */
1278 --i;
1279 }
8cd0a023 1280 cursor->index = i;
6a37e7e4 1281 elm = &node->elms[i];
8cd0a023 1282
b3deaf57 1283 if (hammer_debug_btree) {
47197d71 1284 kprintf("RESULT-I %016llx[%d] %016llx %02x "
2f85fa4d 1285 "key=%016llx cre=%016llx lo=%02x\n",
973c11b9 1286 (long long)cursor->node->node_offset,
eaeff70d 1287 i,
973c11b9 1288 (long long)elm->internal.base.obj_id,
b3deaf57 1289 elm->internal.base.rec_type,
973c11b9
MD
1290 (long long)elm->internal.base.key,
1291 (long long)elm->internal.base.create_tid,
2f85fa4d 1292 elm->internal.base.localization
b3deaf57
MD
1293 );
1294 }
1295
6a37e7e4 1296 /*
f36a9737 1297 * We better have a valid subtree offset.
6a37e7e4 1298 */
f36a9737 1299 KKASSERT(elm->internal.subtree_offset != 0);
6a37e7e4 1300
8cd0a023
MD
1301 /*
1302 * Handle insertion and deletion requirements.
1303 *
1304 * If inserting split full nodes. The split code will
1305 * adjust cursor->node and cursor->index if the current
1306 * index winds up in the new node.
61aeeb33 1307 *
9944ae54
MD
1308 * If inserting and a left or right edge case was detected,
1309 * we cannot correct the left or right boundary and must
1310 * prepend and append an empty leaf node in order to make
1311 * the boundary correction.
1312 *
fd1fcc1a
TK
1313 * If we run out of space we set enospc but continue on
1314 * to a leaf.
8cd0a023 1315 */
61aeeb33 1316 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
fe7678ee 1317 if (btree_node_is_full(node)) {
8cd0a023 1318 error = btree_split_internal(cursor);
d26d0ae9
MD
1319 if (error) {
1320 if (error != ENOSPC)
1321 goto done;
1322 enospc = 1;
d26d0ae9 1323 }
8cd0a023
MD
1324 /*
1325 * reload stale pointers
1326 */
1327 i = cursor->index;
1328 node = cursor->node->ondisk;
1329 }
d26d0ae9 1330 }
427e5fc6
MD
1331
1332 /*
8cd0a023 1333 * Push down (push into new node, existing node becomes
d26d0ae9 1334 * the parent) and continue the search.
427e5fc6 1335 */
8cd0a023 1336 error = hammer_cursor_down(cursor);
47197d71 1337 /* node may have become stale */
8cd0a023
MD
1338 if (error)
1339 goto done;
1340 node = cursor->node->ondisk;
427e5fc6 1341 }
427e5fc6 1342
8cd0a023
MD
1343 /*
1344 * We are at a leaf, do a linear search of the key array.
d26d0ae9
MD
1345 *
1346 * On success the index is set to the matching element and 0
1347 * is returned.
1348 *
1349 * On failure the index is set to the insertion point and ENOENT
1350 * is returned.
8cd0a023
MD
1351 *
1352 * Boundaries are not stored in leaf nodes, so the index can wind
1353 * up to the left of element 0 (index == 0) or past the end of
f36a9737
MD
1354 * the array (index == node->count). It is also possible that the
1355 * leaf might be empty.
8cd0a023 1356 */
47637bff 1357 ++hammer_stats_btree_iterations;
fe7678ee 1358 KKASSERT (node->type == HAMMER_BTREE_TYPE_LEAF);
8cd0a023 1359 KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
46fe7ae1 1360 if (hammer_debug_btree) {
47197d71 1361 kprintf("SEARCH-L %016llx count=%d\n",
973c11b9 1362 (long long)cursor->node->node_offset,
46fe7ae1
MD
1363 node->count);
1364 }
8cd0a023 1365
af209b0f
MD
1366 /*
1367 * Try to shortcut the search before dropping into the
1368 * linear loop. Locate the first node where r <= 1.
1369 */
1370 i = hammer_btree_search_node(&cursor->key_beg, node);
1371 while (i < node->count) {
cb51be26 1372 ++hammer_stats_btree_elements;
fe7678ee
MD
1373 elm = &node->elms[i];
1374
1375 r = hammer_btree_cmp(&cursor->key_beg, &elm->leaf.base);
427e5fc6 1376
d5530d22
MD
1377 if (hammer_debug_btree > 1)
1378 kprintf(" ELM %p %d r=%d\n", &node->elms[i], i, r);
1379
427e5fc6 1380 /*
fe7678ee 1381 * We are at a record element. Stop if we've flipped past
9582c7da
MD
1382 * key_beg, not counting the create_tid test. Allow the
1383 * r == 1 case (key_beg > element but differs only by its
1384 * create_tid) to fall through to the AS-OF check.
427e5fc6 1385 */
fe7678ee
MD
1386 KKASSERT (elm->leaf.base.btype == HAMMER_BTREE_TYPE_RECORD);
1387
9582c7da 1388 if (r < 0)
d5530d22 1389 goto failed;
af209b0f
MD
1390 if (r > 1) {
1391 ++i;
d5530d22 1392 continue;
af209b0f 1393 }
427e5fc6 1394
66325755 1395 /*
9582c7da 1396 * Check our as-of timestamp against the element.
66325755 1397 */
eaeff70d 1398 if (flags & HAMMER_CURSOR_ASOF) {
fe7678ee 1399 if (hammer_btree_chkts(cursor->asof,
d113fda1 1400 &node->elms[i].base) != 0) {
af209b0f 1401 ++i;
d113fda1
MD
1402 continue;
1403 }
eaeff70d
MD
1404 /* success */
1405 } else {
af209b0f
MD
1406 if (r > 0) { /* can only be +1 */
1407 ++i;
9582c7da 1408 continue;
af209b0f 1409 }
eaeff70d 1410 /* success */
66325755 1411 }
d5530d22
MD
1412 cursor->index = i;
1413 error = 0;
eaeff70d 1414 if (hammer_debug_btree) {
47197d71 1415 kprintf("RESULT-L %016llx[%d] (SUCCESS)\n",
973c11b9 1416 (long long)cursor->node->node_offset, i);
eaeff70d 1417 }
d5530d22
MD
1418 goto done;
1419 }
1420
1421 /*
eaeff70d 1422 * The search of the leaf node failed. i is the insertion point.
d5530d22 1423 */
d5530d22 1424failed:
b3deaf57 1425 if (hammer_debug_btree) {
47197d71 1426 kprintf("RESULT-L %016llx[%d] (FAILED)\n",
973c11b9 1427 (long long)cursor->node->node_offset, i);
b3deaf57
MD
1428 }
1429
8cd0a023
MD
1430 /*
1431 * No exact match was found, i is now at the insertion point.
1432 *
1433 * If inserting split a full leaf before returning. This
1434 * may have the side effect of adjusting cursor->node and
1435 * cursor->index.
1436 */
1437 cursor->index = i;
eaeff70d 1438 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0 &&
47197d71 1439 btree_node_is_full(node)) {
8cd0a023 1440 error = btree_split_leaf(cursor);
d26d0ae9
MD
1441 if (error) {
1442 if (error != ENOSPC)
1443 goto done;
1444 enospc = 1;
d26d0ae9
MD
1445 }
1446 /*
1447 * reload stale pointers
1448 */
8cd0a023
MD
1449 /* NOT USED
1450 i = cursor->index;
1451 node = &cursor->node->internal;
1452 */
8cd0a023 1453 }
d26d0ae9
MD
1454
1455 /*
1456 * We reached a leaf but did not find the key we were looking for.
1457 * If this is an insert we will be properly positioned for an insert
fd1fcc1a 1458 * (ENOENT) or unable to insert (ENOSPC).
d26d0ae9
MD
1459 */
1460 error = enospc ? ENOSPC : ENOENT;
8cd0a023 1461done:
427e5fc6
MD
1462 return(error);
1463}
1464
af209b0f
MD
1465/*
1466 * Heuristical search for the first element whos comparison is <= 1. May
1467 * return an index whos compare result is > 1 but may only return an index
1468 * whos compare result is <= 1 if it is the first element with that result.
1469 */
bcac4bbb 1470int
af209b0f
MD
1471hammer_btree_search_node(hammer_base_elm_t elm, hammer_node_ondisk_t node)
1472{
1473 int b;
1474 int s;
1475 int i;
1476 int r;
1477
1478 /*
1479 * Don't bother if the node does not have very many elements
1480 */
1481 b = 0;
1482 s = node->count;
1483 while (s - b > 4) {
1484 i = b + (s - b) / 2;
cb51be26 1485 ++hammer_stats_btree_elements;
af209b0f
MD
1486 r = hammer_btree_cmp(elm, &node->elms[i].leaf.base);
1487 if (r <= 1) {
1488 s = i;
1489 } else {
1490 b = i;
1491 }
1492 }
1493 return(b);
1494}
1495
8cd0a023 1496
427e5fc6 1497/************************************************************************
8cd0a023 1498 * SPLITTING AND MERGING *
427e5fc6
MD
1499 ************************************************************************
1500 *
1501 * These routines do all the dirty work required to split and merge nodes.
1502 */
1503
1504/*
8cd0a023 1505 * Split an internal node into two nodes and move the separator at the split
fe7678ee 1506 * point to the parent.
427e5fc6 1507 *
8cd0a023
MD
1508 * (cursor->node, cursor->index) indicates the element the caller intends
1509 * to push into. We will adjust node and index if that element winds
427e5fc6 1510 * up in the split node.
8cd0a023 1511 *
47197d71
MD
1512 * If we are at the root of the filesystem a new root must be created with
1513 * two elements, one pointing to the original root and one pointing to the
8cd0a023 1514 * newly allocated split node.
427e5fc6
MD
1515 */
1516static
1517int
8cd0a023 1518btree_split_internal(hammer_cursor_t cursor)
427e5fc6 1519{
8cd0a023
MD
1520 hammer_node_ondisk_t ondisk;
1521 hammer_node_t node;
1522 hammer_node_t parent;
1523 hammer_node_t new_node;
1524 hammer_btree_elm_t elm;
1525 hammer_btree_elm_t parent_elm;
1775b6a0 1526 struct hammer_node_lock lockroot;
36f82b23 1527 hammer_mount_t hmp = cursor->trans->hmp;
427e5fc6
MD
1528 int parent_index;
1529 int made_root;
1530 int split;
1531 int error;
7f7c1f84 1532 int i;
8cd0a023 1533 const int esize = sizeof(*elm);
427e5fc6 1534
1775b6a0 1535 hammer_node_lock_init(&lockroot, cursor->node);
24cf83d2 1536 error = hammer_btree_lock_children(cursor, 1, &lockroot, NULL);
47197d71
MD
1537 if (error)
1538 goto done;
7bc5b8c2
MD
1539 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1540 goto done;
cb51be26 1541 ++hammer_stats_btree_splits;
6a37e7e4 1542
427e5fc6 1543 /*
fa2b9a03
MD
1544 * Calculate the split point. If the insertion point is at the
1545 * end of the leaf we adjust the split point significantly to the
1546 * right to try to optimize node fill and flag it. If we hit
1547 * that same leaf again our heuristic failed and we don't try
1548 * to optimize node fill (it could lead to a degenerate case).
427e5fc6 1549 */
8cd0a023
MD
1550 node = cursor->node;
1551 ondisk = node->ondisk;
fa2b9a03
MD
1552 KKASSERT(ondisk->count > 4);
1553 if (cursor->index == ondisk->count &&
1554 (node->flags & HAMMER_NODE_NONLINEAR) == 0) {
1555 split = (ondisk->count + 1) * 3 / 4;
1556 node->flags |= HAMMER_NODE_NONLINEAR;
1557 } else {
1558 /*
1559 * We are splitting but elms[split] will be promoted to
1560 * the parent, leaving the right hand node with one less
1561 * element. If the insertion point will be on the
1562 * left-hand side adjust the split point to give the
1563 * right hand side one additional node.
1564 */
1565 split = (ondisk->count + 1) / 2;
1566 if (cursor->index <= split)
1567 --split;
1568 }
427e5fc6
MD
1569
1570 /*
47197d71
MD
1571 * If we are at the root of the filesystem, create a new root node
1572 * with 1 element and split normally. Avoid making major
1573 * modifications until we know the whole operation will work.
427e5fc6 1574 */
8cd0a023 1575 if (ondisk->parent == 0) {
b4f86ea3 1576 parent = hammer_alloc_btree(cursor->trans, 0, &error);
427e5fc6 1577 if (parent == NULL)
6a37e7e4 1578 goto done;
8cd0a023 1579 hammer_lock_ex(&parent->lock);
36f82b23 1580 hammer_modify_node_noundo(cursor->trans, parent);
8cd0a023
MD
1581 ondisk = parent->ondisk;
1582 ondisk->count = 1;
1583 ondisk->parent = 0;
a56cb012 1584 ondisk->mirror_tid = node->ondisk->mirror_tid;
8cd0a023 1585 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
47197d71 1586 ondisk->elms[0].base = hmp->root_btree_beg;
fe7678ee 1587 ondisk->elms[0].base.btype = node->ondisk->type;
8cd0a023 1588 ondisk->elms[0].internal.subtree_offset = node->node_offset;
f0b930f3 1589 ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
47197d71 1590 ondisk->elms[1].base = hmp->root_btree_end;
10a5d1ba 1591 hammer_modify_node_done(parent);
fe7678ee 1592 /* ondisk->elms[1].base.btype - not used */
427e5fc6 1593 made_root = 1;
8cd0a023 1594 parent_index = 0; /* index of current node in parent */
427e5fc6
MD
1595 } else {
1596 made_root = 0;
8cd0a023
MD
1597 parent = cursor->parent;
1598 parent_index = cursor->parent_index;
427e5fc6 1599 }
427e5fc6
MD
1600
1601 /*
1602 * Split node into new_node at the split point.
1603 *
df2ccbac 1604 * B O O O P N N B <-- P = node->elms[split] (index 4)
427e5fc6
MD
1605 * 0 1 2 3 4 5 6 <-- subtree indices
1606 *
1607 * x x P x x
1608 * s S S s
1609 * / \
1610 * B O O O B B N N B <--- inner boundary points are 'P'
1611 * 0 1 2 3 4 5 6
427e5fc6 1612 */
b4f86ea3 1613 new_node = hammer_alloc_btree(cursor->trans, 0, &error);
427e5fc6 1614 if (new_node == NULL) {
8cd0a023
MD
1615 if (made_root) {
1616 hammer_unlock(&parent->lock);
36f82b23 1617 hammer_delete_node(cursor->trans, parent);
8cd0a023
MD
1618 hammer_rel_node(parent);
1619 }
6a37e7e4 1620 goto done;
427e5fc6 1621 }
8cd0a023 1622 hammer_lock_ex(&new_node->lock);
427e5fc6
MD
1623
1624 /*
8cd0a023 1625 * Create the new node. P becomes the left-hand boundary in the
427e5fc6
MD
1626 * new node. Copy the right-hand boundary as well.
1627 *
1628 * elm is the new separator.
1629 */
36f82b23
MD
1630 hammer_modify_node_noundo(cursor->trans, new_node);
1631 hammer_modify_node_all(cursor->trans, node);
8cd0a023
MD
1632 ondisk = node->ondisk;
1633 elm = &ondisk->elms[split];
1634 bcopy(elm, &new_node->ondisk->elms[0],
1635 (ondisk->count - split + 1) * esize);
1636 new_node->ondisk->count = ondisk->count - split;
1637 new_node->ondisk->parent = parent->node_offset;
1638 new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
a56cb012 1639 new_node->ondisk->mirror_tid = ondisk->mirror_tid;
8cd0a023 1640 KKASSERT(ondisk->type == new_node->ondisk->type);
b3bad96f 1641 hammer_cursor_split_node(node, new_node, split);
427e5fc6
MD
1642
1643 /*
fe7678ee
MD
1644 * Cleanup the original node. Elm (P) becomes the new boundary,
1645 * its subtree_offset was moved to the new node. If we had created
427e5fc6
MD
1646 * a new root its parent pointer may have changed.
1647 */
8cd0a023 1648 elm->internal.subtree_offset = 0;
c0ade690 1649 ondisk->count = split;
427e5fc6
MD
1650
1651 /*
1652 * Insert the separator into the parent, fixup the parent's
1653 * reference to the original node, and reference the new node.
1654 * The separator is P.
1655 *
1656 * Remember that base.count does not include the right-hand boundary.
1657 */
36f82b23 1658 hammer_modify_node_all(cursor->trans, parent);
8cd0a023 1659 ondisk = parent->ondisk;
d26d0ae9 1660 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
8cd0a023 1661 parent_elm = &ondisk->elms[parent_index+1];
427e5fc6 1662 bcopy(parent_elm, parent_elm + 1,
8cd0a023
MD
1663 (ondisk->count - parent_index) * esize);
1664 parent_elm->internal.base = elm->base; /* separator P */
fe7678ee 1665 parent_elm->internal.base.btype = new_node->ondisk->type;
8cd0a023 1666 parent_elm->internal.subtree_offset = new_node->node_offset;
a56cb012 1667 parent_elm->internal.mirror_tid = new_node->ondisk->mirror_tid;
76376933 1668 ++ondisk->count;
10a5d1ba 1669 hammer_modify_node_done(parent);
b3bad96f 1670 hammer_cursor_inserted_element(parent, parent_index + 1);
427e5fc6 1671
7f7c1f84
MD
1672 /*
1673 * The children of new_node need their parent pointer set to new_node.
b33e2cc0
MD
1674 * The children have already been locked by
1675 * hammer_btree_lock_children().
7f7c1f84
MD
1676 */
1677 for (i = 0; i < new_node->ondisk->count; ++i) {
1678 elm = &new_node->ondisk->elms[i];
36f82b23 1679 error = btree_set_parent(cursor->trans, new_node, elm);
7f7c1f84
MD
1680 if (error) {
1681 panic("btree_split_internal: btree-fixup problem");
1682 }
1683 }
10a5d1ba 1684 hammer_modify_node_done(new_node);
7f7c1f84 1685
427e5fc6 1686 /*
47197d71 1687 * The filesystem's root B-Tree pointer may have to be updated.
427e5fc6
MD
1688 */
1689 if (made_root) {
47197d71
MD
1690 hammer_volume_t volume;
1691
1692 volume = hammer_get_root_volume(hmp, &error);
1693 KKASSERT(error == 0);
1694
e8599db1
MD
1695 hammer_modify_volume_field(cursor->trans, volume,
1696 vol0_btree_root);
47197d71 1697 volume->ondisk->vol0_btree_root = parent->node_offset;
10a5d1ba 1698 hammer_modify_volume_done(volume);
8cd0a023
MD
1699 node->ondisk->parent = parent->node_offset;
1700 if (cursor->parent) {
1701 hammer_unlock(&cursor->parent->lock);
1702 hammer_rel_node(cursor->parent);
1703 }
1704 cursor->parent = parent; /* lock'd and ref'd */
47197d71 1705 hammer_rel_volume(volume, 0);
427e5fc6 1706 }
10a5d1ba 1707 hammer_modify_node_done(node);
427e5fc6
MD
1708
1709 /*
1710 * Ok, now adjust the cursor depending on which element the original
1711 * index was pointing at. If we are >= the split point the push node
1712 * is now in the new node.
1713 *
1714 * NOTE: If we are at the split point itself we cannot stay with the
1715 * original node because the push index will point at the right-hand
1716 * boundary, which is illegal.
8cd0a023
MD
1717 *
1718 * NOTE: The cursor's parent or parent_index must be adjusted for
1719 * the case where a new parent (new root) was created, and the case
1720 * where the cursor is now pointing at the split node.
427e5fc6
MD
1721 */
1722 if (cursor->index >= split) {
8cd0a023 1723 cursor->parent_index = parent_index + 1;
427e5fc6 1724 cursor->index -= split;
8cd0a023
MD
1725 hammer_unlock(&cursor->node->lock);
1726 hammer_rel_node(cursor->node);
1727 cursor->node = new_node; /* locked and ref'd */
1728 } else {
1729 cursor->parent_index = parent_index;
1730 hammer_unlock(&new_node->lock);
1731 hammer_rel_node(new_node);
427e5fc6 1732 }
76376933
MD
1733
1734 /*
1735 * Fixup left and right bounds
1736 */
1737 parent_elm = &parent->ondisk->elms[cursor->parent_index];
fbc6e32a
MD
1738 cursor->left_bound = &parent_elm[0].internal.base;
1739 cursor->right_bound = &parent_elm[1].internal.base;
b3deaf57
MD
1740 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1741 &cursor->node->ondisk->elms[0].internal.base) <= 0);
1742 KKASSERT(hammer_btree_cmp(cursor->right_bound,
9944ae54 1743 &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
76376933 1744
6a37e7e4 1745done:
24cf83d2 1746 hammer_btree_unlock_children(cursor->trans->hmp, &lockroot, NULL);
6a37e7e4
MD
1747 hammer_cursor_downgrade(cursor);
1748 return (error);
427e5fc6
MD
1749}
1750
1751/*
1752 * Same as the above, but splits a full leaf node.
1753 */
1754static
1755int
8cd0a023 1756btree_split_leaf(hammer_cursor_t cursor)
427e5fc6 1757{
8cd0a023
MD
1758 hammer_node_ondisk_t ondisk;
1759 hammer_node_t parent;
1760 hammer_node_t leaf;
47197d71 1761 hammer_mount_t hmp;
8cd0a023
MD
1762 hammer_node_t new_leaf;
1763 hammer_btree_elm_t elm;
1764 hammer_btree_elm_t parent_elm;
b3deaf57 1765 hammer_base_elm_t mid_boundary;
427e5fc6
MD
1766 int parent_index;
1767 int made_root;
1768 int split;
1769 int error;
8cd0a023 1770 const size_t esize = sizeof(*elm);
427e5fc6 1771
6a37e7e4
MD
1772 if ((error = hammer_cursor_upgrade(cursor)) != 0)
1773 return(error);
cb51be26 1774 ++hammer_stats_btree_splits;
6a37e7e4 1775
36f82b23
MD
1776 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1777 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1778 KKASSERT(hammer_btree_cmp(cursor->right_bound,
1779 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1780
427e5fc6 1781 /*
fa2b9a03
MD
1782 * Calculate the split point. If the insertion point is at the
1783 * end of the leaf we adjust the split point significantly to the
1784 * right to try to optimize node fill and flag it. If we hit
1785 * that same leaf again our heuristic failed and we don't try
1786 * to optimize node fill (it could lead to a degenerate case).
427e5fc6 1787 */
8cd0a023
MD
1788 leaf = cursor->node;
1789 ondisk = leaf->ondisk;
fa2b9a03
MD
1790 KKASSERT(ondisk->count > 4);
1791 if (cursor->index == ondisk->count &&
1792 (leaf->flags & HAMMER_NODE_NONLINEAR) == 0) {
1793 split = (ondisk->count + 1) * 3 / 4;
1794 leaf->flags |= HAMMER_NODE_NONLINEAR;
1795 } else {
1796 split = (ondisk->count + 1) / 2;
1797 }
1798
1799#if 0
1800 /*
1801 * If the insertion point is at the split point shift the
1802 * split point left so we don't have to worry about
1803 */
1804 if (cursor->index == split)
427e5fc6 1805 --split;
fa2b9a03
MD
1806#endif
1807 KKASSERT(split > 0 && split < ondisk->count);
1808
427e5fc6 1809 error = 0;
40043e7f 1810 hmp = leaf->hmp;
427e5fc6 1811
fe7678ee 1812 elm = &ondisk->elms[split];
fe7678ee 1813
36f82b23
MD
1814 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm[-1].leaf.base) <= 0);
1815 KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
1816 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
1817 KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm[1].leaf.base) > 0);
1818
427e5fc6
MD
1819 /*
1820 * If we are at the root of the tree, create a new root node with
1821 * 1 element and split normally. Avoid making major modifications
1822 * until we know the whole operation will work.
1823 */
8cd0a023 1824 if (ondisk->parent == 0) {
b4f86ea3 1825 parent = hammer_alloc_btree(cursor->trans, 0, &error);
427e5fc6 1826 if (parent == NULL)
6a37e7e4 1827 goto done;
8cd0a023 1828 hammer_lock_ex(&parent->lock);
36f82b23 1829 hammer_modify_node_noundo(cursor->trans, parent);
8cd0a023
MD
1830 ondisk = parent->ondisk;
1831 ondisk->count = 1;
1832 ondisk->parent = 0;
a56cb012 1833 ondisk->mirror_tid = leaf->ondisk->mirror_tid;
8cd0a023 1834 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
47197d71 1835 ondisk->elms[0].base = hmp->root_btree_beg;
fe7678ee 1836 ondisk->elms[0].base.btype = leaf->ondisk->type;
8cd0a023 1837 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
f0b930f3 1838 ondisk->elms[0].internal.mirror_tid = ondisk->mirror_tid;
47197d71 1839 ondisk->elms[1].base = hmp->root_btree_end;
fe7678ee 1840 /* ondisk->elms[1].base.btype = not used */
10a5d1ba 1841 hammer_modify_node_done(parent);
427e5fc6 1842 made_root = 1;
8cd0a023 1843 parent_index = 0; /* insertion point in parent */
427e5fc6
MD
1844 } else {
1845 made_root = 0;
8cd0a023
MD
1846 parent = cursor->parent;
1847 parent_index = cursor->parent_index;
427e5fc6 1848 }
427e5fc6
MD
1849
1850 /*
1851 * Split leaf into new_leaf at the split point. Select a separator
1852 * value in-between the two leafs but with a bent towards the right
1853 * leaf since comparisons use an 'elm >= separator' inequality.
1854 *
1855 * L L L L L L L L
1856 *
1857 * x x P x x
1858 * s S S s
1859 * / \
1860 * L L L L L L L L
1861 */
b4f86ea3 1862 new_leaf = hammer_alloc_btree(cursor->trans, 0, &error);
427e5fc6 1863 if (new_leaf == NULL) {
8cd0a023
MD
1864 if (made_root) {
1865 hammer_unlock(&parent->lock);
36f82b23 1866 hammer_delete_node(cursor->trans, parent);
8cd0a023
MD
1867 hammer_rel_node(parent);
1868 }
6a37e7e4 1869 goto done;
427e5fc6 1870 }
8cd0a023 1871 hammer_lock_ex(&new_leaf->lock);
427e5fc6
MD
1872
1873 /*
36f82b23
MD
1874 * Create the new node and copy the leaf elements from the split
1875 * point on to the new node.
427e5fc6 1876 */
36f82b23
MD
1877 hammer_modify_node_all(cursor->trans, leaf);
1878 hammer_modify_node_noundo(cursor->trans, new_leaf);
8cd0a023
MD
1879 ondisk = leaf->ondisk;
1880 elm = &ondisk->elms[split];
1881 bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1882 new_leaf->ondisk->count = ondisk->count - split;
1883 new_leaf->ondisk->parent = parent->node_offset;
1884 new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
a56cb012 1885 new_leaf->ondisk->mirror_tid = ondisk->mirror_tid;
8cd0a023 1886 KKASSERT(ondisk->type == new_leaf->ondisk->type);
10a5d1ba 1887 hammer_modify_node_done(new_leaf);
b3bad96f 1888 hammer_cursor_split_node(leaf, new_leaf, split);
427e5fc6
MD
1889
1890 /*
8cd0a023
MD
1891 * Cleanup the original node. Because this is a leaf node and
1892 * leaf nodes do not have a right-hand boundary, there
c0ade690
MD
1893 * aren't any special edge cases to clean up. We just fixup the
1894 * count.
427e5fc6 1895 */
c0ade690 1896 ondisk->count = split;
427e5fc6
MD
1897
1898 /*
1899 * Insert the separator into the parent, fixup the parent's
1900 * reference to the original node, and reference the new node.
1901 * The separator is P.
1902 *
1903 * Remember that base.count does not include the right-hand boundary.
1904 * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1905 */
36f82b23 1906 hammer_modify_node_all(cursor->trans, parent);
8cd0a023 1907 ondisk = parent->ondisk;
36f82b23 1908 KKASSERT(split != 0);
d26d0ae9 1909 KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
8cd0a023 1910 parent_elm = &ondisk->elms[parent_index+1];
d26d0ae9
MD
1911 bcopy(parent_elm, parent_elm + 1,
1912 (ondisk->count - parent_index) * esize);
eaeff70d 1913
47197d71 1914 hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
fe7678ee 1915 parent_elm->internal.base.btype = new_leaf->ondisk->type;
8cd0a023 1916 parent_elm->internal.subtree_offset = new_leaf->node_offset;
a56cb012 1917 parent_elm->internal.mirror_tid = new_leaf->ondisk->mirror_tid;
b3deaf57 1918 mid_boundary = &parent_elm->base;
76376933 1919 ++ondisk->count;
10a5d1ba 1920 hammer_modify_node_done(parent);
b3bad96f 1921 hammer_cursor_inserted_element(parent, parent_index + 1);
427e5fc6 1922
fe7678ee 1923 /*
47197d71 1924 * The filesystem's root B-Tree pointer may have to be updated.
427e5fc6
MD
1925 */
1926 if (made_root) {
47197d71
MD
1927 hammer_volume_t volume;
1928
1929 volume = hammer_get_root_volume(hmp, &error);
1930 KKASSERT(error == 0);
1931
e8599db1
MD
1932 hammer_modify_volume_field(cursor->trans, volume,
1933 vol0_btree_root);
47197d71 1934 volume->ondisk->vol0_btree_root = parent->node_offset;
10a5d1ba 1935 hammer_modify_volume_done(volume);
8cd0a023
MD
1936 leaf->ondisk->parent = parent->node_offset;
1937 if (cursor->parent) {
1938 hammer_unlock(&cursor->parent->lock);
1939 hammer_rel_node(cursor->parent);
1940 }
1941 cursor->parent = parent; /* lock'd and ref'd */
47197d71 1942 hammer_rel_volume(volume, 0);
427e5fc6 1943 }
10a5d1ba 1944 hammer_modify_node_done(leaf);
8cd0a023 1945
427e5fc6
MD
1946 /*
1947 * Ok, now adjust the cursor depending on which element the original
1948 * index was pointing at. If we are >= the split point the push node
1949 * is now in the new node.
1950 *
b3deaf57
MD
1951 * NOTE: If we are at the split point itself we need to select the
1952 * old or new node based on where key_beg's insertion point will be.
1953 * If we pick the wrong side the inserted element will wind up in
1954 * the wrong leaf node and outside that node's bounds.
427e5fc6 1955 */
b3deaf57
MD
1956 if (cursor->index > split ||
1957 (cursor->index == split &&
1958 hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
8cd0a023 1959 cursor->parent_index = parent_index + 1;
427e5fc6 1960 cursor->index -= split;
8cd0a023
MD
1961 hammer_unlock(&cursor->node->lock);
1962 hammer_rel_node(cursor->node);
1963 cursor->node = new_leaf;
1964 } else {
1965 cursor->parent_index = parent_index;
1966 hammer_unlock(&new_leaf->lock);
1967 hammer_rel_node(new_leaf);
427e5fc6 1968 }
76376933
MD
1969
1970 /*
1971 * Fixup left and right bounds
1972 */
1973 parent_elm = &parent->ondisk->elms[cursor->parent_index];
fbc6e32a
MD
1974 cursor->left_bound = &parent_elm[0].internal.base;
1975 cursor->right_bound = &parent_elm[1].internal.base;
eaeff70d
MD
1976
1977 /*
47197d71 1978 * Assert that the bounds are correct.
eaeff70d 1979 */
b3deaf57
MD
1980 KKASSERT(hammer_btree_cmp(cursor->left_bound,
1981 &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1982 KKASSERT(hammer_btree_cmp(cursor->right_bound,
47197d71 1983 &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
36f82b23
MD
1984 KKASSERT(hammer_btree_cmp(cursor->left_bound, &cursor->key_beg) <= 0);
1985 KKASSERT(hammer_btree_cmp(cursor->right_bound, &cursor->key_beg) > 0);
76376933 1986
6a37e7e4
MD
1987done:
1988 hammer_cursor_downgrade(cursor);
1989 return (error);
427e5fc6
MD
1990}
1991
adf01747
MD
1992#if 0
1993
32c90105
MD
1994/*
1995 * Recursively correct the right-hand boundary's create_tid to (tid) as
1996 * long as the rest of the key matches. We have to recurse upward in
1997 * the tree as well as down the left side of each parent's right node.
1998 *
1999 * Return EDEADLK if we were only partially successful, forcing the caller
2000 * to try again. The original cursor is not modified. This routine can
2001 * also fail with EDEADLK if it is forced to throw away a portion of its
2002 * record history.
2003 *
2004 * The caller must pass a downgraded cursor to us (otherwise we can't dup it).
2005 */
2006struct hammer_rhb {
2007 TAILQ_ENTRY(hammer_rhb) entry;
2008 hammer_node_t node;
2009 int index;
2010};
2011
2012TAILQ_HEAD(hammer_rhb_list, hammer_rhb);
2013
2014int
2015hammer_btree_correct_rhb(hammer_cursor_t cursor, hammer_tid_t tid)
2016{
bac808fe 2017 struct hammer_mount *hmp;
32c90105
MD
2018 struct hammer_rhb_list rhb_list;
2019 hammer_base_elm_t elm;
2020 hammer_node_t orig_node;
2021 struct hammer_rhb *rhb;
2022 int orig_index;
2023 int error;
2024
2025 TAILQ_INIT(&rhb_list);
bac808fe 2026 hmp = cursor->trans->hmp;
32c90105
MD
2027
2028 /*
2029 * Save our position so we can restore it on return. This also
2030 * gives us a stable 'elm'.
2031 */
2032 orig_node = cursor->node;
2033 hammer_ref_node(orig_node);
2034 hammer_lock_sh(&orig_node->lock);
2035 orig_index = cursor->index;
2036 elm = &orig_node->ondisk->elms[orig_index].base;
2037
2038 /*
2039 * Now build a list of parents going up, allocating a rhb
2040 * structure for each one.
2041 */
2042 while (cursor->parent) {
2043 /*
2044 * Stop if we no longer have any right-bounds to fix up
2045 */
2046 if (elm->obj_id != cursor->right_bound->obj_id ||
2047 elm->rec_type != cursor->right_bound->rec_type ||
2048 elm->key != cursor->right_bound->key) {
2049 break;
2050 }
2051
2052 /*
2053 * Stop if the right-hand bound's create_tid does not
47197d71 2054 * need to be corrected.
32c90105
MD
2055 */
2056 if (cursor->right_bound->create_tid >= tid)
2057 break;
2058
bac808fe 2059 rhb = kmalloc(sizeof(*rhb), hmp->m_misc, M_WAITOK|M_ZERO);
32c90105
MD
2060 rhb->node = cursor->parent;
2061 rhb->index = cursor->parent_index;
2062 hammer_ref_node(rhb->node);
2063 hammer_lock_sh(&rhb->node->lock);
2064 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
2065
2066 hammer_cursor_up(cursor);
2067 }
2068
2069 /*
2070 * now safely adjust the right hand bound for each rhb. This may
2071 * also require taking the right side of the tree and iterating down
2072 * ITS left side.
2073 */
2074 error = 0;
2075 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2076 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
32c90105
MD
2077 if (error)
2078 break;
2079 TAILQ_REMOVE(&rhb_list, rhb, entry);
2080 hammer_unlock(&rhb->node->lock);
2081 hammer_rel_node(rhb->node);
bac808fe 2082 kfree(rhb, hmp->m_misc);
32c90105
MD
2083
2084 switch (cursor->node->ondisk->type) {
2085 case HAMMER_BTREE_TYPE_INTERNAL:
2086 /*
2087 * Right-boundary for parent at internal node
2088 * is one element to the right of the element whos
2089 * right boundary needs adjusting. We must then
2090 * traverse down the left side correcting any left
2091 * bounds (which may now be too far to the left).
2092 */
2093 ++cursor->index;
2094 error = hammer_btree_correct_lhb(cursor, tid);
2095 break;
32c90105
MD
2096 default:
2097 panic("hammer_btree_correct_rhb(): Bad node type");
2098 error = EINVAL;
2099 break;
2100 }
2101 }
2102
2103 /*
2104 * Cleanup
2105 */
2106 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2107 TAILQ_REMOVE(&rhb_list, rhb, entry);
2108 hammer_unlock(&rhb->node->lock);
2109 hammer_rel_node(rhb->node);
bac808fe 2110 kfree(rhb, hmp->m_misc);
32c90105
MD
2111 }
2112 error = hammer_cursor_seek(cursor, orig_node, orig_index);
2113 hammer_unlock(&orig_node->lock);
2114 hammer_rel_node(orig_node);
2115 return (error);
2116}
2117
2118/*
2119 * Similar to rhb (in fact, rhb calls lhb), but corrects the left hand
2120 * bound going downward starting at the current cursor position.
2121 *
2122 * This function does not restore the cursor after use.
2123 */
2124int
2125hammer_btree_correct_lhb(hammer_cursor_t cursor, hammer_tid_t tid)
2126{
2127 struct hammer_rhb_list rhb_list;
2128 hammer_base_elm_t elm;
2129 hammer_base_elm_t cmp;
2130 struct hammer_rhb *rhb;
bac808fe 2131 struct hammer_mount *hmp;
32c90105
MD
2132 int error;
2133
2134 TAILQ_INIT(&rhb_list);
bac808fe 2135 hmp = cursor->trans->hmp;
32c90105
MD
2136
2137 cmp = &cursor->node->ondisk->elms[cursor->index].base;
2138
2139 /*
2140 * Record the node and traverse down the left-hand side for all
2141 * matching records needing a boundary correction.
2142 */
2143 error = 0;
2144 for (;;) {
bac808fe 2145 rhb = kmalloc(sizeof(*rhb), hmp->m_misc, M_WAITOK|M_ZERO);
32c90105
MD
2146 rhb->node = cursor->node;
2147 rhb->index = cursor->index;
2148 hammer_ref_node(rhb->node);
2149 hammer_lock_sh(&rhb->node->lock);
2150 TAILQ_INSERT_HEAD(&rhb_list, rhb, entry);
2151
2152 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2153 /*
2154 * Nothing to traverse down if we are at the right
2155 * boundary of an internal node.
2156 */
2157 if (cursor->index == cursor->node->ondisk->count)
2158 break;
2159 } else {
2160 elm = &cursor->node->ondisk->elms[cursor->index].base;
2161 if (elm->btype == HAMMER_BTREE_TYPE_RECORD)
2162 break;
47197d71 2163 panic("Illegal leaf record type %02x", elm->btype);
32c90105
MD
2164 }
2165 error = hammer_cursor_down(cursor);
2166 if (error)
2167 break;
2168
2169 elm = &cursor->node->ondisk->elms[cursor->index].base;
2170 if (elm->obj_id != cmp->obj_id ||
2171 elm->rec_type != cmp->rec_type ||
2172 elm->key != cmp->key) {
2173 break;
2174 }
2175 if (elm->create_tid >= tid)
2176 break;
2177
2178 }
2179
2180 /*
2181 * Now we can safely adjust the left-hand boundary from the bottom-up.
2182 * The last element we remove from the list is the caller's right hand
2183 * boundary, which must also be adjusted.
2184 */
2185 while (error == 0 && (rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2186 error = hammer_cursor_seek(cursor, rhb->node, rhb->index);
2187 if (error)
2188 break;
2189 TAILQ_REMOVE(&rhb_list, rhb, entry);
2190 hammer_unlock(&rhb->node->lock);
2191 hammer_rel_node(rhb->node);
bac808fe 2192 kfree(rhb, hmp->m_misc);
32c90105
MD
2193
2194 elm = &cursor->node->ondisk->elms[cursor->index].base;
2195 if (cursor->node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
36f82b23 2196 hammer_modify_node(cursor->trans, cursor->node,
19619882
MD
2197 &elm->create_tid,
2198 sizeof(elm->create_tid));
32c90105 2199 elm->create_tid = tid;
10a5d1ba 2200 hammer_modify_node_done(cursor->node);
32c90105
MD
2201 } else {
2202 panic("hammer_btree_correct_lhb(): Bad element type");
2203 }
2204 }
2205
2206 /*
2207 * Cleanup
2208 */
2209 while ((rhb = TAILQ_FIRST(&rhb_list)) != NULL) {
2210 TAILQ_REMOVE(&rhb_list, rhb, entry);
2211 hammer_unlock(&rhb->node->lock);
2212 hammer_rel_node(rhb->node);
bac808fe 2213 kfree(rhb, hmp->m_misc);
32c90105
MD
2214 }
2215 return (error);
2216}
2217
adf01747
MD
2218#endif
2219
427e5fc6 2220/*
f36a9737
MD
2221 * Attempt to remove the locked, empty or want-to-be-empty B-Tree node at
2222 * (cursor->node). Returns 0 on success, EDEADLK if we could not complete
2223 * the operation due to a deadlock, or some other error.
8cd0a023 2224 *
5c8d05e2
MD
2225 * This routine is initially called with an empty leaf and may be
2226 * recursively called with single-element internal nodes.
b3deaf57 2227 *
c82af904
MD
2228 * It should also be noted that when removing empty leaves we must be sure
2229 * to test and update mirror_tid because another thread may have deadlocked
5fa5c92f 2230 * against us (or someone) trying to propagate it up and cannot retry once
c82af904
MD
2231 * the node has been deleted.
2232 *
f36a9737
MD
2233 * On return the cursor may end up pointing to an internal node, suitable
2234 * for further iteration but not for an immediate insertion or deletion.
8cd0a023 2235 */
f36a9737 2236static int
46fe7ae1 2237btree_remove(hammer_cursor_t cursor)
8cd0a023
MD
2238{
2239 hammer_node_ondisk_t ondisk;
195c19a1 2240 hammer_btree_elm_t elm;
195c19a1 2241 hammer_node_t node;
8cd0a023 2242 hammer_node_t parent;
fe7678ee 2243 const int esize = sizeof(*elm);
8cd0a023 2244 int error;
8cd0a023 2245
fe7678ee
MD
2246 node = cursor->node;
2247
47197d71
MD
2248 /*
2249 * When deleting the root of the filesystem convert it to
2250 * an empty leaf node. Internal nodes cannot be empty.
2251 */
c82af904
MD
2252 ondisk = node->ondisk;
2253 if (ondisk->parent == 0) {
f36a9737 2254 KKASSERT(cursor->parent == NULL);
36f82b23 2255 hammer_modify_node_all(cursor->trans, node);
c82af904 2256 KKASSERT(ondisk == node->ondisk);
195c19a1
MD
2257 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
2258 ondisk->count = 0;
10a5d1ba 2259 hammer_modify_node_done(node);
b3deaf57 2260 cursor->index = 0;
47197d71 2261 return(0);
8cd0a023
MD
2262 }
2263
c82af904
MD
2264 parent = cursor->parent;
2265
8cd0a023 2266 /*
f36a9737
MD
2267 * Attempt to remove the parent's reference to the child. If the
2268 * parent would become empty we have to recurse. If we fail we
2269 * leave the parent pointing to an empty leaf node.
5c8d05e2
MD
2270 *
2271 * We have to recurse successfully before we can delete the internal
2272 * node as it is illegal to have empty internal nodes. Even though
2273 * the operation may be aborted we must still fixup any unlocked
2274 * cursors as if we had deleted the element prior to recursing
2275 * (by calling hammer_cursor_deleted_element()) so those cursors
2276 * are properly forced up the chain by the recursion.
8cd0a023 2277 */
f36a9737
MD
2278 if (parent->ondisk->count == 1) {
2279 /*
2280 * This special cursor_up_locked() call leaves the original
2281 * node exclusively locked and referenced, leaves the
2282 * original parent locked (as the new node), and locks the
2283 * new parent. It can return EDEADLK.
f3a4893b
MD
2284 *
2285 * We cannot call hammer_cursor_removed_node() until we are
2286 * actually able to remove the node. If we did then tracked
2287 * cursors in the middle of iterations could be repointed
2288 * to a parent node. If this occurs they could end up
2289 * scanning newly inserted records into the node (that could
2290 * not be deleted) when they push down again.
2291 *
2292 * Due to the way the recursion works the final parent is left
2293 * in cursor->parent after the recursion returns. Each
2294 * layer on the way back up is thus able to call
2295 * hammer_cursor_removed_node() and 'jump' the node up to
2296 * the (same) final parent.
2297 *
2298 * NOTE! The local variable 'parent' is invalid after we
2299 * call hammer_cursor_up_locked().
f36a9737
MD
2300 */
2301 error = hammer_cursor_up_locked(cursor);
f3a4893b
MD
2302 parent = NULL;
2303
f36a9737 2304 if (error == 0) {
5c8d05e2 2305 hammer_cursor_deleted_element(cursor->node, 0);
f36a9737
MD
2306 error = btree_remove(cursor);
2307 if (error == 0) {
901ba05c 2308 KKASSERT(node != cursor->node);
f3a4893b 2309 hammer_cursor_removed_node(
901ba05c
MD
2310 node, cursor->node,
2311 cursor->index);
f36a9737
MD
2312 hammer_modify_node_all(cursor->trans, node);
2313 ondisk = node->ondisk;
2314 ondisk->type = HAMMER_BTREE_TYPE_DELETED;
2315 ondisk->count = 0;
2316 hammer_modify_node_done(node);
250aec18 2317 hammer_flush_node(node, 0);
f36a9737
MD
2318 hammer_delete_node(cursor->trans, node);
2319 } else {
3214ade6
MD
2320 /*
2321 * Defer parent removal because we could not
2322 * get the lock, just let the leaf remain
2323 * empty.
2324 */
2325 /**/
f36a9737
MD
2326 }
2327 hammer_unlock(&node->lock);
2328 hammer_rel_node(node);
2329 } else {
3214ade6
MD
2330 /*
2331 * Defer parent removal because we could not
2332 * get the lock, just let the leaf remain
2333 * empty.
2334 */
2335 /**/
f36a9737
MD
2336 }
2337 } else {
2338 KKASSERT(parent->ondisk->count > 1);
6a37e7e4 2339
f36a9737
MD
2340 hammer_modify_node_all(cursor->trans, parent);
2341 ondisk = parent->ondisk;
2342 KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
c82af904 2343
f36a9737
MD
2344 elm = &ondisk->elms[cursor->parent_index];
2345 KKASSERT(elm->internal.subtree_offset == node->node_offset);
2346 KKASSERT(ondisk->count > 0);
4c038e17
MD
2347
2348 /*
2349 * We must retain the highest mirror_tid. The deleted
2350 * range is now encompassed by the element to the left.
2351 * If we are already at the left edge the new left edge
2352 * inherits mirror_tid.
2353 *
2354 * Note that bounds of the parent to our parent may create
2355 * a gap to the left of our left-most node or to the right
2356 * of our right-most node. The gap is silently included
2357 * in the mirror_tid's area of effect from the point of view
2358 * of the scan.
2359 */
2360 if (cursor->parent_index) {
2361 if (elm[-1].internal.mirror_tid <
2362 elm[0].internal.mirror_tid) {
2363 elm[-1].internal.mirror_tid =
2364 elm[0].internal.mirror_tid;
2365 }
2366 } else {
2367 if (elm[1].internal.mirror_tid <
2368 elm[0].internal.mirror_tid) {
2369 elm[1].internal.mirror_tid =
2370 elm[0].internal.mirror_tid;
2371 }
2372 }
2373
2374 /*
f3a4893b
MD
2375 * Delete the subtree reference in the parent. Include
2376 * boundary element at end.
4c038e17 2377 */
f36a9737
MD
2378 bcopy(&elm[1], &elm[0],
2379 (ondisk->count - cursor->parent_index) * esize);
2380 --ondisk->count;
10a5d1ba 2381 hammer_modify_node_done(parent);
f3a4893b 2382 hammer_cursor_removed_node(node, parent, cursor->parent_index);
6c1f89f4 2383 hammer_cursor_deleted_element(parent, cursor->parent_index);
250aec18 2384 hammer_flush_node(node, 0);
f36a9737 2385 hammer_delete_node(cursor->trans, node);
6a37e7e4 2386
f36a9737
MD
2387 /*
2388 * cursor->node is invalid, cursor up to make the cursor
ec9b6294
MD
2389 * valid again. We have to flag the condition in case
2390 * another thread wiggles an insertion in during an
2391 * iteration.
f36a9737 2392 */
ec9b6294 2393 cursor->flags |= HAMMER_CURSOR_ITERATE_CHECK;
f36a9737 2394 error = hammer_cursor_up(cursor);
6a37e7e4 2395 }
f36a9737 2396 return (error);
6a37e7e4
MD
2397}
2398
602c6cb8
MD
2399/*
2400 * Propagate cursor->trans->tid up the B-Tree starting at the current
2401 * cursor position using pseudofs info gleaned from the passed inode.
2402 *
2403 * The passed inode has no relationship to the cursor position other
2404 * then being in the same pseudofs as the insertion or deletion we
2405 * are propagating the mirror_tid for.
c9ce54d6
MD
2406 *
2407 * WARNING! Because we push and pop the passed cursor, it may be
2408 * modified by other B-Tree operations while it is unlocked
2409 * and things like the node & leaf pointers, and indexes might
2410 * change.
602c6cb8
MD
2411 */
2412void
4c038e17
MD
2413hammer_btree_do_propagation(hammer_cursor_t cursor,
2414 hammer_pseudofs_inmem_t pfsm,
602c6cb8
MD
2415 hammer_btree_leaf_elm_t leaf)
2416{
adf01747
MD
2417 hammer_cursor_t ncursor;
2418 hammer_tid_t mirror_tid;
f31f6d84 2419 int error __debugvar;
602c6cb8
MD
2420
2421 /*
732a1697
MD
2422 * We do not propagate a mirror_tid if the filesystem was mounted
2423 * in no-mirror mode.
602c6cb8 2424 */
732a1697 2425 if (cursor->trans->hmp->master_id < 0)
602c6cb8 2426 return;
602c6cb8 2427
adf01747
MD
2428 /*
2429 * This is a bit of a hack because we cannot deadlock or return
2430 * EDEADLK here. The related operation has already completed and
2431 * we must propagate the mirror_tid now regardless.
2432 *
2433 * Generate a new cursor which inherits the original's locks and
2434 * unlock the original. Use the new cursor to propagate the
2435 * mirror_tid. Then clean up the new cursor and reacquire locks
2436 * on the original.
2437 *
2438 * hammer_dup_cursor() cannot dup locks. The dup inherits the
2439 * original's locks and the original is tracked and must be
2440 * re-locked.
2441 */
2442 mirror_tid = cursor->node->ondisk->mirror_tid;
a56cb012 2443 KKASSERT(mirror_tid != 0);
3f43fb33 2444 ncursor = hammer_push_cursor(cursor);
adf01747
MD
2445 error = hammer_btree_mirror_propagate(ncursor, mirror_tid);
2446 KKASSERT(error == 0);
3f43fb33 2447 hammer_pop_cursor(cursor, ncursor);
c9ce54d6 2448 /* WARNING: cursor's leaf pointer may change after pop */
602c6cb8
MD
2449}
2450
2451
c82af904
MD
2452/*
2453 * Propagate a mirror TID update upwards through the B-Tree to the root.
2454 *
2455 * A locked internal node must be passed in. The node will remain locked
2456 * on return.
2457 *
2458 * This function syncs mirror_tid at the specified internal node's element,
2459 * adjusts the node's aggregation mirror_tid, and then recurses upwards.
2460 */
602c6cb8 2461static int
adf01747 2462hammer_btree_mirror_propagate(hammer_cursor_t cursor, hammer_tid_t mirror_tid)
c82af904
MD
2463{
2464 hammer_btree_internal_elm_t elm;
adf01747 2465 hammer_node_t node;
c82af904
MD
2466 int error;
2467
adf01747
MD
2468 for (;;) {
2469 error = hammer_cursor_up(cursor);
2470 if (error == 0)
2471 error = hammer_cursor_upgrade(cursor);
6dc17446
MD
2472
2473 /*
2474 * We can ignore HAMMER_CURSOR_ITERATE_CHECK, the
2475 * cursor will still be properly positioned for
2476 * mirror propagation, just not for iterations.
2477 */
adf01747
MD
2478 while (error == EDEADLK) {
2479 hammer_recover_cursor(cursor);
2480 error = hammer_cursor_upgrade(cursor);
2481 }
2482 if (error)
2483 break;
95885f20
MD
2484
2485 /*
2486 * If the cursor deadlocked it could end up at a leaf
2487 * after we lost the lock.
2488 */
adf01747 2489 node = cursor->node;
95885f20
MD
2490 if (node->ondisk->type != HAMMER_BTREE_TYPE_INTERNAL)
2491 continue;
c82af904 2492
adf01747
MD
2493 /*
2494 * Adjust the node's element
2495 */
2496 elm = &node->ondisk->elms[cursor->index].internal;
2497 if (elm->mirror_tid >= mirror_tid)
2498 break;
2499 hammer_modify_node(cursor->trans, node, &elm->mirror_tid,
2500 sizeof(elm->mirror_tid));
2501 elm->mirror_tid = mirror_tid;
2502 hammer_modify_node_done(node);
02325004
MD
2503 if (hammer_debug_general & 0x0002) {
2504 kprintf("mirror_propagate: propagate "
2505 "%016llx @%016llx:%d\n",
973c11b9
MD
2506 (long long)mirror_tid,
2507 (long long)node->node_offset,
2508 cursor->index);
02325004
MD
2509 }
2510
c82af904 2511
adf01747
MD
2512 /*
2513 * Adjust the node's mirror_tid aggregator
2514 */
2515 if (node->ondisk->mirror_tid >= mirror_tid)
2516 return(0);
2517 hammer_modify_node_field(cursor->trans, node, mirror_tid);
2518 node->ondisk->mirror_tid = mirror_tid;
2519 hammer_modify_node_done(node);
02325004
MD
2520 if (hammer_debug_general & 0x0002) {
2521 kprintf("mirror_propagate: propagate "
2522 "%016llx @%016llx\n",
973c11b9
MD
2523 (long long)mirror_tid,
2524 (long long)node->node_offset);
02325004 2525 }
c82af904 2526 }
adf01747
MD
2527 if (error == ENOENT)
2528 error = 0;
c82af904
MD
2529 return(error);
2530}
2531
2532hammer_node_t
82010f9f
MD
2533hammer_btree_get_parent(hammer_transaction_t trans, hammer_node_t node,
2534 int *parent_indexp, int *errorp, int try_exclusive)
c82af904
MD
2535{
2536 hammer_node_t parent;
2537 hammer_btree_elm_t elm;
2538 int i;
2539
2540 /*
2541 * Get the node
2542 */
82010f9f 2543 parent = hammer_get_node(trans, node->ondisk->parent, 0, errorp);
c82af904
MD
2544 if (*errorp) {
2545 KKASSERT(parent == NULL);
2546 return(NULL);
2547 }
2548 KKASSERT ((parent->flags & HAMMER_NODE_DELETED) == 0);
2549
2550 /*
2551 * Lock the node
2552 */
2553 if (try_exclusive) {
2554 if (hammer_lock_ex_try(&parent->lock)) {
2555 hammer_rel_node(parent);
2556 *errorp = EDEADLK;
2557 return(NULL);
2558 }
2559 } else {
2560 hammer_lock_sh(&parent->lock);
2561 }
2562
2563 /*
2564 * Figure out which element in the parent is pointing to the
2565 * child.
2566 */
2567 if (node->ondisk->count) {
2568 i = hammer_btree_search_node(&node->ondisk->elms[0].base,
2569 parent->ondisk);
2570 } else {
2571 i = 0;
2572 }
2573 while (i < parent->ondisk->count) {
2574 elm = &parent->ondisk->elms[i];
2575 if (elm->internal.subtree_offset == node->node_offset)
2576 break;
2577 ++i;
2578 }
2579 if (i == parent->ondisk->count) {
2580 hammer_unlock(&parent->lock);
ed20d0e3 2581 panic("Bad B-Tree link: parent %p node %p", parent, node);
c82af904
MD
2582 }
2583 *parent_indexp = i;
2584 KKASSERT(*errorp == 0);
2585 return(parent);
2586}
2587
7f7c1f84 2588/*
fe7678ee
MD
2589 * The element (elm) has been moved to a new internal node (node).
2590 *
2591 * If the element represents a pointer to an internal node that node's
2592 * parent must be adjusted to the element's new location.
2593 *
6a37e7e4 2594 * XXX deadlock potential here with our exclusive locks
7f7c1f84 2595 */
7f7c1f84 2596int
36f82b23
MD
2597btree_set_parent(hammer_transaction_t trans, hammer_node_t node,
2598 hammer_btree_elm_t elm)
7f7c1f84 2599{
7f7c1f84
MD
2600 hammer_node_t child;
2601 int error;
2602
2603 error = 0;
2604
fe7678ee 2605 switch(elm->base.btype) {
7f7c1f84 2606 case HAMMER_BTREE_TYPE_INTERNAL:
fe7678ee 2607 case HAMMER_BTREE_TYPE_LEAF:
82010f9f 2608 child = hammer_get_node(trans, elm->internal.subtree_offset,
19619882 2609 0, &error);
7f7c1f84 2610 if (error == 0) {
c9b9e29d 2611 hammer_modify_node_field(trans, child, parent);
7f7c1f84 2612 child->ondisk->parent = node->node_offset;
10a5d1ba 2613 hammer_modify_node_done(child);
7f7c1f84
MD
2614 hammer_rel_node(child);
2615 }
2616 break;
7f7c1f84 2617 default:
fe7678ee 2618 break;
7f7c1f84
MD
2619 }
2620 return(error);
2621}
2622
1775b6a0
MD
2623/*
2624 * Initialize the root of a recursive B-Tree node lock list structure.
2625 */
2626void
2627hammer_node_lock_init(hammer_node_lock_t parent, hammer_node_t node)
2628{
2629 TAILQ_INIT(&parent->list);
2630 parent->parent = NULL;
2631 parent->node = node;
2632 parent->index = -1;
2633 parent->count = node->ondisk->count;
2634 parent->copy = NULL;
2635 parent->flags = 0;
2636}
2637
24cf83d2
MD
2638/*
2639 * Initialize a cache of hammer_node_lock's including space allocated
2640 * for node copies.
2641 *
2642 * This is used by the rebalancing code to preallocate the copy space
2643 * for ~4096 B-Tree nodes (16MB of data) prior to acquiring any HAMMER
2644 * locks, otherwise we can blow out the pageout daemon's emergency
2645 * reserve and deadlock it.
2646 *
2647 * NOTE: HAMMER_NODE_LOCK_LCACHE is not set on items cached in the lcache.
2648 * The flag is set when the item is pulled off the cache for use.
2649 */
2650void
2651hammer_btree_lcache_init(hammer_mount_t hmp, hammer_node_lock_t lcache,
2652 int depth)
2653{
2654 hammer_node_lock_t item;
2655 int count;
2656
2657 for (count = 1; depth; --depth)
2658 count *= HAMMER_BTREE_LEAF_ELMS;
2659 bzero(lcache, sizeof(*lcache));
2660 TAILQ_INIT(&lcache->list);
2661 while (count) {
2662 item = kmalloc(sizeof(*item), hmp->m_misc, M_WAITOK|M_ZERO);
2663 item->copy = kmalloc(sizeof(*item->copy),
2664 hmp->m_misc, M_WAITOK);
2665 TAILQ_INIT(&item->list);
2666 TAILQ_INSERT_TAIL(&lcache->list, item, entry);
2667 --count;
2668 }
2669}
2670
2671void
2672hammer_btree_lcache_free(hammer_mount_t hmp, hammer_node_lock_t lcache)
2673{
2674 hammer_node_lock_t item;
2675
2676 while ((item = TAILQ_FIRST(&lcache->list)) != NULL) {
2677 TAILQ_REMOVE(&lcache->list, item, entry);
2678 KKASSERT(item->copy);
2679 KKASSERT(TAILQ_EMPTY(&item->list));
2680 kfree(item->copy, hmp->m_misc);
2681 kfree(item, hmp->m_misc);
2682 }
2683 KKASSERT(lcache->copy == NULL);
2684}
2685
b33e2cc0
MD
2686/*
2687 * Exclusively lock all the children of node. This is used by the split
2688 * code to prevent anyone from accessing the children of a cursor node
2689 * while we fix-up its parent offset.
2690 *
2691 * If we don't lock the children we can really mess up cursors which block
2692 * trying to cursor-up into our node.
2693 *
b33e2cc0
MD
2694 * On failure EDEADLK (or some other error) is returned. If a deadlock
2695 * error is returned the cursor is adjusted to block on termination.
1775b6a0
MD
2696 *
2697 * The caller is responsible for managing parent->node, the root's node
2698 * is usually aliased from a cursor.
b33e2cc0
MD
2699 */
2700int
1775b6a0 2701hammer_btree_lock_children(hammer_cursor_t cursor, int depth,
24cf83d2
MD
2702 hammer_node_lock_t parent,
2703 hammer_node_lock_t lcache)
b33e2cc0
MD
2704{
2705 hammer_node_t node;
1775b6a0 2706 hammer_node_lock_t item;
b33e2cc0
MD
2707 hammer_node_ondisk_t ondisk;
2708 hammer_btree_elm_t elm;
b33e2cc0 2709 hammer_node_t child;
bac808fe 2710 struct hammer_mount *hmp;
b33e2cc0
MD
2711 int error;
2712 int i;
2713
1775b6a0 2714 node = parent->node;
b33e2cc0
MD
2715 ondisk = node->ondisk;
2716 error = 0;
bac808fe 2717 hmp = cursor->trans->hmp;
7bc5b8c2
MD
2718
2719 /*
2720 * We really do not want to block on I/O with exclusive locks held,
1775b6a0
MD
2721 * pre-get the children before trying to lock the mess. This is
2722 * only done one-level deep for now.
7bc5b8c2
MD
2723 */
2724 for (i = 0; i < ondisk->count; ++i) {
cb51be26 2725 ++hammer_stats_btree_elements;
7bc5b8c2
MD
2726 elm = &ondisk->elms[i];
2727 if (elm->base.btype != HAMMER_BTREE_TYPE_LEAF &&
2728 elm->base.btype != HAMMER_BTREE_TYPE_INTERNAL) {
2729 continue;
2730 }
82010f9f 2731 child = hammer_get_node(cursor->trans,
7bc5b8c2
MD
2732 elm->internal.subtree_offset,
2733 0, &error);
2734 if (child)
2735 hammer_rel_node(child);
2736 }
2737
2738 /*
2739 * Do it for real
2740 */
b33e2cc0 2741 for (i = 0; error == 0 && i < ondisk->count; ++i) {
cb51be26 2742 ++hammer_stats_btree_elements;
b33e2cc0
MD
2743 elm = &ondisk->elms[i];
2744
b33e2cc0
MD
2745 switch(elm->base.btype) {
2746 case HAMMER_BTREE_TYPE_INTERNAL:
2747 case HAMMER_BTREE_TYPE_LEAF:
f36a9737 2748 KKASSERT(elm->internal.subtree_offset != 0);
82010f9f 2749 child = hammer_get_node(cursor->trans,
b33e2cc0 2750 elm->internal.subtree_offset,
19619882 2751 0, &error);
b33e2cc0 2752 break;
b33e2cc0 2753 default:
47197d71 2754 child = NULL;
b33e2cc0
MD
2755 break;
2756 }
2757 if (child) {
2758 if (hammer_lock_ex_try(&child->lock) != 0) {
2759 if (cursor->deadlk_node == NULL) {
1ff9f58e 2760 cursor->deadlk_node = child;
b33e2cc0
MD
2761 hammer_ref_node(cursor->deadlk_node);
2762 }
2763 error = EDEADLK;
a84a197d 2764 hammer_rel_node(child);
b33e2cc0 2765 } else {
24cf83d2
MD
2766 if (lcache) {
2767 item = TAILQ_FIRST(&lcache->list);
2768 KKASSERT(item != NULL);
2769 item->flags |= HAMMER_NODE_LOCK_LCACHE;
2770 TAILQ_REMOVE(&lcache->list,
2771 item, entry);
2772 } else {
2773 item = kmalloc(sizeof(*item),
2774 hmp->m_misc,
2775 M_WAITOK|M_ZERO);
2776 TAILQ_INIT(&item->list);
2777 }
2778
1775b6a0 2779 TAILQ_INSERT_TAIL(&parent->list, item, entry);
1775b6a0 2780 item->parent = parent;
b33e2cc0 2781 item->node = child;
1775b6a0
MD
2782 item->index = i;
2783 item->count = child->ondisk->count;
2784
2785 /*
2786 * Recurse (used by the rebalancing code)
2787 */
2788 if (depth > 1 && elm->base.btype == HAMMER_BTREE_TYPE_INTERNAL) {
2789 error = hammer_btree_lock_children(
2790 cursor,
2791 depth - 1,
24cf83d2
MD
2792 item,
2793 lcache);
1775b6a0 2794 }
b33e2cc0
MD
2795 }
2796 }
2797 }
2798 if (error)
24cf83d2 2799 hammer_btree_unlock_children(hmp, parent, lcache);
b33e2cc0
MD
2800 return(error);
2801}
2802
1775b6a0
MD
2803/*
2804 * Create an in-memory copy of all B-Tree nodes listed, recursively,
2805 * including the parent.
2806 */
2807void
2808hammer_btree_lock_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
2809{
2810 hammer_mount_t hmp = cursor->trans->hmp;
2811 hammer_node_lock_t item;
2812
2813 if (parent->copy == NULL) {
24cf83d2
MD
2814 KKASSERT((parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0);
2815 parent->copy = kmalloc(sizeof(*parent->copy),
2816 hmp->m_misc, M_WAITOK);
1775b6a0 2817 }
24cf83d2
MD
2818 KKASSERT((parent->flags & HAMMER_NODE_LOCK_UPDATED) == 0);
2819 *parent->copy = *parent->node->ondisk;
1775b6a0
MD
2820 TAILQ_FOREACH(item, &parent->list, entry) {
2821 hammer_btree_lock_copy(cursor, item);
2822 }
2823}
b33e2cc0
MD
2824
2825/*
1775b6a0 2826 * Recursively sync modified copies to the media.
b33e2cc0 2827 */
7ddc70d1 2828int
1775b6a0 2829hammer_btree_sync_copy(hammer_cursor_t cursor, hammer_node_lock_t parent)
b33e2cc0 2830{
1775b6a0 2831 hammer_node_lock_t item;
7ddc70d1 2832 int count = 0;
1775b6a0
MD
2833
2834 if (parent->flags & HAMMER_NODE_LOCK_UPDATED) {
7ddc70d1 2835 ++count;
1775b6a0
MD
2836 hammer_modify_node_all(cursor->trans, parent->node);
2837 *parent->node->ondisk = *parent->copy;
2838 hammer_modify_node_done(parent->node);
2839 if (parent->copy->type == HAMMER_BTREE_TYPE_DELETED) {
250aec18 2840 hammer_flush_node(parent->node, 0);
1775b6a0
MD
2841 hammer_delete_node(cursor->trans, parent->node);
2842 }
2843 }
2844 TAILQ_FOREACH(item, &parent->list, entry) {
7ddc70d1 2845 count += hammer_btree_sync_copy(cursor, item);
1775b6a0 2846 }
7ddc70d1 2847 return(count);
1775b6a0 2848}
b33e2cc0 2849
1775b6a0
MD
2850/*
2851 * Release previously obtained node locks. The caller is responsible for
2852 * cleaning up parent->node itself (its usually just aliased from a cursor),
2853 * but this function will take care of the copies.
24cf83d2
MD
2854 *
2855 * NOTE: The root node is not placed in the lcache and node->copy is not
2856 * deallocated when lcache != NULL.
1775b6a0
MD
2857 */
2858void
24cf83d2
MD
2859hammer_btree_unlock_children(hammer_mount_t hmp, hammer_node_lock_t parent,
2860 hammer_node_lock_t lcache)
1775b6a0
MD
2861{
2862 hammer_node_lock_t item;
24cf83d2 2863 hammer_node_ondisk_t copy;
1775b6a0 2864
1775b6a0
MD
2865 while ((item = TAILQ_FIRST(&parent->list)) != NULL) {
2866 TAILQ_REMOVE(&parent->list, item, entry);
24cf83d2 2867 hammer_btree_unlock_children(hmp, item, lcache);
b33e2cc0
MD
2868 hammer_unlock(&item->node->lock);
2869 hammer_rel_node(item->node);
24cf83d2
MD
2870 if (lcache) {
2871 /*
2872 * NOTE: When placing the item back in the lcache
2873 * the flag is cleared by the bzero().
2874 * Remaining fields are cleared as a safety
2875 * measure.
2876 */
2877 KKASSERT(item->flags & HAMMER_NODE_LOCK_LCACHE);
2878 KKASSERT(TAILQ_EMPTY(&item->list));
2879 copy = item->copy;
2880 bzero(item, sizeof(*item));
2881 TAILQ_INIT(&item->list);
2882 item->copy = copy;
2883 if (copy)
2884 bzero(copy, sizeof(*copy));
2885 TAILQ_INSERT_TAIL(&lcache->list, item, entry);
2886 } else {
2887 kfree(item, hmp->m_misc);
2888 }
2889 }
2890 if (parent->copy && (parent->flags & HAMMER_NODE_LOCK_LCACHE) == 0) {
2891 kfree(parent->copy, hmp->m_misc);
2892 parent->copy = NULL; /* safety */
b33e2cc0
MD
2893 }
2894}
2895
8cd0a023
MD
2896/************************************************************************
2897 * MISCELLANIOUS SUPPORT *
2898 ************************************************************************/
2899
2900/*
d26d0ae9 2901 * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
8cd0a023 2902 *
d113fda1 2903 * Note that for this particular function a return value of -1, 0, or +1
9582c7da 2904 * can denote a match if create_tid is otherwise discounted. A create_tid
d5530d22 2905 * of zero is considered to be 'infinity' in comparisons.
d113fda1 2906 *
8cd0a023 2907 * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
8cd0a023
MD
2908 */
2909int
2910hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
2911{
2f85fa4d
MD
2912 if (key1->localization < key2->localization)
2913 return(-5);
2914 if (key1->localization > key2->localization)
2915 return(5);
2916
d26d0ae9
MD
2917 if (key1->obj_id < key2->obj_id)
2918 return(-4);
2919 if (key1->obj_id > key2->obj_id)
2920 return(4);
8cd0a023 2921
d26d0ae9
MD
2922 if (key1->rec_type < key2->rec_type)
2923 return(-3);
2924 if (key1->rec_type > key2->rec_type)
2925 return(3);
8cd0a023 2926
8cd0a023
MD
2927 if (key1->key < key2->key)
2928 return(-2);
2929 if (key1->key > key2->key)
2930 return(2);
d113fda1 2931
d5530d22 2932 /*
9582c7da
MD
2933 * A create_tid of zero indicates a record which is undeletable
2934 * and must be considered to have a value of positive infinity.
d5530d22 2935 */
9582c7da
MD
2936 if (key1->create_tid == 0) {
2937 if (key2->create_tid == 0)
d5530d22
MD
2938 return(0);
2939 return(1);
2940 }
9582c7da 2941 if (key2->create_tid == 0)
d5530d22 2942 return(-1);
9582c7da 2943 if (key1->create_tid < key2->create_tid)
d113fda1 2944 return(-1);
9582c7da 2945 if (key1->create_tid > key2->create_tid)
d113fda1 2946 return(1);
8cd0a023
MD
2947 return(0);
2948}
2949
c0ade690 2950/*
d5530d22
MD
2951 * Test a timestamp against an element to determine whether the
2952 * element is visible. A timestamp of 0 means 'infinity'.
c0ade690
MD
2953 */
2954int
d5530d22 2955hammer_btree_chkts(hammer_tid_t asof, hammer_base_elm_t base)
c0ade690 2956{
d5530d22
MD
2957 if (asof == 0) {
2958 if (base->delete_tid)
2959 return(1);
2960 return(0);
2961 }
2962 if (asof < base->create_tid)
d26d0ae9 2963 return(-1);
d5530d22 2964 if (base->delete_tid && asof >= base->delete_tid)
d26d0ae9 2965 return(1);
c0ade690
MD
2966 return(0);
2967}
2968
8cd0a023
MD
2969/*
2970 * Create a separator half way inbetween key1 and key2. For fields just
d5530d22
MD
2971 * one unit apart, the separator will match key2. key1 is on the left-hand
2972 * side and key2 is on the right-hand side.
8cd0a023 2973 *
9391cded 2974 * key2 must be >= the separator. It is ok for the separator to match key2.
36f82b23 2975 *
9391cded
MD
2976 * NOTE: Even if key1 does not match key2, the separator may wind up matching
2977 * key2.
2978 *
2979 * NOTE: It might be beneficial to just scrap this whole mess and just
2980 * set the separator to key2.
8cd0a023
MD
2981 */
2982#define MAKE_SEPARATOR(key1, key2, dest, field) \
2983 dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2984
2985static void
2986hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2987 hammer_base_elm_t dest)
2988{
2989 bzero(dest, sizeof(*dest));
d5530d22 2990
9391cded
MD
2991 dest->rec_type = key2->rec_type;
2992 dest->key = key2->key;
2f85fa4d 2993 dest->obj_id = key2->obj_id;
9391cded
MD
2994 dest->create_tid = key2->create_tid;
2995
2f85fa4d
MD
2996 MAKE_SEPARATOR(key1, key2, dest, localization);
2997 if (key1->localization == key2->localization) {
2998 MAKE_SEPARATOR(key1, key2, dest, obj_id);
2999 if (key1->obj_id == key2->obj_id) {
3000 MAKE_SEPARATOR(key1, key2, dest, rec_type);
3001 if (key1->rec_type == key2->rec_type) {
3002 MAKE_SEPARATOR(key1, key2, dest, key);
3003 /*
3004 * Don't bother creating a separator for
3005 * create_tid, which also conveniently avoids
3006 * having to handle the create_tid == 0
3007 * (infinity) case. Just leave create_tid
3008 * set to key2.
3009 *
3010 * Worst case, dest matches key2 exactly,
3011 * which is acceptable.
3012 */
3013 }
d5530d22 3014 }
d113fda1 3015 }
8cd0a023
MD
3016}
3017
3018#undef MAKE_SEPARATOR
3019
3020/*
3021 * Return whether a generic internal or leaf node is full
3022 */
3023static int
3024btree_node_is_full(hammer_node_ondisk_t node)
3025{
3026 switch(node->type) {
3027 case HAMMER_BTREE_TYPE_INTERNAL:
3028 if (node->count == HAMMER_BTREE_INT_ELMS)
3029 return(1);
3030 break;
3031 case HAMMER_BTREE_TYPE_LEAF:
3032 if (node->count == HAMMER_BTREE_LEAF_ELMS)
3033 return(1);
3034 break;
3035 default:
51a31a39 3036 panic("illegal btree type");
8cd0a023
MD
3037 }
3038 return(0);
3039}
9944ae54 3040
8cd0a023
MD
3041#if 0
3042static int
3043btree_max_elements(u_int8_t type)
3044{
3045 if (type == HAMMER_BTREE_TYPE_LEAF)
3046 return(HAMMER_BTREE_LEAF_ELMS);
3047 if (type == HAMMER_BTREE_TYPE_INTERNAL)
3048 return(HAMMER_BTREE_INT_ELMS);
ed20d0e3 3049 panic("btree_max_elements: bad type %d", type);
8cd0a023
MD
3050}
3051#endif
3052
c0ade690
MD
3053void
3054hammer_print_btree_node(hammer_node_ondisk_t ondisk)
3055{
3056 hammer_btree_elm_t elm;
3057 int i;
3058
47197d71 3059 kprintf("node %p count=%d parent=%016llx type=%c\n",
973c11b9
MD
3060 ondisk, ondisk->count,
3061 (long long)ondisk->parent, ondisk->type);
c0ade690
MD
3062
3063 /*
3064 * Dump both boundary elements if an internal node
3065 */
3066 if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
3067 for (i = 0; i <= ondisk->count; ++i) {
3068 elm = &ondisk->elms[i];
3069 hammer_print_btree_elm(elm, ondisk->type, i);
3070 }
3071 } else {
3072 for (i = 0; i < ondisk->count; ++i) {
3073 elm = &ondisk->elms[i];
3074 hammer_print_btree_elm(elm, ondisk->type, i);
3075 }
3076 }
3077}
3078
3079void
3080hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
3081{
3082 kprintf(" %2d", i);
973c11b9
MD
3083 kprintf("\tobj_id = %016llx\n", (long long)elm->base.obj_id);
3084 kprintf("\tkey = %016llx\n", (long long)elm->base.key);
3085 kprintf("\tcreate_tid = %016llx\n", (long long)elm->base.