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