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