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