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