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