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