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