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