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