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