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