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