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