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