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