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