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