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