HAMMER 19/Many - Cleanup pass, cluster recovery code.
[dragonfly.git] / sys / vfs / hammer / hammer_btree.c
1 /*
2  * Copyright (c) 2007 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/vfs/hammer/hammer_btree.c,v 1.18 2008/01/15 06:02:57 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  * INTER-CLUSTER ELEMENTS:  An element of an internal node may reference
71  * the root of another cluster rather then a node in the current cluster.
72  * This is known as an inter-cluster references.  Only B-Tree searches
73  * will cross cluster boundaries.  The rebalancing and collapse code does
74  * not attempt to move children between clusters.  A major effect of this
75  * is that we have to relax minimum element count requirements and allow
76  * trees to become somewhat unabalanced.
77  *
78  * INSERTIONS AND DELETIONS:  When inserting we split full nodes on our
79  * way down as an optimization.  I originally experimented with rebalancing
80  * nodes on the way down for deletions but it created a huge mess due to
81  * the way inter-cluster linkages work.  Instead, now I simply allow
82  * the tree to become unbalanced and allow leaf nodes to become empty.
83  * The delete code will try to clean things up from the bottom-up but
84  * will stop if related elements are not in-core or if it cannot get a node
85  * lock.
86  */
87 #include "hammer.h"
88 #include <sys/buf.h>
89 #include <sys/buf2.h>
90
91 typedef enum btree_search_edge {
92         SEARCH_NONE,
93         SEARCH_LEFT_EDGE,
94         SEARCH_RIGHT_EDGE 
95 } btree_search_edge_t;
96
97 static int btree_search(hammer_cursor_t cursor, int flags);
98 static int btree_edge_internal(hammer_cursor_t cursor,
99                         btree_search_edge_t edge);
100 static int btree_split_internal(hammer_cursor_t cursor);
101 static int btree_split_leaf(hammer_cursor_t cursor);
102 static int btree_remove(hammer_cursor_t cursor);
103 static int btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm);
104 #if 0
105 static int btree_rebalance(hammer_cursor_t cursor);
106 static int btree_collapse(hammer_cursor_t cursor);
107 #endif
108 static int btree_node_is_almost_full(hammer_node_ondisk_t node);
109 static void hammer_make_separator(hammer_base_elm_t key1,
110                         hammer_base_elm_t key2, hammer_base_elm_t dest);
111
112 /*
113  * Iterate records after a search.  The cursor is iterated forwards past
114  * the current record until a record matching the key-range requirements
115  * is found.  ENOENT is returned if the iteration goes past the ending
116  * key.
117  *
118  * The iteration is inclusive of key_beg and can be inclusive or exclusive
119  * of key_end depending on whether HAMMER_CURSOR_END_INCLUSIVE is set.
120  *
121  * cursor->key_beg may or may not be modified by this function during
122  * the iteration.  XXX future - in case of an inverted lock we may have
123  * to reinitiate the lookup and set key_beg to properly pick up where we
124  * left off.
125  */
126 int
127 hammer_btree_iterate(hammer_cursor_t cursor)
128 {
129         hammer_node_ondisk_t node;
130         hammer_btree_elm_t elm;
131         int error;
132         int r;
133         int s;
134
135         /*
136          * Skip past the current record
137          */
138         node = cursor->node->ondisk;
139         if (node == NULL)
140                 return(ENOENT);
141         if (cursor->index < node->count && 
142             (cursor->flags & HAMMER_CURSOR_ATEDISK)) {
143                 ++cursor->index;
144         }
145
146         /*
147          * Loop until an element is found or we are done.
148          */
149         for (;;) {
150                 /*
151                  * We iterate up the tree and then index over one element
152                  * while we are at the last element in the current node.
153                  *
154                  * NOTE: This can pop us up to another cluster.
155                  *
156                  * If we are at the root of the root cluster, cursor_up
157                  * returns ENOENT.
158                  *
159                  * NOTE: hammer_cursor_up() will adjust cursor->key_beg
160                  * when told to re-search for the cluster tag.
161                  *
162                  * XXX this could be optimized by storing the information in
163                  * the parent reference.
164                  *
165                  * XXX we can lose the node lock temporarily, this could mess
166                  * up our scan.
167                  */
168                 if (cursor->index == node->count) {
169                         error = hammer_cursor_up(cursor, 0);
170                         if (error)
171                                 break;
172                         node = cursor->node->ondisk;
173                         KKASSERT(cursor->index != node->count);
174                         ++cursor->index;
175                         continue;
176                 }
177
178                 /*
179                  * Check internal or leaf element.  Determine if the record
180                  * at the cursor has gone beyond the end of our range.
181                  *
182                  * Generally we recurse down through internal nodes.  An
183                  * internal node can only be returned if INCLUSTER is set
184                  * and the node represents a cluster-push record.  Internal
185                  * elements do not contain create_tid/delete_tid information.
186                  */
187                 if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
188                         elm = &node->elms[cursor->index];
189                         r = hammer_btree_cmp(&cursor->key_end, &elm[0].base);
190                         s = hammer_btree_cmp(&cursor->key_beg, &elm[1].base);
191                         if (hammer_debug_btree) {
192                                 kprintf("BRACKETL %p:%d %016llx %02x %016llx %d\n",
193                                         cursor->node, cursor->index,
194                                         elm[0].internal.base.obj_id,
195                                         elm[0].internal.base.rec_type,
196                                         elm[0].internal.base.key,
197                                         r
198                                 );
199                                 kprintf("BRACKETR %p:%d %016llx %02x %016llx %d\n",
200                                         cursor->node, cursor->index + 1,
201                                         elm[1].internal.base.obj_id,
202                                         elm[1].internal.base.rec_type,
203                                         elm[1].internal.base.key,
204                                         s
205                                 );
206                         }
207
208                         if (r < 0) {
209                                 error = ENOENT;
210                                 break;
211                         }
212                         if (r == 0 && (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
213                                 error = ENOENT;
214                                 break;
215                         }
216                         KKASSERT(s <= 0);
217                         if ((cursor->flags & HAMMER_CURSOR_INCLUSTER) == 0 ||
218                             elm->internal.rec_offset == 0) {
219                                 error = hammer_cursor_down(cursor);
220                                 if (error)
221                                         break;
222                                 KKASSERT(cursor->index == 0);
223                                 node = cursor->node->ondisk;
224                                 continue;
225                         }
226                 } else {
227                         elm = &node->elms[cursor->index];
228                         r = hammer_btree_cmp(&cursor->key_end, &elm->base);
229                         if (hammer_debug_btree) {
230                                 kprintf("ELEMENT  %p:%d %016llx %02x %016llx %d\n",
231                                         cursor->node, cursor->index,
232                                         elm[0].leaf.base.obj_id,
233                                         elm[0].leaf.base.rec_type,
234                                         elm[0].leaf.base.key,
235                                         r
236                                 );
237                         }
238                         if (r < 0) {
239                                 error = ENOENT;
240                                 break;
241                         }
242                         if (r == 0 && (cursor->flags & HAMMER_CURSOR_END_INCLUSIVE) == 0) {
243                                 error = ENOENT;
244                                 break;
245                         }
246                         if ((cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0 &&
247                             hammer_btree_chkts(cursor->key_beg.create_tid,
248                                                &elm->base) != 0) {
249                                 ++cursor->index;
250                                 continue;
251                         }
252                 }
253
254                 /*
255                  * Return entry
256                  */
257                 if (hammer_debug_btree) {
258                         int i = cursor->index;
259                         hammer_btree_elm_t elm = &cursor->node->ondisk->elms[i];
260                         kprintf("ITERATE  %p:%d %016llx %02x %016llx\n",
261                                 cursor->node, i,
262                                 elm->internal.base.obj_id,
263                                 elm->internal.base.rec_type,
264                                 elm->internal.base.key
265                         );
266                 }
267                 return(0);
268         }
269         return(error);
270 }
271
272 /*
273  * Lookup cursor->key_beg.  0 is returned on success, ENOENT if the entry
274  * could not be found, and a fatal error otherwise.
275  * 
276  * The cursor is suitably positioned for a deletion on success, and suitably
277  * positioned for an insertion on ENOENT.
278  *
279  * The cursor may begin anywhere, the search will traverse clusters in
280  * either direction to locate the requested element.
281  */
282 int
283 hammer_btree_lookup(hammer_cursor_t cursor)
284 {
285         int error;
286
287         error = btree_search(cursor, 0);
288         if (error == 0 && cursor->flags)
289                 error = hammer_btree_extract(cursor, cursor->flags);
290         return(error);
291 }
292
293 /*
294  * Execute the logic required to start an iteration.  The first record
295  * located within the specified range is returned and iteration control
296  * flags are adjusted for successive hammer_btree_iterate() calls.
297  */
298 int
299 hammer_btree_first(hammer_cursor_t cursor)
300 {
301         int error;
302
303         error = hammer_btree_lookup(cursor);
304         if (error == ENOENT) {
305                 cursor->flags &= ~HAMMER_CURSOR_ATEDISK;
306                 error = hammer_btree_iterate(cursor);
307         }
308         cursor->flags |= HAMMER_CURSOR_ATEDISK;
309         return(error);
310 }
311
312 /*
313  * Extract the record and/or data associated with the cursor's current
314  * position.  Any prior record or data stored in the cursor is replaced.
315  * The cursor must be positioned at a leaf node.
316  *
317  * NOTE: Most extractions occur at the leaf of the B-Tree.  The only
318  *       extraction allowed at an internal element is at a cluster-push.
319  *       Cluster-push elements have records but no data.
320  */
321 int
322 hammer_btree_extract(hammer_cursor_t cursor, int flags)
323 {
324         hammer_node_ondisk_t node;
325         hammer_btree_elm_t elm;
326         hammer_cluster_t cluster;
327         u_int64_t buf_type;
328         int32_t cloff;
329         int32_t roff;
330         int error;
331
332         /*
333          * A cluster record type has no data reference, the information
334          * is stored directly in the record and B-Tree element.
335          *
336          * The case where the data reference resolves to the same buffer
337          * as the record reference must be handled.
338          */
339         node = cursor->node->ondisk;
340         elm = &node->elms[cursor->index];
341         cluster = cursor->node->cluster;
342         cursor->flags &= ~HAMMER_CURSOR_DATA_EMBEDDED;
343         cursor->data = NULL;
344         error = 0;
345
346         /*
347          * Internal elements can only be cluster pushes.  A cluster push has
348          * no data reference.
349          */
350         if (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
351                 cloff = elm->internal.rec_offset;
352                 KKASSERT(cloff != 0);
353                 cursor->record = hammer_bread(cluster, cloff,
354                                               HAMMER_FSBUF_RECORDS, &error,
355                                               &cursor->record_buffer);
356                 return(error);
357         }
358
359         /*
360          * Leaf element.
361          */
362         if ((flags & HAMMER_CURSOR_GET_RECORD) && error == 0) {
363                 cloff = elm->leaf.rec_offset;
364                 cursor->record = hammer_bread(cluster, cloff,
365                                               HAMMER_FSBUF_RECORDS, &error,
366                                               &cursor->record_buffer);
367         } else {
368                 cloff = 0;
369         }
370         if ((flags & HAMMER_CURSOR_GET_DATA) && error == 0) {
371                 if ((cloff ^ elm->leaf.data_offset) & ~HAMMER_BUFMASK) {
372                         /*
373                          * The data is not in the same buffer as the last
374                          * record we cached, but it could still be embedded
375                          * in a record.  Note that we may not have loaded the
376                          * record's buffer above, depending on flags.
377                          */
378                         if ((elm->leaf.rec_offset ^ elm->leaf.data_offset) &
379                             ~HAMMER_BUFMASK) {
380                                 if (elm->leaf.data_len & HAMMER_BUFMASK)
381                                         buf_type = HAMMER_FSBUF_DATA;
382                                 else
383                                         buf_type = 0;   /* pure data buffer */
384                         } else {
385                                 buf_type = HAMMER_FSBUF_RECORDS;
386                         }
387                         cursor->data = hammer_bread(cluster,
388                                                   elm->leaf.data_offset,
389                                                   buf_type, &error,
390                                                   &cursor->data_buffer);
391                 } else {
392                         /*
393                          * Data in same buffer as record.  Note that we
394                          * leave any existing data_buffer intact, even
395                          * though we don't use it in this case, in case
396                          * other records extracted during an iteration
397                          * go back to it.
398                          *
399                          * The data must be embedded in the record for this
400                          * case to be hit.
401                          *
402                          * Just assume the buffer type is correct.
403                          */
404                         cursor->data = (void *)
405                                 ((char *)cursor->record_buffer->ondisk +
406                                  (elm->leaf.data_offset & HAMMER_BUFMASK));
407                         roff = (char *)cursor->data - (char *)cursor->record;
408                         KKASSERT (roff >= 0 && roff < HAMMER_RECORD_SIZE);
409                         cursor->flags |= HAMMER_CURSOR_DATA_EMBEDDED;
410                 }
411         }
412         return(error);
413 }
414
415
416 /*
417  * Insert a leaf element into the B-Tree at the current cursor position.
418  * The cursor is positioned such that the element at and beyond the cursor
419  * are shifted to make room for the new record.
420  *
421  * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
422  * flag set and that call must return ENOENT before this function can be
423  * called.
424  *
425  * ENOSPC is returned if there is no room to insert a new record.
426  */
427 int
428 hammer_btree_insert(hammer_cursor_t cursor, hammer_btree_elm_t elm)
429 {
430         hammer_node_ondisk_t parent;
431         hammer_node_ondisk_t node;
432         int i;
433
434         /*
435          * Insert the element at the leaf node and update the count in the
436          * parent.  It is possible for parent to be NULL, indicating that
437          * the root of the B-Tree in the cluster is a leaf.  It is also
438          * possible for the leaf to be empty.
439          *
440          * Remember that the right-hand boundary is not included in the
441          * count.
442          */
443         hammer_modify_node(cursor->node);
444         node = cursor->node->ondisk;
445         i = cursor->index;
446         KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
447         KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
448         if (i != node->count) {
449                 bcopy(&node->elms[i], &node->elms[i+1],
450                       (node->count - i) * sizeof(*elm));
451         }
452         node->elms[i] = *elm;
453         ++node->count;
454
455         KKASSERT(hammer_btree_cmp(cursor->left_bound, &elm->leaf.base) <= 0);
456         KKASSERT(hammer_btree_cmp(cursor->right_bound, &elm->leaf.base) > 0);
457         if (i)
458                 KKASSERT(hammer_btree_cmp(&node->elms[i-1].leaf.base, &elm->leaf.base) < 0);
459         if (i != node->count - 1)
460                 KKASSERT(hammer_btree_cmp(&node->elms[i+1].leaf.base, &elm->leaf.base) > 0);
461
462         /*
463          * Adjust the sub-tree count in the parent.  note that the parent
464          * may be in a different cluster.
465          */
466         if (cursor->parent) {
467                 hammer_modify_node(cursor->parent);
468                 parent = cursor->parent->ondisk;
469                 i = cursor->parent_index;
470                 ++parent->elms[i].internal.subtree_count;
471                 KKASSERT(parent->elms[i].internal.subtree_count <= node->count);
472         }
473         return(0);
474 }
475
476 /*
477  * Insert a cluster push into the B-Tree at the current cursor position.
478  * The cursor is positioned at a leaf after a failed btree_lookup.
479  *
480  * The caller must call hammer_btree_lookup() with the HAMMER_CURSOR_INSERT
481  * flag set and that call must return ENOENT before this function can be
482  * called.
483  *
484  * This routine is used ONLY during a recovery pass while the originating
485  * cluster is serialized.  The leaf is broken up into up to three pieces,
486  * causing up to an additional internal elements to be added to the parent.
487  *
488  * ENOSPC is returned if there is no room to insert a new record.
489  */
490 int
491 hammer_btree_insert_cluster(hammer_cursor_t cursor, hammer_cluster_t ncluster,
492                             int32_t rec_offset)
493 {
494         hammer_cluster_t ocluster;
495         hammer_node_ondisk_t parent;
496         hammer_node_ondisk_t node;
497         hammer_node_ondisk_t xnode;     /* additional leaf node */
498         hammer_node_t        new_node;
499         hammer_btree_elm_t   elm;
500         const int esize = sizeof(*elm);
501         u_int8_t save;
502         int error = 0;
503         int pi, i;
504
505         kprintf("cursor %p ncluster %p\n", cursor, ncluster);
506         hammer_modify_node(cursor->node);
507         node = cursor->node->ondisk;
508         i = cursor->index;
509         KKASSERT(node->type == HAMMER_BTREE_TYPE_LEAF);
510         KKASSERT(node->count < HAMMER_BTREE_LEAF_ELMS);
511
512         /*
513          * Make sure the spike is legal or the B-Tree code will get really
514          * confused.
515          */
516         KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_beg,
517                                   cursor->left_bound) >= 0);
518         KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
519                                   cursor->right_bound) <= 0);
520         if (i != node->count) {
521                 KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
522                                           &node->elms[i].leaf.base) <= 0);
523         }
524
525         /*
526          * If we are at the local root of the cluster a new root node
527          * must be created, because we need an internal node.  The
528          * caller has already marked the source cluster as undergoing
529          * modification.
530          */
531         ocluster = cursor->node->cluster;
532         if (cursor->parent == NULL) {
533                 cursor->parent = hammer_alloc_btree(ocluster, &error);
534                 if (error)
535                         return(error);
536                 hammer_lock_ex(&cursor->parent->lock);
537                 hammer_modify_node(cursor->parent);
538                 parent = cursor->parent->ondisk;
539                 parent->count = 1;
540                 parent->parent = 0;
541                 parent->type = HAMMER_BTREE_TYPE_INTERNAL;
542                 parent->elms[0].base = ocluster->clu_btree_beg;
543                 parent->elms[0].base.subtree_type = node->type;
544                 parent->elms[0].internal.subtree_offset = cursor->node->node_offset;
545                 parent->elms[0].internal.subtree_count = node->count;
546                 parent->elms[1].base = ocluster->clu_btree_end;
547                 cursor->parent_index = 0;
548                 cursor->left_bound = &parent->elms[0].base;
549                 cursor->right_bound = &parent->elms[1].base;
550                 node->parent = cursor->parent->node_offset;
551                 ocluster->ondisk->clu_btree_root = cursor->parent->node_offset;
552                 kprintf("no parent\n");
553         } else {
554                 kprintf("has parent\n");
555         }
556
557
558         KKASSERT(cursor->parent->ondisk->count <= HAMMER_BTREE_INT_ELMS - 2);
559
560         hammer_modify_node(cursor->parent);
561         parent = cursor->parent->ondisk;
562         pi = cursor->parent_index;
563
564         kprintf("%d node %d/%d (%c) offset=%d parent=%d\n",
565                 cursor->node->cluster->clu_no,
566                 i, node->count, node->type, cursor->node->node_offset, node->parent);
567
568         /*
569          * If the insertion point bisects the node we will need to allocate
570          * a second leaf node to copy the right hand side into.
571          */
572         if (i != 0 && i != node->count) {
573                 new_node = hammer_alloc_btree(cursor->node->cluster, &error);
574                 if (error)
575                         return(error);
576                 xnode = new_node->ondisk;
577                 bcopy(&node->elms[i], &xnode->elms[0],
578                       (node->count - i) * esize);
579                 xnode->count = node->count - i;
580                 xnode->parent = cursor->parent->node_offset;
581                 xnode->type = HAMMER_BTREE_TYPE_LEAF;
582                 node->count = i;
583                 parent->elms[pi].internal.subtree_count = node->count;
584         } else {
585                 new_node = NULL;
586                 xnode = NULL;
587         }
588
589         /*
590          * Adjust the parent and set pi to point at the internal element
591          * which we intended to hold the spike.
592          */
593         if (new_node) {
594                 /*
595                  * Insert spike after parent index.  Spike is at pi + 1.
596                  * Also include room after the spike for new_node
597                  */
598                 ++pi;
599                 bcopy(&parent->elms[pi], &parent->elms[pi+2],
600                       (parent->count - pi + 1) * esize);
601                 parent->count += 2;
602         } else if (i == 0) {
603                 /*
604                  * Insert spike before parent index.  Spike is at pi.
605                  *
606                  * cursor->node's index in the parent (cursor->parent_index)
607                  * has now shifted over by one.
608                  */
609                 bcopy(&parent->elms[pi], &parent->elms[pi+1],
610                       (parent->count - pi + 1) * esize);
611                 ++parent->count;
612                 ++cursor->parent_index;
613         } else {
614                 /*
615                  * Insert spike after parent index.  Spike is at pi + 1.
616                  */
617                 ++pi;
618                 bcopy(&parent->elms[pi], &parent->elms[pi+1],
619                       (parent->count - pi + 1) * esize);
620                 ++parent->count;
621         }
622
623         /*
624          * Load the spike into the parent at (pi).
625          *
626          * WARNING: subtree_type is actually overloaded within base.
627          * WARNING: subtree_clu_no is overloaded on subtree_offset
628          */
629         elm = &parent->elms[pi];
630         elm[0].internal.base = ncluster->ondisk->clu_btree_beg;
631         elm[0].internal.base.subtree_type = HAMMER_BTREE_TYPE_CLUSTER;
632         elm[0].internal.rec_offset = rec_offset;
633         elm[0].internal.subtree_clu_no = ncluster->clu_no;
634         elm[0].internal.subtree_vol_no = ncluster->volume->vol_no;
635         elm[0].internal.subtree_count = 0; /* XXX */
636
637         /*
638          * Load the new node into parent at (pi+1) if non-NULL, and also
639          * set the right-hand boundary for the spike.
640          *
641          * Because new_node is a leaf its elements do not point to any
642          * nodes so we don't have to scan it to adjust parent pointers.
643          *
644          * WARNING: subtree_type is actually overloaded within base.
645          * WARNING: subtree_clu_no is overloaded on subtree_offset
646          *
647          * XXX right-boundary may not match clu_btree_end if spike is
648          *     at the end of the internal node.  For now the cursor search
649          *     insertion code will deal with it.
650          */
651         if (new_node) {
652                 elm[1].internal.base = ncluster->ondisk->clu_btree_end;
653                 elm[1].internal.base.subtree_type = HAMMER_BTREE_TYPE_LEAF;
654                 elm[1].internal.subtree_offset = new_node->node_offset;
655                 elm[1].internal.subtree_count = xnode->count;
656                 elm[1].internal.subtree_vol_no = -1;
657                 elm[1].internal.rec_offset = 0;
658         } else {
659                 /*
660                  * The right boundary is only the base part of elm[1].
661                  * The rest belongs to elm[1]'s recursion.  Note however
662                  * that subtree_type is overloaded within base so we 
663                  * have to retain it as well.
664                  */
665                 save = elm[1].internal.base.subtree_type;
666                 elm[1].internal.base = ncluster->ondisk->clu_btree_end;
667                 elm[1].internal.base.subtree_type = save;
668         }
669
670         /*
671          * The boundaries stored in the cursor for node are probably all
672          * messed up now, fix them.
673          */
674         cursor->left_bound = &parent->elms[cursor->parent_index].base;
675         cursor->right_bound = &parent->elms[cursor->parent_index+1].base;
676
677         KKASSERT(hammer_btree_cmp(&ncluster->ondisk->clu_btree_end,
678                                   &elm[1].internal.base) <= 0);
679
680
681         /*
682          * Adjust the target cluster's parent offset
683          */
684         hammer_modify_cluster(ncluster);
685         ncluster->ondisk->clu_btree_parent_offset = cursor->parent->node_offset;
686
687         if (new_node)
688                 hammer_rel_node(new_node);
689
690         return(0);
691 }
692
693 /*
694  * Delete a record from the B-Tree's at the current cursor position.
695  * The cursor is positioned such that the current element is the one
696  * to be deleted.
697  *
698  * On return the cursor will be positioned after the deleted element and
699  * MAY point to an internal node.  It will be suitable for the continuation
700  * of an iteration but not for an insertion or deletion.
701  *
702  * Deletions will attempt to partially rebalance the B-Tree in an upward
703  * direction.  It is possible to end up with empty leafs.  An empty internal
704  * node is impossible (worst case: it has one element pointing to an empty
705  * leaf).
706  */
707 int
708 hammer_btree_delete(hammer_cursor_t cursor)
709 {
710         hammer_node_ondisk_t ondisk;
711         hammer_node_t node;
712         hammer_node_t parent;
713         hammer_btree_elm_t elm;
714         int error;
715         int i;
716
717         /*
718          * Delete the element from the leaf node. 
719          *
720          * Remember that leaf nodes do not have boundaries.
721          */
722         node = cursor->node;
723         ondisk = node->ondisk;
724         i = cursor->index;
725
726         KKASSERT(ondisk->type == HAMMER_BTREE_TYPE_LEAF);
727         hammer_modify_node(node);
728         if (i + 1 != ondisk->count) {
729                 bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
730                       (ondisk->count - i - 1) * sizeof(ondisk->elms[0]));
731         }
732         --ondisk->count;
733         if (cursor->parent != NULL) {
734                 /*
735                  * Adjust parent's notion of the leaf's count.  subtree_count
736                  * is only approximate, it is allowed to be too small but
737                  * never allowed to be too large.  Make sure we don't drop
738                  * the count below 0.
739                  */
740                 parent = cursor->parent;
741                 hammer_modify_node(parent);
742                 elm = &parent->ondisk->elms[cursor->parent_index];
743                 if (elm->internal.subtree_count)
744                         --elm->internal.subtree_count;
745                 KKASSERT(elm->internal.subtree_count <= ondisk->count);
746         }
747
748         /*
749          * It is possible, but not desireable, to stop here.  If the element
750          * count drops to 0 (which is allowed for a leaf), try recursively
751          * remove the B-Tree node.
752          *
753          * XXX rebalancing calls would go here too.
754          *
755          * This may reposition the cursor at one of the parent's of the
756          * current node.
757          */
758         KKASSERT(cursor->index <= ondisk->count);
759         if (ondisk->count == 0) {
760                 error = btree_remove(cursor);
761                 if (error == EAGAIN)
762                         error = 0;
763         } else {
764                 error = 0;
765         }
766         return(error);
767 }
768
769 /*
770  * PRIMAY B-TREE SEARCH SUPPORT PROCEDURE
771  *
772  * Search a cluster's B-Tree for cursor->key_beg, return the matching node.
773  *
774  * The search can begin ANYWHERE in the B-Tree.  As a first step the search
775  * iterates up the tree as necessary to properly position itself prior to
776  * actually doing the sarch.
777  * 
778  * INSERTIONS: The search will split full nodes and leaves on its way down
779  * and guarentee that the leaf it ends up on is not full.  If we run out
780  * of space the search continues to the leaf (to position the cursor for
781  * the spike), but ENOSPC is returned.
782  *
783  * XXX this isn't optimal - we really need to just locate the end point and
784  * insert space going up, and if we get a deadlock just release and retry
785  * the operation.  Or something like that.  The insertion code can transit
786  * multiple clusters and run splits in unnecessary clusters.
787  *
788  * DELETIONS: The search will rebalance the tree on its way down. XXX
789  *
790  * The search is only guarenteed to end up on a leaf if an error code of 0
791  * is returned, or if inserting and an error code of ENOENT is returned.
792  * Otherwise it can stop at an internal node.  On success a search returns
793  * a leaf node unless INCLUSTER is set and the search located a cluster push
794  * node (which is an internal node).
795  */
796 static 
797 int
798 btree_search(hammer_cursor_t cursor, int flags)
799 {
800         hammer_node_ondisk_t node;
801         hammer_cluster_t cluster;
802         hammer_btree_elm_t elm;
803         btree_search_edge_t edge;
804         int error;
805         int enospc = 0;
806         int i;
807         int r;
808
809         flags |= cursor->flags;
810
811         if (hammer_debug_btree) {
812                 kprintf("SEARCH   %p:%d %016llx %02x key=%016llx tid=%016llx\n",
813                         cursor->node, cursor->index,
814                         cursor->key_beg.obj_id,
815                         cursor->key_beg.rec_type,
816                         cursor->key_beg.key,
817                         cursor->key_beg.create_tid
818                 );
819         }
820
821         /*
822          * Move our cursor up the tree until we find a node whos range covers
823          * the key we are trying to locate.  This may move us between
824          * clusters.
825          *
826          * The left bound is inclusive, the right bound is non-inclusive.
827          * It is ok to cursor up too far so when cursoring across a cluster
828          * boundary.
829          *
830          * First see if we can skip the whole cluster.  hammer_cursor_up()
831          * handles both cases but this way we don't check the cluster
832          * bounds when going up the tree within a cluster.
833          *
834          * NOTE: If INCLUSTER is set and we are at the root of the cluster,
835          * hammer_cursor_up() will return ENOENT.
836          */
837         cluster = cursor->node->cluster;
838         while (
839             hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_beg) < 0 ||
840             hammer_btree_cmp(&cursor->key_beg, &cluster->clu_btree_end) >= 0) {
841                 error = hammer_cursor_toroot(cursor);
842                 if (error)
843                         goto done;
844                 KKASSERT(cursor->parent);
845                 error = hammer_cursor_up(cursor, 0);
846                 if (error)
847                         goto done;
848                 cluster = cursor->node->cluster;
849         }
850
851         /*
852          * Deal with normal cursoring within a cluster.  The right bound
853          * is non-inclusive.  That is, the bounds form a separator.
854          */
855         while (hammer_btree_cmp(&cursor->key_beg, cursor->left_bound) < 0 ||
856                hammer_btree_cmp(&cursor->key_beg, cursor->right_bound) >= 0) {
857                 KKASSERT(cursor->parent);
858                 error = hammer_cursor_up(cursor, 0);
859                 if (error)
860                         goto done;
861         }
862
863         /*
864          * We better have ended up with a node somewhere, and our second
865          * while loop had better not have traversed up a cluster.
866          */
867         KKASSERT(cursor->node != NULL && cursor->node->cluster == cluster);
868
869         /*
870          * If we are inserting we can't start at a full node if the parent
871          * is also full (because there is no way to split the node),
872          * continue running up the tree until we hit the root of the
873          * root cluster or until the requirement is satisfied.
874          *
875          * NOTE: These cursor-up's CAN continue to cross cluster boundaries.
876          *
877          * NOTE: We must guarantee at least two open spots in the parent
878          *       to deal with hammer_btree_insert_cluster().
879          *
880          * XXX as an optimization it should be possible to unbalance the tree
881          * and stop at the root of the current cluster.
882          */
883         while ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
884                 if (btree_node_is_almost_full(cursor->node->ondisk) == 0)
885                         break;
886                 if (cursor->parent == NULL)
887                         break;
888                 if (cursor->parent->ondisk->count != HAMMER_BTREE_INT_ELMS)
889                         break;
890                 error = hammer_cursor_up(cursor, 0);
891                 /* cluster and node are now may become stale */
892                 if (error)
893                         goto done;
894         }
895         /* cluster = cursor->node->cluster; not needed until next cluster = */
896
897 #if 0
898         /*
899          * If we are deleting we can't start at an internal node with only
900          * one element unless it is root, because all of our code assumes
901          * that internal nodes will never be empty.  Just do this generally
902          * for both leaf and internal nodes to get better balance.
903          *
904          * This handles the case where the cursor is sitting at a leaf and
905          * either the leaf or parent contain an insufficient number of
906          * elements.
907          *
908          * NOTE: These cursor-up's CAN continue to cross cluster boundaries.
909          *
910          * XXX NOTE: Iterations may not set this flag anyway.
911          */
912         while (flags & HAMMER_CURSOR_DELETE) {
913                 if (cursor->node->ondisk->count > 1)
914                         break;
915                 if (cursor->parent == NULL)
916                         break;
917                 KKASSERT(cursor->node->ondisk->count != 0);
918                 error = hammer_cursor_up(cursor, 0);
919                 /* cluster and node are now may become stale */
920                 if (error)
921                         goto done;
922         }
923 #endif
924
925 /*new_cluster:*/
926         /*
927          * Push down through internal nodes to locate the requested key.
928          */
929         cluster = cursor->node->cluster;
930         node = cursor->node->ondisk;
931         while (node->type == HAMMER_BTREE_TYPE_INTERNAL) {
932 #if 0
933                 /*
934                  * If we are a the root node and deleting, try to collapse
935                  * all of the root's children into the root.  This is the
936                  * only point where tree depth is reduced.
937                  *
938                  * XXX NOTE: Iterations may not set this flag anyway.
939                  */
940                 if ((flags & HAMMER_CURSOR_DELETE) && cursor->parent == NULL) {
941                         error = btree_collapse(cursor);
942                         /* node becomes stale after call */
943                         /* XXX ENOSPC */
944                         if (error)
945                                 goto done;
946                 }
947                 node = cursor->node->ondisk;
948 #endif
949                 /*
950                  * Scan the node to find the subtree index to push down into.
951                  * We go one-past, then back-up.
952                  *
953                  * We have a serious issue with the midpoints for internal
954                  * nodes when the midpoint bisects two historical records
955                  * (where only create_tid is different).  Short of iterating
956                  * through the record's entire history the only solution is
957                  * to calculate a midpoint that isn't a midpoint in that
958                  * case.   Please see hammer_make_separator() for more
959                  * information.
960                  *
961                  * The right boundary is included in the search.
962                  */
963                 for (i = 0; i <= node->count; ++i) {
964                         elm = &node->elms[i];
965                         r = hammer_btree_cmp(&cursor->key_beg, &elm->base);
966                         if (r < 0)
967                                 break;
968                 }
969
970                 /*
971                  * These cases occur when the parent's idea of the boundary
972                  * is wider then the child's idea of the boundary, and
973                  * require special handling.  If not inserting we can
974                  * terminate the search early for these cases but the
975                  * child's boundaries cannot be unconditionally modified.
976                  */
977                 edge = SEARCH_NONE;
978                 if (i == 0) {
979                         /*
980                          * If i == 0 the search terminated to the LEFT of the
981                          * left_boundary but to the RIGHT of the parent's left
982                          * boundary.
983                          */
984                         u_int8_t save;
985
986                         if ((flags & HAMMER_CURSOR_INSERT) == 0) {
987                                 cursor->index = 0;
988                                 return(ENOENT);
989                         }
990                         elm = &node->elms[0];
991
992                         if (elm->base.subtree_type ==
993                             HAMMER_BTREE_TYPE_CLUSTER) {
994                                 edge = SEARCH_LEFT_EDGE;
995                         } else {
996                                 /*
997                                  * Correct a left-hand boundary mismatch.
998                                  */
999                                 hammer_modify_node(cursor->node);
1000                                 save = node->elms[0].base.subtree_type;
1001                                 node->elms[0].base = *cursor->left_bound;
1002                                 node->elms[0].base.subtree_type = save;
1003                         }
1004                 } else if (i == node->count + 1) {
1005                         /*
1006                          * If i == node->count + 1 the search terminated to
1007                          * the RIGHT of the right boundary but to the LEFT
1008                          * of the parent's right boundary.
1009                          *
1010                          * Note that the last element in this case is
1011                          * elms[i-2] prior to adjustments to 'i'.
1012                          */
1013                         --i;
1014                         if ((flags & HAMMER_CURSOR_INSERT) == 0) {
1015                                 cursor->index = i;
1016                                 return(ENOENT);
1017                         }
1018
1019                         elm = &node->elms[i];
1020                         if (elm[-1].base.subtree_type ==
1021                             HAMMER_BTREE_TYPE_CLUSTER) {
1022                                 edge = SEARCH_RIGHT_EDGE;
1023                         } else {
1024                                 hammer_modify_node(cursor->node);
1025                                 elm->base = *cursor->right_bound;
1026                         }
1027                 } else {
1028                         /*
1029                          * The push-down index is now i - 1.  If we had
1030                          * terminated on the right boundary this will point
1031                          * us at the last element.
1032                          */
1033                         --i;
1034                 }
1035                 cursor->index = i;
1036
1037                 if (hammer_debug_btree) {
1038                         elm = &node->elms[i];
1039                         kprintf("SEARCH-I %p:%d %016llx %02x key=%016llx tid=%016llx\n",
1040                                 cursor->node, i,
1041                                 elm->internal.base.obj_id,
1042                                 elm->internal.base.rec_type,
1043                                 elm->internal.base.key,
1044                                 elm->internal.base.create_tid
1045                         );
1046                 }
1047
1048                 /*
1049                  * Handle insertion and deletion requirements.
1050                  *
1051                  * If inserting split full nodes.  The split code will
1052                  * adjust cursor->node and cursor->index if the current
1053                  * index winds up in the new node.
1054                  *
1055                  * If inserting and a left or right edge case was detected,
1056                  * we cannot correct the left or right boundary and must
1057                  * prepend and append an empty leaf node in order to make
1058                  * the boundary correction.
1059                  *
1060                  * If we run out of space we set enospc and continue on
1061                  * to a leaf to provide the spike code with a good point
1062                  * of entry.  Enospc is reset if we cross a cluster boundary.
1063                  */
1064                 if ((flags & HAMMER_CURSOR_INSERT) && enospc == 0) {
1065                         if (btree_node_is_almost_full(node)) {
1066                                 error = btree_split_internal(cursor);
1067                                 if (error) {
1068                                         if (error != ENOSPC)
1069                                                 goto done;
1070                                         enospc = 1;
1071                                 }
1072                                 /*
1073                                  * reload stale pointers
1074                                  */
1075                                 i = cursor->index;
1076                                 node = cursor->node->ondisk;
1077                         }
1078                         if (edge != SEARCH_NONE && enospc == 0) {
1079                                 error = btree_edge_internal(cursor, edge);
1080                                 if (error) {
1081                                         if (error != ENOSPC)
1082                                                 goto done;
1083                                         enospc = 1;
1084                                 }
1085                                 /*
1086                                  * reload stale pointers
1087                                  */
1088                                 i = cursor->index;
1089                                 node = cursor->node->ondisk;
1090                         }
1091                 }
1092
1093 #if 0
1094                 /*
1095                  * If deleting rebalance - do not allow the child to have
1096                  * just one element or we will not be able to delete it.
1097                  *
1098                  * Neither internal or leaf nodes (except a root-leaf) are
1099                  * allowed to drop to 0 elements.  (XXX - well, leaf nodes
1100                  * can at the moment).
1101                  *
1102                  * Our separators may have been reorganized after rebalancing,
1103                  * so we have to pop back up and rescan.
1104                  *
1105                  * XXX test for subtree_count < maxelms / 2, minus 1 or 2
1106                  * for hysteresis?
1107                  *
1108                  * XXX NOTE: Iterations may not set this flag anyway.
1109                  */
1110                 if (flags & HAMMER_CURSOR_DELETE) {
1111                         if (node->elms[i].internal.subtree_count <= 1) {
1112                                 error = btree_rebalance(cursor);
1113                                 if (error)
1114                                         goto done;
1115                                 /* cursor->index is invalid after call */
1116                                 goto new_cluster;
1117                         }
1118                 }
1119 #endif
1120                 /*
1121                  * A non-zero rec_offset specifies a cluster push.
1122                  * If this is a cluster push we reset the enospc flag,
1123                  * which reenables the insertion code in the new cluster.
1124                  * This also ensures that if a spike occurs both its node
1125                  * and its parent will be in the same cluster.
1126                  *
1127                  * If INCLUSTER is set we terminate at the cluster boundary.
1128                  * In this case we must determine whether key_beg is within
1129                  * the cluster's boundary or not. XXX
1130                  */
1131                 elm = &node->elms[i];
1132                 if (elm->internal.rec_offset) {
1133                         KKASSERT(elm->base.subtree_type ==
1134                                  HAMMER_BTREE_TYPE_CLUSTER);
1135                         enospc = 0;
1136                         if (flags & HAMMER_CURSOR_INCLUSTER) {
1137                                 KKASSERT((flags & HAMMER_CURSOR_INSERT) == 0);
1138                                 r = hammer_btree_cmp(&cursor->key_beg,
1139                                                      &elm[1].base);
1140                                 error = (r < 0) ? 0 : ENOENT;
1141                                 goto done;
1142                         }
1143                 }
1144
1145                 /*
1146                  * Push down (push into new node, existing node becomes
1147                  * the parent) and continue the search.
1148                  */
1149                 error = hammer_cursor_down(cursor);
1150                 /* node and cluster become stale */
1151                 if (error)
1152                         goto done;
1153                 node = cursor->node->ondisk;
1154                 cluster = cursor->node->cluster;
1155         }
1156
1157         /*
1158          * We are at a leaf, do a linear search of the key array.
1159          *
1160          * On success the index is set to the matching element and 0
1161          * is returned.
1162          *
1163          * On failure the index is set to the insertion point and ENOENT
1164          * is returned.
1165          *
1166          * Boundaries are not stored in leaf nodes, so the index can wind
1167          * up to the left of element 0 (index == 0) or past the end of
1168          * the array (index == node->count).
1169          */
1170         KKASSERT(node->count <= HAMMER_BTREE_LEAF_ELMS);
1171
1172         for (i = 0; i < node->count; ++i) {
1173                 r = hammer_btree_cmp(&cursor->key_beg, &node->elms[i].base);
1174
1175                 /*
1176                  * Stop if we've flipped past key_beg.  This includes a
1177                  * record whos create_tid is larger then our asof id.
1178                  */
1179                 if (r < 0)
1180                         break;
1181
1182                 /*
1183                  * Return an exact match.  In this case we have to do special
1184                  * checks if the only difference in the records is the
1185                  * create_ts, in order to properly match against our as-of
1186                  * query.
1187                  */
1188                 if (r >= 0 && r <= 1) {
1189                         if ((cursor->flags & HAMMER_CURSOR_ALLHISTORY) == 0 &&
1190                             hammer_btree_chkts(cursor->key_beg.create_tid,
1191                                                &node->elms[i].base) != 0) {
1192                                 continue;
1193                         }
1194                         cursor->index = i;
1195                         error = 0;
1196                         if (hammer_debug_btree) {
1197                                 kprintf("SEARCH-L %p:%d (SUCCESS)\n",
1198                                         cursor->node, i);
1199                         }
1200                         goto done;
1201                 }
1202         }
1203
1204         if (hammer_debug_btree) {
1205                 kprintf("SEARCH-L %p:%d (FAILED)\n",
1206                         cursor->node, i);
1207         }
1208
1209         /*
1210          * No exact match was found, i is now at the insertion point.
1211          *
1212          * If inserting split a full leaf before returning.  This
1213          * may have the side effect of adjusting cursor->node and
1214          * cursor->index.
1215          */
1216         cursor->index = i;
1217         if ((flags & HAMMER_CURSOR_INSERT) && btree_node_is_almost_full(node)) {
1218                 error = btree_split_leaf(cursor);
1219                 if (error) {
1220                         if (error != ENOSPC)
1221                                 goto done;
1222                         enospc = 1;
1223                         flags &= ~HAMMER_CURSOR_INSERT;
1224                 }
1225                 /*
1226                  * reload stale pointers
1227                  */
1228                 /* NOT USED
1229                 i = cursor->index;
1230                 node = &cursor->node->internal;
1231                 */
1232         }
1233
1234         /*
1235          * We reached a leaf but did not find the key we were looking for.
1236          * If this is an insert we will be properly positioned for an insert
1237          * (ENOENT) or spike (ENOSPC) operation.
1238          */
1239         error = enospc ? ENOSPC : ENOENT;
1240 done:
1241         return(error);
1242 }
1243
1244
1245 /************************************************************************
1246  *                         SPLITTING AND MERGING                        *
1247  ************************************************************************
1248  *
1249  * These routines do all the dirty work required to split and merge nodes.
1250  */
1251
1252 /*
1253  * This case occurs when we are trying to insert and have come across a
1254  * mismatched left or right boundary which could not be adjusted due to
1255  * being part of a spike.  In order to be able to adjust the boundary
1256  * we have to prepend or append an empty leaf node.
1257  */
1258 static
1259 int
1260 btree_edge_internal(hammer_cursor_t cursor, btree_search_edge_t edge)
1261 {
1262         hammer_node_ondisk_t old_disk;
1263         hammer_node_ondisk_t new_disk;
1264         hammer_node_t new_node;
1265         hammer_btree_elm_t elm;
1266         int error;
1267         int n;
1268         const int esize = sizeof(*elm);
1269
1270         old_disk = cursor->node->ondisk;
1271         KKASSERT(old_disk->type == HAMMER_BTREE_TYPE_INTERNAL);
1272         KKASSERT(old_disk->count < HAMMER_BTREE_INT_ELMS);
1273
1274         /*
1275          * Allocate a new leaf node.
1276          */
1277         new_node = hammer_alloc_btree(cursor->node->cluster, &error);
1278         if (error)
1279                 return(error);
1280
1281         hammer_lock_ex(&new_node->lock);
1282         hammer_modify_node(cursor->node);
1283         hammer_modify_node(new_node);
1284         new_disk = new_node->ondisk;
1285         n = old_disk->count;
1286
1287         /*
1288          * Prepend or append the leaf node and correct the boundary
1289          * mismatch.
1290          */
1291         switch(edge) {
1292         case SEARCH_LEFT_EDGE:
1293                 KKASSERT(cursor->index == 0);
1294                 elm = &old_disk->elms[0];
1295                 bcopy(elm, elm + 1, (n + 1) * esize);
1296                 elm->base = *cursor->left_bound;
1297                 break;
1298         case SEARCH_RIGHT_EDGE:
1299                 KKASSERT(cursor->index == old_disk->count);
1300                 elm = &old_disk->elms[n];
1301                 elm[1].base = *cursor->right_bound;
1302                 break;
1303         default:
1304                 panic("btree_edge_internal: bad edge");
1305                 break;
1306         }
1307         ++old_disk->count;
1308         elm->base.subtree_type = HAMMER_BTREE_TYPE_LEAF;
1309         elm->internal.subtree_offset = new_node->node_offset;
1310         elm->internal.subtree_vol_no = -1;
1311         elm->internal.subtree_count = 0;
1312
1313         new_disk->count = 0;
1314         new_disk->parent = cursor->node->node_offset;
1315         new_disk->type = HAMMER_BTREE_TYPE_LEAF;
1316
1317         hammer_unlock(&new_node->lock);
1318         hammer_rel_node(new_node);
1319
1320         /*
1321          * Cursor->index remains unchanged.  It now points to our new leaf
1322          * node and cursor->node's boundaries have been synchronized with
1323          * the parent.
1324          */
1325         return(0);
1326 }
1327
1328 /*
1329  * Split an internal node into two nodes and move the separator at the split
1330  * point to the parent.  Note that the parent's parent's element pointing
1331  * to our parent will have an incorrect subtree_count (we don't update it).
1332  * It will be low, which is ok.
1333  *
1334  * (cursor->node, cursor->index) indicates the element the caller intends
1335  * to push into.  We will adjust node and index if that element winds
1336  * up in the split node.
1337  *
1338  * If we are at the root of a cluster a new root must be created with two
1339  * elements, one pointing to the original root and one pointing to the
1340  * newly allocated split node.
1341  *
1342  * NOTE! Being at the root of a cluster is different from being at the
1343  * root of the root cluster.  cursor->parent will not be NULL and
1344  * cursor->node->ondisk.parent must be tested against 0.  Theoretically
1345  * we could propogate the algorithm into the parent and deal with multiple
1346  * 'roots' in the cluster header, but it's easier not to.
1347  */
1348 static
1349 int
1350 btree_split_internal(hammer_cursor_t cursor)
1351 {
1352         hammer_node_ondisk_t ondisk;
1353         hammer_node_t node;
1354         hammer_node_t parent;
1355         hammer_node_t new_node;
1356         hammer_btree_elm_t elm;
1357         hammer_btree_elm_t parent_elm;
1358         int parent_index;
1359         int made_root;
1360         int split;
1361         int error;
1362         int i;
1363         const int esize = sizeof(*elm);
1364
1365         /* 
1366          * We are splitting but elms[split] will be promoted to the parent,
1367          * leaving the right hand node with one less element.  If the
1368          * insertion point will be on the left-hand side adjust the split
1369          * point to give the right hand side one additional node.
1370          */
1371         node = cursor->node;
1372         ondisk = node->ondisk;
1373         split = (ondisk->count + 1) / 2;
1374         if (cursor->index <= split)
1375                 --split;
1376         error = 0;
1377
1378         /*
1379          * If we are at the root of the cluster, create a new root node with
1380          * 1 element and split normally.  Avoid making major modifications
1381          * until we know the whole operation will work.
1382          *
1383          * The root of the cluster is different from the root of the root
1384          * cluster.  Use the node's on-disk structure's parent offset to
1385          * detect the case.
1386          */
1387         if (ondisk->parent == 0) {
1388                 parent = hammer_alloc_btree(node->cluster, &error);
1389                 if (parent == NULL)
1390                         return(error);
1391                 hammer_lock_ex(&parent->lock);
1392                 hammer_modify_node(parent);
1393                 ondisk = parent->ondisk;
1394                 ondisk->count = 1;
1395                 ondisk->parent = 0;
1396                 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1397                 ondisk->elms[0].base = node->cluster->clu_btree_beg;
1398                 ondisk->elms[0].base.subtree_type = node->ondisk->type;
1399                 ondisk->elms[0].internal.subtree_offset = node->node_offset;
1400                 ondisk->elms[1].base = node->cluster->clu_btree_end;
1401                 /* ondisk->elms[1].base.subtree_Type - not used */
1402                 made_root = 1;
1403                 parent_index = 0;       /* index of current node in parent */
1404         } else {
1405                 made_root = 0;
1406                 parent = cursor->parent;
1407                 parent_index = cursor->parent_index;
1408                 KKASSERT(parent->cluster == node->cluster);
1409         }
1410
1411         /*
1412          * Split node into new_node at the split point.
1413          *
1414          *  B O O O P N N B     <-- P = node->elms[split]
1415          *   0 1 2 3 4 5 6      <-- subtree indices
1416          *
1417          *       x x P x x
1418          *        s S S s  
1419          *         /   \
1420          *  B O O O B    B N N B        <--- inner boundary points are 'P'
1421          *   0 1 2 3      4 5 6  
1422          *
1423          */
1424         new_node = hammer_alloc_btree(node->cluster, &error);
1425         if (new_node == NULL) {
1426                 if (made_root) {
1427                         hammer_unlock(&parent->lock);
1428                         parent->flags |= HAMMER_NODE_DELETED;
1429                         hammer_rel_node(parent);
1430                 }
1431                 return(error);
1432         }
1433         hammer_lock_ex(&new_node->lock);
1434
1435         /*
1436          * Create the new node.  P becomes the left-hand boundary in the
1437          * new node.  Copy the right-hand boundary as well.
1438          *
1439          * elm is the new separator.
1440          */
1441         hammer_modify_node(new_node);
1442         hammer_modify_node(node);
1443         ondisk = node->ondisk;
1444         elm = &ondisk->elms[split];
1445         bcopy(elm, &new_node->ondisk->elms[0],
1446               (ondisk->count - split + 1) * esize);
1447         new_node->ondisk->count = ondisk->count - split;
1448         new_node->ondisk->parent = parent->node_offset;
1449         new_node->ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1450         KKASSERT(ondisk->type == new_node->ondisk->type);
1451
1452         /*
1453          * Cleanup the original node.  P becomes the new boundary, its
1454          * subtree_offset was moved to the new node.  If we had created
1455          * a new root its parent pointer may have changed.
1456          */
1457         elm->internal.subtree_offset = 0;
1458         elm->internal.rec_offset = 0;
1459         ondisk->count = split;
1460
1461         /*
1462          * Insert the separator into the parent, fixup the parent's
1463          * reference to the original node, and reference the new node.
1464          * The separator is P.
1465          *
1466          * Remember that base.count does not include the right-hand boundary.
1467          */
1468         hammer_modify_node(parent);
1469         ondisk = parent->ondisk;
1470         KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1471         ondisk->elms[parent_index].internal.subtree_count = split;
1472         parent_elm = &ondisk->elms[parent_index+1];
1473         bcopy(parent_elm, parent_elm + 1,
1474               (ondisk->count - parent_index) * esize);
1475         parent_elm->internal.base = elm->base;  /* separator P */
1476         parent_elm->internal.base.subtree_type = new_node->ondisk->type;
1477         parent_elm->internal.subtree_offset = new_node->node_offset;
1478         parent_elm->internal.subtree_count = new_node->ondisk->count;
1479         parent_elm->internal.subtree_vol_no = 0;
1480         parent_elm->internal.rec_offset = 0;
1481         ++ondisk->count;
1482
1483         /*
1484          * The children of new_node need their parent pointer set to new_node.
1485          */
1486         for (i = 0; i < new_node->ondisk->count; ++i) {
1487                 elm = &new_node->ondisk->elms[i];
1488                 error = btree_set_parent(new_node, elm);
1489                 if (error) {
1490                         panic("btree_split_internal: btree-fixup problem");
1491                 }
1492         }
1493
1494         /*
1495          * The cluster's root pointer may have to be updated.
1496          */
1497         if (made_root) {
1498                 hammer_modify_cluster(node->cluster);
1499                 node->cluster->ondisk->clu_btree_root = parent->node_offset;
1500                 node->ondisk->parent = parent->node_offset;
1501                 if (cursor->parent) {
1502                         hammer_unlock(&cursor->parent->lock);
1503                         hammer_rel_node(cursor->parent);
1504                 }
1505                 cursor->parent = parent;        /* lock'd and ref'd */
1506         }
1507
1508
1509         /*
1510          * Ok, now adjust the cursor depending on which element the original
1511          * index was pointing at.  If we are >= the split point the push node
1512          * is now in the new node.
1513          *
1514          * NOTE: If we are at the split point itself we cannot stay with the
1515          * original node because the push index will point at the right-hand
1516          * boundary, which is illegal.
1517          *
1518          * NOTE: The cursor's parent or parent_index must be adjusted for
1519          * the case where a new parent (new root) was created, and the case
1520          * where the cursor is now pointing at the split node.
1521          */
1522         if (cursor->index >= split) {
1523                 cursor->parent_index = parent_index + 1;
1524                 cursor->index -= split;
1525                 hammer_unlock(&cursor->node->lock);
1526                 hammer_rel_node(cursor->node);
1527                 cursor->node = new_node;        /* locked and ref'd */
1528         } else {
1529                 cursor->parent_index = parent_index;
1530                 hammer_unlock(&new_node->lock);
1531                 hammer_rel_node(new_node);
1532         }
1533
1534         /*
1535          * Fixup left and right bounds
1536          */
1537         parent_elm = &parent->ondisk->elms[cursor->parent_index];
1538         cursor->left_bound = &parent_elm[0].internal.base;
1539         cursor->right_bound = &parent_elm[1].internal.base;
1540         KKASSERT(hammer_btree_cmp(cursor->left_bound,
1541                  &cursor->node->ondisk->elms[0].internal.base) <= 0);
1542         KKASSERT(hammer_btree_cmp(cursor->right_bound,
1543                  &cursor->node->ondisk->elms[cursor->node->ondisk->count].internal.base) >= 0);
1544
1545         return (0);
1546 }
1547
1548 /*
1549  * Same as the above, but splits a full leaf node.
1550  */
1551 static
1552 int
1553 btree_split_leaf(hammer_cursor_t cursor)
1554 {
1555         hammer_node_ondisk_t ondisk;
1556         hammer_node_t parent;
1557         hammer_node_t leaf;
1558         hammer_node_t new_leaf;
1559         hammer_btree_elm_t elm;
1560         hammer_btree_elm_t parent_elm;
1561         hammer_base_elm_t mid_boundary;
1562         int parent_index;
1563         int made_root;
1564         int split;
1565         int error;
1566         const size_t esize = sizeof(*elm);
1567
1568         /* 
1569          * Calculate the split point.  If the insertion point will be on
1570          * the left-hand side adjust the split point to give the right
1571          * hand side one additional node.
1572          */
1573         leaf = cursor->node;
1574         ondisk = leaf->ondisk;
1575         split = (ondisk->count + 1) / 2;
1576         if (cursor->index <= split)
1577                 --split;
1578         error = 0;
1579
1580         /*
1581          * If we are at the root of the tree, create a new root node with
1582          * 1 element and split normally.  Avoid making major modifications
1583          * until we know the whole operation will work.
1584          */
1585         if (ondisk->parent == 0) {
1586                 parent = hammer_alloc_btree(leaf->cluster, &error);
1587                 if (parent == NULL)
1588                         return(error);
1589                 hammer_lock_ex(&parent->lock);
1590                 hammer_modify_node(parent);
1591                 ondisk = parent->ondisk;
1592                 ondisk->count = 1;
1593                 ondisk->parent = 0;
1594                 ondisk->type = HAMMER_BTREE_TYPE_INTERNAL;
1595                 ondisk->elms[0].base = leaf->cluster->clu_btree_beg;
1596                 ondisk->elms[0].base.subtree_type = leaf->ondisk->type;
1597                 ondisk->elms[0].internal.subtree_offset = leaf->node_offset;
1598                 ondisk->elms[1].base = leaf->cluster->clu_btree_end;
1599                 /* ondisk->elms[1].base.subtree_type = not used */
1600                 made_root = 1;
1601                 parent_index = 0;       /* insertion point in parent */
1602         } else {
1603                 made_root = 0;
1604                 parent = cursor->parent;
1605                 parent_index = cursor->parent_index;
1606                 KKASSERT(parent->cluster == leaf->cluster);
1607         }
1608
1609         /*
1610          * Split leaf into new_leaf at the split point.  Select a separator
1611          * value in-between the two leafs but with a bent towards the right
1612          * leaf since comparisons use an 'elm >= separator' inequality.
1613          *
1614          *  L L L L L L L L
1615          *
1616          *       x x P x x
1617          *        s S S s  
1618          *         /   \
1619          *  L L L L     L L L L
1620          */
1621         new_leaf = hammer_alloc_btree(leaf->cluster, &error);
1622         if (new_leaf == NULL) {
1623                 if (made_root) {
1624                         hammer_unlock(&parent->lock);
1625                         parent->flags |= HAMMER_NODE_DELETED;
1626                         hammer_rel_node(parent);
1627                 }
1628                 return(error);
1629         }
1630         hammer_lock_ex(&new_leaf->lock);
1631
1632         /*
1633          * Create the new node.  P become the left-hand boundary in the
1634          * new node.  Copy the right-hand boundary as well.
1635          */
1636         hammer_modify_node(leaf);
1637         hammer_modify_node(new_leaf);
1638         ondisk = leaf->ondisk;
1639         elm = &ondisk->elms[split];
1640         bcopy(elm, &new_leaf->ondisk->elms[0], (ondisk->count - split) * esize);
1641         new_leaf->ondisk->count = ondisk->count - split;
1642         new_leaf->ondisk->parent = parent->node_offset;
1643         new_leaf->ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1644         KKASSERT(ondisk->type == new_leaf->ondisk->type);
1645
1646         /*
1647          * Cleanup the original node.  Because this is a leaf node and
1648          * leaf nodes do not have a right-hand boundary, there
1649          * aren't any special edge cases to clean up.  We just fixup the
1650          * count.
1651          */
1652         ondisk->count = split;
1653
1654         /*
1655          * Insert the separator into the parent, fixup the parent's
1656          * reference to the original node, and reference the new node.
1657          * The separator is P.
1658          *
1659          * Remember that base.count does not include the right-hand boundary.
1660          * We are copying parent_index+1 to parent_index+2, not +0 to +1.
1661          */
1662         hammer_modify_node(parent);
1663         ondisk = parent->ondisk;
1664         KKASSERT(ondisk->count != HAMMER_BTREE_INT_ELMS);
1665         ondisk->elms[parent_index].internal.subtree_count = split;
1666         parent_elm = &ondisk->elms[parent_index+1];
1667         bcopy(parent_elm, parent_elm + 1,
1668               (ondisk->count - parent_index) * esize);
1669         hammer_make_separator(&elm[-1].base, &elm[0].base, &parent_elm->base);
1670         parent_elm->internal.base.subtree_type = new_leaf->ondisk->type;
1671         parent_elm->internal.subtree_offset = new_leaf->node_offset;
1672         parent_elm->internal.subtree_count = new_leaf->ondisk->count;
1673         parent_elm->internal.subtree_vol_no = 0;
1674         parent_elm->internal.rec_offset = 0;
1675         mid_boundary = &parent_elm->base;
1676         ++ondisk->count;
1677
1678         /*
1679          * The cluster's root pointer may have to be updated.
1680          */
1681         if (made_root) {
1682                 hammer_modify_cluster(leaf->cluster);
1683                 leaf->cluster->ondisk->clu_btree_root = parent->node_offset;
1684                 leaf->ondisk->parent = parent->node_offset;
1685                 if (cursor->parent) {
1686                         hammer_unlock(&cursor->parent->lock);
1687                         hammer_rel_node(cursor->parent);
1688                 }
1689                 cursor->parent = parent;        /* lock'd and ref'd */
1690         }
1691
1692         /*
1693          * Ok, now adjust the cursor depending on which element the original
1694          * index was pointing at.  If we are >= the split point the push node
1695          * is now in the new node.
1696          *
1697          * NOTE: If we are at the split point itself we need to select the
1698          * old or new node based on where key_beg's insertion point will be.
1699          * If we pick the wrong side the inserted element will wind up in
1700          * the wrong leaf node and outside that node's bounds.
1701          */
1702         if (cursor->index > split ||
1703             (cursor->index == split &&
1704              hammer_btree_cmp(&cursor->key_beg, mid_boundary) >= 0)) {
1705                 cursor->parent_index = parent_index + 1;
1706                 cursor->index -= split;
1707                 hammer_unlock(&cursor->node->lock);
1708                 hammer_rel_node(cursor->node);
1709                 cursor->node = new_leaf;
1710         } else {
1711                 cursor->parent_index = parent_index;
1712                 hammer_unlock(&new_leaf->lock);
1713                 hammer_rel_node(new_leaf);
1714         }
1715
1716         /*
1717          * Fixup left and right bounds
1718          */
1719         parent_elm = &parent->ondisk->elms[cursor->parent_index];
1720         cursor->left_bound = &parent_elm[0].internal.base;
1721         cursor->right_bound = &parent_elm[1].internal.base;
1722         KKASSERT(hammer_btree_cmp(cursor->left_bound,
1723                  &cursor->node->ondisk->elms[0].leaf.base) <= 0);
1724         KKASSERT(hammer_btree_cmp(cursor->right_bound,
1725                  &cursor->node->ondisk->elms[cursor->node->ondisk->count-1].leaf.base) > 0);
1726
1727         return (0);
1728 }
1729
1730 /*
1731  * Attempt to remove the empty B-Tree node at (cursor->node).  Returns 0
1732  * on success, EAGAIN if we could not acquire the necessary locks, or some
1733  * other error.
1734  *
1735  * On return the cursor may end up pointing at an internal node, suitable
1736  * for further iteration but not for an immediate insertion or deletion.
1737  *
1738  * cursor->node may be an internal node or a leaf node.
1739  *
1740  * NOTE: If cursor->node has one element it is the parent trying to delete
1741  * that element, make sure cursor->index is properly adjusted on success.
1742  */
1743 int
1744 btree_remove(hammer_cursor_t cursor)
1745 {
1746         hammer_node_ondisk_t ondisk;
1747         hammer_btree_elm_t elm;
1748         hammer_node_t save;
1749         hammer_node_t node;
1750         hammer_node_t parent;
1751         int error;
1752         int i;
1753
1754         /*
1755          * If we are at the root of the root cluster there is nothing to
1756          * remove, but an internal node at the root of a cluster is not
1757          * allowed to be empty so convert it to a leaf node.
1758          */
1759         if (cursor->parent == NULL) {
1760                 hammer_modify_node(cursor->node);
1761                 ondisk = cursor->node->ondisk;
1762                 KKASSERT(ondisk->parent == 0);
1763                 ondisk->type = HAMMER_BTREE_TYPE_LEAF;
1764                 ondisk->count = 0;
1765                 cursor->index = 0;
1766                 kprintf("EMPTY ROOT OF ROOT CLUSTER -> LEAF\n");
1767                 return(0);
1768         }
1769
1770         /*
1771          * Retain a reference to cursor->node, ex-lock again (2 locks now)
1772          * so we do not lose the lock when we cursor around.
1773          */
1774         save = cursor->node;
1775         hammer_ref_node(save);
1776         hammer_lock_ex(&save->lock);
1777
1778         /*
1779          * We need to be able to lock the parent of the parent.  Do this
1780          * non-blocking and return EAGAIN if the lock cannot be acquired.
1781          * non-blocking is required in order to avoid a deadlock.
1782          *
1783          * After we cursor up, parent is moved to node and the new parent
1784          * is the parent of the parent.
1785          */
1786         error = hammer_cursor_up(cursor, 1);
1787         if (error) {
1788                 kprintf("BTREE_REMOVE: Cannot lock parent, skipping\n");
1789                 goto failure;
1790         }
1791
1792         /*
1793          * At this point we want to remove the element at (node, index),
1794          * which is now the (original) parent pointing to the saved node.
1795          * Removing the element allows us to then free the node it was
1796          * pointing to.
1797          *
1798          * However, an internal node is not allowed to have 0 elements, so
1799          * if the count would drop to 0 we have to recurse.  It is possible
1800          * for the recursion to fail.
1801          *
1802          * NOTE: The cursor is in an indeterminant position after recursing,
1803          * but will still be suitable for an iteration.
1804          */
1805         node = cursor->node;
1806         KKASSERT(node->ondisk->count > 0);
1807         if (node->ondisk->count == 1) {
1808                 error = btree_remove(cursor);
1809                 if (error == 0) {
1810                         /*kprintf("BTREE_REMOVE: Successful!\n");*/
1811                         goto success;
1812                 } else {
1813                         kprintf("BTREE_REMOVE: Recursion failed %d\n", error);
1814                         goto failure;
1815                 }
1816         }
1817
1818         /*
1819          * Remove the element at (node, index) and adjust the parent's
1820          * subtree_count.
1821          *
1822          * NOTE! If removing element 0 an internal node's left-hand boundary
1823          * will no longer match its parent.  If removing a mid-element the
1824          * boundary will no longer match a child's left hand or right hand
1825          * boundary.
1826          *
1827          *      BxBxBxB         remove a (x[0]): internal node's left-hand
1828          *       | | |                           boundary no longer matches
1829          *       a b c                           parent.
1830          *
1831          *                      remove b (x[1]): a's right hand boundary no
1832          *                                       longer matches parent.
1833          *
1834          *                      remove c (x[2]): b's right hand boundary no
1835          *                                       longer matches parent.
1836          *
1837          * These cases are corrected in btree_search().
1838          */
1839 #if 0
1840         kprintf("BTREE_REMOVE: Removing element %d\n", cursor->index);
1841 #endif
1842         KKASSERT(node->ondisk->type == HAMMER_BTREE_TYPE_INTERNAL);
1843         KKASSERT(cursor->index < node->ondisk->count);
1844         hammer_modify_node(node);
1845         ondisk = node->ondisk;
1846         i = cursor->index;
1847
1848         /*
1849          * WARNING: For historical lookups to work properly we cannot
1850          * recalculate the mid-point or we might blow up historical searches
1851          * which depend on the mid-point matching the first right-hand element
1852          * XXX
1853          */
1854         bcopy(&ondisk->elms[i+1], &ondisk->elms[i],
1855               (ondisk->count - i) * sizeof(ondisk->elms[0]));
1856         --ondisk->count;
1857
1858         /*
1859          * Adjust the parent-parent's (now parent) reference to the parent
1860          * (now node).
1861          */
1862         if ((parent = cursor->parent) != NULL) {
1863                 elm = &parent->ondisk->elms[cursor->parent_index];
1864                 if (elm->internal.subtree_count != ondisk->count) {
1865                         hammer_modify_node(parent);
1866                         elm->internal.subtree_count = ondisk->count;
1867                 }
1868                 if (elm->base.subtree_type != HAMMER_BTREE_TYPE_CLUSTER &&
1869                     elm->base.subtree_type != ondisk->type) {
1870                         hammer_modify_node(parent);
1871                         elm->base.subtree_type = ondisk->type;
1872                 }
1873         }
1874
1875 success:
1876         /*
1877          * Free the saved node.  If the saved node was the root of a
1878          * cluster, free the entire cluster.
1879          */
1880         hammer_flush_node(save);
1881         save->flags |= HAMMER_NODE_DELETED;
1882
1883         error = 0;
1884 failure:
1885         hammer_unlock(&save->lock);
1886         hammer_rel_node(save);
1887         return(error);
1888 }
1889
1890 /*
1891  * The child represented by the element in internal node node needs
1892  * to have its parent pointer adjusted.
1893  */
1894 static
1895 int
1896 btree_set_parent(hammer_node_t node, hammer_btree_elm_t elm)
1897 {
1898         hammer_volume_t volume;
1899         hammer_cluster_t cluster;
1900         hammer_node_t child;
1901         int error;
1902
1903         error = 0;
1904
1905         switch(elm->internal.base.subtree_type) {
1906         case HAMMER_BTREE_TYPE_LEAF:
1907         case HAMMER_BTREE_TYPE_INTERNAL:
1908                 child = hammer_get_node(node->cluster,
1909                                         elm->internal.subtree_offset, &error);
1910                 if (error == 0) {
1911                         hammer_modify_node(child);
1912                         hammer_lock_ex(&child->lock);
1913                         child->ondisk->parent = node->node_offset;
1914                         hammer_unlock(&child->lock);
1915                         hammer_rel_node(child);
1916                 }
1917                 break;
1918         case HAMMER_BTREE_TYPE_CLUSTER:
1919                 volume = hammer_get_volume(node->cluster->volume->hmp,
1920                                         elm->internal.subtree_vol_no, &error);
1921                 if (error)
1922                         break;
1923                 cluster = hammer_get_cluster(volume,
1924                                         elm->internal.subtree_clu_no,
1925                                         &error, 0);
1926                 hammer_rel_volume(volume, 0);
1927                 if (error)
1928                         break;
1929                 hammer_modify_cluster(cluster);
1930                 hammer_lock_ex(&cluster->io.lock);
1931                 cluster->ondisk->clu_btree_parent_offset = node->node_offset;
1932                 hammer_unlock(&cluster->io.lock);
1933                 KKASSERT(cluster->ondisk->clu_btree_parent_clu_no ==
1934                          node->cluster->clu_no);
1935                 KKASSERT(cluster->ondisk->clu_btree_parent_vol_no ==
1936                          node->cluster->volume->vol_no);
1937                 hammer_rel_cluster(cluster, 0);
1938                 break;
1939         default:
1940                 hammer_print_btree_elm(elm, HAMMER_BTREE_TYPE_INTERNAL, -1);
1941                 panic("btree_set_parent: bad subtree_type");
1942                 break; /* NOT REACHED */
1943         }
1944         return(error);
1945 }
1946
1947 /************************************************************************
1948  *                         MISCELLANIOUS SUPPORT                        *
1949  ************************************************************************/
1950
1951 /*
1952  * Compare two B-Tree elements, return -N, 0, or +N (e.g. similar to strcmp).
1953  *
1954  * Note that for this particular function a return value of -1, 0, or +1
1955  * can denote a match if create_tid is otherwise discounted.
1956  *
1957  * See also hammer_rec_rb_compare() and hammer_rec_cmp() in hammer_object.c.
1958  */
1959 int
1960 hammer_btree_cmp(hammer_base_elm_t key1, hammer_base_elm_t key2)
1961 {
1962         if (key1->obj_id < key2->obj_id)
1963                 return(-4);
1964         if (key1->obj_id > key2->obj_id)
1965                 return(4);
1966
1967         if (key1->rec_type < key2->rec_type)
1968                 return(-3);
1969         if (key1->rec_type > key2->rec_type)
1970                 return(3);
1971
1972         if (key1->key < key2->key)
1973                 return(-2);
1974         if (key1->key > key2->key)
1975                 return(2);
1976
1977         if (key1->create_tid < key2->create_tid)
1978                 return(-1);
1979         if (key1->create_tid > key2->create_tid)
1980                 return(1);
1981         return(0);
1982 }
1983
1984 /*
1985  * Test a non-zero timestamp against an element to determine whether the
1986  * element is visible.
1987  */
1988 int
1989 hammer_btree_chkts(hammer_tid_t create_tid, hammer_base_elm_t base)
1990 {
1991         if (create_tid < base->create_tid)
1992                 return(-1);
1993         if (base->delete_tid && create_tid >= base->delete_tid)
1994                 return(1);
1995         return(0);
1996 }
1997
1998 /*
1999  * Create a separator half way inbetween key1 and key2.  For fields just
2000  * one unit apart, the separator will match key2.
2001  *
2002  * At the moment require that the separator never match key2 exactly.
2003  *
2004  * We have to special case the separator between two historical keys,
2005  * where all elements except create_tid match.  In this case our B-Tree
2006  * searches can't figure out which branch of an internal node to go down
2007  * unless the mid point's create_tid is exactly key2.
2008  * (see btree_search()'s scan code on HAMMER_BTREE_TYPE_INTERNAL).
2009  */
2010 #define MAKE_SEPARATOR(key1, key2, dest, field) \
2011         dest->field = key1->field + ((key2->field - key1->field + 1) >> 1);
2012
2013 static void
2014 hammer_make_separator(hammer_base_elm_t key1, hammer_base_elm_t key2,
2015                       hammer_base_elm_t dest)
2016 {
2017         bzero(dest, sizeof(*dest));
2018         MAKE_SEPARATOR(key1, key2, dest, obj_id);
2019         MAKE_SEPARATOR(key1, key2, dest, rec_type);
2020         MAKE_SEPARATOR(key1, key2, dest, key);
2021         if (key1->obj_id == key2->obj_id &&
2022             key1->rec_type == key2->rec_type &&
2023             key1->key == key2->key) {
2024                 dest->create_tid = key2->create_tid;
2025         } else {
2026                 dest->create_tid = 0;
2027         }
2028 }
2029
2030 #undef MAKE_SEPARATOR
2031
2032 #if 0
2033 /*
2034  * Return whether a generic internal or leaf node is full
2035  */
2036 static int
2037 btree_node_is_full(hammer_node_ondisk_t node)
2038 {
2039         switch(node->type) {
2040         case HAMMER_BTREE_TYPE_INTERNAL:
2041                 if (node->count == HAMMER_BTREE_INT_ELMS)
2042                         return(1);
2043                 break;
2044         case HAMMER_BTREE_TYPE_LEAF:
2045                 if (node->count == HAMMER_BTREE_LEAF_ELMS)
2046                         return(1);
2047                 break;
2048         default:
2049                 panic("illegal btree subtype");
2050         }
2051         return(0);
2052 }
2053 #endif
2054
2055 /*
2056  * Return whether a generic internal or leaf node is almost full.  This
2057  * routine is used as a helper for search insertions to guarentee at 
2058  * least 2 available slots in the internal node(s) leading up to a leaf,
2059  * so hammer_btree_insert_cluster() will function properly.
2060  */
2061 static int
2062 btree_node_is_almost_full(hammer_node_ondisk_t node)
2063 {
2064         switch(node->type) {
2065         case HAMMER_BTREE_TYPE_INTERNAL:
2066                 if (node->count > HAMMER_BTREE_INT_ELMS - 2)
2067                         return(1);
2068                 break;
2069         case HAMMER_BTREE_TYPE_LEAF:
2070                 if (node->count > HAMMER_BTREE_LEAF_ELMS - 2)
2071                         return(1);
2072                 break;
2073         default:
2074                 panic("illegal btree subtype");
2075         }
2076         return(0);
2077 }
2078
2079 #if 0
2080 static int
2081 btree_max_elements(u_int8_t type)
2082 {
2083         if (type == HAMMER_BTREE_TYPE_LEAF)
2084                 return(HAMMER_BTREE_LEAF_ELMS);
2085         if (type == HAMMER_BTREE_TYPE_INTERNAL)
2086                 return(HAMMER_BTREE_INT_ELMS);
2087         panic("btree_max_elements: bad type %d\n", type);
2088 }
2089 #endif
2090
2091 void
2092 hammer_print_btree_node(hammer_node_ondisk_t ondisk)
2093 {
2094         hammer_btree_elm_t elm;
2095         int i;
2096
2097         kprintf("node %p count=%d parent=%d type=%c\n",
2098                 ondisk, ondisk->count, ondisk->parent, ondisk->type);
2099
2100         /*
2101          * Dump both boundary elements if an internal node
2102          */
2103         if (ondisk->type == HAMMER_BTREE_TYPE_INTERNAL) {
2104                 for (i = 0; i <= ondisk->count; ++i) {
2105                         elm = &ondisk->elms[i];
2106                         hammer_print_btree_elm(elm, ondisk->type, i);
2107                 }
2108         } else {
2109                 for (i = 0; i < ondisk->count; ++i) {
2110                         elm = &ondisk->elms[i];
2111                         hammer_print_btree_elm(elm, ondisk->type, i);
2112                 }
2113         }
2114 }
2115
2116 void
2117 hammer_print_btree_elm(hammer_btree_elm_t elm, u_int8_t type, int i)
2118 {
2119         kprintf("  %2d", i);
2120         kprintf("\tobjid        = %016llx\n", elm->base.obj_id);
2121         kprintf("\tkey          = %016llx\n", elm->base.key);
2122         kprintf("\tcreate_tid   = %016llx\n", elm->base.create_tid);
2123         kprintf("\tdelete_tid   = %016llx\n", elm->base.delete_tid);
2124         kprintf("\trec_type     = %04x\n", elm->base.rec_type);
2125         kprintf("\tobj_type     = %02x\n", elm->base.obj_type);
2126         kprintf("\tsubtree_type = %02x\n", elm->base.subtree_type);
2127
2128         if (type == HAMMER_BTREE_TYPE_INTERNAL) {
2129                 if (elm->internal.rec_offset) {
2130                         kprintf("\tcluster_rec  = %08x\n",
2131                                 elm->internal.rec_offset);
2132                         kprintf("\tcluster_id   = %08x\n",
2133                                 elm->internal.subtree_clu_no);
2134                         kprintf("\tvolno        = %08x\n",
2135                                 elm->internal.subtree_vol_no);
2136                 } else {
2137                         kprintf("\tsubtree_off  = %08x\n",
2138                                 elm->internal.subtree_offset);
2139                 }
2140                 kprintf("\tsubtree_count= %d\n", elm->internal.subtree_count);
2141         } else {
2142                 kprintf("\trec_offset   = %08x\n", elm->leaf.rec_offset);
2143                 kprintf("\tdata_offset  = %08x\n", elm->leaf.data_offset);
2144                 kprintf("\tdata_len     = %08x\n", elm->leaf.data_len);
2145                 kprintf("\tdata_crc     = %08x\n", elm->leaf.data_crc);
2146         }
2147 }