1 /*
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2022 Tomohiro Kusumi <tkusumi@netbsd.org>
5  * Copyright (c) 2011-2022 The DragonFly Project.  All rights reserved.
6  *
7  * This code is derived from software contributed to The DragonFly Project
8  * by Matthew Dillon <dillon@dragonflybsd.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  * 3. Neither the name of The DragonFly Project nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific, prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
28  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
32  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 /*
38  * This subsystem implements most of the core support functions for
39  * the hammer2_chain structure.
40  *
41  * Chains are the in-memory version on media objects (volume header, inodes,
42  * indirect blocks, data blocks, etc).  Chains represent a portion of the
43  * HAMMER2 topology.
44  *
45  * Chains are no-longer delete-duplicated.  Instead, the original in-memory
46  * chain will be moved along with its block reference (e.g. for things like
47  * renames, hardlink operations, modifications, etc), and will be indexed
48  * on a secondary list for flush handling instead of propagating a flag
49  * upward to the root.
50  *
51  * Concurrent front-end operations can still run against backend flushes
52  * as long as they do not cross the current flush boundary.  An operation
53  * running above the current flush (in areas not yet flushed) can become
54  * part of the current flush while ano peration running below the current
55  * flush can become part of the next flush.
56  */
57 /*
58 #include <sys/cdefs.h>
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/types.h>
62 #include <sys/lock.h>
63 #include <sys/buf.h>
64 
65 #include <crypto/sha2/sha2.h>
66 */
67 
68 #include "hammer2.h"
69 
70 static hammer2_chain_t *hammer2_chain_create_indirect(
71 		hammer2_chain_t *parent,
72 		hammer2_key_t key, int keybits,
73 		hammer2_tid_t mtid, int for_type, int *errorp);
74 static int hammer2_chain_delete_obref(hammer2_chain_t *parent,
75 		hammer2_chain_t *chain,
76 		hammer2_tid_t mtid, int flags,
77 		hammer2_blockref_t *obref);
78 static hammer2_chain_t *hammer2_combined_find(
79 		hammer2_chain_t *parent,
80 		hammer2_blockref_t *base, int count,
81 		hammer2_key_t *key_nextp,
82 		hammer2_key_t key_beg, hammer2_key_t key_end,
83 		hammer2_blockref_t **brefp);
84 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
85 				int depth);
86 static void hammer2_chain_lru_flush(hammer2_pfs_t *pmp);
87 
88 /*
89  * There are many degenerate situations where an extreme rate of console
90  * output can occur from warnings and errors.  Make sure this output does
91  * not impede operations.
92  */
93 /*
94 static struct krate krate_h2chk = { .freq = 5 };
95 static struct krate krate_h2me = { .freq = 1 };
96 static struct krate krate_h2em = { .freq = 1 };
97 */
98 
99 /*
100  * Basic RBTree for chains (core.rbtree).
101  */
102 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
103 
104 int
105 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
106 {
107 	hammer2_key_t c1_beg;
108 	hammer2_key_t c1_end;
109 	hammer2_key_t c2_beg;
110 	hammer2_key_t c2_end;
111 
112 	/*
113 	 * Compare chains.  Overlaps are not supposed to happen and catch
114 	 * any software issues early we count overlaps as a match.
115 	 */
116 	c1_beg = chain1->bref.key;
117 	c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
118 	c2_beg = chain2->bref.key;
119 	c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
120 
121 	if (c1_end < c2_beg)	/* fully to the left */
122 		return(-1);
123 	if (c1_beg > c2_end)	/* fully to the right */
124 		return(1);
125 	return(0);		/* overlap (must not cross edge boundary) */
126 }
127 
128 /*
129  * Assert that a chain has no media data associated with it.
130  */
131 static __inline void
132 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
133 {
134 	KKASSERT(chain->dio == NULL);
135 	if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
136 	    chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
137 	    chain->data) {
138 		panic("hammer2_chain_assert_no_data: chain %p still has data",
139 		    chain);
140 	}
141 }
142 
143 /*
144  * Make a chain visible to the flusher.  The flusher operates using a top-down
145  * recursion based on the ONFLUSH flag.  It locates MODIFIED and UPDATE chains,
146  * flushes them, and updates blocks back to the volume root.
147  *
148  * This routine sets the ONFLUSH flag upward from the triggering chain until
149  * it hits an inode root or the volume root.  Inode chains serve as inflection
150  * points, requiring the flusher to bridge across trees.  Inodes include
151  * regular inodes, PFS roots (pmp->iroot), and the media super root
152  * (spmp->iroot).
153  */
154 void
155 hammer2_chain_setflush(hammer2_chain_t *chain)
156 {
157 	hammer2_chain_t *parent;
158 
159 	if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
160 		hammer2_spin_sh(&chain->core.spin);
161 		while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
162 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
163 			if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
164 				break;
165 			if ((parent = chain->parent) == NULL)
166 				break;
167 			hammer2_spin_sh(&parent->core.spin);
168 			hammer2_spin_unsh(&chain->core.spin);
169 			chain = parent;
170 		}
171 		hammer2_spin_unsh(&chain->core.spin);
172 	}
173 }
174 
175 /*
176  * Allocate a new disconnected chain element representing the specified
177  * bref.  chain->refs is set to 1 and the passed bref is copied to
178  * chain->bref.  chain->bytes is derived from the bref.
179  *
180  * chain->pmp inherits pmp unless the chain is an inode (other than the
181  * super-root inode).
182  *
183  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
184  */
185 hammer2_chain_t *
186 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
187 		    hammer2_blockref_t *bref)
188 {
189 	hammer2_chain_t *chain;
190 	u_int bytes;
191 
192 	/*
193 	 * Special case - radix of 0 indicates a chain that does not
194 	 * need a data reference (context is completely embedded in the
195 	 * bref).
196 	 */
197 	if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
198 		bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
199 	else
200 		bytes = 0;
201 
202 	switch(bref->type) {
203 	case HAMMER2_BREF_TYPE_INODE:
204 	case HAMMER2_BREF_TYPE_INDIRECT:
205 	case HAMMER2_BREF_TYPE_DATA:
206 	case HAMMER2_BREF_TYPE_DIRENT:
207 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
208 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
209 	case HAMMER2_BREF_TYPE_FREEMAP:
210 	case HAMMER2_BREF_TYPE_VOLUME:
211 		chain = kmalloc_obj(sizeof(*chain), hmp->mchain,
212 				    M_WAITOK | M_ZERO);
213 		atomic_add_long(&hammer2_chain_allocs, 1);
214 		break;
215 	case HAMMER2_BREF_TYPE_EMPTY:
216 	default:
217 		panic("hammer2_chain_alloc: unrecognized blockref type: %d",
218 		      bref->type);
219 		break;
220 	}
221 
222 	/*
223 	 * Initialize the new chain structure.  pmp must be set to NULL for
224 	 * chains belonging to the super-root topology of a device mount.
225 	 */
226 	if (pmp == hmp->spmp)
227 		chain->pmp = NULL;
228 	else
229 		chain->pmp = pmp;
230 
231 	chain->hmp = hmp;
232 	chain->bref = *bref;
233 	chain->bytes = bytes;
234 	chain->refs = 1;
235 	chain->flags = HAMMER2_CHAIN_ALLOCATED;
236 	lockinit(&chain->diolk, "chdio", 0, 0);
237 
238 	/*
239 	 * Set the PFS boundary flag if this chain represents a PFS root.
240 	 */
241 	if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
242 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
243 	hammer2_chain_core_init(chain);
244 
245 	return (chain);
246 }
247 
248 /*
249  * Initialize a chain's core structure.  This structure used to be allocated
250  * but is now embedded.
251  *
252  * The core is not locked.  No additional refs on the chain are made.
253  */
254 void
255 hammer2_chain_core_init(hammer2_chain_t *chain)
256 {
257 	RB_INIT(&chain->core.rbtree);	/* live chains */
258 	hammer2_mtx_init(&chain->lock, "h2chain");
259 	hammer2_spin_init(&chain->core.spin, "h2chain");
260 }
261 
262 /*
263  * Add a reference to a chain element, preventing its destruction.
264  *
265  * (can be called with spinlock held)
266  */
267 void
268 hammer2_chain_ref(hammer2_chain_t *chain)
269 {
270 	if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
271 		/*
272 		 * Just flag that the chain was used and should be recycled
273 		 * on the LRU if it encounters it later.
274 		 */
275 		if (chain->flags & HAMMER2_CHAIN_ONLRU)
276 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
277 
278 #if 0
279 		/*
280 		 * REMOVED - reduces contention, lru_list is more heuristical
281 		 * now.
282 		 *
283 		 * 0->non-zero transition must ensure that chain is removed
284 		 * from the LRU list.
285 		 *
286 		 * NOTE: Already holding lru_spin here so we cannot call
287 		 *	 hammer2_chain_ref() to get it off lru_list, do
288 		 *	 it manually.
289 		 */
290 		if (chain->flags & HAMMER2_CHAIN_ONLRU) {
291 			hammer2_pfs_t *pmp = chain->pmp;
292 			hammer2_spin_ex(&pmp->lru_spin);
293 			if (chain->flags & HAMMER2_CHAIN_ONLRU) {
294 				atomic_add_int(&pmp->lru_count, -1);
295 				atomic_clear_int(&chain->flags,
296 						 HAMMER2_CHAIN_ONLRU);
297 				TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
298 			}
299 			hammer2_spin_unex(&pmp->lru_spin);
300 		}
301 #endif
302 	}
303 }
304 
305 /*
306  * Ref a locked chain and force the data to be held across an unlock.
307  * Chain must be currently locked.  The user of the chain who desires
308  * to release the hold must call hammer2_chain_lock_unhold() to relock
309  * and unhold the chain, then unlock normally, or may simply call
310  * hammer2_chain_drop_unhold() (which is safer against deadlocks).
311  */
312 void
313 hammer2_chain_ref_hold(hammer2_chain_t *chain)
314 {
315 	atomic_add_int(&chain->lockcnt, 1);
316 	hammer2_chain_ref(chain);
317 }
318 
319 /*
320  * Insert the chain in the core rbtree.
321  *
322  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
323  * chain is a special case used by the flush code that is placed on the
324  * unstaged deleted list to avoid confusing the live view.
325  */
326 #define HAMMER2_CHAIN_INSERT_SPIN	0x0001
327 #define HAMMER2_CHAIN_INSERT_LIVE	0x0002
328 #define HAMMER2_CHAIN_INSERT_RACE	0x0004
329 
330 static
331 int
332 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
333 		     int flags, int generation)
334 {
335 	hammer2_chain_t *xchain;
336 	int error = 0;
337 
338 	if (flags & HAMMER2_CHAIN_INSERT_SPIN)
339 		hammer2_spin_ex(&parent->core.spin);
340 
341 	/*
342 	 * Interlocked by spinlock, check for race
343 	 */
344 	if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
345 	    parent->core.generation != generation) {
346 		error = HAMMER2_ERROR_EAGAIN;
347 		goto failed;
348 	}
349 
350 	/*
351 	 * Insert chain
352 	 */
353 	xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
354 	KASSERT(xchain == NULL,
355 		("hammer2_chain_insert: collision %p %p (key=%016jx)",
356 		chain, xchain, chain->bref.key));
357 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
358 	chain->parent = parent;
359 	++parent->core.chain_count;
360 	++parent->core.generation;	/* XXX incs for _get() too, XXX */
361 
362 	/*
363 	 * We have to keep track of the effective live-view blockref count
364 	 * so the create code knows when to push an indirect block.
365 	 */
366 	if (flags & HAMMER2_CHAIN_INSERT_LIVE)
367 		atomic_add_int(&parent->core.live_count, 1);
368 failed:
369 	if (flags & HAMMER2_CHAIN_INSERT_SPIN)
370 		hammer2_spin_unex(&parent->core.spin);
371 	return error;
372 }
373 
374 /*
375  * Drop the caller's reference to the chain.  When the ref count drops to
376  * zero this function will try to disassociate the chain from its parent and
377  * deallocate it, then recursely drop the parent using the implied ref
378  * from the chain's chain->parent.
379  *
380  * Nobody should own chain's mutex on the 1->0 transition, unless this drop
381  * races an acquisition by another cpu.  Therefore we can loop if we are
382  * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
383  * race against another drop.
384  */
385 void
386 hammer2_chain_drop(hammer2_chain_t *chain)
387 {
388 	u_int refs;
389 
390 	KKASSERT(chain->refs > 0);
391 
392 	while (chain) {
393 		refs = chain->refs;
394 		cpu_ccfence();
395 		KKASSERT(refs > 0);
396 
397 		if (refs == 1) {
398 			if (hammer2_mtx_ex_try(&chain->lock) == 0)
399 				chain = hammer2_chain_lastdrop(chain, 0);
400 			/* retry the same chain, or chain from lastdrop */
401 		} else {
402 			if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
403 				break;
404 			/* retry the same chain */
405 		}
406 		cpu_pause();
407 	}
408 }
409 
410 /*
411  * Unhold a held and probably not-locked chain, ensure that the data is
412  * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
413  * lock and then simply unlocking the chain.
414  */
415 void
416 hammer2_chain_unhold(hammer2_chain_t *chain)
417 {
418 	u_int lockcnt;
419 	int iter = 0;
420 
421 	for (;;) {
422 		lockcnt = chain->lockcnt;
423 		cpu_ccfence();
424 		if (lockcnt > 1) {
425 			if (atomic_cmpset_int(&chain->lockcnt,
426 					      lockcnt, lockcnt - 1)) {
427 				break;
428 			}
429 		} else if (hammer2_mtx_ex_try(&chain->lock) == 0) {
430 			hammer2_chain_unlock(chain);
431 			break;
432 		} else {
433 			/*
434 			 * This situation can easily occur on SMP due to
435 			 * the gap inbetween the 1->0 transition and the
436 			 * final unlock.  We cannot safely block on the
437 			 * mutex because lockcnt might go above 1.
438 			 *
439 			 * XXX Sleep for one tick if it takes too long.
440 			 */
441 			if (++iter > 1000) {
442 				if (iter > 1000 + hz) {
443 					kprintf("hammer2: h2race1 %p\n", chain);
444 					iter = 1000;
445 				}
446 				tsleep(&iter, 0, "h2race1", 1);
447 			}
448 			cpu_pause();
449 		}
450 	}
451 }
452 
453 void
454 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
455 {
456 	hammer2_chain_unhold(chain);
457 	hammer2_chain_drop(chain);
458 }
459 
460 void
461 hammer2_chain_rehold(hammer2_chain_t *chain)
462 {
463 	hammer2_chain_lock(chain, HAMMER2_RESOLVE_SHARED);
464 	atomic_add_int(&chain->lockcnt, 1);
465 	hammer2_chain_unlock(chain);
466 }
467 
468 /*
469  * Handles the (potential) last drop of chain->refs from 1->0.  Called with
470  * the mutex exclusively locked, refs == 1, and lockcnt 0.  SMP races are
471  * possible against refs and lockcnt.  We must dispose of the mutex on chain.
472  *
473  * This function returns an unlocked chain for recursive drop or NULL.  It
474  * can return the same chain if it determines it has raced another ref.
475  *
476  * --
477  *
478  * When two chains need to be recursively dropped we use the chain we
479  * would otherwise free to placehold the additional chain.  It's a bit
480  * convoluted but we can't just recurse without potentially blowing out
481  * the kernel stack.
482  *
483  * The chain cannot be freed if it has any children.
484  * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
485  * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
486  * Any dedup registration can remain intact.
487  *
488  * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
489  */
490 static
491 hammer2_chain_t *
492 hammer2_chain_lastdrop(hammer2_chain_t *chain, int depth)
493 {
494 	hammer2_pfs_t *pmp;
495 	hammer2_dev_t *hmp;
496 	hammer2_chain_t *parent;
497 	hammer2_chain_t *rdrop;
498 
499 	/*
500 	 * We need chain's spinlock to interlock the sub-tree test.
501 	 * We already have chain's mutex, protecting chain->parent.
502 	 *
503 	 * Remember that chain->refs can be in flux.
504 	 */
505 	hammer2_spin_ex(&chain->core.spin);
506 
507 	if (chain->parent != NULL) {
508 		/*
509 		 * If the chain has a parent the UPDATE bit prevents scrapping
510 		 * as the chain is needed to properly flush the parent.  Try
511 		 * to complete the 1->0 transition and return NULL.  Retry
512 		 * (return chain) if we are unable to complete the 1->0
513 		 * transition, else return NULL (nothing more to do).
514 		 *
515 		 * If the chain has a parent the MODIFIED bit prevents
516 		 * scrapping.
517 		 *
518 		 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
519 		 */
520 		if (chain->flags & (HAMMER2_CHAIN_UPDATE |
521 				    HAMMER2_CHAIN_MODIFIED)) {
522 			if (atomic_cmpset_int(&chain->refs, 1, 0)) {
523 				hammer2_spin_unex(&chain->core.spin);
524 				hammer2_chain_assert_no_data(chain);
525 				hammer2_mtx_unlock(&chain->lock);
526 				chain = NULL;
527 			} else {
528 				hammer2_spin_unex(&chain->core.spin);
529 				hammer2_mtx_unlock(&chain->lock);
530 			}
531 			return (chain);
532 		}
533 		/* spinlock still held */
534 	} else if (chain->bref.type == HAMMER2_BREF_TYPE_VOLUME ||
535 		   chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP) {
536 		/*
537 		 * Retain the static vchain and fchain.  Clear bits that
538 		 * are not relevant.  Do not clear the MODIFIED bit,
539 		 * and certainly do not put it on the delayed-flush queue.
540 		 */
541 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
542 	} else {
543 		/*
544 		 * The chain has no parent and can be flagged for destruction.
545 		 * Since it has no parent, UPDATE can also be cleared.
546 		 */
547 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
548 		if (chain->flags & HAMMER2_CHAIN_UPDATE)
549 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
550 
551 		/*
552 		 * If the chain has children we must propagate the DESTROY
553 		 * flag downward and rip the disconnected topology apart.
554 		 * This is accomplished by calling hammer2_flush() on the
555 		 * chain.
556 		 *
557 		 * Any dedup is already handled by the underlying DIO, so
558 		 * we do not have to specifically flush it here.
559 		 */
560 		if (chain->core.chain_count) {
561 			hammer2_spin_unex(&chain->core.spin);
562 			hammer2_flush(chain, HAMMER2_FLUSH_TOP |
563 					     HAMMER2_FLUSH_ALL);
564 			hammer2_mtx_unlock(&chain->lock);
565 
566 			return(chain);	/* retry drop */
567 		}
568 
569 		/*
570 		 * Otherwise we can scrap the MODIFIED bit if it is set,
571 		 * and continue along the freeing path.
572 		 *
573 		 * Be sure to clean-out any dedup bits.  Without a parent
574 		 * this chain will no longer be visible to the flush code.
575 		 * Easy check data_off to avoid the volume root.
576 		 */
577 		if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
578 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
579 			atomic_add_long(&hammer2_count_modified_chains, -1);
580 			if (chain->pmp)
581 				hammer2_pfs_memory_wakeup(chain->pmp, -1);
582 		}
583 		/* spinlock still held */
584 	}
585 
586 	/* spinlock still held */
587 
588 	/*
589 	 * If any children exist we must leave the chain intact with refs == 0.
590 	 * They exist because chains are retained below us which have refs or
591 	 * may require flushing.
592 	 *
593 	 * Retry (return chain) if we fail to transition the refs to 0, else
594 	 * return NULL indication nothing more to do.
595 	 *
596 	 * Chains with children are NOT put on the LRU list.
597 	 */
598 	if (chain->core.chain_count) {
599 		if (atomic_cmpset_int(&chain->refs, 1, 0)) {
600 			hammer2_spin_unex(&chain->core.spin);
601 			hammer2_chain_assert_no_data(chain);
602 			hammer2_mtx_unlock(&chain->lock);
603 			chain = NULL;
604 		} else {
605 			hammer2_spin_unex(&chain->core.spin);
606 			hammer2_mtx_unlock(&chain->lock);
607 		}
608 		return (chain);
609 	}
610 	/* spinlock still held */
611 	/* no chains left under us */
612 
613 	/*
614 	 * chain->core has no children left so no accessors can get to our
615 	 * chain from there.  Now we have to lock the parent core to interlock
616 	 * remaining possible accessors that might bump chain's refs before
617 	 * we can safely drop chain's refs with intent to free the chain.
618 	 */
619 	hmp = chain->hmp;
620 	pmp = chain->pmp;	/* can be NULL */
621 	rdrop = NULL;
622 
623 	parent = chain->parent;
624 
625 	/*
626 	 * WARNING! chain's spin lock is still held here, and other spinlocks
627 	 *	    will be acquired and released in the code below.  We
628 	 *	    cannot be making fancy procedure calls!
629 	 */
630 
631 	/*
632 	 * We can cache the chain if it is associated with a pmp
633 	 * and not flagged as being destroyed or requesting a full
634 	 * release.  In this situation the chain is not removed
635 	 * from its parent, i.e. it can still be looked up.
636 	 *
637 	 * We intentionally do not cache DATA chains because these
638 	 * were likely used to load data into the logical buffer cache
639 	 * and will not be accessed again for some time.
640 	 */
641 	if ((chain->flags &
642 	     (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
643 	    chain->pmp &&
644 	    chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
645 		if (parent)
646 			hammer2_spin_ex(&parent->core.spin);
647 		if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
648 			/*
649 			 * 1->0 transition failed, retry.  Do not drop
650 			 * the chain's data yet!
651 			 */
652 			if (parent)
653 				hammer2_spin_unex(&parent->core.spin);
654 			hammer2_spin_unex(&chain->core.spin);
655 			hammer2_mtx_unlock(&chain->lock);
656 
657 			return(chain);
658 		}
659 
660 		/*
661 		 * Success
662 		 */
663 		hammer2_chain_assert_no_data(chain);
664 
665 		/*
666 		 * Make sure we are on the LRU list, clean up excessive
667 		 * LRU entries.  We can only really drop one but there might
668 		 * be other entries that we can remove from the lru_list
669 		 * without dropping.
670 		 *
671 		 * NOTE: HAMMER2_CHAIN_ONLRU may only be safely set when
672 		 *	 chain->core.spin AND pmp->lru_spin are held, but
673 		 *	 can be safely cleared only holding pmp->lru_spin.
674 		 */
675 		if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
676 			hammer2_spin_ex(&pmp->lru_spin);
677 			if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
678 				atomic_set_int(&chain->flags,
679 					       HAMMER2_CHAIN_ONLRU);
680 				TAILQ_INSERT_TAIL(&pmp->lru_list,
681 						  chain, lru_node);
682 				atomic_add_int(&pmp->lru_count, 1);
683 			}
684 			if (pmp->lru_count < HAMMER2_LRU_LIMIT)
685 				depth = 1;	/* disable lru_list flush */
686 			hammer2_spin_unex(&pmp->lru_spin);
687 		} else {
688 			/* disable lru flush */
689 			depth = 1;
690 		}
691 
692 		if (parent) {
693 			hammer2_spin_unex(&parent->core.spin);
694 			parent = NULL;	/* safety */
695 		}
696 		hammer2_spin_unex(&chain->core.spin);
697 		hammer2_mtx_unlock(&chain->lock);
698 
699 		/*
700 		 * lru_list hysteresis (see above for depth overrides).
701 		 * Note that depth also prevents excessive lastdrop recursion.
702 		 */
703 		if (depth == 0)
704 			hammer2_chain_lru_flush(pmp);
705 
706 		return NULL;
707 		/* NOT REACHED */
708 	}
709 
710 	/*
711 	 * Make sure we are not on the LRU list.
712 	 */
713 	if (chain->flags & HAMMER2_CHAIN_ONLRU) {
714 		hammer2_spin_ex(&pmp->lru_spin);
715 		if (chain->flags & HAMMER2_CHAIN_ONLRU) {
716 			atomic_add_int(&pmp->lru_count, -1);
717 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
718 			TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
719 		}
720 		hammer2_spin_unex(&pmp->lru_spin);
721 	}
722 
723 	/*
724 	 * Spinlock the parent and try to drop the last ref on chain.
725 	 * On success determine if we should dispose of the chain
726 	 * (remove the chain from its parent, etc).
727 	 *
728 	 * (normal core locks are top-down recursive but we define
729 	 * core spinlocks as bottom-up recursive, so this is safe).
730 	 */
731 	if (parent) {
732 		hammer2_spin_ex(&parent->core.spin);
733 		if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
734 			/*
735 			 * 1->0 transition failed, retry.
736 			 */
737 			hammer2_spin_unex(&parent->core.spin);
738 			hammer2_spin_unex(&chain->core.spin);
739 			hammer2_mtx_unlock(&chain->lock);
740 
741 			return(chain);
742 		}
743 
744 		/*
745 		 * 1->0 transition successful, parent spin held to prevent
746 		 * new lookups, chain spinlock held to protect parent field.
747 		 * Remove chain from the parent.
748 		 *
749 		 * If the chain is being removed from the parent's btree but
750 		 * is not blkmapped, we have to adjust live_count downward.  If
751 		 * it is blkmapped then the blockref is retained in the parent
752 		 * as is its associated live_count.  This case can occur when
753 		 * a chain added to the topology is unable to flush and is
754 		 * then later deleted.
755 		 */
756 		if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
757 			if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) &&
758 			    (chain->flags & HAMMER2_CHAIN_BLKMAPPED) == 0) {
759 				atomic_add_int(&parent->core.live_count, -1);
760 			}
761 			RB_REMOVE(hammer2_chain_tree,
762 				  &parent->core.rbtree, chain);
763 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
764 			--parent->core.chain_count;
765 			chain->parent = NULL;
766 		}
767 
768 		/*
769 		 * If our chain was the last chain in the parent's core the
770 		 * core is now empty and its parent might have to be
771 		 * re-dropped if it has 0 refs.
772 		 */
773 		if (parent->core.chain_count == 0) {
774 			rdrop = parent;
775 			atomic_add_int(&rdrop->refs, 1);
776 			/*
777 			if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
778 				rdrop = NULL;
779 			*/
780 		}
781 		hammer2_spin_unex(&parent->core.spin);
782 		parent = NULL;	/* safety */
783 		/* FALL THROUGH */
784 	} else {
785 		/*
786 		 * No-parent case.
787 		 */
788 		if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
789 			/*
790 			 * 1->0 transition failed, retry.
791 			 */
792 			hammer2_spin_unex(&parent->core.spin);
793 			hammer2_spin_unex(&chain->core.spin);
794 			hammer2_mtx_unlock(&chain->lock);
795 
796 			return(chain);
797 		}
798 	}
799 
800 	/*
801 	 * Successful 1->0 transition, no parent, no children... no way for
802 	 * anyone to ref this chain any more.  We can clean-up and free it.
803 	 *
804 	 * We still have the core spinlock, and core's chain_count is 0.
805 	 * Any parent spinlock is gone.
806 	 */
807 	hammer2_spin_unex(&chain->core.spin);
808 	hammer2_chain_assert_no_data(chain);
809 	hammer2_mtx_unlock(&chain->lock);
810 	KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
811 		 chain->core.chain_count == 0);
812 
813 	/*
814 	 * All locks are gone, no pointers remain to the chain, finish
815 	 * freeing it.
816 	 */
817 	KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
818 				  HAMMER2_CHAIN_MODIFIED)) == 0);
819 
820 	/*
821 	 * Once chain resources are gone we can use the now dead chain
822 	 * structure to placehold what might otherwise require a recursive
823 	 * drop, because we have potentially two things to drop and can only
824 	 * return one directly.
825 	 */
826 	if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
827 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
828 		chain->hmp = NULL;
829 		kfree_obj(chain, hmp->mchain);
830 		atomic_add_long(&hammer2_chain_allocs, -1);
831 	}
832 
833 	/*
834 	 * Possible chaining loop when parent re-drop needed.
835 	 */
836 	return(rdrop);
837 }
838 
839 /*
840  * Heuristical flush of the LRU, try to reduce the number of entries
841  * on the LRU to (HAMMER2_LRU_LIMIT * 2 / 3).  This procedure is called
842  * only when lru_count exceeds HAMMER2_LRU_LIMIT.
843  */
844 static
845 void
846 hammer2_chain_lru_flush(hammer2_pfs_t *pmp)
847 {
848 	hammer2_chain_t *chain;
849 
850 again:
851 	chain = NULL;
852 	hammer2_spin_ex(&pmp->lru_spin);
853 	while (pmp->lru_count > HAMMER2_LRU_LIMIT * 2 / 3) {
854 		/*
855 		 * Pick a chain off the lru_list, just recycle it quickly
856 		 * if LRUHINT is set (the chain was ref'd but left on
857 		 * the lru_list, so cycle to the end).
858 		 */
859 		chain = TAILQ_FIRST(&pmp->lru_list);
860 		TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
861 
862 		if (chain->flags & HAMMER2_CHAIN_LRUHINT) {
863 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
864 			TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
865 			chain = NULL;
866 			continue;
867 		}
868 
869 		/*
870 		 * Ok, we are off the LRU.  We must adjust refs before we
871 		 * can safely clear the ONLRU flag.
872 		 */
873 		atomic_add_int(&pmp->lru_count, -1);
874 		if (atomic_cmpset_int(&chain->refs, 0, 1)) {
875 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
876 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
877 			break;
878 		}
879 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
880 		chain = NULL;
881 	}
882 	hammer2_spin_unex(&pmp->lru_spin);
883 	if (chain == NULL)
884 		return;
885 
886 	/*
887 	 * If we picked a chain off the lru list we may be able to lastdrop
888 	 * it.  Use a depth of 1 to prevent excessive lastdrop recursion.
889 	 */
890 	while (chain) {
891 		u_int refs;
892 
893 		refs = chain->refs;
894 		cpu_ccfence();
895 		KKASSERT(refs > 0);
896 
897 		if (refs == 1) {
898 			if (hammer2_mtx_ex_try(&chain->lock) == 0)
899 				chain = hammer2_chain_lastdrop(chain, 1);
900 			/* retry the same chain, or chain from lastdrop */
901 		} else {
902 			if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
903 				break;
904 			/* retry the same chain */
905 		}
906 		cpu_pause();
907 	}
908 	goto again;
909 }
910 
911 /*
912  * On last lock release.
913  */
914 static hammer2_io_t *
915 hammer2_chain_drop_data(hammer2_chain_t *chain)
916 {
917 	hammer2_io_t *dio;
918 
919 	if ((dio = chain->dio) != NULL) {
920 		chain->dio = NULL;
921 		chain->data = NULL;
922 	} else {
923 		switch(chain->bref.type) {
924 		case HAMMER2_BREF_TYPE_VOLUME:
925 		case HAMMER2_BREF_TYPE_FREEMAP:
926 			break;
927 		default:
928 			if (chain->data != NULL) {
929 				hammer2_spin_unex(&chain->core.spin);
930 				panic("chain data not null: "
931 				      "chain %p bref %016jx.%02x "
932 				      "refs %d parent %p dio %p data %p",
933 				      chain, chain->bref.data_off,
934 				      chain->bref.type, chain->refs,
935 				      chain->parent,
936 				      chain->dio, chain->data);
937 			}
938 			KKASSERT(chain->data == NULL);
939 			break;
940 		}
941 	}
942 	return dio;
943 }
944 
945 /*
946  * Lock a referenced chain element, acquiring its data with I/O if necessary,
947  * and specify how you would like the data to be resolved.
948  *
949  * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
950  *
951  * The lock is allowed to recurse, multiple locking ops will aggregate
952  * the requested resolve types.  Once data is assigned it will not be
953  * removed until the last unlock.
954  *
955  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
956  *			   (typically used to avoid device/logical buffer
957  *			    aliasing for data)
958  *
959  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
960  *			   the INITIAL-create state (indirect blocks only).
961  *
962  *			   Do not resolve data elements for DATA chains.
963  *			   (typically used to avoid device/logical buffer
964  *			    aliasing for data)
965  *
966  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
967  *
968  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
969  *			   it will be locked exclusive.
970  *
971  * HAMMER2_RESOLVE_NONBLOCK- (flag) The chain is locked non-blocking.  If
972  *			   the lock fails, EAGAIN is returned.
973  *
974  * NOTE: Embedded elements (volume header, inodes) are always resolved
975  *	 regardless.
976  *
977  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
978  *	 element will instantiate and zero its buffer, and flush it on
979  *	 release.
980  *
981  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
982  *	 so as not to instantiate a device buffer, which could alias against
983  *	 a logical file buffer.  However, if ALWAYS is specified the
984  *	 device buffer will be instantiated anyway.
985  *
986  * NOTE: The return value is always 0 unless NONBLOCK is specified, in which
987  *	 case it can be either 0 or EAGAIN.
988  *
989  * WARNING! This function blocks on I/O if data needs to be fetched.  This
990  *	    blocking can run concurrent with other compatible lock holders
991  *	    who do not need data returning.  The lock is not upgraded to
992  *	    exclusive during a data fetch, a separate bit is used to
993  *	    interlock I/O.  However, an exclusive lock holder can still count
994  *	    on being interlocked against an I/O fetch managed by a shared
995  *	    lock holder.
996  */
997 int
998 hammer2_chain_lock(hammer2_chain_t *chain, int how)
999 {
1000 	KKASSERT(chain->refs > 0);
1001 
1002 	if (how & HAMMER2_RESOLVE_NONBLOCK) {
1003 		/*
1004 		 * We still have to bump lockcnt before acquiring the lock,
1005 		 * even for non-blocking operation, because the unlock code
1006 		 * live-loops on lockcnt == 1 when dropping the last lock.
1007 		 *
1008 		 * If the non-blocking operation fails we have to use an
1009 		 * unhold sequence to undo the mess.
1010 		 *
1011 		 * NOTE: LOCKAGAIN must always succeed without blocking,
1012 		 *	 even if NONBLOCK is specified.
1013 		 */
1014 		atomic_add_int(&chain->lockcnt, 1);
1015 		if (how & HAMMER2_RESOLVE_SHARED) {
1016 			if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1017 				hammer2_mtx_sh_again(&chain->lock);
1018 			} else {
1019 				if (hammer2_mtx_sh_try(&chain->lock) != 0) {
1020 					hammer2_chain_unhold(chain);
1021 					return EAGAIN;
1022 				}
1023 			}
1024 		} else {
1025 			if (hammer2_mtx_ex_try(&chain->lock) != 0) {
1026 				hammer2_chain_unhold(chain);
1027 				return EAGAIN;
1028 			}
1029 		}
1030 	} else {
1031 		/*
1032 		 * Get the appropriate lock.  If LOCKAGAIN is flagged with
1033 		 * SHARED the caller expects a shared lock to already be
1034 		 * present and we are giving it another ref.  This case must
1035 		 * importantly not block if there is a pending exclusive lock
1036 		 * request.
1037 		 */
1038 		atomic_add_int(&chain->lockcnt, 1);
1039 		if (how & HAMMER2_RESOLVE_SHARED) {
1040 			if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1041 				hammer2_mtx_sh_again(&chain->lock);
1042 			} else {
1043 				hammer2_mtx_sh(&chain->lock);
1044 			}
1045 		} else {
1046 			hammer2_mtx_ex(&chain->lock);
1047 		}
1048 	}
1049 
1050 	/*
1051 	 * If we already have a valid data pointer make sure the data is
1052 	 * synchronized to the current cpu, and then no further action is
1053 	 * necessary.
1054 	 */
1055 	if (chain->data) {
1056 		if (chain->dio)
1057 			hammer2_io_bkvasync(chain->dio);
1058 		return 0;
1059 	}
1060 
1061 	/*
1062 	 * Do we have to resolve the data?  This is generally only
1063 	 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
1064 	 * Other BREF types expects the data to be there.
1065 	 */
1066 	switch(how & HAMMER2_RESOLVE_MASK) {
1067 	case HAMMER2_RESOLVE_NEVER:
1068 		return 0;
1069 	case HAMMER2_RESOLVE_MAYBE:
1070 		if (chain->flags & HAMMER2_CHAIN_INITIAL)
1071 			return 0;
1072 		if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1073 			return 0;
1074 #if 0
1075 		if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
1076 			return 0;
1077 		if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
1078 			return 0;
1079 #endif
1080 		/* fall through */
1081 	case HAMMER2_RESOLVE_ALWAYS:
1082 	default:
1083 		break;
1084 	}
1085 
1086 	/*
1087 	 * Caller requires data
1088 	 */
1089 	hammer2_chain_load_data(chain);
1090 
1091 	return 0;
1092 }
1093 
1094 /*
1095  * Lock the chain, retain the hold, and drop the data persistence count.
1096  * The data should remain valid because we never transitioned lockcnt
1097  * through 0.
1098  */
1099 void
1100 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
1101 {
1102 	hammer2_chain_lock(chain, how);
1103 	atomic_add_int(&chain->lockcnt, -1);
1104 }
1105 
1106 #if 0
1107 /*
1108  * Downgrade an exclusive chain lock to a shared chain lock.
1109  *
1110  * NOTE: There is no upgrade equivalent due to the ease of
1111  *	 deadlocks in that direction.
1112  */
1113 void
1114 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1115 {
1116 	hammer2_mtx_downgrade(&chain->lock);
1117 }
1118 #endif
1119 
1120 /*
1121  * Issue I/O and install chain->data.  Caller must hold a chain lock, lock
1122  * may be of any type.
1123  *
1124  * Once chain->data is set it cannot be disposed of until all locks are
1125  * released.
1126  *
1127  * Make sure the data is synchronized to the current cpu.
1128  */
1129 void
1130 hammer2_chain_load_data(hammer2_chain_t *chain)
1131 {
1132 	hammer2_blockref_t *bref;
1133 	hammer2_dev_t *hmp;
1134 	hammer2_io_t *dio;
1135 	char *bdata;
1136 	int error;
1137 
1138 	/*
1139 	 * Degenerate case, data already present, or chain has no media
1140 	 * reference to load.
1141 	 */
1142 	KKASSERT(chain->lock.mtx_lock & MTX_MASK);
1143 	if (chain->data) {
1144 		if (chain->dio)
1145 			hammer2_io_bkvasync(chain->dio);
1146 		return;
1147 	}
1148 	if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0)
1149 		return;
1150 
1151 	hmp = chain->hmp;
1152 	KKASSERT(hmp != NULL);
1153 
1154 	/*
1155 	 * Gain the IOINPROG bit, interlocked block.
1156 	 */
1157 	for (;;) {
1158 		u_int oflags;
1159 		u_int nflags;
1160 
1161 		oflags = chain->flags;
1162 		cpu_ccfence();
1163 		if (oflags & HAMMER2_CHAIN_IOINPROG) {
1164 			nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1165 			tsleep_interlock(&chain->flags, 0);
1166 			if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1167 				tsleep(&chain->flags, PINTERLOCKED,
1168 					"h2iocw", 0);
1169 			}
1170 			/* retry */
1171 		} else {
1172 			nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1173 			if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1174 				break;
1175 			}
1176 			/* retry */
1177 		}
1178 	}
1179 
1180 	/*
1181 	 * We own CHAIN_IOINPROG
1182 	 *
1183 	 * Degenerate case if we raced another load.
1184 	 */
1185 	if (chain->data) {
1186 		if (chain->dio)
1187 			hammer2_io_bkvasync(chain->dio);
1188 		goto done;
1189 	}
1190 
1191 	/*
1192 	 * We must resolve to a device buffer, either by issuing I/O or
1193 	 * by creating a zero-fill element.  We do not mark the buffer
1194 	 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1195 	 * API must still be used to do that).
1196 	 *
1197 	 * The device buffer is variable-sized in powers of 2 down
1198 	 * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
1199 	 * chunk always contains buffers of the same size. (XXX)
1200 	 *
1201 	 * The minimum physical IO size may be larger than the variable
1202 	 * block size.
1203 	 */
1204 	bref = &chain->bref;
1205 
1206 	/*
1207 	 * The getblk() optimization can only be used on newly created
1208 	 * elements if the physical block size matches the request.
1209 	 */
1210 	if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1211 		error = hammer2_io_new(hmp, bref->type,
1212 				       bref->data_off, chain->bytes,
1213 				       &chain->dio);
1214 	} else {
1215 		error = hammer2_io_bread(hmp, bref->type,
1216 					 bref->data_off, chain->bytes,
1217 					 &chain->dio);
1218 		hammer2_adjreadcounter(chain->bref.type, chain->bytes);
1219 	}
1220 	if (error) {
1221 		chain->error = HAMMER2_ERROR_EIO;
1222 		kprintf("hammer2_chain_load_data: I/O error %016jx: %d\n",
1223 			(intmax_t)bref->data_off, error);
1224 		hammer2_io_bqrelse(&chain->dio);
1225 		goto done;
1226 	}
1227 	chain->error = 0;
1228 
1229 	/*
1230 	 * This isn't perfect and can be ignored on OSs which do not have
1231 	 * an indication as to whether a buffer is coming from cache or
1232 	 * if I/O was actually issued for the read.  TESTEDGOOD will work
1233 	 * pretty well without the B_IOISSUED logic because chains are
1234 	 * cached, but in that situation (without B_IOISSUED) it will not
1235 	 * detect whether a re-read via I/O is corrupted verses the original
1236 	 * read.
1237 	 *
1238 	 * We can't re-run the CRC on every fresh lock.  That would be
1239 	 * insanely expensive.
1240 	 *
1241 	 * If the underlying kernel buffer covers the entire chain we can
1242 	 * use the B_IOISSUED indication to determine if we have to re-run
1243 	 * the CRC on chain data for chains that managed to stay cached
1244 	 * across the kernel disposal of the original buffer.
1245 	 */
1246 	if ((dio = chain->dio) != NULL && dio->bp) {
1247 		//struct buf *bp = dio->bp;
1248 
1249 		if (dio->psize == chain->bytes //&&
1250 		    /*(bp->b_flags & B_IOISSUED)*/) {
1251 			atomic_clear_int(&chain->flags,
1252 					 HAMMER2_CHAIN_TESTEDGOOD);
1253 			//bp->b_flags &= ~B_IOISSUED;
1254 		}
1255 	}
1256 
1257 	/*
1258 	 * NOTE: A locked chain's data cannot be modified without first
1259 	 *	 calling hammer2_chain_modify().
1260 	 */
1261 
1262 	/*
1263 	 * NOTE: hammer2_io_data() call issues bkvasync()
1264 	 */
1265 	bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1266 
1267 	if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1268 		/*
1269 		 * Clear INITIAL.  In this case we used io_new() and the
1270 		 * buffer has been zero'd and marked dirty.
1271 		 *
1272 		 * CHAIN_MODIFIED has not been set yet, and we leave it
1273 		 * that way for now.  Set a temporary CHAIN_NOTTESTED flag
1274 		 * to prevent hammer2_chain_testcheck() from trying to match
1275 		 * a check code that has not yet been generated.  This bit
1276 		 * should NOT end up on the actual media.
1277 		 */
1278 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1279 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_NOTTESTED);
1280 	} else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1281 		/*
1282 		 * check data not currently synchronized due to
1283 		 * modification.  XXX assumes data stays in the buffer
1284 		 * cache, which might not be true (need biodep on flush
1285 		 * to calculate crc?  or simple crc?).
1286 		 */
1287 	} else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1288 		if (hammer2_chain_testcheck(chain, bdata) == 0) {
1289 			chain->error = HAMMER2_ERROR_CHECK;
1290 		} else {
1291 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1292 		}
1293 	}
1294 
1295 	/*
1296 	 * Setup the data pointer, either pointing it to an embedded data
1297 	 * structure and copying the data from the buffer, or pointing it
1298 	 * into the buffer.
1299 	 *
1300 	 * The buffer is not retained when copying to an embedded data
1301 	 * structure in order to avoid potential deadlocks or recursions
1302 	 * on the same physical buffer.
1303 	 *
1304 	 * WARNING! Other threads can start using the data the instant we
1305 	 *	    set chain->data non-NULL.
1306 	 */
1307 	switch (bref->type) {
1308 	case HAMMER2_BREF_TYPE_VOLUME:
1309 	case HAMMER2_BREF_TYPE_FREEMAP:
1310 		/*
1311 		 * Copy data from bp to embedded buffer
1312 		 */
1313 		panic("hammer2_chain_load_data: unresolved volume header");
1314 		break;
1315 	case HAMMER2_BREF_TYPE_DIRENT:
1316 		KKASSERT(chain->bytes != 0);
1317 		/* fall through */
1318 	case HAMMER2_BREF_TYPE_INODE:
1319 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1320 	case HAMMER2_BREF_TYPE_INDIRECT:
1321 	case HAMMER2_BREF_TYPE_DATA:
1322 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1323 	default:
1324 		/*
1325 		 * Point data at the device buffer and leave dio intact.
1326 		 */
1327 		chain->data = (void *)bdata;
1328 		break;
1329 	}
1330 
1331 	/*
1332 	 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1333 	 */
1334 done:
1335 	for (;;) {
1336 		u_int oflags;
1337 		u_int nflags;
1338 
1339 		oflags = chain->flags;
1340 		nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1341 				    HAMMER2_CHAIN_IOSIGNAL);
1342 		KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1343 		if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1344 			if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1345 				wakeup(&chain->flags);
1346 			break;
1347 		}
1348 	}
1349 }
1350 
1351 /*
1352  * Unlock and deref a chain element.
1353  *
1354  * Remember that the presence of children under chain prevent the chain's
1355  * destruction but do not add additional references, so the dio will still
1356  * be dropped.
1357  */
1358 void
1359 hammer2_chain_unlock(hammer2_chain_t *chain)
1360 {
1361 	hammer2_io_t *dio;
1362 	u_int lockcnt;
1363 	int iter = 0;
1364 
1365 	/*
1366 	 * If multiple locks are present (or being attempted) on this
1367 	 * particular chain we can just unlock, drop refs, and return.
1368 	 *
1369 	 * Otherwise fall-through on the 1->0 transition.
1370 	 */
1371 	for (;;) {
1372 		lockcnt = chain->lockcnt;
1373 		KKASSERT(lockcnt > 0);
1374 		cpu_ccfence();
1375 		if (lockcnt > 1) {
1376 			if (atomic_cmpset_int(&chain->lockcnt,
1377 					      lockcnt, lockcnt - 1)) {
1378 				hammer2_mtx_unlock(&chain->lock);
1379 				return;
1380 			}
1381 		} else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1382 			/* while holding the mutex exclusively */
1383 			if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1384 				break;
1385 		} else {
1386 			/*
1387 			 * This situation can easily occur on SMP due to
1388 			 * the gap inbetween the 1->0 transition and the
1389 			 * final unlock.  We cannot safely block on the
1390 			 * mutex because lockcnt might go above 1.
1391 			 *
1392 			 * XXX Sleep for one tick if it takes too long.
1393 			 */
1394 			if (++iter > 1000) {
1395 				if (iter > 1000 + hz) {
1396 					kprintf("hammer2: h2race2 %p\n", chain);
1397 					iter = 1000;
1398 				}
1399 				tsleep(&iter, 0, "h2race2", 1);
1400 			}
1401 			cpu_pause();
1402 		}
1403 		/* retry */
1404 	}
1405 
1406 	/*
1407 	 * Last unlock / mutex upgraded to exclusive.  Drop the data
1408 	 * reference.
1409 	 */
1410 	dio = hammer2_chain_drop_data(chain);
1411 	if (dio)
1412 		hammer2_io_bqrelse(&dio);
1413 	hammer2_mtx_unlock(&chain->lock);
1414 }
1415 
1416 /*
1417  * Unlock and hold chain data intact
1418  */
1419 void
1420 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1421 {
1422 	atomic_add_int(&chain->lockcnt, 1);
1423 	hammer2_chain_unlock(chain);
1424 }
1425 
1426 /*
1427  * Helper to obtain the blockref[] array base and count for a chain.
1428  *
1429  * XXX Not widely used yet, various use cases need to be validated and
1430  *     converted to use this function.
1431  */
1432 static
1433 hammer2_blockref_t *
1434 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1435 {
1436 	hammer2_blockref_t *base;
1437 	int count;
1438 
1439 	if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1440 		base = NULL;
1441 
1442 		switch(parent->bref.type) {
1443 		case HAMMER2_BREF_TYPE_INODE:
1444 			count = HAMMER2_SET_COUNT;
1445 			break;
1446 		case HAMMER2_BREF_TYPE_INDIRECT:
1447 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1448 			count = parent->bytes / sizeof(hammer2_blockref_t);
1449 			break;
1450 		case HAMMER2_BREF_TYPE_VOLUME:
1451 			count = HAMMER2_SET_COUNT;
1452 			break;
1453 		case HAMMER2_BREF_TYPE_FREEMAP:
1454 			count = HAMMER2_SET_COUNT;
1455 			break;
1456 		default:
1457 			panic("hammer2_chain_base_and_count: "
1458 			      "unrecognized blockref type: %d",
1459 			      parent->bref.type);
1460 			count = 0;
1461 			break;
1462 		}
1463 	} else {
1464 		switch(parent->bref.type) {
1465 		case HAMMER2_BREF_TYPE_INODE:
1466 			base = &parent->data->ipdata.u.blockset.blockref[0];
1467 			count = HAMMER2_SET_COUNT;
1468 			break;
1469 		case HAMMER2_BREF_TYPE_INDIRECT:
1470 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1471 			base = &parent->data->npdata[0];
1472 			count = parent->bytes / sizeof(hammer2_blockref_t);
1473 			break;
1474 		case HAMMER2_BREF_TYPE_VOLUME:
1475 			base = &parent->data->voldata.
1476 					sroot_blockset.blockref[0];
1477 			count = HAMMER2_SET_COUNT;
1478 			break;
1479 		case HAMMER2_BREF_TYPE_FREEMAP:
1480 			base = &parent->data->blkset.blockref[0];
1481 			count = HAMMER2_SET_COUNT;
1482 			break;
1483 		default:
1484 			panic("hammer2_chain_base_and_count: "
1485 			      "unrecognized blockref type: %d",
1486 			      parent->bref.type);
1487 			base = NULL;
1488 			count = 0;
1489 			break;
1490 		}
1491 	}
1492 	*countp = count;
1493 
1494 	return base;
1495 }
1496 
1497 /*
1498  * This counts the number of live blockrefs in a block array and
1499  * also calculates the point at which all remaining blockrefs are empty.
1500  * This routine can only be called on a live chain.
1501  *
1502  * Caller holds the chain locked, but possibly with a shared lock.  We
1503  * must use an exclusive spinlock to prevent corruption.
1504  *
1505  * NOTE: Flag is not set until after the count is complete, allowing
1506  *	 callers to test the flag without holding the spinlock.
1507  *
1508  * NOTE: If base is NULL the related chain is still in the INITIAL
1509  *	 state and there are no blockrefs to count.
1510  *
1511  * NOTE: live_count may already have some counts accumulated due to
1512  *	 creation and deletion and could even be initially negative.
1513  */
1514 void
1515 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1516 			 hammer2_blockref_t *base, int count)
1517 {
1518 	hammer2_spin_ex(&chain->core.spin);
1519 	if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1520 		if (base) {
1521 			while (--count >= 0) {
1522 				if (base[count].type != HAMMER2_BREF_TYPE_EMPTY)
1523 					break;
1524 			}
1525 			chain->core.live_zero = count + 1;
1526 			while (count >= 0) {
1527 				if (base[count].type != HAMMER2_BREF_TYPE_EMPTY)
1528 					atomic_add_int(&chain->core.live_count,
1529 						       1);
1530 				--count;
1531 			}
1532 		} else {
1533 			chain->core.live_zero = 0;
1534 		}
1535 		/* else do not modify live_count */
1536 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1537 	}
1538 	hammer2_spin_unex(&chain->core.spin);
1539 }
1540 
1541 /*
1542  * Resize the chain's physical storage allocation in-place.  This function does
1543  * not usually adjust the data pointer and must be followed by (typically) a
1544  * hammer2_chain_modify() call to copy any old data over and adjust the
1545  * data pointer.
1546  *
1547  * Chains can be resized smaller without reallocating the storage.  Resizing
1548  * larger will reallocate the storage.  Excess or prior storage is reclaimed
1549  * asynchronously at a later time.
1550  *
1551  * An nradix value of 0 is special-cased to mean that the storage should
1552  * be disassociated, that is the chain is being resized to 0 bytes (not 1
1553  * byte).
1554  *
1555  * Must be passed an exclusively locked parent and chain.
1556  *
1557  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1558  * to avoid instantiating a device buffer that conflicts with the vnode data
1559  * buffer.  However, because H2 can compress or encrypt data, the chain may
1560  * have a dio assigned to it in those situations, and they do not conflict.
1561  *
1562  * XXX return error if cannot resize.
1563  */
1564 int
1565 hammer2_chain_resize(hammer2_chain_t *chain,
1566 		     hammer2_tid_t mtid, hammer2_off_t dedup_off,
1567 		     int nradix, int flags)
1568 {
1569 	hammer2_dev_t *hmp;
1570 	size_t obytes;
1571 	size_t nbytes;
1572 	int error;
1573 
1574 	hmp = chain->hmp;
1575 
1576 	/*
1577 	 * Only data and indirect blocks can be resized for now.
1578 	 * (The volu root, inodes, and freemap elements use a fixed size).
1579 	 */
1580 	KKASSERT(chain != &hmp->vchain);
1581 	KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1582 		 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1583 		 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1584 
1585 	/*
1586 	 * Nothing to do if the element is already the proper size
1587 	 */
1588 	obytes = chain->bytes;
1589 	nbytes = (nradix) ? (1U << nradix) : 0;
1590 	if (obytes == nbytes)
1591 		return (chain->error);
1592 
1593 	/*
1594 	 * Make sure the old data is instantiated so we can copy it.  If this
1595 	 * is a data block, the device data may be superfluous since the data
1596 	 * might be in a logical block, but compressed or encrypted data is
1597 	 * another matter.
1598 	 *
1599 	 * NOTE: The modify will set BLKMAPUPD for us if BLKMAPPED is set.
1600 	 */
1601 	error = hammer2_chain_modify(chain, mtid, dedup_off, 0);
1602 	if (error)
1603 		return error;
1604 
1605 	/*
1606 	 * Reallocate the block, even if making it smaller (because different
1607 	 * block sizes may be in different regions).
1608 	 *
1609 	 * NOTE: Operation does not copy the data and may only be used
1610 	 *	 to resize data blocks in-place, or directory entry blocks
1611 	 *	 which are about to be modified in some manner.
1612 	 */
1613 	error = hammer2_freemap_alloc(chain, nbytes);
1614 	if (error)
1615 		return error;
1616 
1617 	chain->bytes = nbytes;
1618 
1619 	/*
1620 	 * We don't want the followup chain_modify() to try to copy data
1621 	 * from the old (wrong-sized) buffer.  It won't know how much to
1622 	 * copy.  This case should only occur during writes when the
1623 	 * originator already has the data to write in-hand.
1624 	 */
1625 	if (chain->dio) {
1626 		KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1627 			 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1628 		hammer2_io_brelse(&chain->dio);
1629 		chain->data = NULL;
1630 	}
1631 	return (chain->error);
1632 }
1633 
1634 /*
1635  * Set the chain modified so its data can be changed by the caller, or
1636  * install deduplicated data.  The caller must call this routine for each
1637  * set of modifications it makes, even if the chain is already flagged
1638  * MODIFIED.
1639  *
1640  * Sets bref.modify_tid to mtid only if mtid != 0.  Note that bref.modify_tid
1641  * is a CLC (cluster level change) field and is not updated by parent
1642  * propagation during a flush.
1643  *
1644  * Returns an appropriate HAMMER2_ERROR_* code, which will generally reflect
1645  * chain->error except for HAMMER2_ERROR_ENOSPC.  If the allocation fails
1646  * due to no space available, HAMMER2_ERROR_ENOSPC is returned and the chain
1647  * remains unmodified with its old data ref intact and chain->error
1648  * unchanged.
1649  *
1650  *				 Dedup Handling
1651  *
1652  * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1653  * even if the chain is still flagged MODIFIED.  In this case the chain's
1654  * DEDUPABLE flag will be cleared once the new storage has been assigned.
1655  *
1656  * If the caller passes a non-zero dedup_off we will use it to assign the
1657  * new storage.  The MODIFIED flag will be *CLEARED* in this case, and
1658  * DEDUPABLE will be set (NOTE: the UPDATE flag is always set).  The caller
1659  * must not modify the data content upon return.
1660  */
1661 int
1662 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1663 		     hammer2_off_t dedup_off, int flags)
1664 {
1665 	hammer2_dev_t *hmp;
1666 	hammer2_io_t *dio;
1667 	int error;
1668 	int wasinitial;
1669 	int setmodified;
1670 	int setupdate;
1671 	int newmod;
1672 	char *bdata;
1673 
1674 	hmp = chain->hmp;
1675 	KKASSERT(chain->lock.mtx_lock & MTX_EXCLUSIVE);
1676 
1677 	/*
1678 	 * Data is not optional for freemap chains (we must always be sure
1679 	 * to copy the data on COW storage allocations).
1680 	 */
1681 	if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1682 	    chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1683 		KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1684 			 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1685 	}
1686 
1687 	/*
1688 	 * Data must be resolved if already assigned, unless explicitly
1689 	 * flagged otherwise.  If we cannot safety load the data the
1690 	 * modification fails and we return early.
1691 	 */
1692 	if (chain->data == NULL && chain->bytes != 0 &&
1693 	    (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1694 	    (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1695 		hammer2_chain_load_data(chain);
1696 		if (chain->error)
1697 			return (chain->error);
1698 	}
1699 	error = 0;
1700 
1701 	/*
1702 	 * Set MODIFIED to indicate that the chain has been modified.  A new
1703 	 * allocation is required when modifying a chain.
1704 	 *
1705 	 * Set UPDATE to ensure that the blockref is updated in the parent.
1706 	 *
1707 	 * If MODIFIED is already set determine if we can reuse the assigned
1708 	 * data block or if we need a new data block.
1709 	 */
1710 	if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1711 		/*
1712 		 * Must set modified bit.
1713 		 */
1714 		atomic_add_long(&hammer2_count_modified_chains, 1);
1715 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1716 		hammer2_pfs_memory_inc(chain->pmp);  /* can be NULL */
1717 		setmodified = 1;
1718 
1719 		/*
1720 		 * We may be able to avoid a copy-on-write if the chain's
1721 		 * check mode is set to NONE and the chain's current
1722 		 * modify_tid is beyond the last explicit snapshot tid.
1723 		 *
1724 		 * This implements HAMMER2's overwrite-in-place feature.
1725 		 *
1726 		 * NOTE! This data-block cannot be used as a de-duplication
1727 		 *	 source when the check mode is set to NONE.
1728 		 */
1729 		if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1730 		     chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1731 		    (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1732 		    (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1733 		    HAMMER2_DEC_CHECK(chain->bref.methods) ==
1734 		     HAMMER2_CHECK_NONE &&
1735 		    chain->pmp &&
1736 		    chain->bref.modify_tid >
1737 		     chain->pmp->iroot->meta.pfs_lsnap_tid) {
1738 			/*
1739 			 * Sector overwrite allowed.
1740 			 */
1741 			newmod = 0;
1742 		} else if ((hmp->hflags & HMNT2_EMERG) &&
1743 			   chain->pmp &&
1744 			   chain->bref.modify_tid >
1745 			    chain->pmp->iroot->meta.pfs_lsnap_tid) {
1746 			/*
1747 			 * If in emergency delete mode then do a modify-in-
1748 			 * place on any chain type belonging to the PFS as
1749 			 * long as it doesn't mess up a snapshot.  We might
1750 			 * be forced to do this anyway a little further down
1751 			 * in the code if the allocation fails.
1752 			 *
1753 			 * Also note that in emergency mode, these modify-in-
1754 			 * place operations are NOT SAFE.  A storage failure,
1755 			 * power failure, or panic can corrupt the filesystem.
1756 			 */
1757 			newmod = 0;
1758 		} else {
1759 			/*
1760 			 * Sector overwrite not allowed, must copy-on-write.
1761 			 */
1762 			newmod = 1;
1763 		}
1764 	} else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1765 		/*
1766 		 * If the modified chain was registered for dedup we need
1767 		 * a new allocation.  This only happens for delayed-flush
1768 		 * chains (i.e. which run through the front-end buffer
1769 		 * cache).
1770 		 */
1771 		newmod = 1;
1772 		setmodified = 0;
1773 	} else {
1774 		/*
1775 		 * Already flagged modified, no new allocation is needed.
1776 		 */
1777 		newmod = 0;
1778 		setmodified = 0;
1779 	}
1780 
1781 	/*
1782 	 * Flag parent update required.
1783 	 */
1784 	if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1785 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1786 		setupdate = 1;
1787 	} else {
1788 		setupdate = 0;
1789 	}
1790 
1791 	/*
1792 	 * The XOP code returns held but unlocked focus chains.  This
1793 	 * prevents the chain from being destroyed but does not prevent
1794 	 * it from being modified.  diolk is used to interlock modifications
1795 	 * against XOP frontend accesses to the focus.
1796 	 *
1797 	 * This allows us to theoretically avoid deadlocking the frontend
1798 	 * if one of the backends lock up by not formally locking the
1799 	 * focused chain in the frontend.  In addition, the synchronization
1800 	 * code relies on this mechanism to avoid deadlocking concurrent
1801 	 * synchronization threads.
1802 	 */
1803 	lockmgr(&chain->diolk, LK_EXCLUSIVE);
1804 
1805 	/*
1806 	 * The modification or re-modification requires an allocation and
1807 	 * possible COW.  If an error occurs, the previous content and data
1808 	 * reference is retained and the modification fails.
1809 	 *
1810 	 * If dedup_off is non-zero, the caller is requesting a deduplication
1811 	 * rather than a modification.  The MODIFIED bit is not set and the
1812 	 * data offset is set to the deduplication offset.  The data cannot
1813 	 * be modified.
1814 	 *
1815 	 * NOTE: The dedup offset is allowed to be in a partially free state
1816 	 *	 and we must be sure to reset it to a fully allocated state
1817 	 *	 to force two bulkfree passes to free it again.
1818 	 *
1819 	 * NOTE: Only applicable when chain->bytes != 0.
1820 	 *
1821 	 * XXX can a chain already be marked MODIFIED without a data
1822 	 * assignment?  If not, assert here instead of testing the case.
1823 	 */
1824 	if (chain != &hmp->vchain && chain != &hmp->fchain &&
1825 	    chain->bytes) {
1826 		if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1827 		    newmod
1828 		) {
1829 			/*
1830 			 * NOTE: We do not have to remove the dedup
1831 			 *	 registration because the area is still
1832 			 *	 allocated and the underlying DIO will
1833 			 *	 still be flushed.
1834 			 */
1835 			if (dedup_off) {
1836 				chain->bref.data_off = dedup_off;
1837 				if ((int)(dedup_off & HAMMER2_OFF_MASK_RADIX))
1838 					chain->bytes = 1 <<
1839 						(int)(dedup_off &
1840 						HAMMER2_OFF_MASK_RADIX);
1841 				else
1842 					chain->bytes = 0;
1843 				chain->error = 0;
1844 				atomic_clear_int(&chain->flags,
1845 						 HAMMER2_CHAIN_MODIFIED);
1846 				atomic_add_long(&hammer2_count_modified_chains,
1847 						-1);
1848 				if (chain->pmp) {
1849 					hammer2_pfs_memory_wakeup(
1850 						chain->pmp, -1);
1851 				}
1852 				hammer2_freemap_adjust(hmp, &chain->bref,
1853 						HAMMER2_FREEMAP_DORECOVER);
1854 				atomic_set_int(&chain->flags,
1855 						HAMMER2_CHAIN_DEDUPABLE);
1856 			} else {
1857 				error = hammer2_freemap_alloc(chain,
1858 							      chain->bytes);
1859 				atomic_clear_int(&chain->flags,
1860 						HAMMER2_CHAIN_DEDUPABLE);
1861 
1862 				/*
1863 				 * If we are unable to allocate a new block
1864 				 * but we are in emergency mode, issue a
1865 				 * warning to the console and reuse the same
1866 				 * block.
1867 				 *
1868 				 * We behave as if the allocation were
1869 				 * successful.
1870 				 *
1871 				 * THIS IS IMPORTANT: These modifications
1872 				 * are virtually guaranteed to corrupt any
1873 				 * snapshots related to this filesystem.
1874 				 */
1875 				if (error && (hmp->hflags & HMNT2_EMERG)) {
1876 					error = 0;
1877 					chain->bref.flags |=
1878 						HAMMER2_BREF_FLAG_EMERG_MIP;
1879 
1880 					krateprintf(&krate_h2em,
1881 					    "hammer2: Emergency Mode WARNING: "
1882 					    "Operation will likely corrupt "
1883 					    "related snapshot: "
1884 					    "%016jx.%02x key=%016jx\n",
1885 					    chain->bref.data_off,
1886 					    chain->bref.type,
1887 					    chain->bref.key);
1888 				} else if (error == 0) {
1889 					chain->bref.flags &=
1890 						~HAMMER2_BREF_FLAG_EMERG_MIP;
1891 				}
1892 			}
1893 		}
1894 	}
1895 
1896 	/*
1897 	 * Stop here if error.  We have to undo any flag bits we might
1898 	 * have set above.
1899 	 */
1900 	if (error) {
1901 		if (setmodified) {
1902 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1903 			atomic_add_long(&hammer2_count_modified_chains, -1);
1904 			if (chain->pmp)
1905 				hammer2_pfs_memory_wakeup(chain->pmp, -1);
1906 		}
1907 		if (setupdate) {
1908 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1909 		}
1910 		lockmgr(&chain->diolk, LK_RELEASE);
1911 
1912 		return error;
1913 	}
1914 
1915 	/*
1916 	 * Update mirror_tid and modify_tid.  modify_tid is only updated
1917 	 * if not passed as zero (during flushes, parent propagation passes
1918 	 * the value 0).
1919 	 *
1920 	 * NOTE: chain->pmp could be the device spmp.
1921 	 */
1922 	chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1923 	if (mtid)
1924 		chain->bref.modify_tid = mtid;
1925 
1926 	/*
1927 	 * Set BLKMAPUPD to tell the flush code that an existing blockmap entry
1928 	 * requires updating as well as to tell the delete code that the
1929 	 * chain's blockref might not exactly match (in terms of physical size
1930 	 * or block offset) the one in the parent's blocktable.  The base key
1931 	 * of course will still match.
1932 	 */
1933 	if (chain->flags & HAMMER2_CHAIN_BLKMAPPED)
1934 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_BLKMAPUPD);
1935 
1936 	/*
1937 	 * Short-cut data block handling when the caller does not need an
1938 	 * actual data reference to (aka OPTDATA), as long as the chain does
1939 	 * not already have a data pointer to the data and no de-duplication
1940 	 * occurred.
1941 	 *
1942 	 * This generally means that the modifications are being done via the
1943 	 * logical buffer cache.
1944 	 *
1945 	 * NOTE: If deduplication occurred we have to run through the data
1946 	 *	 stuff to clear INITIAL, and the caller will likely want to
1947 	 *	 assign the check code anyway.  Leaving INITIAL set on a
1948 	 *	 dedup can be deadly (it can cause the block to be zero'd!).
1949 	 *
1950 	 * This code also handles bytes == 0 (most dirents).
1951 	 */
1952 	if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1953 	    (flags & HAMMER2_MODIFY_OPTDATA) &&
1954 	    chain->data == NULL) {
1955 		if (dedup_off == 0) {
1956 			KKASSERT(chain->dio == NULL);
1957 			goto skip2;
1958 		}
1959 	}
1960 
1961 	/*
1962 	 * Clearing the INITIAL flag (for indirect blocks) indicates that
1963 	 * we've processed the uninitialized storage allocation.
1964 	 *
1965 	 * If this flag is already clear we are likely in a copy-on-write
1966 	 * situation but we have to be sure NOT to bzero the storage if
1967 	 * no data is present.
1968 	 *
1969 	 * Clearing of NOTTESTED is allowed if the MODIFIED bit is set,
1970 	 */
1971 	if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1972 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1973 		wasinitial = 1;
1974 	} else {
1975 		wasinitial = 0;
1976 	}
1977 
1978 	/*
1979 	 * Instantiate data buffer and possibly execute COW operation
1980 	 */
1981 	switch(chain->bref.type) {
1982 	case HAMMER2_BREF_TYPE_VOLUME:
1983 	case HAMMER2_BREF_TYPE_FREEMAP:
1984 		/*
1985 		 * The data is embedded, no copy-on-write operation is
1986 		 * needed.
1987 		 */
1988 		KKASSERT(chain->dio == NULL);
1989 		break;
1990 	case HAMMER2_BREF_TYPE_DIRENT:
1991 		/*
1992 		 * The data might be fully embedded.
1993 		 */
1994 		if (chain->bytes == 0) {
1995 			KKASSERT(chain->dio == NULL);
1996 			break;
1997 		}
1998 		/* fall through */
1999 	case HAMMER2_BREF_TYPE_INODE:
2000 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2001 	case HAMMER2_BREF_TYPE_DATA:
2002 	case HAMMER2_BREF_TYPE_INDIRECT:
2003 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2004 		/*
2005 		 * Perform the copy-on-write operation
2006 		 *
2007 		 * zero-fill or copy-on-write depending on whether
2008 		 * chain->data exists or not and set the dirty state for
2009 		 * the new buffer.  hammer2_io_new() will handle the
2010 		 * zero-fill.
2011 		 *
2012 		 * If a dedup_off was supplied this is an existing block
2013 		 * and no COW, copy, or further modification is required.
2014 		 */
2015 		KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
2016 
2017 		if (wasinitial && dedup_off == 0) {
2018 			error = hammer2_io_new(hmp, chain->bref.type,
2019 					       chain->bref.data_off,
2020 					       chain->bytes, &dio);
2021 		} else {
2022 			error = hammer2_io_bread(hmp, chain->bref.type,
2023 						 chain->bref.data_off,
2024 						 chain->bytes, &dio);
2025 		}
2026 		hammer2_adjreadcounter(chain->bref.type, chain->bytes);
2027 
2028 		/*
2029 		 * If an I/O error occurs make sure callers cannot accidently
2030 		 * modify the old buffer's contents and corrupt the filesystem.
2031 		 *
2032 		 * NOTE: hammer2_io_data() call issues bkvasync()
2033 		 */
2034 		if (error) {
2035 			kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
2036 				hmp);
2037 			chain->error = HAMMER2_ERROR_EIO;
2038 			hammer2_io_brelse(&dio);
2039 			hammer2_io_brelse(&chain->dio);
2040 			chain->data = NULL;
2041 			break;
2042 		}
2043 		chain->error = 0;
2044 		bdata = hammer2_io_data(dio, chain->bref.data_off);
2045 
2046 		if (chain->data) {
2047 			/*
2048 			 * COW (unless a dedup).
2049 			 */
2050 			KKASSERT(chain->dio != NULL);
2051 			if (chain->data != (void *)bdata && dedup_off == 0) {
2052 				bcopy(chain->data, bdata, chain->bytes);
2053 			}
2054 		} else if (wasinitial == 0 && dedup_off == 0) {
2055 			/*
2056 			 * We have a problem.  We were asked to COW but
2057 			 * we don't have any data to COW with!
2058 			 */
2059 			panic("hammer2_chain_modify: having a COW %p\n",
2060 			      chain);
2061 		}
2062 
2063 		/*
2064 		 * Retire the old buffer, replace with the new.  Dirty or
2065 		 * redirty the new buffer.
2066 		 *
2067 		 * WARNING! The system buffer cache may have already flushed
2068 		 *	    the buffer, so we must be sure to [re]dirty it
2069 		 *	    for further modification.
2070 		 *
2071 		 *	    If dedup_off was supplied, the caller is not
2072 		 *	    expected to make any further modification to the
2073 		 *	    buffer.
2074 		 *
2075 		 * WARNING! hammer2_get_gdata() assumes dio never transitions
2076 		 *	    through NULL in order to optimize away unnecessary
2077 		 *	    diolk operations.
2078 		 */
2079 		{
2080 			hammer2_io_t *tio;
2081 
2082 			if ((tio = chain->dio) != NULL)
2083 				hammer2_io_bqrelse(&tio);
2084 			chain->data = (void *)bdata;
2085 			chain->dio = dio;
2086 			if (dedup_off == 0)
2087 				hammer2_io_setdirty(dio);
2088 		}
2089 		break;
2090 	default:
2091 		panic("hammer2_chain_modify: illegal non-embedded type %d",
2092 		      chain->bref.type);
2093 		break;
2094 
2095 	}
2096 skip2:
2097 	/*
2098 	 * setflush on parent indicating that the parent must recurse down
2099 	 * to us.  Do not call on chain itself which might already have it
2100 	 * set.
2101 	 */
2102 	if (chain->parent)
2103 		hammer2_chain_setflush(chain->parent);
2104 	lockmgr(&chain->diolk, LK_RELEASE);
2105 
2106 	return (chain->error);
2107 }
2108 
2109 /*
2110  * Modify the chain associated with an inode.
2111  */
2112 int
2113 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
2114 			hammer2_tid_t mtid, int flags)
2115 {
2116 	int error;
2117 
2118 	hammer2_inode_modify(ip);
2119 	error = hammer2_chain_modify(chain, mtid, 0, flags);
2120 
2121 	return error;
2122 }
2123 
2124 /*
2125  * This function returns the chain at the nearest key within the specified
2126  * range.  The returned chain will be referenced but not locked.
2127  *
2128  * This function will recurse through chain->rbtree as necessary and will
2129  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
2130  * the iteration value is less than the current value of *key_nextp.
2131  *
2132  * The caller should use (*key_nextp) to calculate the actual range of
2133  * the returned element, which will be (key_beg to *key_nextp - 1), because
2134  * there might be another element which is superior to the returned element
2135  * and overlaps it.
2136  *
2137  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
2138  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
2139  * it will wind up being (key_end + 1).
2140  *
2141  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
2142  *	     held through the operation.
2143  */
2144 struct hammer2_chain_find_info {
2145 	hammer2_chain_t		*best;
2146 	hammer2_key_t		key_beg;
2147 	hammer2_key_t		key_end;
2148 	hammer2_key_t		key_next;
2149 };
2150 
2151 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
2152 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
2153 
2154 static
2155 hammer2_chain_t *
2156 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
2157 			  hammer2_key_t key_beg, hammer2_key_t key_end)
2158 {
2159 	struct hammer2_chain_find_info info;
2160 
2161 	info.best = NULL;
2162 	info.key_beg = key_beg;
2163 	info.key_end = key_end;
2164 	info.key_next = *key_nextp;
2165 
2166 	RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
2167 		hammer2_chain_find_cmp, hammer2_chain_find_callback,
2168 		&info);
2169 	*key_nextp = info.key_next;
2170 #if 0
2171 	kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
2172 		parent, key_beg, key_end, *key_nextp);
2173 #endif
2174 
2175 	return (info.best);
2176 }
2177 
2178 static
2179 int
2180 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
2181 {
2182 	struct hammer2_chain_find_info *info = data;
2183 	hammer2_key_t child_beg;
2184 	hammer2_key_t child_end;
2185 
2186 	child_beg = child->bref.key;
2187 	child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
2188 
2189 	if (child_end < info->key_beg)
2190 		return(-1);
2191 	if (child_beg > info->key_end)
2192 		return(1);
2193 	return(0);
2194 }
2195 
2196 static
2197 int
2198 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
2199 {
2200 	struct hammer2_chain_find_info *info = data;
2201 	hammer2_chain_t *best;
2202 	hammer2_key_t child_end;
2203 
2204 	/*
2205 	 * WARNING! Layerq is scanned forwards, exact matches should keep
2206 	 *	    the existing info->best.
2207 	 */
2208 	if ((best = info->best) == NULL) {
2209 		/*
2210 		 * No previous best.  Assign best
2211 		 */
2212 		info->best = child;
2213 	} else if (best->bref.key <= info->key_beg &&
2214 		   child->bref.key <= info->key_beg) {
2215 		/*
2216 		 * Illegal overlap.
2217 		 */
2218 		KKASSERT(0);
2219 		/*info->best = child;*/
2220 	} else if (child->bref.key < best->bref.key) {
2221 		/*
2222 		 * Child has a nearer key and best is not flush with key_beg.
2223 		 * Set best to child.  Truncate key_next to the old best key.
2224 		 */
2225 		info->best = child;
2226 		if (info->key_next > best->bref.key || info->key_next == 0)
2227 			info->key_next = best->bref.key;
2228 	} else if (child->bref.key == best->bref.key) {
2229 		/*
2230 		 * If our current best is flush with the child then this
2231 		 * is an illegal overlap.
2232 		 *
2233 		 * key_next will automatically be limited to the smaller of
2234 		 * the two end-points.
2235 		 */
2236 		KKASSERT(0);
2237 		info->best = child;
2238 	} else {
2239 		/*
2240 		 * Keep the current best but truncate key_next to the child's
2241 		 * base.
2242 		 *
2243 		 * key_next will also automatically be limited to the smaller
2244 		 * of the two end-points (probably not necessary for this case
2245 		 * but we do it anyway).
2246 		 */
2247 		if (info->key_next > child->bref.key || info->key_next == 0)
2248 			info->key_next = child->bref.key;
2249 	}
2250 
2251 	/*
2252 	 * Always truncate key_next based on child's end-of-range.
2253 	 */
2254 	child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2255 	if (child_end && (info->key_next > child_end || info->key_next == 0))
2256 		info->key_next = child_end;
2257 
2258 	return(0);
2259 }
2260 
2261 /*
2262  * Retrieve the specified chain from a media blockref, creating the
2263  * in-memory chain structure which reflects it.  The returned chain is
2264  * held and locked according to (how) (HAMMER2_RESOLVE_*).  The caller must
2265  * handle crc-checks and so forth, and should check chain->error before
2266  * assuming that the data is good.
2267  *
2268  * To handle insertion races pass the INSERT_RACE flag along with the
2269  * generation number of the core.  NULL will be returned if the generation
2270  * number changes before we have a chance to insert the chain.  Insert
2271  * races can occur because the parent might be held shared.
2272  *
2273  * Caller must hold the parent locked shared or exclusive since we may
2274  * need the parent's bref array to find our block.
2275  *
2276  * WARNING! chain->pmp is always set to NULL for any chain representing
2277  *	    part of the super-root topology.
2278  */
2279 hammer2_chain_t *
2280 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2281 		  hammer2_blockref_t *bref, int how)
2282 {
2283 	hammer2_dev_t *hmp = parent->hmp;
2284 	hammer2_chain_t *chain;
2285 	int error;
2286 
2287 	/*
2288 	 * Allocate a chain structure representing the existing media
2289 	 * entry.  Resulting chain has one ref and is not locked.
2290 	 */
2291 	if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2292 		chain = hammer2_chain_alloc(hmp, NULL, bref);
2293 	else
2294 		chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2295 	/* ref'd chain returned */
2296 
2297 	/*
2298 	 * Flag that the chain is in the parent's blockmap so delete/flush
2299 	 * knows what to do with it.
2300 	 */
2301 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_BLKMAPPED);
2302 
2303 	/*
2304 	 * chain must be locked to avoid unexpected ripouts
2305 	 */
2306 	hammer2_chain_lock(chain, how);
2307 
2308 	/*
2309 	 * Link the chain into its parent.  A spinlock is required to safely
2310 	 * access the RBTREE, and it is possible to collide with another
2311 	 * hammer2_chain_get() operation because the caller might only hold
2312 	 * a shared lock on the parent.
2313 	 *
2314 	 * NOTE: Get races can occur quite often when we distribute
2315 	 *	 asynchronous read-aheads across multiple threads.
2316 	 */
2317 	KKASSERT(parent->refs > 0);
2318 	error = hammer2_chain_insert(parent, chain,
2319 				     HAMMER2_CHAIN_INSERT_SPIN |
2320 				     HAMMER2_CHAIN_INSERT_RACE,
2321 				     generation);
2322 	if (error) {
2323 		KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2324 		/*kprintf("chain %p get race\n", chain);*/
2325 		hammer2_chain_unlock(chain);
2326 		hammer2_chain_drop(chain);
2327 		chain = NULL;
2328 	} else {
2329 		KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2330 	}
2331 
2332 	/*
2333 	 * Return our new chain referenced but not locked, or NULL if
2334 	 * a race occurred.
2335 	 */
2336 	return (chain);
2337 }
2338 
2339 /*
2340  * Lookup initialization/completion API
2341  */
2342 hammer2_chain_t *
2343 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2344 {
2345 	hammer2_chain_ref(parent);
2346 	if (flags & HAMMER2_LOOKUP_SHARED) {
2347 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2348 					   HAMMER2_RESOLVE_SHARED);
2349 	} else {
2350 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2351 	}
2352 	return (parent);
2353 }
2354 
2355 void
2356 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2357 {
2358 	if (parent) {
2359 		hammer2_chain_unlock(parent);
2360 		hammer2_chain_drop(parent);
2361 	}
2362 }
2363 
2364 /*
2365  * Take the locked chain and return a locked parent.  The chain remains
2366  * locked on return, but may have to be temporarily unlocked to acquire
2367  * the parent.  Because of this, (chain) must be stable and cannot be
2368  * deleted while it was temporarily unlocked (typically means that (chain)
2369  * is an inode).
2370  *
2371  * Pass HAMMER2_RESOLVE_* flags in flags.
2372  *
2373  * This will work even if the chain is errored, and the caller can check
2374  * parent->error on return if desired since the parent will be locked.
2375  *
2376  * This function handles the lock order reversal.
2377  */
2378 hammer2_chain_t *
2379 hammer2_chain_getparent(hammer2_chain_t *chain, int flags)
2380 {
2381 	hammer2_chain_t *parent;
2382 
2383 	/*
2384 	 * Be careful of order, chain must be unlocked before parent
2385 	 * is locked below to avoid a deadlock.  Try it trivially first.
2386 	 */
2387 	parent = chain->parent;
2388 	if (parent == NULL)
2389 		panic("hammer2_chain_getparent: no parent");
2390 	hammer2_chain_ref(parent);
2391 	if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0)
2392 		return parent;
2393 
2394 	for (;;) {
2395 		hammer2_chain_unlock(chain);
2396 		hammer2_chain_lock(parent, flags);
2397 		hammer2_chain_lock(chain, flags);
2398 
2399 		/*
2400 		 * Parent relinking races are quite common.  We have to get
2401 		 * it right or we will blow up the block table.
2402 		 */
2403 		if (chain->parent == parent)
2404 			break;
2405 		hammer2_chain_unlock(parent);
2406 		hammer2_chain_drop(parent);
2407 		cpu_ccfence();
2408 		parent = chain->parent;
2409 		if (parent == NULL)
2410 			panic("hammer2_chain_getparent: no parent");
2411 		hammer2_chain_ref(parent);
2412 	}
2413 	return parent;
2414 }
2415 
2416 /*
2417  * Take the locked chain and return a locked parent.  The chain is unlocked
2418  * and dropped.  *chainp is set to the returned parent as a convenience.
2419  * Pass HAMMER2_RESOLVE_* flags in flags.
2420  *
2421  * This will work even if the chain is errored, and the caller can check
2422  * parent->error on return if desired since the parent will be locked.
2423  *
2424  * The chain does NOT need to be stable.  We use a tracking structure
2425  * to track the expected parent if the chain is deleted out from under us.
2426  *
2427  * This function handles the lock order reversal.
2428  */
2429 hammer2_chain_t *
2430 hammer2_chain_repparent(hammer2_chain_t **chainp, int flags)
2431 {
2432 	hammer2_chain_t *chain;
2433 	hammer2_chain_t *parent;
2434 	struct hammer2_reptrack reptrack;
2435 	struct hammer2_reptrack **repp;
2436 
2437 	/*
2438 	 * Be careful of order, chain must be unlocked before parent
2439 	 * is locked below to avoid a deadlock.  Try it trivially first.
2440 	 */
2441 	chain = *chainp;
2442 	parent = chain->parent;
2443 	if (parent == NULL) {
2444 		hammer2_spin_unex(&chain->core.spin);
2445 		panic("hammer2_chain_repparent: no parent");
2446 	}
2447 	hammer2_chain_ref(parent);
2448 	if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0) {
2449 		hammer2_chain_unlock(chain);
2450 		hammer2_chain_drop(chain);
2451 		*chainp = parent;
2452 
2453 		return parent;
2454 	}
2455 
2456 	/*
2457 	 * Ok, now it gets a bit nasty.  There are multiple situations where
2458 	 * the parent might be in the middle of a deletion, or where the child
2459 	 * (chain) might be deleted the instant we let go of its lock.
2460 	 * We can potentially end up in a no-win situation!
2461 	 *
2462 	 * In particular, the indirect_maintenance() case can cause these
2463 	 * situations.
2464 	 *
2465 	 * To deal with this we install a reptrack structure in the parent
2466 	 * This reptrack structure 'owns' the parent ref and will automatically
2467 	 * migrate to the parent's parent if the parent is deleted permanently.
2468 	 */
2469 	hammer2_spin_init(&reptrack.spin, "h2reptrk");
2470 	reptrack.chain = parent;
2471 	hammer2_chain_ref(parent);		/* for the reptrack */
2472 
2473 	hammer2_spin_ex(&parent->core.spin);
2474 	reptrack.next = parent->core.reptrack;
2475 	parent->core.reptrack = &reptrack;
2476 	hammer2_spin_unex(&parent->core.spin);
2477 
2478 	hammer2_chain_unlock(chain);
2479 	hammer2_chain_drop(chain);
2480 	chain = NULL;	/* gone */
2481 
2482 	/*
2483 	 * At the top of this loop, chain is gone and parent is refd both
2484 	 * by us explicitly AND via our reptrack.  We are attempting to
2485 	 * lock parent.
2486 	 */
2487 	for (;;) {
2488 		hammer2_chain_lock(parent, flags);
2489 
2490 		if (reptrack.chain == parent)
2491 			break;
2492 		hammer2_chain_unlock(parent);
2493 		hammer2_chain_drop(parent);
2494 
2495 		kprintf("hammer2: debug REPTRACK %p->%p\n",
2496 			parent, reptrack.chain);
2497 		hammer2_spin_ex(&reptrack.spin);
2498 		parent = reptrack.chain;
2499 		hammer2_chain_ref(parent);
2500 		hammer2_spin_unex(&reptrack.spin);
2501 	}
2502 
2503 	/*
2504 	 * Once parent is locked and matches our reptrack, our reptrack
2505 	 * will be stable and we have our parent.  We can unlink our
2506 	 * reptrack.
2507 	 *
2508 	 * WARNING!  Remember that the chain lock might be shared.  Chains
2509 	 *	     locked shared have stable parent linkages.
2510 	 */
2511 	hammer2_spin_ex(&parent->core.spin);
2512 	repp = &parent->core.reptrack;
2513 	while (*repp != &reptrack)
2514 		repp = &(*repp)->next;
2515 	*repp = reptrack.next;
2516 	hammer2_spin_unex(&parent->core.spin);
2517 
2518 	hammer2_chain_drop(parent);	/* reptrack ref */
2519 	*chainp = parent;		/* return parent lock+ref */
2520 
2521 	return parent;
2522 }
2523 
2524 /*
2525  * Dispose of any linked reptrack structures in (chain) by shifting them to
2526  * (parent).  Both (chain) and (parent) must be exclusively locked.
2527  *
2528  * This is interlocked against any children of (chain) on the other side.
2529  * No children so remain as-of when this is called so we can test
2530  * core.reptrack without holding the spin-lock.
2531  *
2532  * Used whenever the caller intends to permanently delete chains related
2533  * to topological recursions (BREF_TYPE_INDIRECT, BREF_TYPE_FREEMAP_NODE),
2534  * where the chains underneath the node being deleted are given a new parent
2535  * above the node being deleted.
2536  */
2537 static
2538 void
2539 hammer2_chain_repchange(hammer2_chain_t *parent, hammer2_chain_t *chain)
2540 {
2541 	struct hammer2_reptrack *reptrack;
2542 
2543 	KKASSERT(chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree));
2544 	while (chain->core.reptrack) {
2545 		hammer2_spin_ex(&parent->core.spin);
2546 		hammer2_spin_ex(&chain->core.spin);
2547 		reptrack = chain->core.reptrack;
2548 		if (reptrack == NULL) {
2549 			hammer2_spin_unex(&chain->core.spin);
2550 			hammer2_spin_unex(&parent->core.spin);
2551 			break;
2552 		}
2553 		hammer2_spin_ex(&reptrack->spin);
2554 		chain->core.reptrack = reptrack->next;
2555 		reptrack->chain = parent;
2556 		reptrack->next = parent->core.reptrack;
2557 		parent->core.reptrack = reptrack;
2558 		hammer2_chain_ref(parent);		/* reptrack */
2559 
2560 		hammer2_spin_unex(&chain->core.spin);
2561 		hammer2_spin_unex(&parent->core.spin);
2562 		kprintf("hammer2: debug repchange %p %p->%p\n",
2563 			reptrack, chain, parent);
2564 		hammer2_chain_drop(chain);		/* reptrack */
2565 	}
2566 }
2567 
2568 /*
2569  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2570  * (*parentp) typically points to an inode but can also point to a related
2571  * indirect block and this function will recurse upwards and find the inode
2572  * or the nearest undeleted indirect block covering the key range.
2573  *
2574  * This function unconditionally sets *errorp, replacing any previous value.
2575  *
2576  * (*parentp) must be exclusive or shared locked (depending on flags) and
2577  * referenced and can be an inode or an existing indirect block within the
2578  * inode.
2579  *
2580  * If (*parent) is errored out, this function will not attempt to recurse
2581  * the radix tree and will return NULL along with an appropriate *errorp.
2582  * If NULL is returned and *errorp is 0, the requested lookup could not be
2583  * located.
2584  *
2585  * On return (*parentp) will be modified to point at the deepest parent chain
2586  * element encountered during the search, as a helper for an insertion or
2587  * deletion.
2588  *
2589  * The new (*parentp) will be locked shared or exclusive (depending on flags),
2590  * and referenced, and the old will be unlocked and dereferenced (no change
2591  * if they are both the same).  This is particularly important if the caller
2592  * wishes to insert a new chain, (*parentp) will be set properly even if NULL
2593  * is returned, as long as no error occurred.
2594  *
2595  * The matching chain will be returned locked according to flags.
2596  *
2597  * --
2598  *
2599  * NULL is returned if no match was found, but (*parentp) will still
2600  * potentially be adjusted.
2601  *
2602  * On return (*key_nextp) will point to an iterative value for key_beg.
2603  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2604  *
2605  * This function will also recurse up the chain if the key is not within the
2606  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
2607  * can simply allow (*parentp) to float inside the loop.
2608  *
2609  * NOTE!  chain->data is not always resolved.  By default it will not be
2610  *	  resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
2611  *	  HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2612  *	  BREF_TYPE_DATA as the device buffer can alias the logical file
2613  *	  buffer).
2614  */
2615 hammer2_chain_t *
2616 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2617 		     hammer2_key_t key_beg, hammer2_key_t key_end,
2618 		     int *errorp, int flags)
2619 {
2620 	hammer2_chain_t *parent;
2621 	hammer2_chain_t *chain;
2622 	hammer2_blockref_t *base;
2623 	hammer2_blockref_t *bref;
2624 	hammer2_blockref_t bsave;
2625 	hammer2_key_t scan_beg;
2626 	hammer2_key_t scan_end;
2627 	int count = 0;
2628 	int how_always = HAMMER2_RESOLVE_ALWAYS;
2629 	int how_maybe = HAMMER2_RESOLVE_MAYBE;
2630 	int how;
2631 	int generation;
2632 	int maxloops = 300000;
2633 
2634 	if (flags & HAMMER2_LOOKUP_ALWAYS) {
2635 		how_maybe = how_always;
2636 		how = HAMMER2_RESOLVE_ALWAYS;
2637 	} else if (flags & HAMMER2_LOOKUP_NODATA) {
2638 		how = HAMMER2_RESOLVE_NEVER;
2639 	} else {
2640 		how = HAMMER2_RESOLVE_MAYBE;
2641 	}
2642 	if (flags & HAMMER2_LOOKUP_SHARED) {
2643 		how_maybe |= HAMMER2_RESOLVE_SHARED;
2644 		how_always |= HAMMER2_RESOLVE_SHARED;
2645 		how |= HAMMER2_RESOLVE_SHARED;
2646 	}
2647 
2648 	/*
2649 	 * Recurse (*parentp) upward if necessary until the parent completely
2650 	 * encloses the key range or we hit the inode.
2651 	 *
2652 	 * Handle races against the flusher deleting indirect nodes on its
2653 	 * way back up by continuing to recurse upward past the deletion.
2654 	 */
2655 	parent = *parentp;
2656 	*errorp = 0;
2657 
2658 	while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2659 	       parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2660 		scan_beg = parent->bref.key;
2661 		scan_end = scan_beg +
2662 			   ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2663 		if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2664 			if (key_beg >= scan_beg && key_end <= scan_end)
2665 				break;
2666 		}
2667 		parent = hammer2_chain_repparent(parentp, how_maybe);
2668 	}
2669 again:
2670 	if (--maxloops == 0)
2671 		panic("hammer2_chain_lookup: maxloops");
2672 
2673 	/*
2674 	 * MATCHIND case that does not require parent->data (do prior to
2675 	 * parent->error check).
2676 	 */
2677 	switch(parent->bref.type) {
2678 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2679 	case HAMMER2_BREF_TYPE_INDIRECT:
2680 		if (flags & HAMMER2_LOOKUP_MATCHIND) {
2681 			scan_beg = parent->bref.key;
2682 			scan_end = scan_beg +
2683 			       ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2684 			if (key_beg == scan_beg && key_end == scan_end) {
2685 				chain = parent;
2686 				hammer2_chain_ref(chain);
2687 				hammer2_chain_lock(chain, how_maybe);
2688 				*key_nextp = scan_end + 1;
2689 				goto done;
2690 			}
2691 		}
2692 		break;
2693 	default:
2694 		break;
2695 	}
2696 
2697 	/*
2698 	 * No lookup is possible if the parent is errored.  We delayed
2699 	 * this check as long as we could to ensure that the parent backup,
2700 	 * embedded data, and MATCHIND code could still execute.
2701 	 */
2702 	if (parent->error) {
2703 		*errorp = parent->error;
2704 		return NULL;
2705 	}
2706 
2707 	/*
2708 	 * Locate the blockref array.  Currently we do a fully associative
2709 	 * search through the array.
2710 	 */
2711 	switch(parent->bref.type) {
2712 	case HAMMER2_BREF_TYPE_INODE:
2713 		/*
2714 		 * Special shortcut for embedded data returns the inode
2715 		 * itself.  Callers must detect this condition and access
2716 		 * the embedded data (the strategy code does this for us).
2717 		 *
2718 		 * This is only applicable to regular files and softlinks.
2719 		 *
2720 		 * We need a second lock on parent.  Since we already have
2721 		 * a lock we must pass LOCKAGAIN to prevent unexpected
2722 		 * blocking (we don't want to block on a second shared
2723 		 * ref if an exclusive lock is pending)
2724 		 */
2725 		if (parent->data->ipdata.meta.op_flags &
2726 		    HAMMER2_OPFLAG_DIRECTDATA) {
2727 			if (flags & HAMMER2_LOOKUP_NODIRECT) {
2728 				chain = NULL;
2729 				*key_nextp = key_end + 1;
2730 				goto done;
2731 			}
2732 			hammer2_chain_ref(parent);
2733 			hammer2_chain_lock(parent, how_always |
2734 						   HAMMER2_RESOLVE_LOCKAGAIN);
2735 			*key_nextp = key_end + 1;
2736 			return (parent);
2737 		}
2738 		base = &parent->data->ipdata.u.blockset.blockref[0];
2739 		count = HAMMER2_SET_COUNT;
2740 		break;
2741 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2742 	case HAMMER2_BREF_TYPE_INDIRECT:
2743 		/*
2744 		 * Optimize indirect blocks in the INITIAL state to avoid
2745 		 * I/O.
2746 		 *
2747 		 * Debugging: Enter permanent wait state instead of
2748 		 * panicing on unexpectedly NULL data for the moment.
2749 		 */
2750 		if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2751 			base = NULL;
2752 		} else {
2753 			if (parent->data == NULL) {
2754 				kprintf("hammer2: unexpected NULL data "
2755 					"on %p\n", parent);
2756 				while (1)
2757 					tsleep(parent, 0, "xxx", 0);
2758 			}
2759 			base = &parent->data->npdata[0];
2760 		}
2761 		count = parent->bytes / sizeof(hammer2_blockref_t);
2762 		break;
2763 	case HAMMER2_BREF_TYPE_VOLUME:
2764 		base = &parent->data->voldata.sroot_blockset.blockref[0];
2765 		count = HAMMER2_SET_COUNT;
2766 		break;
2767 	case HAMMER2_BREF_TYPE_FREEMAP:
2768 		base = &parent->data->blkset.blockref[0];
2769 		count = HAMMER2_SET_COUNT;
2770 		break;
2771 	default:
2772 		panic("hammer2_chain_lookup: unrecognized "
2773 		      "blockref(B) type: %d",
2774 		      parent->bref.type);
2775 		base = NULL;	/* safety */
2776 		count = 0;	/* safety */
2777 		break;
2778 	}
2779 
2780 	/*
2781 	 * Merged scan to find next candidate.
2782 	 *
2783 	 * hammer2_base_*() functions require the parent->core.live_* fields
2784 	 * to be synchronized.
2785 	 *
2786 	 * We need to hold the spinlock to access the block array and RB tree
2787 	 * and to interlock chain creation.
2788 	 */
2789 	if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2790 		hammer2_chain_countbrefs(parent, base, count);
2791 
2792 	/*
2793 	 * Combined search
2794 	 */
2795 	hammer2_spin_ex(&parent->core.spin);
2796 	chain = hammer2_combined_find(parent, base, count,
2797 				      key_nextp,
2798 				      key_beg, key_end,
2799 				      &bref);
2800 	generation = parent->core.generation;
2801 
2802 	/*
2803 	 * Exhausted parent chain, iterate.
2804 	 */
2805 	if (bref == NULL) {
2806 		KKASSERT(chain == NULL);
2807 		hammer2_spin_unex(&parent->core.spin);
2808 		if (key_beg == key_end)	/* short cut single-key case */
2809 			return (NULL);
2810 
2811 		/*
2812 		 * Stop if we reached the end of the iteration.
2813 		 */
2814 		if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2815 		    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2816 			return (NULL);
2817 		}
2818 
2819 		/*
2820 		 * Calculate next key, stop if we reached the end of the
2821 		 * iteration, otherwise go up one level and loop.
2822 		 */
2823 		key_beg = parent->bref.key +
2824 			  ((hammer2_key_t)1 << parent->bref.keybits);
2825 		if (key_beg == 0 || key_beg > key_end)
2826 			return (NULL);
2827 		parent = hammer2_chain_repparent(parentp, how_maybe);
2828 		goto again;
2829 	}
2830 
2831 	/*
2832 	 * Selected from blockref or in-memory chain.
2833 	 */
2834 	bsave = *bref;
2835 	if (chain == NULL) {
2836 		hammer2_spin_unex(&parent->core.spin);
2837 		if (bsave.type == HAMMER2_BREF_TYPE_INDIRECT ||
2838 		    bsave.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2839 			chain = hammer2_chain_get(parent, generation,
2840 						  &bsave, how_maybe);
2841 		} else {
2842 			chain = hammer2_chain_get(parent, generation,
2843 						  &bsave, how);
2844 		}
2845 		if (chain == NULL)
2846 			goto again;
2847 	} else {
2848 		hammer2_chain_ref(chain);
2849 		hammer2_spin_unex(&parent->core.spin);
2850 
2851 		/*
2852 		 * chain is referenced but not locked.  We must lock the
2853 		 * chain to obtain definitive state.
2854 		 */
2855 		if (bsave.type == HAMMER2_BREF_TYPE_INDIRECT ||
2856 		    bsave.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2857 			hammer2_chain_lock(chain, how_maybe);
2858 		} else {
2859 			hammer2_chain_lock(chain, how);
2860 		}
2861 		KKASSERT(chain->parent == parent);
2862 	}
2863 	if (bcmp(&bsave, &chain->bref, sizeof(bsave)) ||
2864 	    chain->parent != parent) {
2865 		hammer2_chain_unlock(chain);
2866 		hammer2_chain_drop(chain);
2867 		chain = NULL;	/* SAFETY */
2868 		goto again;
2869 	}
2870 
2871 
2872 	/*
2873 	 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2874 	 *
2875 	 * NOTE: Chain's key range is not relevant as there might be
2876 	 *	 one-offs within the range that are not deleted.
2877 	 *
2878 	 * NOTE: Lookups can race delete-duplicate because
2879 	 *	 delete-duplicate does not lock the parent's core
2880 	 *	 (they just use the spinlock on the core).
2881 	 */
2882 	if (chain->flags & HAMMER2_CHAIN_DELETED) {
2883 		kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2884 			chain->bref.data_off, chain->bref.type,
2885 			chain->bref.key);
2886 		hammer2_chain_unlock(chain);
2887 		hammer2_chain_drop(chain);
2888 		chain = NULL;	/* SAFETY */
2889 		key_beg = *key_nextp;
2890 		if (key_beg == 0 || key_beg > key_end)
2891 			return(NULL);
2892 		goto again;
2893 	}
2894 
2895 	/*
2896 	 * If the chain element is an indirect block it becomes the new
2897 	 * parent and we loop on it.  We must maintain our top-down locks
2898 	 * to prevent the flusher from interfering (i.e. doing a
2899 	 * delete-duplicate and leaving us recursing down a deleted chain).
2900 	 *
2901 	 * The parent always has to be locked with at least RESOLVE_MAYBE
2902 	 * so we can access its data.  It might need a fixup if the caller
2903 	 * passed incompatible flags.  Be careful not to cause a deadlock
2904 	 * as a data-load requires an exclusive lock.
2905 	 *
2906 	 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2907 	 * range is within the requested key range we return the indirect
2908 	 * block and do NOT loop.  This is usually only used to acquire
2909 	 * freemap nodes.
2910 	 */
2911 	if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2912 	    chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2913 		hammer2_chain_unlock(parent);
2914 		hammer2_chain_drop(parent);
2915 		*parentp = parent = chain;
2916 		chain = NULL;	/* SAFETY */
2917 		goto again;
2918 	}
2919 done:
2920 	/*
2921 	 * All done, return the locked chain.
2922 	 *
2923 	 * If the caller does not want a locked chain, replace the lock with
2924 	 * a ref.  Perhaps this can eventually be optimized to not obtain the
2925 	 * lock in the first place for situations where the data does not
2926 	 * need to be resolved.
2927 	 *
2928 	 * NOTE! A chain->error must be tested by the caller upon return.
2929 	 *	 *errorp is only set based on issues which occur while
2930 	 *	 trying to reach the chain.
2931 	 */
2932 	return (chain);
2933 }
2934 
2935 /*
2936  * After having issued a lookup we can iterate all matching keys.
2937  *
2938  * If chain is non-NULL we continue the iteration from just after it's index.
2939  *
2940  * If chain is NULL we assume the parent was exhausted and continue the
2941  * iteration at the next parent.
2942  *
2943  * If a fatal error occurs (typically an I/O error), a dummy chain is
2944  * returned with chain->error and error-identifying information set.  This
2945  * chain will assert if you try to do anything fancy with it.
2946  *
2947  * XXX Depending on where the error occurs we should allow continued iteration.
2948  *
2949  * parent must be locked on entry and remains locked throughout.  chain's
2950  * lock status must match flags.  Chain is always at least referenced.
2951  *
2952  * WARNING!  The MATCHIND flag does not apply to this function.
2953  */
2954 hammer2_chain_t *
2955 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2956 		   hammer2_key_t *key_nextp,
2957 		   hammer2_key_t key_beg, hammer2_key_t key_end,
2958 		   int *errorp, int flags)
2959 {
2960 	hammer2_chain_t *parent;
2961 	int how_maybe;
2962 
2963 	/*
2964 	 * Calculate locking flags for upward recursion.
2965 	 */
2966 	how_maybe = HAMMER2_RESOLVE_MAYBE;
2967 	if (flags & HAMMER2_LOOKUP_SHARED)
2968 		how_maybe |= HAMMER2_RESOLVE_SHARED;
2969 
2970 	parent = *parentp;
2971 	*errorp = 0;
2972 
2973 	/*
2974 	 * Calculate the next index and recalculate the parent if necessary.
2975 	 */
2976 	if (chain) {
2977 		key_beg = chain->bref.key +
2978 			  ((hammer2_key_t)1 << chain->bref.keybits);
2979 		hammer2_chain_unlock(chain);
2980 		hammer2_chain_drop(chain);
2981 
2982 		/*
2983 		 * chain invalid past this point, but we can still do a
2984 		 * pointer comparison w/parent.
2985 		 *
2986 		 * Any scan where the lookup returned degenerate data embedded
2987 		 * in the inode has an invalid index and must terminate.
2988 		 */
2989 		if (chain == parent)
2990 			return(NULL);
2991 		if (key_beg == 0 || key_beg > key_end)
2992 			return(NULL);
2993 		chain = NULL;
2994 	} else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2995 		   parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2996 		/*
2997 		 * We reached the end of the iteration.
2998 		 */
2999 		return (NULL);
3000 	} else {
3001 		/*
3002 		 * Continue iteration with next parent unless the current
3003 		 * parent covers the range.
3004 		 *
3005 		 * (This also handles the case of a deleted, empty indirect
3006 		 * node).
3007 		 */
3008 		key_beg = parent->bref.key +
3009 			  ((hammer2_key_t)1 << parent->bref.keybits);
3010 		if (key_beg == 0 || key_beg > key_end)
3011 			return (NULL);
3012 		parent = hammer2_chain_repparent(parentp, how_maybe);
3013 	}
3014 
3015 	/*
3016 	 * And execute
3017 	 */
3018 	return (hammer2_chain_lookup(parentp, key_nextp,
3019 				     key_beg, key_end,
3020 				     errorp, flags));
3021 }
3022 
3023 /*
3024  * Caller wishes to iterate chains under parent, loading new chains into
3025  * chainp.  Caller must initialize *chainp to NULL and *firstp to 1, and
3026  * then call hammer2_chain_scan() repeatedly until a non-zero return.
3027  * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
3028  * with the returned chain for the scan.  The returned *chainp will be
3029  * locked and referenced.  Any prior contents will be unlocked and dropped.
3030  *
3031  * Caller should check the return value.  A normal scan EOF will return
3032  * exactly HAMMER2_ERROR_EOF.  Any other non-zero value indicates an
3033  * error trying to access parent data.  Any error in the returned chain
3034  * must be tested separately by the caller.
3035  *
3036  * (*chainp) is dropped on each scan, but will only be set if the returned
3037  * element itself can recurse.  Leaf elements are NOT resolved, loaded, or
3038  * returned via *chainp.  The caller will get their bref only.
3039  *
3040  * The raw scan function is similar to lookup/next but does not seek to a key.
3041  * Blockrefs are iterated via first_bref = (parent, NULL) and
3042  * next_chain = (parent, bref).
3043  *
3044  * The passed-in parent must be locked and its data resolved.  The function
3045  * nominally returns a locked and referenced *chainp != NULL for chains
3046  * the caller might need to recurse on (and will dipose of any *chainp passed
3047  * in).  The caller must check the chain->bref.type either way.
3048  */
3049 int
3050 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
3051 		   hammer2_blockref_t *bref, int *firstp,
3052 		   int flags)
3053 {
3054 	hammer2_blockref_t *base;
3055 	hammer2_blockref_t *bref_ptr;
3056 	hammer2_key_t key;
3057 	hammer2_key_t next_key;
3058 	hammer2_chain_t *chain = NULL;
3059 	int count = 0;
3060 	int how;
3061 	int generation;
3062 	int maxloops = 300000;
3063 	int error;
3064 
3065 	error = 0;
3066 
3067 	/*
3068 	 * Scan flags borrowed from lookup.
3069 	 */
3070 	if (flags & HAMMER2_LOOKUP_ALWAYS) {
3071 		how = HAMMER2_RESOLVE_ALWAYS;
3072 	} else if (flags & HAMMER2_LOOKUP_NODATA) {
3073 		how = HAMMER2_RESOLVE_NEVER;
3074 	} else {
3075 		how = HAMMER2_RESOLVE_MAYBE;
3076 	}
3077 	if (flags & HAMMER2_LOOKUP_SHARED) {
3078 		how |= HAMMER2_RESOLVE_SHARED;
3079 	}
3080 
3081 	/*
3082 	 * Calculate key to locate first/next element, unlocking the previous
3083 	 * element as we go.  Be careful, the key calculation can overflow.
3084 	 *
3085 	 * (also reset bref to NULL)
3086 	 */
3087 	if (*firstp) {
3088 		key = 0;
3089 		*firstp = 0;
3090 	} else {
3091 		key = bref->key + ((hammer2_key_t)1 << bref->keybits);
3092 		if ((chain = *chainp) != NULL) {
3093 			*chainp = NULL;
3094 			hammer2_chain_unlock(chain);
3095 			hammer2_chain_drop(chain);
3096 			chain = NULL;
3097 		}
3098 		if (key == 0) {
3099 			error |= HAMMER2_ERROR_EOF;
3100 			goto done;
3101 		}
3102 	}
3103 
3104 again:
3105 	if (parent->error) {
3106 		error = parent->error;
3107 		goto done;
3108 	}
3109 	if (--maxloops == 0)
3110 		panic("hammer2_chain_scan: maxloops");
3111 
3112 	/*
3113 	 * Locate the blockref array.  Currently we do a fully associative
3114 	 * search through the array.
3115 	 */
3116 	switch(parent->bref.type) {
3117 	case HAMMER2_BREF_TYPE_INODE:
3118 		/*
3119 		 * An inode with embedded data has no sub-chains.
3120 		 *
3121 		 * WARNING! Bulk scan code may pass a static chain marked
3122 		 *	    as BREF_TYPE_INODE with a copy of the volume
3123 		 *	    root blockset to snapshot the volume.
3124 		 */
3125 		if (parent->data->ipdata.meta.op_flags &
3126 		    HAMMER2_OPFLAG_DIRECTDATA) {
3127 			error |= HAMMER2_ERROR_EOF;
3128 			goto done;
3129 		}
3130 		base = &parent->data->ipdata.u.blockset.blockref[0];
3131 		count = HAMMER2_SET_COUNT;
3132 		break;
3133 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3134 	case HAMMER2_BREF_TYPE_INDIRECT:
3135 		/*
3136 		 * Optimize indirect blocks in the INITIAL state to avoid
3137 		 * I/O.
3138 		 */
3139 		if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3140 			base = NULL;
3141 		} else {
3142 			if (parent->data == NULL)
3143 				panic("parent->data is NULL");
3144 			base = &parent->data->npdata[0];
3145 		}
3146 		count = parent->bytes / sizeof(hammer2_blockref_t);
3147 		break;
3148 	case HAMMER2_BREF_TYPE_VOLUME:
3149 		base = &parent->data->voldata.sroot_blockset.blockref[0];
3150 		count = HAMMER2_SET_COUNT;
3151 		break;
3152 	case HAMMER2_BREF_TYPE_FREEMAP:
3153 		base = &parent->data->blkset.blockref[0];
3154 		count = HAMMER2_SET_COUNT;
3155 		break;
3156 	default:
3157 		panic("hammer2_chain_scan: unrecognized blockref type: %d",
3158 		      parent->bref.type);
3159 		base = NULL;	/* safety */
3160 		count = 0;	/* safety */
3161 		break;
3162 	}
3163 
3164 	/*
3165 	 * Merged scan to find next candidate.
3166 	 *
3167 	 * hammer2_base_*() functions require the parent->core.live_* fields
3168 	 * to be synchronized.
3169 	 *
3170 	 * We need to hold the spinlock to access the block array and RB tree
3171 	 * and to interlock chain creation.
3172 	 */
3173 	if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3174 		hammer2_chain_countbrefs(parent, base, count);
3175 
3176 	next_key = 0;
3177 	bref_ptr = NULL;
3178 	hammer2_spin_ex(&parent->core.spin);
3179 	chain = hammer2_combined_find(parent, base, count,
3180 				      &next_key,
3181 				      key, HAMMER2_KEY_MAX,
3182 				      &bref_ptr);
3183 	generation = parent->core.generation;
3184 
3185 	/*
3186 	 * Exhausted parent chain, we're done.
3187 	 */
3188 	if (bref_ptr == NULL) {
3189 		hammer2_spin_unex(&parent->core.spin);
3190 		KKASSERT(chain == NULL);
3191 		error |= HAMMER2_ERROR_EOF;
3192 		goto done;
3193 	}
3194 
3195 	/*
3196 	 * Copy into the supplied stack-based blockref.
3197 	 */
3198 	*bref = *bref_ptr;
3199 
3200 	/*
3201 	 * Selected from blockref or in-memory chain.
3202 	 */
3203 	if (chain == NULL) {
3204 		switch(bref->type) {
3205 		case HAMMER2_BREF_TYPE_INODE:
3206 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3207 		case HAMMER2_BREF_TYPE_INDIRECT:
3208 		case HAMMER2_BREF_TYPE_VOLUME:
3209 		case HAMMER2_BREF_TYPE_FREEMAP:
3210 			/*
3211 			 * Recursion, always get the chain
3212 			 */
3213 			hammer2_spin_unex(&parent->core.spin);
3214 			chain = hammer2_chain_get(parent, generation,
3215 						  bref, how);
3216 			if (chain == NULL)
3217 				goto again;
3218 			break;
3219 		default:
3220 			/*
3221 			 * No recursion, do not waste time instantiating
3222 			 * a chain, just iterate using the bref.
3223 			 */
3224 			hammer2_spin_unex(&parent->core.spin);
3225 			break;
3226 		}
3227 	} else {
3228 		/*
3229 		 * Recursion or not we need the chain in order to supply
3230 		 * the bref.
3231 		 */
3232 		hammer2_chain_ref(chain);
3233 		hammer2_spin_unex(&parent->core.spin);
3234 		hammer2_chain_lock(chain, how);
3235 	}
3236 	if (chain &&
3237 	    (bcmp(bref, &chain->bref, sizeof(*bref)) ||
3238 	     chain->parent != parent)) {
3239 		hammer2_chain_unlock(chain);
3240 		hammer2_chain_drop(chain);
3241 		chain = NULL;
3242 		goto again;
3243 	}
3244 
3245 	/*
3246 	 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
3247 	 *
3248 	 * NOTE: chain's key range is not relevant as there might be
3249 	 *	 one-offs within the range that are not deleted.
3250 	 *
3251 	 * NOTE: XXX this could create problems with scans used in
3252 	 *	 situations other than mount-time recovery.
3253 	 *
3254 	 * NOTE: Lookups can race delete-duplicate because
3255 	 *	 delete-duplicate does not lock the parent's core
3256 	 *	 (they just use the spinlock on the core).
3257 	 */
3258 	if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3259 		hammer2_chain_unlock(chain);
3260 		hammer2_chain_drop(chain);
3261 		chain = NULL;
3262 
3263 		key = next_key;
3264 		if (key == 0) {
3265 			error |= HAMMER2_ERROR_EOF;
3266 			goto done;
3267 		}
3268 		goto again;
3269 	}
3270 
3271 done:
3272 	/*
3273 	 * All done, return the bref or NULL, supply chain if necessary.
3274 	 */
3275 	if (chain)
3276 		*chainp = chain;
3277 	return (error);
3278 }
3279 
3280 /*
3281  * Create and return a new hammer2 system memory structure of the specified
3282  * key, type and size and insert it under (*parentp).  This is a full
3283  * insertion, based on the supplied key/keybits, and may involve creating
3284  * indirect blocks and moving other chains around via delete/duplicate.
3285  *
3286  * This call can be made with parent == NULL as long as a non -1 methods
3287  * is supplied.  hmp must also be supplied in this situation (otherwise
3288  * hmp is extracted from the supplied parent).  The chain will be detached
3289  * from the topology.  A later call with both parent and chain can be made
3290  * to attach it.
3291  *
3292  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
3293  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3294  * FULL.  This typically means that the caller is creating the chain after
3295  * doing a hammer2_chain_lookup().
3296  *
3297  * (*parentp) must be exclusive locked and may be replaced on return
3298  * depending on how much work the function had to do.
3299  *
3300  * (*parentp) must not be errored or this function will assert.
3301  *
3302  * (*chainp) usually starts out NULL and returns the newly created chain,
3303  * but if the caller desires the caller may allocate a disconnected chain
3304  * and pass it in instead.
3305  *
3306  * This function should NOT be used to insert INDIRECT blocks.  It is
3307  * typically used to create/insert inodes and data blocks.
3308  *
3309  * Caller must pass-in an exclusively locked parent the new chain is to
3310  * be inserted under, and optionally pass-in a disconnected, exclusively
3311  * locked chain to insert (else we create a new chain).  The function will
3312  * adjust (*parentp) as necessary, create or connect the chain, and
3313  * return an exclusively locked chain in *chainp.
3314  *
3315  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
3316  * and will be reassigned.
3317  *
3318  * NOTE: returns HAMMER_ERROR_* flags
3319  */
3320 int
3321 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
3322 		     hammer2_dev_t *hmp, hammer2_pfs_t *pmp, int methods,
3323 		     hammer2_key_t key, int keybits, int type, size_t bytes,
3324 		     hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
3325 {
3326 	hammer2_chain_t *chain;
3327 	hammer2_chain_t *parent;
3328 	hammer2_blockref_t *base;
3329 	hammer2_blockref_t dummy;
3330 	int allocated = 0;
3331 	int error = 0;
3332 	int count;
3333 	int maxloops = 300000;
3334 
3335 	/*
3336 	 * Topology may be crossing a PFS boundary.
3337 	 */
3338 	parent = *parentp;
3339 	if (parent) {
3340 		KKASSERT(hammer2_mtx_owned(&parent->lock));
3341 		KKASSERT(parent->error == 0);
3342 		hmp = parent->hmp;
3343 	}
3344 	chain = *chainp;
3345 
3346 	if (chain == NULL) {
3347 		/*
3348 		 * First allocate media space and construct the dummy bref,
3349 		 * then allocate the in-memory chain structure.  Set the
3350 		 * INITIAL flag for fresh chains which do not have embedded
3351 		 * data.
3352 		 */
3353 		bzero(&dummy, sizeof(dummy));
3354 		dummy.type = type;
3355 		dummy.key = key;
3356 		dummy.keybits = keybits;
3357 		dummy.data_off = hammer2_getradix(bytes);
3358 
3359 		/*
3360 		 * Inherit methods from parent by default.  Primarily used
3361 		 * for BREF_TYPE_DATA.  Non-data types *must* be set to
3362 		 * a non-NONE check algorithm.
3363 		 */
3364 		if (methods == HAMMER2_METH_DEFAULT)
3365 			dummy.methods = parent->bref.methods;
3366 		else
3367 			dummy.methods = (uint8_t)methods;
3368 
3369 		if (type != HAMMER2_BREF_TYPE_DATA &&
3370 		    HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3371 			dummy.methods |=
3372 				HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3373 		}
3374 
3375 		chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3376 
3377 		/*
3378 		 * Lock the chain manually, chain_lock will load the chain
3379 		 * which we do NOT want to do.  (note: chain->refs is set
3380 		 * to 1 by chain_alloc() for us, but lockcnt is not).
3381 		 */
3382 		chain->lockcnt = 1;
3383 		hammer2_mtx_ex(&chain->lock);
3384 		allocated = 1;
3385 
3386 		/*
3387 		 * Set INITIAL to optimize I/O.  The flag will generally be
3388 		 * processed when we call hammer2_chain_modify().
3389 		 */
3390 		switch(type) {
3391 		case HAMMER2_BREF_TYPE_VOLUME:
3392 		case HAMMER2_BREF_TYPE_FREEMAP:
3393 			panic("hammer2_chain_create: called with volume type");
3394 			break;
3395 		case HAMMER2_BREF_TYPE_INDIRECT:
3396 			panic("hammer2_chain_create: cannot be used to"
3397 			      "create indirect block");
3398 			break;
3399 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3400 			panic("hammer2_chain_create: cannot be used to"
3401 			      "create freemap root or node");
3402 			break;
3403 		case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3404 			KKASSERT(bytes == sizeof(chain->data->bmdata));
3405 			/* fall through */
3406 		case HAMMER2_BREF_TYPE_DIRENT:
3407 		case HAMMER2_BREF_TYPE_INODE:
3408 		case HAMMER2_BREF_TYPE_DATA:
3409 		default:
3410 			/*
3411 			 * leave chain->data NULL, set INITIAL
3412 			 */
3413 			KKASSERT(chain->data == NULL);
3414 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3415 			break;
3416 		}
3417 	} else {
3418 		/*
3419 		 * We are reattaching a previously deleted chain, possibly
3420 		 * under a new parent and possibly with a new key/keybits.
3421 		 * The chain does not have to be in a modified state.  The
3422 		 * UPDATE flag will be set later on in this routine.
3423 		 *
3424 		 * Do NOT mess with the current state of the INITIAL flag.
3425 		 */
3426 		chain->bref.key = key;
3427 		chain->bref.keybits = keybits;
3428 		if (chain->flags & HAMMER2_CHAIN_DELETED)
3429 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3430 		KKASSERT(chain->parent == NULL);
3431 	}
3432 
3433 	/*
3434 	 * Set the appropriate bref flag if requested.
3435 	 *
3436 	 * NOTE! Callers can call this function to move chains without
3437 	 *	 knowing about special flags, so don't clear bref flags
3438 	 *	 here!
3439 	 */
3440 	if (flags & HAMMER2_INSERT_PFSROOT)
3441 		chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3442 
3443 	if (parent == NULL)
3444 		goto skip;
3445 
3446 	/*
3447 	 * Calculate how many entries we have in the blockref array and
3448 	 * determine if an indirect block is required when inserting into
3449 	 * the parent.
3450 	 */
3451 again:
3452 	if (--maxloops == 0)
3453 		panic("hammer2_chain_create: maxloops");
3454 
3455 	switch(parent->bref.type) {
3456 	case HAMMER2_BREF_TYPE_INODE:
3457 		if ((parent->data->ipdata.meta.op_flags &
3458 		     HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3459 			kprintf("hammer2: parent set for direct-data! "
3460 				"pkey=%016jx ckey=%016jx\n",
3461 				parent->bref.key,
3462 				chain->bref.key);
3463 	        }
3464 		KKASSERT((parent->data->ipdata.meta.op_flags &
3465 			  HAMMER2_OPFLAG_DIRECTDATA) == 0);
3466 		KKASSERT(parent->data != NULL);
3467 		base = &parent->data->ipdata.u.blockset.blockref[0];
3468 		count = HAMMER2_SET_COUNT;
3469 		break;
3470 	case HAMMER2_BREF_TYPE_INDIRECT:
3471 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3472 		if (parent->flags & HAMMER2_CHAIN_INITIAL)
3473 			base = NULL;
3474 		else
3475 			base = &parent->data->npdata[0];
3476 		count = parent->bytes / sizeof(hammer2_blockref_t);
3477 		break;
3478 	case HAMMER2_BREF_TYPE_VOLUME:
3479 		KKASSERT(parent->data != NULL);
3480 		base = &parent->data->voldata.sroot_blockset.blockref[0];
3481 		count = HAMMER2_SET_COUNT;
3482 		break;
3483 	case HAMMER2_BREF_TYPE_FREEMAP:
3484 		KKASSERT(parent->data != NULL);
3485 		base = &parent->data->blkset.blockref[0];
3486 		count = HAMMER2_SET_COUNT;
3487 		break;
3488 	default:
3489 		panic("hammer2_chain_create: unrecognized blockref type: %d",
3490 		      parent->bref.type);
3491 		base = NULL;
3492 		count = 0;
3493 		break;
3494 	}
3495 
3496 	/*
3497 	 * Make sure we've counted the brefs
3498 	 */
3499 	if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3500 		hammer2_chain_countbrefs(parent, base, count);
3501 
3502 	KASSERT(parent->core.live_count >= 0 &&
3503 		parent->core.live_count <= count,
3504 		("bad live_count %d/%d (%02x, %d)",
3505 			parent->core.live_count, count,
3506 			parent->bref.type, parent->bytes));
3507 
3508 	/*
3509 	 * If no free blockref could be found we must create an indirect
3510 	 * block and move a number of blockrefs into it.  With the parent
3511 	 * locked we can safely lock each child in order to delete+duplicate
3512 	 * it without causing a deadlock.
3513 	 *
3514 	 * This may return the new indirect block or the old parent depending
3515 	 * on where the key falls.  NULL is returned on error.
3516 	 */
3517 	if (parent->core.live_count == count) {
3518 		hammer2_chain_t *nparent;
3519 
3520 		KKASSERT((flags & HAMMER2_INSERT_SAMEPARENT) == 0);
3521 
3522 		nparent = hammer2_chain_create_indirect(parent, key, keybits,
3523 							mtid, type, &error);
3524 		if (nparent == NULL) {
3525 			if (allocated)
3526 				hammer2_chain_drop(chain);
3527 			chain = NULL;
3528 			goto done;
3529 		}
3530 		if (parent != nparent) {
3531 			hammer2_chain_unlock(parent);
3532 			hammer2_chain_drop(parent);
3533 			parent = *parentp = nparent;
3534 		}
3535 		goto again;
3536 	}
3537 
3538 	/*
3539 	 * fall through if parent, or skip to here if no parent.
3540 	 */
3541 skip:
3542 	if (chain->flags & HAMMER2_CHAIN_DELETED)
3543 		kprintf("Inserting deleted chain @%016jx\n",
3544 			chain->bref.key);
3545 
3546 	/*
3547 	 * Link the chain into its parent.
3548 	 */
3549 	if (chain->parent != NULL)
3550 		panic("hammer2: hammer2_chain_create: chain already connected");
3551 	KKASSERT(chain->parent == NULL);
3552 	if (parent) {
3553 		KKASSERT(parent->core.live_count < count);
3554 		hammer2_chain_insert(parent, chain,
3555 				     HAMMER2_CHAIN_INSERT_SPIN |
3556 				     HAMMER2_CHAIN_INSERT_LIVE,
3557 				     0);
3558 	}
3559 
3560 	if (allocated) {
3561 		/*
3562 		 * Mark the newly created chain modified.  This will cause
3563 		 * UPDATE to be set and process the INITIAL flag.
3564 		 *
3565 		 * Device buffers are not instantiated for DATA elements
3566 		 * as these are handled by logical buffers.
3567 		 *
3568 		 * Indirect and freemap node indirect blocks are handled
3569 		 * by hammer2_chain_create_indirect() and not by this
3570 		 * function.
3571 		 *
3572 		 * Data for all other bref types is expected to be
3573 		 * instantiated (INODE, LEAF).
3574 		 */
3575 		switch(chain->bref.type) {
3576 		case HAMMER2_BREF_TYPE_DATA:
3577 		case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3578 		case HAMMER2_BREF_TYPE_DIRENT:
3579 		case HAMMER2_BREF_TYPE_INODE:
3580 			error = hammer2_chain_modify(chain, mtid, dedup_off,
3581 						     HAMMER2_MODIFY_OPTDATA);
3582 			break;
3583 		default:
3584 			/*
3585 			 * Remaining types are not supported by this function.
3586 			 * In particular, INDIRECT and LEAF_NODE types are
3587 			 * handled by create_indirect().
3588 			 */
3589 			panic("hammer2_chain_create: bad type: %d",
3590 			      chain->bref.type);
3591 			/* NOT REACHED */
3592 			break;
3593 		}
3594 	} else {
3595 		/*
3596 		 * When reconnecting a chain we must set UPDATE and
3597 		 * setflush so the flush recognizes that it must update
3598 		 * the bref in the parent.
3599 		 */
3600 		if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3601 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3602 	}
3603 
3604 	/*
3605 	 * We must setflush(parent) to ensure that it recurses through to
3606 	 * chain.  setflush(chain) might not work because ONFLUSH is possibly
3607 	 * already set in the chain (so it won't recurse up to set it in the
3608 	 * parent).
3609 	 */
3610 	if (parent)
3611 		hammer2_chain_setflush(parent);
3612 
3613 done:
3614 	*chainp = chain;
3615 
3616 	return (error);
3617 }
3618 
3619 /*
3620  * Move the chain from its old parent to a new parent.  The chain must have
3621  * already been deleted or already disconnected (or never associated) with
3622  * a parent.  The chain is reassociated with the new parent and the deleted
3623  * flag will be cleared (no longer deleted).  The chain's modification state
3624  * is not altered.
3625  *
3626  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3627  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3628  * FULL.  This typically means that the caller is creating the chain after
3629  * doing a hammer2_chain_lookup().
3630  *
3631  * Neither (parent) or (chain) can be errored.
3632  *
3633  * If (parent) is non-NULL then the chain is inserted under the parent.
3634  *
3635  * If (parent) is NULL then the newly duplicated chain is not inserted
3636  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3637  * passing into hammer2_chain_create() after this function returns).
3638  *
3639  * WARNING! This function calls create which means it can insert indirect
3640  *	    blocks.  This can cause other unrelated chains in the parent to
3641  *	    be moved to a newly inserted indirect block in addition to the
3642  *	    specific chain.
3643  */
3644 void
3645 hammer2_chain_rename(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3646 		     hammer2_tid_t mtid, int flags)
3647 {
3648 	hammer2_blockref_t *bref;
3649 	hammer2_chain_t *parent;
3650 
3651 	/*
3652 	 * WARNING!  We should never resolve DATA to device buffers
3653 	 *	     (XXX allow it if the caller did?), and since
3654 	 *	     we currently do not have the logical buffer cache
3655 	 *	     buffer in-hand to fix its cached physical offset
3656 	 *	     we also force the modify code to not COW it. XXX
3657 	 *
3658 	 * NOTE!     We allow error'd chains to be renamed.  The bref itself
3659 	 *	     is good and can be renamed.  The content, however, may
3660 	 *	     be inaccessible.
3661 	 */
3662 	KKASSERT(chain->parent == NULL);
3663 	/*KKASSERT(chain->error == 0); allow */
3664 	bref = &chain->bref;
3665 
3666 	/*
3667 	 * If parent is not NULL the duplicated chain will be entered under
3668 	 * the parent and the UPDATE bit set to tell flush to update
3669 	 * the blockref.
3670 	 *
3671 	 * We must setflush(parent) to ensure that it recurses through to
3672 	 * chain.  setflush(chain) might not work because ONFLUSH is possibly
3673 	 * already set in the chain (so it won't recurse up to set it in the
3674 	 * parent).
3675 	 *
3676 	 * Having both chains locked is extremely important for atomicy.
3677 	 */
3678 	if (parentp && (parent = *parentp) != NULL) {
3679 		KKASSERT(hammer2_mtx_owned(&parent->lock));
3680 		KKASSERT(parent->refs > 0);
3681 		KKASSERT(parent->error == 0);
3682 
3683 		hammer2_chain_create(parentp, &chain, NULL, chain->pmp,
3684 				     HAMMER2_METH_DEFAULT,
3685 				     bref->key, bref->keybits, bref->type,
3686 				     chain->bytes, mtid, 0, flags);
3687 		KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3688 		hammer2_chain_setflush(*parentp);
3689 	}
3690 }
3691 
3692 /*
3693  * This works in tandem with delete_obref() to install a blockref in
3694  * (typically) an indirect block that is associated with the chain being
3695  * moved to *parentp.
3696  *
3697  * The reason we need this function is that the caller needs to maintain
3698  * the blockref as it was, and not generate a new blockref for what might
3699  * be a modified chain.  Otherwise stuff will leak into the flush that
3700  * the flush code's FLUSH_INODE_STOP flag is unable to catch.
3701  *
3702  * It is EXTREMELY important that we properly set CHAIN_BLKMAPUPD and
3703  * CHAIN_UPDATE.  We must set BLKMAPUPD if the bref does not match, and
3704  * we must clear CHAIN_UPDATE (that was likely set by the chain_rename) if
3705  * it does.  Otherwise we can end up in a situation where H2 is unable to
3706  * clean up the in-memory chain topology.
3707  *
3708  * The reason for this is that flushes do not generally flush through
3709  * BREF_TYPE_INODE chains and depend on a hammer2_inode_t queued to syncq
3710  * or sideq to properly flush and dispose of the related inode chain's flags.
3711  * Situations where the inode is not actually modified by the frontend,
3712  * but where we have to move the related chains around as we insert or cleanup
3713  * indirect blocks, can leave us with a 'dirty' (non-disposable) in-memory
3714  * inode chain that does not have a hammer2_inode_t associated with it.
3715  */
3716 static void
3717 hammer2_chain_rename_obref(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3718 			   hammer2_tid_t mtid, int flags,
3719 			   hammer2_blockref_t *obref)
3720 {
3721 	hammer2_chain_rename(parentp, chain, mtid, flags);
3722 
3723 	if (obref->type != HAMMER2_BREF_TYPE_EMPTY) {
3724 		hammer2_blockref_t *tbase;
3725 		int tcount;
3726 
3727 		KKASSERT((chain->flags & HAMMER2_CHAIN_BLKMAPPED) == 0);
3728 		hammer2_chain_modify(*parentp, mtid, 0, 0);
3729 		tbase = hammer2_chain_base_and_count(*parentp, &tcount);
3730 		hammer2_base_insert(*parentp, tbase, tcount, chain, obref);
3731 		if (bcmp(obref, &chain->bref, sizeof(chain->bref))) {
3732 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_BLKMAPUPD |
3733 						      HAMMER2_CHAIN_UPDATE);
3734 		} else {
3735 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3736 		}
3737 	}
3738 }
3739 
3740 /*
3741  * Helper function for deleting chains.
3742  *
3743  * The chain is removed from the live view (the RBTREE) as well as the parent's
3744  * blockmap.  Both chain and its parent must be locked.
3745  *
3746  * parent may not be errored.  chain can be errored.
3747  */
3748 static int
3749 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3750 			     hammer2_tid_t mtid, int flags,
3751 			     hammer2_blockref_t *obref)
3752 {
3753 	int error = 0;
3754 
3755 	KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
3756 	KKASSERT(chain->parent == parent);
3757 
3758 	if (chain->flags & HAMMER2_CHAIN_BLKMAPPED) {
3759 		/*
3760 		 * Chain is blockmapped, so there must be a parent.
3761 		 * Atomically remove the chain from the parent and remove
3762 		 * the blockmap entry.  The parent must be set modified
3763 		 * to remove the blockmap entry.
3764 		 */
3765 		hammer2_blockref_t *base;
3766 		int count;
3767 
3768 		KKASSERT(parent != NULL);
3769 		KKASSERT(parent->error == 0);
3770 		KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3771 		error = hammer2_chain_modify(parent, mtid, 0, 0);
3772 		if (error)
3773 			goto done;
3774 
3775 		/*
3776 		 * Calculate blockmap pointer
3777 		 */
3778 		KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3779 		hammer2_spin_ex(&chain->core.spin);
3780 		hammer2_spin_ex(&parent->core.spin);
3781 
3782 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3783 		atomic_add_int(&parent->core.live_count, -1);
3784 		++parent->core.generation;
3785 		RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3786 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3787 		--parent->core.chain_count;
3788 		chain->parent = NULL;
3789 
3790 		switch(parent->bref.type) {
3791 		case HAMMER2_BREF_TYPE_INODE:
3792 			/*
3793 			 * Access the inode's block array.  However, there
3794 			 * is no block array if the inode is flagged
3795 			 * DIRECTDATA.
3796 			 */
3797 			if (parent->data &&
3798 			    (parent->data->ipdata.meta.op_flags &
3799 			     HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3800 				base =
3801 				   &parent->data->ipdata.u.blockset.blockref[0];
3802 			} else {
3803 				base = NULL;
3804 			}
3805 			count = HAMMER2_SET_COUNT;
3806 			break;
3807 		case HAMMER2_BREF_TYPE_INDIRECT:
3808 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3809 			if (parent->data)
3810 				base = &parent->data->npdata[0];
3811 			else
3812 				base = NULL;
3813 			count = parent->bytes / sizeof(hammer2_blockref_t);
3814 			break;
3815 		case HAMMER2_BREF_TYPE_VOLUME:
3816 			base = &parent->data->voldata.
3817 					sroot_blockset.blockref[0];
3818 			count = HAMMER2_SET_COUNT;
3819 			break;
3820 		case HAMMER2_BREF_TYPE_FREEMAP:
3821 			base = &parent->data->blkset.blockref[0];
3822 			count = HAMMER2_SET_COUNT;
3823 			break;
3824 		default:
3825 			base = NULL;
3826 			count = 0;
3827 			panic("_hammer2_chain_delete_helper: "
3828 			      "unrecognized blockref type: %d",
3829 			      parent->bref.type);
3830 			break;
3831 		}
3832 
3833 		/*
3834 		 * delete blockmapped chain from its parent.
3835 		 *
3836 		 * The parent is not affected by any statistics in chain
3837 		 * which are pending synchronization.  That is, there is
3838 		 * nothing to undo in the parent since they have not yet
3839 		 * been incorporated into the parent.
3840 		 *
3841 		 * The parent is affected by statistics stored in inodes.
3842 		 * Those have already been synchronized, so they must be
3843 		 * undone.  XXX split update possible w/delete in middle?
3844 		 */
3845 		if (base) {
3846 			hammer2_base_delete(parent, base, count, chain, obref);
3847 		}
3848 		hammer2_spin_unex(&parent->core.spin);
3849 		hammer2_spin_unex(&chain->core.spin);
3850 	} else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3851 		/*
3852 		 * Chain is not blockmapped but a parent is present.
3853 		 * Atomically remove the chain from the parent.  There is
3854 		 * no blockmap entry to remove.
3855 		 *
3856 		 * Because chain was associated with a parent but not
3857 		 * synchronized, the chain's *_count_up fields contain
3858 		 * inode adjustment statistics which must be undone.
3859 		 */
3860 		hammer2_spin_ex(&chain->core.spin);
3861 		hammer2_spin_ex(&parent->core.spin);
3862 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3863 		atomic_add_int(&parent->core.live_count, -1);
3864 		++parent->core.generation;
3865 		RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3866 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3867 		--parent->core.chain_count;
3868 		chain->parent = NULL;
3869 		hammer2_spin_unex(&parent->core.spin);
3870 		hammer2_spin_unex(&chain->core.spin);
3871 	} else {
3872 		/*
3873 		 * Chain is not blockmapped and has no parent.  This
3874 		 * is a degenerate case.
3875 		 */
3876 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3877 	}
3878 done:
3879 	return error;
3880 }
3881 
3882 /*
3883  * Create an indirect block that covers one or more of the elements in the
3884  * current parent.  Either returns the existing parent with no locking or
3885  * ref changes or returns the new indirect block locked and referenced
3886  * and leaving the original parent lock/ref intact as well.
3887  *
3888  * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3889  *
3890  * The returned chain depends on where the specified key falls.
3891  *
3892  * The key/keybits for the indirect mode only needs to follow three rules:
3893  *
3894  * (1) That all elements underneath it fit within its key space and
3895  *
3896  * (2) That all elements outside it are outside its key space.
3897  *
3898  * (3) When creating the new indirect block any elements in the current
3899  *     parent that fit within the new indirect block's keyspace must be
3900  *     moved into the new indirect block.
3901  *
3902  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3903  *     keyspace the the current parent, but lookup/iteration rules will
3904  *     ensure (and must ensure) that rule (2) for all parents leading up
3905  *     to the nearest inode or the root volume header is adhered to.  This
3906  *     is accomplished by always recursing through matching keyspaces in
3907  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
3908  *
3909  * The current implementation calculates the current worst-case keyspace by
3910  * iterating the current parent and then divides it into two halves, choosing
3911  * whichever half has the most elements (not necessarily the half containing
3912  * the requested key).
3913  *
3914  * We can also opt to use the half with the least number of elements.  This
3915  * causes lower-numbered keys (aka logical file offsets) to recurse through
3916  * fewer indirect blocks and higher-numbered keys to recurse through more.
3917  * This also has the risk of not moving enough elements to the new indirect
3918  * block and being forced to create several indirect blocks before the element
3919  * can be inserted.
3920  *
3921  * Must be called with an exclusively locked parent.
3922  *
3923  * NOTE: *errorp set to HAMMER_ERROR_* flags
3924  */
3925 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3926 				hammer2_key_t *keyp, int keybits,
3927 				hammer2_blockref_t *base, int count);
3928 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3929 				hammer2_key_t *keyp, int keybits,
3930 				hammer2_blockref_t *base, int count,
3931 				int ncount);
3932 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3933 				hammer2_key_t *keyp, int keybits,
3934 				hammer2_blockref_t *base, int count,
3935 				int ncount);
3936 static
3937 hammer2_chain_t *
3938 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3939 			      hammer2_key_t create_key, int create_bits,
3940 			      hammer2_tid_t mtid, int for_type, int *errorp)
3941 {
3942 	hammer2_dev_t *hmp;
3943 	hammer2_blockref_t *base;
3944 	hammer2_blockref_t *bref;
3945 	hammer2_blockref_t bsave;
3946 	hammer2_blockref_t dummy;
3947 	hammer2_chain_t *chain;
3948 	hammer2_chain_t *ichain;
3949 	hammer2_key_t key = create_key;
3950 	hammer2_key_t key_beg;
3951 	hammer2_key_t key_end;
3952 	hammer2_key_t key_next;
3953 	int keybits = create_bits;
3954 	int count;
3955 	int ncount;
3956 	int nbytes;
3957 	int loops;
3958 	int error;
3959 	int reason;
3960 	int generation;
3961 	int maxloops = 300000;
3962 
3963 	/*
3964 	 * Calculate the base blockref pointer or NULL if the chain
3965 	 * is known to be empty.  We need to calculate the array count
3966 	 * for RB lookups either way.
3967 	 */
3968 	hmp = parent->hmp;
3969 	KKASSERT(hammer2_mtx_owned(&parent->lock));
3970 
3971 	/*
3972 	 * Pre-modify the parent now to avoid having to deal with error
3973 	 * processing if we tried to later (in the middle of our loop).
3974 	 *
3975 	 * We are going to be moving bref's around, the indirect blocks
3976 	 * cannot be in an initial state.  Do not pass MODIFY_OPTDATA.
3977 	 */
3978 	*errorp = hammer2_chain_modify(parent, mtid, 0, 0);
3979 	if (*errorp) {
3980 		kprintf("hammer2_chain_create_indirect: error %08x %s\n",
3981 			*errorp, hammer2_error_str(*errorp));
3982 		return NULL;
3983 	}
3984 	KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3985 
3986 	/*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3987 	base = hammer2_chain_base_and_count(parent, &count);
3988 
3989 	/*
3990 	 * How big should our new indirect block be?  It has to be at least
3991 	 * as large as its parent for splits to work properly.
3992 	 *
3993 	 * The freemap uses a specific indirect block size.  The number of
3994 	 * levels are built dynamically and ultimately depend on the size
3995 	 * volume.  Because freemap blocks are taken from the reserved areas
3996 	 * of the volume our goal is efficiency (fewer levels) and not so
3997 	 * much to save disk space.
3998 	 *
3999 	 * The first indirect block level for a directory usually uses
4000 	 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries).  Due to
4001 	 * the hash mechanism, this typically gives us a nominal
4002 	 * 32 * 4 entries with one level of indirection.
4003 	 *
4004 	 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
4005 	 * indirect blocks.  The initial 4 entries in the inode gives us
4006 	 * 256KB.  Up to 4 indirect blocks gives us 32MB.  Three levels
4007 	 * of indirection gives us 137GB, and so forth.  H2 can support
4008 	 * huge file sizes but they are not typical, so we try to stick
4009 	 * with compactness and do not use a larger indirect block size.
4010 	 *
4011 	 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
4012 	 * due to the way indirect blocks are created this usually winds
4013 	 * up being extremely inefficient for small files.  Even though
4014 	 * 16KB requires more levels of indirection for very large files,
4015 	 * the 16KB records can be ganged together into 64KB DIOs.
4016 	 */
4017 	if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4018 	    for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4019 		nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
4020 	} else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4021 		if (parent->data->ipdata.meta.type ==
4022 		    HAMMER2_OBJTYPE_DIRECTORY)
4023 			nbytes = HAMMER2_IND_BYTES_MIN;	/* 4KB = 32 entries */
4024 		else
4025 			nbytes = HAMMER2_IND_BYTES_NOM;	/* 16KB = ~8MB file */
4026 
4027 	} else {
4028 		nbytes = HAMMER2_IND_BYTES_NOM;
4029 	}
4030 	if (nbytes < count * sizeof(hammer2_blockref_t)) {
4031 		KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
4032 			 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
4033 		nbytes = count * sizeof(hammer2_blockref_t);
4034 	}
4035 	ncount = nbytes / sizeof(hammer2_blockref_t);
4036 
4037 	/*
4038 	 * When creating an indirect block for a freemap node or leaf
4039 	 * the key/keybits must be fitted to static radix levels because
4040 	 * particular radix levels use particular reserved blocks in the
4041 	 * related zone.
4042 	 *
4043 	 * This routine calculates the key/radix of the indirect block
4044 	 * we need to create, and whether it is on the high-side or the
4045 	 * low-side.
4046 	 */
4047 	switch(for_type) {
4048 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4049 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4050 		keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
4051 						       base, count);
4052 		break;
4053 	case HAMMER2_BREF_TYPE_DATA:
4054 		keybits = hammer2_chain_indkey_file(parent, &key, keybits,
4055 						    base, count, ncount);
4056 		break;
4057 	case HAMMER2_BREF_TYPE_DIRENT:
4058 	case HAMMER2_BREF_TYPE_INODE:
4059 		keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
4060 						   base, count, ncount);
4061 		break;
4062 	default:
4063 		panic("illegal indirect block for bref type %d", for_type);
4064 		break;
4065 	}
4066 
4067 	/*
4068 	 * Normalize the key for the radix being represented, keeping the
4069 	 * high bits and throwing away the low bits.
4070 	 */
4071 	key &= ~(((hammer2_key_t)1 << keybits) - 1);
4072 
4073 	/*
4074 	 * Ok, create our new indirect block
4075 	 */
4076 	bzero(&dummy, sizeof(dummy));
4077 	if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4078 	    for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4079 		dummy.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
4080 	} else {
4081 		dummy.type = HAMMER2_BREF_TYPE_INDIRECT;
4082 	}
4083 	dummy.key = key;
4084 	dummy.keybits = keybits;
4085 	dummy.data_off = hammer2_getradix(nbytes);
4086 	dummy.methods =
4087 		HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
4088 		HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
4089 
4090 	ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy);
4091 	atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
4092 	hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
4093 	/* ichain has one ref at this point */
4094 
4095 	/*
4096 	 * We have to mark it modified to allocate its block, but use
4097 	 * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
4098 	 * it won't be acted upon by the flush code.
4099 	 *
4100 	 * XXX remove OPTDATA, we need a fully initialized indirect block to
4101 	 * be able to move the original blockref.
4102 	 */
4103 	*errorp = hammer2_chain_modify(ichain, mtid, 0, 0);
4104 	if (*errorp) {
4105 		kprintf("hammer2_chain_create_indirect: error %08x %s\n",
4106 			*errorp, hammer2_error_str(*errorp));
4107 		hammer2_chain_unlock(ichain);
4108 		hammer2_chain_drop(ichain);
4109 		return NULL;
4110 	}
4111 	KKASSERT((ichain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4112 
4113 	/*
4114 	 * Iterate the original parent and move the matching brefs into
4115 	 * the new indirect block.
4116 	 *
4117 	 * XXX handle flushes.
4118 	 */
4119 	key_beg = 0;
4120 	key_end = HAMMER2_KEY_MAX;
4121 	key_next = 0;	/* avoid gcc warnings */
4122 	hammer2_spin_ex(&parent->core.spin);
4123 	loops = 0;
4124 	reason = 0;
4125 
4126 	for (;;) {
4127 		/*
4128 		 * Parent may have been modified, relocating its block array.
4129 		 * Reload the base pointer.
4130 		 */
4131 		base = hammer2_chain_base_and_count(parent, &count);
4132 
4133 		if (++loops > 100000) {
4134 		    hammer2_spin_unex(&parent->core.spin);
4135 		    panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
4136 			  reason, parent, base, count, key_next);
4137 		}
4138 
4139 		/*
4140 		 * NOTE: spinlock stays intact, returned chain (if not NULL)
4141 		 *	 is not referenced or locked which means that we
4142 		 *	 cannot safely check its flagged / deletion status
4143 		 *	 until we lock it.
4144 		 */
4145 		chain = hammer2_combined_find(parent, base, count,
4146 					      &key_next,
4147 					      key_beg, key_end,
4148 					      &bref);
4149 		generation = parent->core.generation;
4150 		if (bref == NULL)
4151 			break;
4152 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4153 
4154 		/*
4155 		 * Skip keys that are not within the key/radix of the new
4156 		 * indirect block.  They stay in the parent.
4157 		 */
4158 		if (rounddown2(key ^ bref->key, (hammer2_key_t)1 << keybits) != 0) {
4159 			goto next_key_spinlocked;
4160 		}
4161 
4162 		/*
4163 		 * Load the new indirect block by acquiring the related
4164 		 * chains (potentially from media as it might not be
4165 		 * in-memory).  Then move it to the new parent (ichain).
4166 		 *
4167 		 * chain is referenced but not locked.  We must lock the
4168 		 * chain to obtain definitive state.
4169 		 */
4170 		bsave = *bref;
4171 		if (chain) {
4172 			/*
4173 			 * Use chain already present in the RBTREE
4174 			 */
4175 			hammer2_chain_ref(chain);
4176 			hammer2_spin_unex(&parent->core.spin);
4177 			hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
4178 		} else {
4179 			/*
4180 			 * Get chain for blockref element.  _get returns NULL
4181 			 * on insertion race.
4182 			 */
4183 			hammer2_spin_unex(&parent->core.spin);
4184 			chain = hammer2_chain_get(parent, generation, &bsave,
4185 						  HAMMER2_RESOLVE_NEVER);
4186 			if (chain == NULL) {
4187 				reason = 1;
4188 				hammer2_spin_ex(&parent->core.spin);
4189 				continue;
4190 			}
4191 		}
4192 
4193 		/*
4194 		 * This is always live so if the chain has been deleted
4195 		 * we raced someone and we have to retry.
4196 		 *
4197 		 * NOTE: Lookups can race delete-duplicate because
4198 		 *	 delete-duplicate does not lock the parent's core
4199 		 *	 (they just use the spinlock on the core).
4200 		 *
4201 		 *	 (note reversed logic for this one)
4202 		 */
4203 		if (bcmp(&bsave, &chain->bref, sizeof(bsave)) ||
4204 		    chain->parent != parent ||
4205 		    (chain->flags & HAMMER2_CHAIN_DELETED)) {
4206 			hammer2_chain_unlock(chain);
4207 			hammer2_chain_drop(chain);
4208 			if (hammer2_debug & 0x0040) {
4209 				kprintf("LOST PARENT RETRY "
4210 				"RETRY (%p,%p)->%p %08x\n",
4211 				parent, chain->parent, chain, chain->flags);
4212 			}
4213 			hammer2_spin_ex(&parent->core.spin);
4214 			continue;
4215 		}
4216 
4217 		/*
4218 		 * Shift the chain to the indirect block.
4219 		 *
4220 		 * WARNING! No reason for us to load chain data, pass NOSTATS
4221 		 *	    to prevent delete/insert from trying to access
4222 		 *	    inode stats (and thus asserting if there is no
4223 		 *	    chain->data loaded).
4224 		 *
4225 		 * WARNING! The (parent, chain) deletion may modify the parent
4226 		 *	    and invalidate the base pointer.
4227 		 *
4228 		 * WARNING! Parent must already be marked modified, so we
4229 		 *	    can assume that chain_delete always suceeds.
4230 		 *
4231 		 * WARNING! hammer2_chain_repchange() does not have to be
4232 		 *	    called (and doesn't work anyway because we are
4233 		 *	    only doing a partial shift).  A recursion that is
4234 		 *	    in-progress can continue at the current parent
4235 		 *	    and will be able to properly find its next key.
4236 		 */
4237 		error = hammer2_chain_delete_obref(parent, chain, mtid, 0,
4238 						   &bsave);
4239 		KKASSERT(error == 0);
4240 		hammer2_chain_rename_obref(&ichain, chain, mtid, 0, &bsave);
4241 		hammer2_chain_unlock(chain);
4242 		hammer2_chain_drop(chain);
4243 		KKASSERT(parent->refs > 0);
4244 		chain = NULL;
4245 		base = NULL;	/* safety */
4246 		hammer2_spin_ex(&parent->core.spin);
4247 next_key_spinlocked:
4248 		if (--maxloops == 0)
4249 			panic("hammer2_chain_create_indirect: maxloops");
4250 		reason = 4;
4251 		if (key_next == 0 || key_next > key_end)
4252 			break;
4253 		key_beg = key_next;
4254 		/* loop */
4255 	}
4256 	hammer2_spin_unex(&parent->core.spin);
4257 
4258 	/*
4259 	 * Insert the new indirect block into the parent now that we've
4260 	 * cleared out some entries in the parent.  We calculated a good
4261 	 * insertion index in the loop above (ichain->index).
4262 	 *
4263 	 * We don't have to set UPDATE here because we mark ichain
4264 	 * modified down below (so the normal modified -> flush -> set-moved
4265 	 * sequence applies).
4266 	 *
4267 	 * The insertion shouldn't race as this is a completely new block
4268 	 * and the parent is locked.
4269 	 */
4270 	base = NULL;	/* safety, parent modify may change address */
4271 	KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
4272 	KKASSERT(parent->core.live_count < count);
4273 	hammer2_chain_insert(parent, ichain,
4274 			     HAMMER2_CHAIN_INSERT_SPIN |
4275 			     HAMMER2_CHAIN_INSERT_LIVE,
4276 			     0);
4277 
4278 	/*
4279 	 * Make sure flushes propogate after our manual insertion.
4280 	 */
4281 	hammer2_chain_setflush(ichain);
4282 	hammer2_chain_setflush(parent);
4283 
4284 	/*
4285 	 * Figure out what to return.
4286 	 */
4287 	if (rounddown2(create_key ^ key, (hammer2_key_t)1 << keybits)) {
4288 		/*
4289 		 * Key being created is outside the key range,
4290 		 * return the original parent.
4291 		 */
4292 		hammer2_chain_unlock(ichain);
4293 		hammer2_chain_drop(ichain);
4294 	} else {
4295 		/*
4296 		 * Otherwise its in the range, return the new parent.
4297 		 * (leave both the new and old parent locked).
4298 		 */
4299 		parent = ichain;
4300 	}
4301 
4302 	return(parent);
4303 }
4304 
4305 /*
4306  * Do maintenance on an indirect chain.  Both parent and chain are locked.
4307  *
4308  * Returns non-zero if (chain) is deleted, either due to being empty or
4309  * because its children were safely moved into the parent.
4310  */
4311 int
4312 hammer2_chain_indirect_maintenance(hammer2_chain_t *parent,
4313 				   hammer2_chain_t *chain)
4314 {
4315 	hammer2_blockref_t *chain_base;
4316 	hammer2_blockref_t *base;
4317 	hammer2_blockref_t *bref;
4318 	hammer2_blockref_t bsave;
4319 	hammer2_key_t key_next;
4320 	hammer2_key_t key_beg;
4321 	hammer2_key_t key_end;
4322 	hammer2_chain_t *sub;
4323 	int chain_count;
4324 	int count;
4325 	int error;
4326 	int generation;
4327 
4328 	/*
4329 	 * Make sure we have an accurate live_count
4330 	 */
4331 	if ((chain->flags & (HAMMER2_CHAIN_INITIAL |
4332 			     HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4333 		base = &chain->data->npdata[0];
4334 		count = chain->bytes / sizeof(hammer2_blockref_t);
4335 		hammer2_chain_countbrefs(chain, base, count);
4336 	}
4337 
4338 	/*
4339 	 * If the indirect block is empty we can delete it.
4340 	 * (ignore deletion error)
4341 	 */
4342 	if (chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree)) {
4343 		hammer2_chain_delete(parent, chain,
4344 				     chain->bref.modify_tid,
4345 				     HAMMER2_DELETE_PERMANENT);
4346 		hammer2_chain_repchange(parent, chain);
4347 		return 1;
4348 	}
4349 
4350 	base = hammer2_chain_base_and_count(parent, &count);
4351 
4352 	if ((parent->flags & (HAMMER2_CHAIN_INITIAL |
4353 			     HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4354 		hammer2_chain_countbrefs(parent, base, count);
4355 	}
4356 
4357 	/*
4358 	 * Determine if we can collapse chain into parent, calculate
4359 	 * hysteresis for chain emptiness.
4360 	 */
4361 	if (parent->core.live_count + chain->core.live_count - 1 > count)
4362 		return 0;
4363 	chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4364 	if (chain->core.live_count > chain_count * 3 / 4)
4365 		return 0;
4366 
4367 	/*
4368 	 * Ok, theoretically we can collapse chain's contents into
4369 	 * parent.  chain is locked, but any in-memory children of chain
4370 	 * are not.  For this to work, we must be able to dispose of any
4371 	 * in-memory children of chain.
4372 	 *
4373 	 * For now require that there are no in-memory children of chain.
4374 	 *
4375 	 * WARNING! Both chain and parent must remain locked across this
4376 	 *	    entire operation.
4377 	 */
4378 
4379 	/*
4380 	 * Parent must be marked modified.  Don't try to collapse it if we
4381 	 * can't mark it modified.  Once modified, destroy chain to make room
4382 	 * and to get rid of what will be a conflicting key (this is included
4383 	 * in the calculation above).  Finally, move the children of chain
4384 	 * into chain's parent.
4385 	 *
4386 	 * This order creates an accounting problem for bref.embed.stats
4387 	 * because we destroy chain before we remove its children.  Any
4388 	 * elements whos blockref is already synchronized will be counted
4389 	 * twice.  To deal with the problem we clean out chain's stats prior
4390 	 * to deleting it.
4391 	 */
4392 	error = hammer2_chain_modify(parent, 0, 0, 0);
4393 	if (error) {
4394 		krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4395 			    hammer2_error_str(error));
4396 		return 0;
4397 	}
4398 	error = hammer2_chain_modify(chain, chain->bref.modify_tid, 0, 0);
4399 	if (error) {
4400 		krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4401 			    hammer2_error_str(error));
4402 		return 0;
4403 	}
4404 
4405 	chain->bref.embed.stats.inode_count = 0;
4406 	chain->bref.embed.stats.data_count = 0;
4407 	error = hammer2_chain_delete(parent, chain,
4408 				     chain->bref.modify_tid,
4409 				     HAMMER2_DELETE_PERMANENT);
4410 	KKASSERT(error == 0);
4411 
4412 	/*
4413 	 * The combined_find call requires core.spin to be held.  One would
4414 	 * think there wouldn't be any conflicts since we hold chain
4415 	 * exclusively locked, but the caching mechanism for 0-ref children
4416 	 * does not require a chain lock.
4417 	 */
4418 	hammer2_spin_ex(&chain->core.spin);
4419 
4420 	key_next = 0;
4421 	key_beg = 0;
4422 	key_end = HAMMER2_KEY_MAX;
4423 	for (;;) {
4424 		chain_base = &chain->data->npdata[0];
4425 		chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4426 		sub = hammer2_combined_find(chain, chain_base, chain_count,
4427 					    &key_next,
4428 					    key_beg, key_end,
4429 					    &bref);
4430 		generation = chain->core.generation;
4431 		if (bref == NULL)
4432 			break;
4433 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4434 
4435 		bsave = *bref;
4436 		if (sub) {
4437 			hammer2_chain_ref(sub);
4438 			hammer2_spin_unex(&chain->core.spin);
4439 			hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4440 		} else {
4441 			hammer2_spin_unex(&chain->core.spin);
4442 			sub = hammer2_chain_get(chain, generation, &bsave,
4443 						HAMMER2_RESOLVE_NEVER);
4444 			if (sub == NULL) {
4445 				hammer2_spin_ex(&chain->core.spin);
4446 				continue;
4447 			}
4448 		}
4449 		if (bcmp(&bsave, &sub->bref, sizeof(bsave)) ||
4450 		    sub->parent != chain ||
4451 		    (sub->flags & HAMMER2_CHAIN_DELETED)) {
4452 			hammer2_chain_unlock(sub);
4453 			hammer2_chain_drop(sub);
4454 			hammer2_spin_ex(&chain->core.spin);
4455 			sub = NULL;	/* safety */
4456 			continue;
4457 		}
4458 		error = hammer2_chain_delete_obref(chain, sub,
4459 						   sub->bref.modify_tid, 0,
4460 						   &bsave);
4461 		KKASSERT(error == 0);
4462 		hammer2_chain_rename_obref(&parent, sub,
4463 				     sub->bref.modify_tid,
4464 				     HAMMER2_INSERT_SAMEPARENT, &bsave);
4465 		hammer2_chain_unlock(sub);
4466 		hammer2_chain_drop(sub);
4467 		hammer2_spin_ex(&chain->core.spin);
4468 
4469 		if (key_next == 0)
4470 			break;
4471 		key_beg = key_next;
4472 	}
4473 	hammer2_spin_unex(&chain->core.spin);
4474 
4475 	hammer2_chain_repchange(parent, chain);
4476 
4477 	return 1;
4478 }
4479 
4480 /*
4481  * Freemap indirect blocks
4482  *
4483  * Calculate the keybits and highside/lowside of the freemap node the
4484  * caller is creating.
4485  *
4486  * This routine will specify the next higher-level freemap key/radix
4487  * representing the lowest-ordered set.  By doing so, eventually all
4488  * low-ordered sets will be moved one level down.
4489  *
4490  * We have to be careful here because the freemap reserves a limited
4491  * number of blocks for a limited number of levels.  So we can't just
4492  * push indiscriminately.
4493  */
4494 int
4495 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4496 			     int keybits, hammer2_blockref_t *base, int count)
4497 {
4498 	hammer2_chain_t *chain;
4499 	hammer2_blockref_t *bref;
4500 	hammer2_key_t key;
4501 	hammer2_key_t key_beg;
4502 	hammer2_key_t key_end;
4503 	hammer2_key_t key_next;
4504 	int maxloops = 300000;
4505 
4506 	key = *keyp;
4507 	keybits = 64;
4508 
4509 	/*
4510 	 * Calculate the range of keys in the array being careful to skip
4511 	 * slots which are overridden with a deletion.
4512 	 */
4513 	key_beg = 0;
4514 	key_end = HAMMER2_KEY_MAX;
4515 	hammer2_spin_ex(&parent->core.spin);
4516 
4517 	for (;;) {
4518 		if (--maxloops == 0) {
4519 			panic("indkey_freemap shit %p %p:%d\n",
4520 			      parent, base, count);
4521 		}
4522 		chain = hammer2_combined_find(parent, base, count,
4523 					      &key_next,
4524 					      key_beg, key_end,
4525 					      &bref);
4526 
4527 		/*
4528 		 * Exhausted search
4529 		 */
4530 		if (bref == NULL)
4531 			break;
4532 
4533 		/*
4534 		 * Skip deleted chains.
4535 		 */
4536 		if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4537 			if (key_next == 0 || key_next > key_end)
4538 				break;
4539 			key_beg = key_next;
4540 			continue;
4541 		}
4542 
4543 		/*
4544 		 * Use the full live (not deleted) element for the scan
4545 		 * iteration.  HAMMER2 does not allow partial replacements.
4546 		 *
4547 		 * XXX should be built into hammer2_combined_find().
4548 		 */
4549 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4550 
4551 		if (keybits > bref->keybits) {
4552 			key = bref->key;
4553 			keybits = bref->keybits;
4554 		} else if (keybits == bref->keybits && bref->key < key) {
4555 			key = bref->key;
4556 		}
4557 		if (key_next == 0)
4558 			break;
4559 		key_beg = key_next;
4560 	}
4561 	hammer2_spin_unex(&parent->core.spin);
4562 
4563 	/*
4564 	 * Return the keybits for a higher-level FREEMAP_NODE covering
4565 	 * this node.
4566 	 */
4567 	switch(keybits) {
4568 	case HAMMER2_FREEMAP_LEVEL0_RADIX:
4569 		keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4570 		break;
4571 	case HAMMER2_FREEMAP_LEVEL1_RADIX:
4572 		keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4573 		break;
4574 	case HAMMER2_FREEMAP_LEVEL2_RADIX:
4575 		keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4576 		break;
4577 	case HAMMER2_FREEMAP_LEVEL3_RADIX:
4578 		keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4579 		break;
4580 	case HAMMER2_FREEMAP_LEVEL4_RADIX:
4581 		keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4582 		break;
4583 	case HAMMER2_FREEMAP_LEVEL5_RADIX:
4584 		panic("hammer2_chain_indkey_freemap: level too high");
4585 		break;
4586 	default:
4587 		panic("hammer2_chain_indkey_freemap: bad radix");
4588 		break;
4589 	}
4590 	*keyp = key;
4591 
4592 	return (keybits);
4593 }
4594 
4595 /*
4596  * File indirect blocks
4597  *
4598  * Calculate the key/keybits for the indirect block to create by scanning
4599  * existing keys.  The key being created is also passed in *keyp and can be
4600  * inside or outside the indirect block.  Regardless, the indirect block
4601  * must hold at least two keys in order to guarantee sufficient space.
4602  *
4603  * We use a modified version of the freemap's fixed radix tree, but taylored
4604  * for file data.  Basically we configure an indirect block encompassing the
4605  * smallest key.
4606  */
4607 static int
4608 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4609 			    int keybits, hammer2_blockref_t *base, int count,
4610 			    int ncount)
4611 {
4612 	hammer2_chain_t *chain;
4613 	hammer2_blockref_t *bref;
4614 	hammer2_key_t key;
4615 	hammer2_key_t key_beg;
4616 	hammer2_key_t key_end;
4617 	hammer2_key_t key_next;
4618 	int nradix;
4619 	int maxloops = 300000;
4620 
4621 	key = *keyp;
4622 	keybits = 64;
4623 
4624 	/*
4625 	 * Calculate the range of keys in the array being careful to skip
4626 	 * slots which are overridden with a deletion.
4627 	 *
4628 	 * Locate the smallest key.
4629 	 */
4630 	key_beg = 0;
4631 	key_end = HAMMER2_KEY_MAX;
4632 	hammer2_spin_ex(&parent->core.spin);
4633 
4634 	for (;;) {
4635 		if (--maxloops == 0) {
4636 			panic("indkey_freemap shit %p %p:%d\n",
4637 			      parent, base, count);
4638 		}
4639 		chain = hammer2_combined_find(parent, base, count,
4640 					      &key_next,
4641 					      key_beg, key_end,
4642 					      &bref);
4643 
4644 		/*
4645 		 * Exhausted search
4646 		 */
4647 		if (bref == NULL)
4648 			break;
4649 
4650 		/*
4651 		 * Skip deleted chains.
4652 		 */
4653 		if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4654 			if (key_next == 0 || key_next > key_end)
4655 				break;
4656 			key_beg = key_next;
4657 			continue;
4658 		}
4659 
4660 		/*
4661 		 * Use the full live (not deleted) element for the scan
4662 		 * iteration.  HAMMER2 does not allow partial replacements.
4663 		 *
4664 		 * XXX should be built into hammer2_combined_find().
4665 		 */
4666 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4667 
4668 		if (keybits > bref->keybits) {
4669 			key = bref->key;
4670 			keybits = bref->keybits;
4671 		} else if (keybits == bref->keybits && bref->key < key) {
4672 			key = bref->key;
4673 		}
4674 		if (key_next == 0)
4675 			break;
4676 		key_beg = key_next;
4677 	}
4678 	hammer2_spin_unex(&parent->core.spin);
4679 
4680 	/*
4681 	 * Calculate the static keybits for a higher-level indirect block
4682 	 * that contains the key.
4683 	 */
4684 	*keyp = key;
4685 
4686 	switch(ncount) {
4687 	case HAMMER2_IND_COUNT_MIN:
4688 		nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4689 		break;
4690 	case HAMMER2_IND_COUNT_NOM:
4691 		nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4692 		break;
4693 	case HAMMER2_IND_COUNT_MAX:
4694 		nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4695 		break;
4696 	default:
4697 		panic("bad ncount %d\n", ncount);
4698 		nradix = 0;
4699 		break;
4700 	}
4701 
4702 	/*
4703 	 * The largest radix that can be returned for an indirect block is
4704 	 * 63 bits.  (The largest practical indirect block radix is actually
4705 	 * 62 bits because the top-level inode or volume root contains four
4706 	 * entries, but allow 63 to be returned).
4707 	 */
4708 	if (nradix >= 64)
4709 		nradix = 63;
4710 
4711 	return keybits + nradix;
4712 }
4713 
4714 #if 1
4715 
4716 /*
4717  * Directory indirect blocks.
4718  *
4719  * Covers both the inode index (directory of inodes), and directory contents
4720  * (filenames hardlinked to inodes).
4721  *
4722  * Because directory keys are hashed we generally try to cut the space in
4723  * half.  We accomodate the inode index (which tends to have linearly
4724  * increasing inode numbers) by ensuring that the keyspace is at least large
4725  * enough to fill up the indirect block being created.
4726  */
4727 static int
4728 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4729 			 int keybits, hammer2_blockref_t *base, int count,
4730 			 int ncount)
4731 {
4732 	hammer2_blockref_t *bref;
4733 	hammer2_chain_t	*chain;
4734 	hammer2_key_t key_beg;
4735 	hammer2_key_t key_end;
4736 	hammer2_key_t key_next;
4737 	hammer2_key_t key;
4738 	int nkeybits;
4739 	int locount;
4740 	int hicount;
4741 	int maxloops = 300000;
4742 
4743 	/*
4744 	 * NOTE: We can't take a shortcut here anymore for inodes because
4745 	 *	 the root directory can contain a mix of inodes and directory
4746 	 *	 entries (we used to just return 63 if parent->bref.type was
4747 	 *	 HAMMER2_BREF_TYPE_INODE.
4748 	 */
4749 	key = *keyp;
4750 	locount = 0;
4751 	hicount = 0;
4752 
4753 	/*
4754 	 * Calculate the range of keys in the array being careful to skip
4755 	 * slots which are overridden with a deletion.
4756 	 */
4757 	key_beg = 0;
4758 	key_end = HAMMER2_KEY_MAX;
4759 	hammer2_spin_ex(&parent->core.spin);
4760 
4761 	for (;;) {
4762 		if (--maxloops == 0) {
4763 			panic("indkey_freemap shit %p %p:%d\n",
4764 			      parent, base, count);
4765 		}
4766 		chain = hammer2_combined_find(parent, base, count,
4767 					      &key_next,
4768 					      key_beg, key_end,
4769 					      &bref);
4770 
4771 		/*
4772 		 * Exhausted search
4773 		 */
4774 		if (bref == NULL)
4775 			break;
4776 
4777 		/*
4778 		 * Deleted object
4779 		 */
4780 		if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4781 			if (key_next == 0 || key_next > key_end)
4782 				break;
4783 			key_beg = key_next;
4784 			continue;
4785 		}
4786 
4787 		/*
4788 		 * Use the full live (not deleted) element for the scan
4789 		 * iteration.  HAMMER2 does not allow partial replacements.
4790 		 *
4791 		 * XXX should be built into hammer2_combined_find().
4792 		 */
4793 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4794 
4795 		/*
4796 		 * Expand our calculated key range (key, keybits) to fit
4797 		 * the scanned key.  nkeybits represents the full range
4798 		 * that we will later cut in half (two halves @ nkeybits - 1).
4799 		 */
4800 		nkeybits = keybits;
4801 		if (nkeybits < bref->keybits) {
4802 			if (bref->keybits > 64) {
4803 				kprintf("bad bref chain %p bref %p\n",
4804 					chain, bref);
4805 				Debugger("fubar");
4806 			}
4807 			nkeybits = bref->keybits;
4808 		}
4809 		while (nkeybits < 64 &&
4810 		       rounddown2(key ^ bref->key, (hammer2_key_t)1 << nkeybits) != 0) {
4811 			++nkeybits;
4812 		}
4813 
4814 		/*
4815 		 * If the new key range is larger we have to determine
4816 		 * which side of the new key range the existing keys fall
4817 		 * under by checking the high bit, then collapsing the
4818 		 * locount into the hicount or vise-versa.
4819 		 */
4820 		if (keybits != nkeybits) {
4821 			if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4822 				hicount += locount;
4823 				locount = 0;
4824 			} else {
4825 				locount += hicount;
4826 				hicount = 0;
4827 			}
4828 			keybits = nkeybits;
4829 		}
4830 
4831 		/*
4832 		 * The newly scanned key will be in the lower half or the
4833 		 * upper half of the (new) key range.
4834 		 */
4835 		if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4836 			++hicount;
4837 		else
4838 			++locount;
4839 
4840 		if (key_next == 0)
4841 			break;
4842 		key_beg = key_next;
4843 	}
4844 	hammer2_spin_unex(&parent->core.spin);
4845 	bref = NULL;	/* now invalid (safety) */
4846 
4847 	/*
4848 	 * Adjust keybits to represent half of the full range calculated
4849 	 * above (radix 63 max) for our new indirect block.
4850 	 */
4851 	--keybits;
4852 
4853 	/*
4854 	 * Expand keybits to hold at least ncount elements.  ncount will be
4855 	 * a power of 2.  This is to try to completely fill leaf nodes (at
4856 	 * least for keys which are not hashes).
4857 	 *
4858 	 * We aren't counting 'in' or 'out', we are counting 'high side'
4859 	 * and 'low side' based on the bit at (1LL << keybits).  We want
4860 	 * everything to be inside in these cases so shift it all to
4861 	 * the low or high side depending on the new high bit.
4862 	 */
4863 	while (((hammer2_key_t)1 << keybits) < ncount) {
4864 		++keybits;
4865 		if (key & ((hammer2_key_t)1 << keybits)) {
4866 			hicount += locount;
4867 			locount = 0;
4868 		} else {
4869 			locount += hicount;
4870 			hicount = 0;
4871 		}
4872 	}
4873 
4874 	if (hicount > locount)
4875 		key |= (hammer2_key_t)1 << keybits;
4876 	else
4877 		key &= ~(hammer2_key_t)1 << keybits;
4878 
4879 	*keyp = key;
4880 
4881 	return (keybits);
4882 }
4883 
4884 #else
4885 
4886 /*
4887  * Directory indirect blocks.
4888  *
4889  * Covers both the inode index (directory of inodes), and directory contents
4890  * (filenames hardlinked to inodes).
4891  *
4892  * Because directory keys are hashed we generally try to cut the space in
4893  * half.  We accomodate the inode index (which tends to have linearly
4894  * increasing inode numbers) by ensuring that the keyspace is at least large
4895  * enough to fill up the indirect block being created.
4896  */
4897 static int
4898 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4899 			 int keybits, hammer2_blockref_t *base, int count,
4900 			 int ncount)
4901 {
4902 	hammer2_blockref_t *bref;
4903 	hammer2_chain_t	*chain;
4904 	hammer2_key_t key_beg;
4905 	hammer2_key_t key_end;
4906 	hammer2_key_t key_next;
4907 	hammer2_key_t key;
4908 	int nkeybits;
4909 	int locount;
4910 	int hicount;
4911 	int maxloops = 300000;
4912 
4913 	/*
4914 	 * Shortcut if the parent is the inode.  In this situation the
4915 	 * parent has 4+1 directory entries and we are creating an indirect
4916 	 * block capable of holding many more.
4917 	 */
4918 	if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4919 		return 63;
4920 	}
4921 
4922 	key = *keyp;
4923 	locount = 0;
4924 	hicount = 0;
4925 
4926 	/*
4927 	 * Calculate the range of keys in the array being careful to skip
4928 	 * slots which are overridden with a deletion.
4929 	 */
4930 	key_beg = 0;
4931 	key_end = HAMMER2_KEY_MAX;
4932 	hammer2_spin_ex(&parent->core.spin);
4933 
4934 	for (;;) {
4935 		if (--maxloops == 0) {
4936 			panic("indkey_freemap shit %p %p:%d\n",
4937 			      parent, base, count);
4938 		}
4939 		chain = hammer2_combined_find(parent, base, count,
4940 					      &key_next,
4941 					      key_beg, key_end,
4942 					      &bref);
4943 
4944 		/*
4945 		 * Exhausted search
4946 		 */
4947 		if (bref == NULL)
4948 			break;
4949 
4950 		/*
4951 		 * Deleted object
4952 		 */
4953 		if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4954 			if (key_next == 0 || key_next > key_end)
4955 				break;
4956 			key_beg = key_next;
4957 			continue;
4958 		}
4959 
4960 		/*
4961 		 * Use the full live (not deleted) element for the scan
4962 		 * iteration.  HAMMER2 does not allow partial replacements.
4963 		 *
4964 		 * XXX should be built into hammer2_combined_find().
4965 		 */
4966 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4967 
4968 		/*
4969 		 * Expand our calculated key range (key, keybits) to fit
4970 		 * the scanned key.  nkeybits represents the full range
4971 		 * that we will later cut in half (two halves @ nkeybits - 1).
4972 		 */
4973 		nkeybits = keybits;
4974 		if (nkeybits < bref->keybits) {
4975 			if (bref->keybits > 64) {
4976 				kprintf("bad bref chain %p bref %p\n",
4977 					chain, bref);
4978 				Debugger("fubar");
4979 			}
4980 			nkeybits = bref->keybits;
4981 		}
4982 		while (nkeybits < 64 &&
4983 		       (~(((hammer2_key_t)1 << nkeybits) - 1) &
4984 		        (key ^ bref->key)) != 0) {
4985 			++nkeybits;
4986 		}
4987 
4988 		/*
4989 		 * If the new key range is larger we have to determine
4990 		 * which side of the new key range the existing keys fall
4991 		 * under by checking the high bit, then collapsing the
4992 		 * locount into the hicount or vise-versa.
4993 		 */
4994 		if (keybits != nkeybits) {
4995 			if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4996 				hicount += locount;
4997 				locount = 0;
4998 			} else {
4999 				locount += hicount;
5000 				hicount = 0;
5001 			}
5002 			keybits = nkeybits;
5003 		}
5004 
5005 		/*
5006 		 * The newly scanned key will be in the lower half or the
5007 		 * upper half of the (new) key range.
5008 		 */
5009 		if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
5010 			++hicount;
5011 		else
5012 			++locount;
5013 
5014 		if (key_next == 0)
5015 			break;
5016 		key_beg = key_next;
5017 	}
5018 	hammer2_spin_unex(&parent->core.spin);
5019 	bref = NULL;	/* now invalid (safety) */
5020 
5021 	/*
5022 	 * Adjust keybits to represent half of the full range calculated
5023 	 * above (radix 63 max) for our new indirect block.
5024 	 */
5025 	--keybits;
5026 
5027 	/*
5028 	 * Expand keybits to hold at least ncount elements.  ncount will be
5029 	 * a power of 2.  This is to try to completely fill leaf nodes (at
5030 	 * least for keys which are not hashes).
5031 	 *
5032 	 * We aren't counting 'in' or 'out', we are counting 'high side'
5033 	 * and 'low side' based on the bit at (1LL << keybits).  We want
5034 	 * everything to be inside in these cases so shift it all to
5035 	 * the low or high side depending on the new high bit.
5036 	 */
5037 	while (((hammer2_key_t)1 << keybits) < ncount) {
5038 		++keybits;
5039 		if (key & ((hammer2_key_t)1 << keybits)) {
5040 			hicount += locount;
5041 			locount = 0;
5042 		} else {
5043 			locount += hicount;
5044 			hicount = 0;
5045 		}
5046 	}
5047 
5048 	if (hicount > locount)
5049 		key |= (hammer2_key_t)1 << keybits;
5050 	else
5051 		key &= ~(hammer2_key_t)1 << keybits;
5052 
5053 	*keyp = key;
5054 
5055 	return (keybits);
5056 }
5057 
5058 #endif
5059 
5060 /*
5061  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
5062  * it exists.
5063  *
5064  * Both parent and chain must be locked exclusively.
5065  *
5066  * This function will modify the parent if the blockref requires removal
5067  * from the parent's block table.
5068  *
5069  * This function is NOT recursive.  Any entity already pushed into the
5070  * chain (such as an inode) may still need visibility into its contents,
5071  * as well as the ability to read and modify the contents.  For example,
5072  * for an unlinked file which is still open.
5073  *
5074  * Also note that the flusher is responsible for cleaning up empty
5075  * indirect blocks.
5076  */
5077 int
5078 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
5079 		     hammer2_tid_t mtid, int flags)
5080 {
5081 	int error = 0;
5082 
5083 	KKASSERT(hammer2_mtx_owned(&chain->lock));
5084 
5085 	/*
5086 	 * Nothing to do if already marked.
5087 	 *
5088 	 * We need the spinlock on the core whos RBTREE contains chain
5089 	 * to protect against races.
5090 	 */
5091 	if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5092 		KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5093 			 chain->parent == parent);
5094 		error = _hammer2_chain_delete_helper(parent, chain,
5095 						     mtid, flags, NULL);
5096 	}
5097 
5098 	/*
5099 	 * Permanent deletions mark the chain as destroyed.
5100 	 *
5101 	 * NOTE: We do not setflush the chain unless the deletion is
5102 	 *	 permanent, since the deletion of a chain does not actually
5103 	 *	 require it to be flushed.
5104 	 */
5105 	if (error == 0) {
5106 		if (flags & HAMMER2_DELETE_PERMANENT) {
5107 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5108 			hammer2_chain_setflush(chain);
5109 		}
5110 	}
5111 
5112 	return error;
5113 }
5114 
5115 static int
5116 hammer2_chain_delete_obref(hammer2_chain_t *parent, hammer2_chain_t *chain,
5117 		     hammer2_tid_t mtid, int flags,
5118 		     hammer2_blockref_t *obref)
5119 {
5120 	int error = 0;
5121 
5122 	KKASSERT(hammer2_mtx_owned(&chain->lock));
5123 
5124 	/*
5125 	 * Nothing to do if already marked.
5126 	 *
5127 	 * We need the spinlock on the core whos RBTREE contains chain
5128 	 * to protect against races.
5129 	 */
5130 	obref->type = HAMMER2_BREF_TYPE_EMPTY;
5131 	if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5132 		KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5133 			 chain->parent == parent);
5134 		error = _hammer2_chain_delete_helper(parent, chain,
5135 						     mtid, flags, obref);
5136 	}
5137 
5138 	/*
5139 	 * Permanent deletions mark the chain as destroyed.
5140 	 *
5141 	 * NOTE: We do not setflush the chain unless the deletion is
5142 	 *	 permanent, since the deletion of a chain does not actually
5143 	 *	 require it to be flushed.
5144 	 */
5145 	if (error == 0) {
5146 		if (flags & HAMMER2_DELETE_PERMANENT) {
5147 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5148 			hammer2_chain_setflush(chain);
5149 		}
5150 	}
5151 
5152 	return error;
5153 }
5154 
5155 /*
5156  * Returns the index of the nearest element in the blockref array >= elm.
5157  * Returns (count) if no element could be found.
5158  *
5159  * Sets *key_nextp to the next key for loop purposes but does not modify
5160  * it if the next key would be higher than the current value of *key_nextp.
5161  * Note that *key_nexp can overflow to 0, which should be tested by the
5162  * caller.
5163  *
5164  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
5165  *	     held through the operation.
5166  */
5167 static int
5168 hammer2_base_find(hammer2_chain_t *parent,
5169 		  hammer2_blockref_t *base, int count,
5170 		  hammer2_key_t *key_nextp,
5171 		  hammer2_key_t key_beg, hammer2_key_t key_end)
5172 {
5173 	hammer2_blockref_t *scan;
5174 	hammer2_key_t scan_end;
5175 	int i;
5176 	int limit;
5177 
5178 	/*
5179 	 * Require the live chain's already have their core's counted
5180 	 * so we can optimize operations.
5181 	 */
5182 	KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
5183 
5184 	/*
5185 	 * Degenerate case
5186 	 */
5187 	if (count == 0 || base == NULL)
5188 		return(count);
5189 
5190 	/*
5191 	 * Sequential optimization using parent->cache_index.  This is
5192 	 * the most likely scenario.
5193 	 *
5194 	 * We can avoid trailing empty entries on live chains, otherwise
5195 	 * we might have to check the whole block array.
5196 	 */
5197 	i = parent->cache_index;	/* SMP RACE OK */
5198 	cpu_ccfence();
5199 	limit = parent->core.live_zero;
5200 	if (i >= limit)
5201 		i = limit - 1;
5202 	if (i < 0)
5203 		i = 0;
5204 	KKASSERT(i < count);
5205 
5206 	/*
5207 	 * Search backwards
5208 	 */
5209 	scan = &base[i];
5210 	while (i > 0 && (scan->type == HAMMER2_BREF_TYPE_EMPTY ||
5211 	    scan->key > key_beg)) {
5212 		--scan;
5213 		--i;
5214 	}
5215 	parent->cache_index = i;
5216 
5217 	/*
5218 	 * Search forwards, stop when we find a scan element which
5219 	 * encloses the key or until we know that there are no further
5220 	 * elements.
5221 	 */
5222 	while (i < count) {
5223 		if (scan->type != HAMMER2_BREF_TYPE_EMPTY) {
5224 			scan_end = scan->key +
5225 				   ((hammer2_key_t)1 << scan->keybits) - 1;
5226 			if (scan->key > key_beg || scan_end >= key_beg)
5227 				break;
5228 		}
5229 		if (i >= limit)
5230 			return (count);
5231 		++scan;
5232 		++i;
5233 	}
5234 	if (i != count) {
5235 		parent->cache_index = i;
5236 		if (i >= limit) {
5237 			i = count;
5238 		} else {
5239 			scan_end = scan->key +
5240 				   ((hammer2_key_t)1 << scan->keybits);
5241 			if (scan_end && (*key_nextp > scan_end ||
5242 					 *key_nextp == 0)) {
5243 				*key_nextp = scan_end;
5244 			}
5245 		}
5246 	}
5247 	return (i);
5248 }
5249 
5250 /*
5251  * Do a combined search and return the next match either from the blockref
5252  * array or from the in-memory chain.  Sets *brefp to the returned bref in
5253  * both cases, or sets it to NULL if the search exhausted.  Only returns
5254  * a non-NULL chain if the search matched from the in-memory chain.
5255  *
5256  * When no in-memory chain has been found and a non-NULL bref is returned
5257  * in *brefp.
5258  *
5259  *
5260  * The returned chain is not locked or referenced.  Use the returned bref
5261  * to determine if the search exhausted or not.  Iterate if the base find
5262  * is chosen but matches a deleted chain.
5263  *
5264  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
5265  *	     held through the operation.
5266  */
5267 static hammer2_chain_t *
5268 hammer2_combined_find(hammer2_chain_t *parent,
5269 		      hammer2_blockref_t *base, int count,
5270 		      hammer2_key_t *key_nextp,
5271 		      hammer2_key_t key_beg, hammer2_key_t key_end,
5272 		      hammer2_blockref_t **brefp)
5273 {
5274 	hammer2_blockref_t *bref;
5275 	hammer2_chain_t *chain;
5276 	int i;
5277 
5278 	/*
5279 	 * Lookup in block array and in rbtree.
5280 	 */
5281 	*key_nextp = key_end + 1;
5282 	i = hammer2_base_find(parent, base, count, key_nextp,
5283 			      key_beg, key_end);
5284 	chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
5285 
5286 	/*
5287 	 * Neither matched
5288 	 */
5289 	if (i == count && chain == NULL) {
5290 		*brefp = NULL;
5291 		return(NULL);
5292 	}
5293 
5294 	/*
5295 	 * Only chain matched.
5296 	 */
5297 	if (i == count) {
5298 		bref = &chain->bref;
5299 		goto found;
5300 	}
5301 
5302 	/*
5303 	 * Only blockref matched.
5304 	 */
5305 	if (chain == NULL) {
5306 		bref = &base[i];
5307 		goto found;
5308 	}
5309 
5310 	/*
5311 	 * Both in-memory and blockref matched, select the nearer element.
5312 	 *
5313 	 * If both are flush with the left-hand side or both are the
5314 	 * same distance away, select the chain.  In this situation the
5315 	 * chain must have been loaded from the matching blockmap.
5316 	 */
5317 	if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
5318 	    chain->bref.key == base[i].key) {
5319 		KKASSERT(chain->bref.key == base[i].key);
5320 		bref = &chain->bref;
5321 		goto found;
5322 	}
5323 
5324 	/*
5325 	 * Select the nearer key
5326 	 */
5327 	if (chain->bref.key < base[i].key) {
5328 		bref = &chain->bref;
5329 	} else {
5330 		bref = &base[i];
5331 		chain = NULL;
5332 	}
5333 
5334 	/*
5335 	 * If the bref is out of bounds we've exhausted our search.
5336 	 */
5337 found:
5338 	if (bref->key > key_end) {
5339 		*brefp = NULL;
5340 		chain = NULL;
5341 	} else {
5342 		*brefp = bref;
5343 	}
5344 	return(chain);
5345 }
5346 
5347 /*
5348  * Locate the specified block array element and delete it.  The element
5349  * must exist.
5350  *
5351  * The spin lock on the related chain must be held.
5352  *
5353  * NOTE: live_count was adjusted when the chain was deleted, so it does not
5354  *	 need to be adjusted when we commit the media change.
5355  */
5356 void
5357 hammer2_base_delete(hammer2_chain_t *parent,
5358 		    hammer2_blockref_t *base, int count,
5359 		    hammer2_chain_t *chain,
5360 		    hammer2_blockref_t *obref)
5361 {
5362 	hammer2_blockref_t *elm = &chain->bref;
5363 	hammer2_blockref_t *scan;
5364 	hammer2_key_t key_next;
5365 	int i;
5366 
5367 	/*
5368 	 * Delete element.  Expect the element to exist.
5369 	 *
5370 	 * XXX see caller, flush code not yet sophisticated enough to prevent
5371 	 *     re-flushed in some cases.
5372 	 */
5373 	key_next = 0; /* max range */
5374 	i = hammer2_base_find(parent, base, count, &key_next,
5375 			      elm->key, elm->key);
5376 	scan = &base[i];
5377 	if (i == count || scan->type == HAMMER2_BREF_TYPE_EMPTY ||
5378 	    scan->key != elm->key ||
5379 	    ((chain->flags & HAMMER2_CHAIN_BLKMAPUPD) == 0 &&
5380 	     scan->keybits != elm->keybits)) {
5381 		hammer2_spin_unex(&parent->core.spin);
5382 		panic("delete base %p element not found at %d/%d elm %p\n",
5383 		      base, i, count, elm);
5384 		return;
5385 	}
5386 
5387 	/*
5388 	 * Update stats and zero the entry.
5389 	 *
5390 	 * NOTE: Handle radix == 0 (0 bytes) case.
5391 	 */
5392 	if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
5393 		parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
5394 				(int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
5395 	}
5396 	switch(scan->type) {
5397 	case HAMMER2_BREF_TYPE_INODE:
5398 		--parent->bref.embed.stats.inode_count;
5399 		/* fall through */
5400 	case HAMMER2_BREF_TYPE_DATA:
5401 		if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5402 			atomic_set_int(&chain->flags,
5403 				       HAMMER2_CHAIN_HINT_LEAF_COUNT);
5404 		} else {
5405 			if (parent->bref.leaf_count)
5406 				--parent->bref.leaf_count;
5407 		}
5408 		/* fall through */
5409 	case HAMMER2_BREF_TYPE_INDIRECT:
5410 		if (scan->type != HAMMER2_BREF_TYPE_DATA) {
5411 			parent->bref.embed.stats.data_count -=
5412 				scan->embed.stats.data_count;
5413 			parent->bref.embed.stats.inode_count -=
5414 				scan->embed.stats.inode_count;
5415 		}
5416 		if (scan->type == HAMMER2_BREF_TYPE_INODE)
5417 			break;
5418 		if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5419 			atomic_set_int(&chain->flags,
5420 				       HAMMER2_CHAIN_HINT_LEAF_COUNT);
5421 		} else {
5422 			if (parent->bref.leaf_count <= scan->leaf_count)
5423 				parent->bref.leaf_count = 0;
5424 			else
5425 				parent->bref.leaf_count -= scan->leaf_count;
5426 		}
5427 		break;
5428 	case HAMMER2_BREF_TYPE_DIRENT:
5429 		if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5430 			atomic_set_int(&chain->flags,
5431 				       HAMMER2_CHAIN_HINT_LEAF_COUNT);
5432 		} else {
5433 			if (parent->bref.leaf_count)
5434 				--parent->bref.leaf_count;
5435 		}
5436 	default:
5437 		break;
5438 	}
5439 
5440 	if (obref)
5441 		*obref = *scan;
5442 	bzero(scan, sizeof(*scan));
5443 
5444 	/*
5445 	 * We can only optimize parent->core.live_zero for live chains.
5446 	 */
5447 	if (parent->core.live_zero == i + 1) {
5448 		while (--i >= 0 && base[i].type == HAMMER2_BREF_TYPE_EMPTY)
5449 			;
5450 		parent->core.live_zero = i + 1;
5451 	}
5452 
5453 	/*
5454 	 * Clear appropriate blockmap flags in chain.
5455 	 */
5456 	atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BLKMAPPED |
5457 					HAMMER2_CHAIN_BLKMAPUPD);
5458 }
5459 
5460 /*
5461  * Insert the specified element.  The block array must not already have the
5462  * element and must have space available for the insertion.
5463  *
5464  * The spin lock on the related chain must be held.
5465  *
5466  * NOTE: live_count was adjusted when the chain was deleted, so it does not
5467  *	 need to be adjusted when we commit the media change.
5468  */
5469 void
5470 hammer2_base_insert(hammer2_chain_t *parent,
5471 		    hammer2_blockref_t *base, int count,
5472 		    hammer2_chain_t *chain, hammer2_blockref_t *elm)
5473 {
5474 	hammer2_key_t key_next;
5475 	hammer2_key_t xkey;
5476 	int i;
5477 	int j;
5478 	int k;
5479 	int l;
5480 	int u = 1;
5481 
5482 	/*
5483 	 * Insert new element.  Expect the element to not already exist
5484 	 * unless we are replacing it.
5485 	 *
5486 	 * XXX see caller, flush code not yet sophisticated enough to prevent
5487 	 *     re-flushed in some cases.
5488 	 */
5489 	key_next = 0; /* max range */
5490 	i = hammer2_base_find(parent, base, count, &key_next,
5491 			      elm->key, elm->key);
5492 
5493 	/*
5494 	 * Shortcut fill optimization, typical ordered insertion(s) may not
5495 	 * require a search.
5496 	 */
5497 	KKASSERT(i >= 0 && i <= count);
5498 
5499 	/*
5500 	 * Set appropriate blockmap flags in chain (if not NULL)
5501 	 */
5502 	if (chain)
5503 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_BLKMAPPED);
5504 
5505 	/*
5506 	 * Update stats and zero the entry
5507 	 */
5508 	if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
5509 		parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
5510 				(int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
5511 	}
5512 	switch(elm->type) {
5513 	case HAMMER2_BREF_TYPE_INODE:
5514 		++parent->bref.embed.stats.inode_count;
5515 		/* fall through */
5516 	case HAMMER2_BREF_TYPE_DATA:
5517 		if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5518 			++parent->bref.leaf_count;
5519 		/* fall through */
5520 	case HAMMER2_BREF_TYPE_INDIRECT:
5521 		if (elm->type != HAMMER2_BREF_TYPE_DATA) {
5522 			parent->bref.embed.stats.data_count +=
5523 				elm->embed.stats.data_count;
5524 			parent->bref.embed.stats.inode_count +=
5525 				elm->embed.stats.inode_count;
5526 		}
5527 		if (elm->type == HAMMER2_BREF_TYPE_INODE)
5528 			break;
5529 		if (parent->bref.leaf_count + elm->leaf_count <
5530 		    HAMMER2_BLOCKREF_LEAF_MAX) {
5531 			parent->bref.leaf_count += elm->leaf_count;
5532 		} else {
5533 			parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5534 		}
5535 		break;
5536 	case HAMMER2_BREF_TYPE_DIRENT:
5537 		if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5538 			++parent->bref.leaf_count;
5539 		break;
5540 	default:
5541 		break;
5542 	}
5543 
5544 
5545 	/*
5546 	 * We can only optimize parent->core.live_zero for live chains.
5547 	 */
5548 	if (i == count && parent->core.live_zero < count) {
5549 		i = parent->core.live_zero++;
5550 		base[i] = *elm;
5551 		return;
5552 	}
5553 
5554 	xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5555 	if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5556 		hammer2_spin_unex(&parent->core.spin);
5557 		panic("insert base %p overlapping elements at %d elm %p\n",
5558 		      base, i, elm);
5559 	}
5560 
5561 	/*
5562 	 * Try to find an empty slot before or after.
5563 	 */
5564 	j = i;
5565 	k = i;
5566 	while (j > 0 || k < count) {
5567 		--j;
5568 		if (j >= 0 && base[j].type == HAMMER2_BREF_TYPE_EMPTY) {
5569 			if (j == i - 1) {
5570 				base[j] = *elm;
5571 			} else {
5572 				bcopy(&base[j+1], &base[j],
5573 				      (i - j - 1) * sizeof(*base));
5574 				base[i - 1] = *elm;
5575 			}
5576 			goto validate;
5577 		}
5578 		++k;
5579 		if (k < count && base[k].type == HAMMER2_BREF_TYPE_EMPTY) {
5580 			bcopy(&base[i], &base[i+1],
5581 			      (k - i) * sizeof(hammer2_blockref_t));
5582 			base[i] = *elm;
5583 
5584 			/*
5585 			 * We can only update parent->core.live_zero for live
5586 			 * chains.
5587 			 */
5588 			if (parent->core.live_zero <= k)
5589 				parent->core.live_zero = k + 1;
5590 			u = 2;
5591 			goto validate;
5592 		}
5593 	}
5594 	panic("hammer2_base_insert: no room!");
5595 
5596 	/*
5597 	 * Debugging
5598 	 */
5599 validate:
5600 	key_next = 0;
5601 	for (l = 0; l < count; ++l) {
5602 		if (base[l].type != HAMMER2_BREF_TYPE_EMPTY) {
5603 			key_next = base[l].key +
5604 				   ((hammer2_key_t)1 << base[l].keybits) - 1;
5605 			break;
5606 		}
5607 	}
5608 	while (++l < count) {
5609 		if (base[l].type != HAMMER2_BREF_TYPE_EMPTY) {
5610 			if (base[l].key <= key_next)
5611 				panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5612 			key_next = base[l].key +
5613 				   ((hammer2_key_t)1 << base[l].keybits) - 1;
5614 
5615 		}
5616 	}
5617 
5618 }
5619 
5620 #if 0
5621 
5622 /*
5623  * Sort the blockref array for the chain.  Used by the flush code to
5624  * sort the blockref[] array.
5625  *
5626  * The chain must be exclusively locked AND spin-locked.
5627  */
5628 typedef hammer2_blockref_t *hammer2_blockref_p;
5629 
5630 static
5631 int
5632 hammer2_base_sort_callback(const void *v1, const void *v2)
5633 {
5634 	hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5635 	hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5636 
5637 	/*
5638 	 * Make sure empty elements are placed at the end of the array
5639 	 */
5640 	if (bref1->type == HAMMER2_BREF_TYPE_EMPTY) {
5641 		if (bref2->type == HAMMER2_BREF_TYPE_EMPTY)
5642 			return(0);
5643 		return(1);
5644 	} else if (bref2->type == HAMMER2_BREF_TYPE_EMPTY) {
5645 		return(-1);
5646 	}
5647 
5648 	/*
5649 	 * Sort by key
5650 	 */
5651 	if (bref1->key < bref2->key)
5652 		return(-1);
5653 	if (bref1->key > bref2->key)
5654 		return(1);
5655 	return(0);
5656 }
5657 
5658 void
5659 hammer2_base_sort(hammer2_chain_t *chain)
5660 {
5661 	hammer2_blockref_t *base;
5662 	int count;
5663 
5664 	switch(chain->bref.type) {
5665 	case HAMMER2_BREF_TYPE_INODE:
5666 		/*
5667 		 * Special shortcut for embedded data returns the inode
5668 		 * itself.  Callers must detect this condition and access
5669 		 * the embedded data (the strategy code does this for us).
5670 		 *
5671 		 * This is only applicable to regular files and softlinks.
5672 		 */
5673 		if (chain->data->ipdata.meta.op_flags &
5674 		    HAMMER2_OPFLAG_DIRECTDATA) {
5675 			return;
5676 		}
5677 		base = &chain->data->ipdata.u.blockset.blockref[0];
5678 		count = HAMMER2_SET_COUNT;
5679 		break;
5680 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5681 	case HAMMER2_BREF_TYPE_INDIRECT:
5682 		/*
5683 		 * Optimize indirect blocks in the INITIAL state to avoid
5684 		 * I/O.
5685 		 */
5686 		KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5687 		base = &chain->data->npdata[0];
5688 		count = chain->bytes / sizeof(hammer2_blockref_t);
5689 		break;
5690 	case HAMMER2_BREF_TYPE_VOLUME:
5691 		base = &chain->data->voldata.sroot_blockset.blockref[0];
5692 		count = HAMMER2_SET_COUNT;
5693 		break;
5694 	case HAMMER2_BREF_TYPE_FREEMAP:
5695 		base = &chain->data->blkset.blockref[0];
5696 		count = HAMMER2_SET_COUNT;
5697 		break;
5698 	default:
5699 		panic("hammer2_base_sort: unrecognized "
5700 		      "blockref(A) type: %d",
5701 		      chain->bref.type);
5702 		base = NULL;	/* safety */
5703 		count = 0;	/* safety */
5704 		break;
5705 	}
5706 	kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5707 }
5708 
5709 #endif
5710 
5711 /*
5712  * Set the check data for a chain.  This can be a heavy-weight operation
5713  * and typically only runs on-flush.  For file data check data is calculated
5714  * when the logical buffers are flushed.
5715  */
5716 void
5717 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5718 {
5719 	atomic_clear_int(&chain->flags, HAMMER2_CHAIN_NOTTESTED);
5720 
5721 	switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5722 	case HAMMER2_CHECK_NONE:
5723 		break;
5724 	case HAMMER2_CHECK_DISABLED:
5725 		break;
5726 	case HAMMER2_CHECK_ISCSI32:
5727 		chain->bref.check.iscsi32.value =
5728 			hammer2_icrc32(bdata, chain->bytes);
5729 		break;
5730 	case HAMMER2_CHECK_XXHASH64:
5731 		chain->bref.check.xxhash64.value =
5732 			XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5733 		break;
5734 	case HAMMER2_CHECK_SHA192:
5735 		assert(0); /* XXX unsupported */
5736 		/*
5737 		{
5738 			SHA256_CTX hash_ctx;
5739 			union {
5740 				uint8_t digest[SHA256_DIGEST_LENGTH];
5741 				uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5742 			} u;
5743 
5744 			SHA256_Init(&hash_ctx);
5745 			SHA256_Update(&hash_ctx, bdata, chain->bytes);
5746 			SHA256_Final(u.digest, &hash_ctx);
5747 			u.digest64[2] ^= u.digest64[3];
5748 			bcopy(u.digest,
5749 			      chain->bref.check.sha192.data,
5750 			      sizeof(chain->bref.check.sha192.data));
5751 		}
5752 		*/
5753 		break;
5754 	case HAMMER2_CHECK_FREEMAP:
5755 		chain->bref.check.freemap.icrc32 =
5756 			hammer2_icrc32(bdata, chain->bytes);
5757 		break;
5758 	default:
5759 		kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5760 			chain->bref.methods);
5761 		break;
5762 	}
5763 }
5764 
5765 /*
5766  * Characterize a failed check code and try to trace back to the inode.
5767  */
5768 static void
5769 hammer2_characterize_failed_chain(hammer2_chain_t *chain, uint64_t check,
5770 				  int bits)
5771 {
5772 	hammer2_chain_t *lchain;
5773 	hammer2_chain_t *ochain;
5774 	int did;
5775 
5776 	did = krateprintf(&krate_h2chk,
5777 		"chain %016jx.%02x (%s) meth=%02x CHECK FAIL "
5778 		"(flags=%08x, bref/data ",
5779 		chain->bref.data_off,
5780 		chain->bref.type,
5781 		hammer2_bref_type_str(chain->bref.type),
5782 		chain->bref.methods,
5783 		chain->flags);
5784 	if (did == 0)
5785 		return;
5786 
5787 	if (bits == 32) {
5788 		kprintf("%08x/%08x)\n",
5789 			chain->bref.check.iscsi32.value,
5790 			(uint32_t)check);
5791 	} else {
5792 		kprintf("%016jx/%016jx)\n",
5793 			chain->bref.check.xxhash64.value,
5794 			check);
5795 	}
5796 
5797 	/*
5798 	 * Run up the chains to try to find the governing inode so we
5799 	 * can report it.
5800 	 *
5801 	 * XXX This error reporting is not really MPSAFE
5802 	 */
5803 	ochain = chain;
5804 	lchain = chain;
5805 	while (chain && chain->bref.type != HAMMER2_BREF_TYPE_INODE) {
5806 		lchain = chain;
5807 		chain = chain->parent;
5808 	}
5809 
5810 	if (chain && chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
5811 	    ((chain->bref.flags & HAMMER2_BREF_FLAG_PFSROOT) == 0 ||
5812 	     (lchain->bref.key & HAMMER2_DIRHASH_VISIBLE))) {
5813 		kprintf("   Resides at/in inode %ld\n",
5814 			chain->bref.key);
5815 	} else if (chain && chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5816 		kprintf("   Resides in inode index - CRITICAL!!!\n");
5817 	} else {
5818 		kprintf("   Resides in root index - CRITICAL!!!\n");
5819 	}
5820 	if (ochain->hmp) {
5821 		const char *pfsname = "UNKNOWN";
5822 		int i;
5823 
5824 		if (ochain->pmp) {
5825 			for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
5826 				if (ochain->pmp->pfs_hmps[i] == ochain->hmp &&
5827 				    ochain->pmp->pfs_names[i]) {
5828 					pfsname = ochain->pmp->pfs_names[i];
5829 					break;
5830 				}
5831 			}
5832 		}
5833 		kprintf("   In pfs %s on device %s\n",
5834 			pfsname, ochain->hmp->devrepname);
5835 	}
5836 }
5837 
5838 /*
5839  * Returns non-zero on success, 0 on failure.
5840  */
5841 int
5842 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5843 {
5844 	uint32_t check32;
5845 	uint64_t check64;
5846 	int r;
5847 
5848 	if (chain->flags & HAMMER2_CHAIN_NOTTESTED)
5849 		return 1;
5850 
5851 	switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5852 	case HAMMER2_CHECK_NONE:
5853 		r = 1;
5854 		break;
5855 	case HAMMER2_CHECK_DISABLED:
5856 		r = 1;
5857 		break;
5858 	case HAMMER2_CHECK_ISCSI32:
5859 		check32 = hammer2_icrc32(bdata, chain->bytes);
5860 		r = (chain->bref.check.iscsi32.value == check32);
5861 		if (r == 0) {
5862 			hammer2_characterize_failed_chain(chain, check32, 32);
5863 		}
5864 		hammer2_process_icrc32 += chain->bytes;
5865 		break;
5866 	case HAMMER2_CHECK_XXHASH64:
5867 		check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5868 		r = (chain->bref.check.xxhash64.value == check64);
5869 		if (r == 0) {
5870 			hammer2_characterize_failed_chain(chain, check64, 64);
5871 		}
5872 		hammer2_process_xxhash64 += chain->bytes;
5873 		break;
5874 	case HAMMER2_CHECK_SHA192:
5875 		assert(0); /* XXX unsupported */
5876 		/*
5877 		{
5878 			SHA256_CTX hash_ctx;
5879 			union {
5880 				uint8_t digest[SHA256_DIGEST_LENGTH];
5881 				uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5882 			} u;
5883 
5884 			SHA256_Init(&hash_ctx);
5885 			SHA256_Update(&hash_ctx, bdata, chain->bytes);
5886 			SHA256_Final(u.digest, &hash_ctx);
5887 			u.digest64[2] ^= u.digest64[3];
5888 			if (bcmp(u.digest,
5889 				 chain->bref.check.sha192.data,
5890 			         sizeof(chain->bref.check.sha192.data)) == 0) {
5891 				r = 1;
5892 			} else {
5893 				r = 0;
5894 				krateprintf(&krate_h2chk,
5895 					"chain %016jx.%02x meth=%02x "
5896 					"CHECK FAIL\n",
5897 					chain->bref.data_off,
5898 					chain->bref.type,
5899 					chain->bref.methods);
5900 			}
5901 		}
5902 		*/
5903 		break;
5904 	case HAMMER2_CHECK_FREEMAP:
5905 		r = (chain->bref.check.freemap.icrc32 ==
5906 		     hammer2_icrc32(bdata, chain->bytes));
5907 		if (r == 0) {
5908 			int did;
5909 
5910 			did = krateprintf(&krate_h2chk,
5911 					  "chain %016jx.%02x meth=%02x "
5912 					  "CHECK FAIL\n",
5913 					  chain->bref.data_off,
5914 					  chain->bref.type,
5915 					  chain->bref.methods);
5916 			if (did) {
5917 				kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5918 					chain->bref.check.freemap.icrc32,
5919 					hammer2_icrc32(bdata, chain->bytes),
5920 					chain->bytes);
5921 				if (chain->dio) {
5922 					kprintf("dio %p buf %016jx,%ld "
5923 						"bdata %p/%p\n",
5924 						chain->dio,
5925 						chain->dio->bp->b_loffset,
5926 						chain->dio->bp->b_bufsize,
5927 						bdata,
5928 						chain->dio->bp->b_data);
5929 				}
5930 			}
5931 		}
5932 		break;
5933 	default:
5934 		kprintf("hammer2_chain_testcheck: unknown check type %02x\n",
5935 			chain->bref.methods);
5936 		r = 1;
5937 		break;
5938 	}
5939 	return r;
5940 }
5941 
5942 /*
5943  * Acquire the chain and parent representing the specified inode for the
5944  * device at the specified cluster index.
5945  *
5946  * The flags passed in are LOOKUP flags, not RESOLVE flags.
5947  *
5948  * If we are unable to locate the inode, HAMMER2_ERROR_EIO or HAMMER2_ERROR_CHECK
5949  * is returned.  In case of error, *chainp and/or *parentp may still be returned
5950  * non-NULL.
5951  *
5952  * The caller may pass-in a locked *parentp and/or *chainp, or neither.
5953  * They will be unlocked and released by this function.  The *parentp and
5954  * *chainp representing the located inode are returned locked.
5955  *
5956  * The returned error includes any error on the returned chain in addition to
5957  * errors incurred while trying to lookup the inode.  However, a chain->error
5958  * might not be recognized if HAMMER2_LOOKUP_NODATA is passed.  This flag may
5959  * not be passed to this function.
5960  */
5961 int
5962 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5963 			 int clindex, int flags,
5964 			 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5965 {
5966 	hammer2_chain_t *parent;
5967 	hammer2_chain_t *rchain;
5968 	hammer2_key_t key_dummy;
5969 	hammer2_inode_t *ip;
5970 	int resolve_flags;
5971 	int error;
5972 
5973 	KKASSERT((flags & HAMMER2_LOOKUP_NODATA) == 0);
5974 
5975 	resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5976 			HAMMER2_RESOLVE_SHARED : 0;
5977 
5978 	/*
5979 	 * Caller expects us to replace these.
5980 	 */
5981 	if (*chainp) {
5982 		hammer2_chain_unlock(*chainp);
5983 		hammer2_chain_drop(*chainp);
5984 		*chainp = NULL;
5985 	}
5986 	if (*parentp) {
5987 		hammer2_chain_unlock(*parentp);
5988 		hammer2_chain_drop(*parentp);
5989 		*parentp = NULL;
5990 	}
5991 
5992 	/*
5993 	 * Be very careful, this is a backend function and we CANNOT
5994 	 * lock any frontend inode structure we find.  But we have to
5995 	 * look the inode up this way first in case it exists but is
5996 	 * detached from the radix tree.
5997 	 */
5998 	ip = hammer2_inode_lookup(pmp, inum);
5999 	if (ip) {
6000 		*chainp = hammer2_inode_chain_and_parent(ip, clindex,
6001 						       parentp,
6002 						       resolve_flags);
6003 		hammer2_inode_drop(ip);
6004 		if (*chainp)
6005 			return (*chainp)->error;
6006 		hammer2_chain_unlock(*chainp);
6007 		hammer2_chain_drop(*chainp);
6008 		*chainp = NULL;
6009 		if (*parentp) {
6010 			hammer2_chain_unlock(*parentp);
6011 			hammer2_chain_drop(*parentp);
6012 			*parentp = NULL;
6013 		}
6014 	}
6015 
6016 	/*
6017 	 * Inodes hang off of the iroot (bit 63 is clear, differentiating
6018 	 * inodes from root directory entries in the key lookup).
6019 	 */
6020 	parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
6021 	rchain = NULL;
6022 	if (parent) {
6023 		/*
6024 		 * NOTE: rchain can be returned as NULL even if error == 0
6025 		 *	 (i.e. not found)
6026 		 */
6027 		rchain = hammer2_chain_lookup(&parent, &key_dummy,
6028 					      inum, inum,
6029 					      &error, flags);
6030 		/*
6031 		 * Propagate a chain-specific error to caller.
6032 		 *
6033 		 * If the chain is not errored, we must still validate that the inode
6034 		 * number is correct, because all hell will break loose if it isn't
6035 		 * correct.  It should always be correct so print to the console and
6036 		 * simulate a CHECK error if it is not.
6037 		 */
6038 		if (error == 0 && rchain) {
6039 			error = rchain->error;
6040 			if (error == 0 && rchain->data) {
6041 				if (inum != rchain->data->ipdata.meta.inum) {
6042 					kprintf("hammer2_chain_inode_find: lookup inum %ld, "
6043 						"got valid inode but with inum %ld\n",
6044 						inum, rchain->data->ipdata.meta.inum);
6045 					error = HAMMER2_ERROR_CHECK;
6046 					rchain->error = error;
6047 				}
6048 			}
6049 		}
6050 	} else {
6051 		error = HAMMER2_ERROR_EIO;
6052 	}
6053 	*parentp = parent;
6054 	*chainp = rchain;
6055 
6056 	return error;
6057 }
6058 
6059 /*
6060  * Used by the bulkscan code to snapshot the synchronized storage for
6061  * a volume, allowing it to be scanned concurrently against normal
6062  * operation.
6063  */
6064 hammer2_chain_t *
6065 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
6066 {
6067 	hammer2_chain_t *copy;
6068 
6069 	copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
6070 	copy->data = kmalloc(sizeof(copy->data->voldata),
6071 			     hmp->mmsg, M_WAITOK | M_ZERO);
6072 	hammer2_voldata_lock(hmp);
6073 	copy->data->voldata = hmp->volsync;
6074 	hammer2_voldata_unlock(hmp);
6075 
6076 	return copy;
6077 }
6078 
6079 void
6080 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
6081 {
6082 	KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
6083 	KKASSERT(copy->data);
6084 	kfree(copy->data, copy->hmp->mmsg);
6085 	copy->data = NULL;
6086 	hammer2_chain_drop(copy);
6087 }
6088 
6089 /*
6090  * Returns non-zero if the chain (INODE or DIRENT) matches the
6091  * filename.
6092  */
6093 int
6094 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
6095 			  size_t name_len)
6096 {
6097 	const hammer2_inode_data_t *ripdata;
6098 
6099 	if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
6100 		ripdata = &chain->data->ipdata;
6101 		if (ripdata->meta.name_len == name_len &&
6102 		    bcmp(ripdata->filename, name, name_len) == 0) {
6103 			return 1;
6104 		}
6105 	}
6106 	if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
6107 	    chain->bref.embed.dirent.namlen == name_len) {
6108 		if (name_len > sizeof(chain->bref.check.buf) &&
6109 		    bcmp(chain->data->buf, name, name_len) == 0) {
6110 			return 1;
6111 		}
6112 		if (name_len <= sizeof(chain->bref.check.buf) &&
6113 		    bcmp(chain->bref.check.buf, name, name_len) == 0) {
6114 			return 1;
6115 		}
6116 	}
6117 	return 0;
6118 }
6119