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