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