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