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