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