xref: /dragonfly/sys/vfs/hammer2/hammer2_chain.c (revision 279dd846)
1 /*
2  * Copyright (c) 2011-2015 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * and Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 /*
36  * This subsystem implements most of the core support functions for
37  * the hammer2_chain structure.
38  *
39  * Chains are the in-memory version on media objects (volume header, inodes,
40  * indirect blocks, data blocks, etc).  Chains represent a portion of the
41  * HAMMER2 topology.
42  *
43  * Chains are no-longer delete-duplicated.  Instead, the original in-memory
44  * chain will be moved along with its block reference (e.g. for things like
45  * renames, hardlink operations, modifications, etc), and will be indexed
46  * on a secondary list for flush handling instead of propagating a flag
47  * upward to the root.
48  *
49  * Concurrent front-end operations can still run against backend flushes
50  * as long as they do not cross the current flush boundary.  An operation
51  * running above the current flush (in areas not yet flushed) can become
52  * part of the current flush while ano peration running below the current
53  * flush can become part of the next flush.
54  */
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
59 #include <sys/lock.h>
60 #include <sys/kern_syscall.h>
61 #include <sys/uuid.h>
62 
63 #include <crypto/sha2/sha2.h>
64 
65 #include "hammer2.h"
66 
67 static int hammer2_indirect_optimize;	/* XXX SYSCTL */
68 
69 static hammer2_chain_t *hammer2_chain_create_indirect(
70 		hammer2_chain_t *parent,
71 		hammer2_key_t key, int keybits,
72 		hammer2_tid_t mtid, int for_type, int *errorp);
73 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
74 static hammer2_chain_t *hammer2_combined_find(
75 		hammer2_chain_t *parent,
76 		hammer2_blockref_t *base, int count,
77 		int *cache_indexp, hammer2_key_t *key_nextp,
78 		hammer2_key_t key_beg, hammer2_key_t key_end,
79 		hammer2_blockref_t **bresp);
80 
81 /*
82  * Basic RBTree for chains (core->rbtree and core->dbtree).  Chains cannot
83  * overlap in the RB trees.  Deleted chains are moved from rbtree to either
84  * dbtree or to dbq.
85  *
86  * Chains in delete-duplicate sequences can always iterate through core_entry
87  * to locate the live version of the chain.
88  */
89 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
90 
91 int
92 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
93 {
94 	hammer2_key_t c1_beg;
95 	hammer2_key_t c1_end;
96 	hammer2_key_t c2_beg;
97 	hammer2_key_t c2_end;
98 
99 	/*
100 	 * Compare chains.  Overlaps are not supposed to happen and catch
101 	 * any software issues early we count overlaps as a match.
102 	 */
103 	c1_beg = chain1->bref.key;
104 	c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
105 	c2_beg = chain2->bref.key;
106 	c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
107 
108 	if (c1_end < c2_beg)	/* fully to the left */
109 		return(-1);
110 	if (c1_beg > c2_end)	/* fully to the right */
111 		return(1);
112 	return(0);		/* overlap (must not cross edge boundary) */
113 }
114 
115 static __inline
116 int
117 hammer2_isclusterable(hammer2_chain_t *chain)
118 {
119 	if (hammer2_cluster_enable) {
120 		if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
121 		    chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
122 		    chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
123 			return(1);
124 		}
125 	}
126 	return(0);
127 }
128 
129 /*
130  * Make a chain visible to the flusher.  The flusher needs to be able to
131  * do flushes of subdirectory chains or single files so it does a top-down
132  * recursion using the ONFLUSH flag for the recursion.  It locates MODIFIED
133  * or UPDATE chains and flushes back up the chain to the volume root.
134  *
135  * This routine sets ONFLUSH upward until it hits the volume root.  For
136  * simplicity we ignore PFSROOT boundaries whos rules can be complex.
137  * Extra ONFLUSH flagging doesn't hurt the filesystem.
138  */
139 void
140 hammer2_chain_setflush(hammer2_chain_t *chain)
141 {
142 	hammer2_chain_t *parent;
143 
144 	if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145 		hammer2_spin_sh(&chain->core.spin);
146 		while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
147 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
148 			if ((parent = chain->parent) == NULL)
149 				break;
150 			hammer2_spin_sh(&parent->core.spin);
151 			hammer2_spin_unsh(&chain->core.spin);
152 			chain = parent;
153 		}
154 		hammer2_spin_unsh(&chain->core.spin);
155 	}
156 }
157 
158 /*
159  * Allocate a new disconnected chain element representing the specified
160  * bref.  chain->refs is set to 1 and the passed bref is copied to
161  * chain->bref.  chain->bytes is derived from the bref.
162  *
163  * chain->pmp inherits pmp unless the chain is an inode (other than the
164  * super-root inode).
165  *
166  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
167  */
168 hammer2_chain_t *
169 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
170 		    hammer2_blockref_t *bref)
171 {
172 	hammer2_chain_t *chain;
173 	u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
174 
175 	/*
176 	 * Construct the appropriate system structure.
177 	 */
178 	switch(bref->type) {
179 	case HAMMER2_BREF_TYPE_INODE:
180 	case HAMMER2_BREF_TYPE_INDIRECT:
181 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
182 	case HAMMER2_BREF_TYPE_DATA:
183 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
184 		/*
185 		 * Chain's are really only associated with the hmp but we
186 		 * maintain a pmp association for per-mount memory tracking
187 		 * purposes.  The pmp can be NULL.
188 		 */
189 		chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
190 		break;
191 	case HAMMER2_BREF_TYPE_VOLUME:
192 	case HAMMER2_BREF_TYPE_FREEMAP:
193 		/*
194 		 * Only hammer2_chain_bulksnap() calls this function with these
195 		 * types.
196 		 */
197 		chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
198 		break;
199 	default:
200 		chain = NULL;
201 		panic("hammer2_chain_alloc: unrecognized blockref type: %d",
202 		      bref->type);
203 	}
204 
205 	/*
206 	 * Initialize the new chain structure.  pmp must be set to NULL for
207 	 * chains belonging to the super-root topology of a device mount.
208 	 */
209 	if (pmp == hmp->spmp)
210 		chain->pmp = NULL;
211 	else
212 		chain->pmp = pmp;
213 	chain->hmp = hmp;
214 	chain->bref = *bref;
215 	chain->bytes = bytes;
216 	chain->refs = 1;
217 	chain->flags = HAMMER2_CHAIN_ALLOCATED;
218 
219 	/*
220 	 * Set the PFS boundary flag if this chain represents a PFS root.
221 	 */
222 	if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
223 		chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
224 	hammer2_chain_core_init(chain);
225 
226 	return (chain);
227 }
228 
229 /*
230  * Initialize a chain's core structure.  This structure used to be allocated
231  * but is now embedded.
232  *
233  * The core is not locked.  No additional refs on the chain are made.
234  * (trans) must not be NULL if (core) is not NULL.
235  */
236 void
237 hammer2_chain_core_init(hammer2_chain_t *chain)
238 {
239 	/*
240 	 * Fresh core under nchain (no multi-homing of ochain's
241 	 * sub-tree).
242 	 */
243 	RB_INIT(&chain->core.rbtree);	/* live chains */
244 	hammer2_mtx_init(&chain->lock, "h2chain");
245 }
246 
247 /*
248  * Add a reference to a chain element, preventing its destruction.
249  *
250  * (can be called with spinlock held)
251  */
252 void
253 hammer2_chain_ref(hammer2_chain_t *chain)
254 {
255 	atomic_add_int(&chain->refs, 1);
256 #if 0
257 	kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
258 	print_backtrace(8);
259 #endif
260 }
261 
262 /*
263  * Insert the chain in the core rbtree.
264  *
265  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
266  * chain is a special case used by the flush code that is placed on the
267  * unstaged deleted list to avoid confusing the live view.
268  */
269 #define HAMMER2_CHAIN_INSERT_SPIN	0x0001
270 #define HAMMER2_CHAIN_INSERT_LIVE	0x0002
271 #define HAMMER2_CHAIN_INSERT_RACE	0x0004
272 
273 static
274 int
275 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
276 		     int flags, int generation)
277 {
278 	hammer2_chain_t *xchain;
279 	int error = 0;
280 
281 	if (flags & HAMMER2_CHAIN_INSERT_SPIN)
282 		hammer2_spin_ex(&parent->core.spin);
283 
284 	/*
285 	 * Interlocked by spinlock, check for race
286 	 */
287 	if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
288 	    parent->core.generation != generation) {
289 		error = EAGAIN;
290 		goto failed;
291 	}
292 
293 	/*
294 	 * Insert chain
295 	 */
296 	xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
297 	KASSERT(xchain == NULL,
298 		("hammer2_chain_insert: collision %p %p", chain, xchain));
299 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
300 	chain->parent = parent;
301 	++parent->core.chain_count;
302 	++parent->core.generation;	/* XXX incs for _get() too, XXX */
303 
304 	/*
305 	 * We have to keep track of the effective live-view blockref count
306 	 * so the create code knows when to push an indirect block.
307 	 */
308 	if (flags & HAMMER2_CHAIN_INSERT_LIVE)
309 		atomic_add_int(&parent->core.live_count, 1);
310 failed:
311 	if (flags & HAMMER2_CHAIN_INSERT_SPIN)
312 		hammer2_spin_unex(&parent->core.spin);
313 	return error;
314 }
315 
316 /*
317  * Drop the caller's reference to the chain.  When the ref count drops to
318  * zero this function will try to disassociate the chain from its parent and
319  * deallocate it, then recursely drop the parent using the implied ref
320  * from the chain's chain->parent.
321  */
322 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
323 
324 void
325 hammer2_chain_drop(hammer2_chain_t *chain)
326 {
327 	u_int refs;
328 	u_int need = 0;
329 
330 	if (hammer2_debug & 0x200000)
331 		Debugger("drop");
332 #if 0
333 	kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
334 	print_backtrace(8);
335 #endif
336 
337 	if (chain->flags & HAMMER2_CHAIN_UPDATE)
338 		++need;
339 	if (chain->flags & HAMMER2_CHAIN_MODIFIED)
340 		++need;
341 	KKASSERT(chain->refs > need);
342 
343 	while (chain) {
344 		refs = chain->refs;
345 		cpu_ccfence();
346 		KKASSERT(refs > 0);
347 
348 		if (refs == 1) {
349 			chain = hammer2_chain_lastdrop(chain);
350 		} else {
351 			if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
352 				break;
353 			/* retry the same chain */
354 		}
355 	}
356 }
357 
358 /*
359  * Safe handling of the 1->0 transition on chain.  Returns a chain for
360  * recursive drop or NULL, possibly returning the same chain if the atomic
361  * op fails.
362  *
363  * Whem two chains need to be recursively dropped we use the chain
364  * we would otherwise free to placehold the additional chain.  It's a bit
365  * convoluted but we can't just recurse without potentially blowing out
366  * the kernel stack.
367  *
368  * The chain cannot be freed if it has any children.
369  *
370  * The core spinlock is allowed nest child-to-parent (not parent-to-child).
371  */
372 static
373 hammer2_chain_t *
374 hammer2_chain_lastdrop(hammer2_chain_t *chain)
375 {
376 	hammer2_pfs_t *pmp;
377 	hammer2_dev_t *hmp;
378 	hammer2_chain_t *parent;
379 	hammer2_chain_t *rdrop;
380 
381 	/*
382 	 * Spinlock the core and check to see if it is empty.  If it is
383 	 * not empty we leave chain intact with refs == 0.  The elements
384 	 * in core->rbtree are associated with other chains contemporary
385 	 * with ours but not with our chain directly.
386 	 */
387 	hammer2_spin_ex(&chain->core.spin);
388 
389 	/*
390 	 * We can't free non-stale chains with children until we are
391 	 * able to free the children because there might be a flush
392 	 * dependency.  Flushes of stale children (which should also
393 	 * have their deleted flag set) short-cut recursive flush
394 	 * dependencies and can be freed here.  Any flushes which run
395 	 * through stale children due to the flush synchronization
396 	 * point should have a FLUSH_* bit set in the chain and not
397 	 * reach lastdrop at this time.
398 	 *
399 	 * NOTE: We return (chain) on failure to retry.
400 	 */
401 	if (chain->core.chain_count) {
402 		if (atomic_cmpset_int(&chain->refs, 1, 0)) {
403 			hammer2_spin_unex(&chain->core.spin);
404 			chain = NULL;	/* success */
405 		} else {
406 			hammer2_spin_unex(&chain->core.spin);
407 		}
408 		return(chain);
409 	}
410 	/* no chains left under us */
411 
412 	/*
413 	 * chain->core has no children left so no accessors can get to our
414 	 * chain from there.  Now we have to lock the parent core to interlock
415 	 * remaining possible accessors that might bump chain's refs before
416 	 * we can safely drop chain's refs with intent to free the chain.
417 	 */
418 	hmp = chain->hmp;
419 	pmp = chain->pmp;	/* can be NULL */
420 	rdrop = NULL;
421 
422 	/*
423 	 * Spinlock the parent and try to drop the last ref on chain.
424 	 * On success remove chain from its parent, otherwise return NULL.
425 	 *
426 	 * (normal core locks are top-down recursive but we define core
427 	 *  spinlocks as bottom-up recursive, so this is safe).
428 	 */
429 	if ((parent = chain->parent) != NULL) {
430 		hammer2_spin_ex(&parent->core.spin);
431 		if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
432 			/* 1->0 transition failed */
433 			hammer2_spin_unex(&parent->core.spin);
434 			hammer2_spin_unex(&chain->core.spin);
435 			return(chain);	/* retry */
436 		}
437 
438 		/*
439 		 * 1->0 transition successful, remove chain from its
440 		 * above core.
441 		 */
442 		if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
443 			RB_REMOVE(hammer2_chain_tree,
444 				  &parent->core.rbtree, chain);
445 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
446 			--parent->core.chain_count;
447 			chain->parent = NULL;
448 		}
449 
450 		/*
451 		 * If our chain was the last chain in the parent's core the
452 		 * core is now empty and its parent might have to be
453 		 * re-dropped if it has 0 refs.
454 		 */
455 		if (parent->core.chain_count == 0) {
456 			rdrop = parent;
457 			if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
458 				rdrop = NULL;
459 			}
460 		}
461 		hammer2_spin_unex(&parent->core.spin);
462 		parent = NULL;	/* safety */
463 	}
464 
465 	/*
466 	 * Successful 1->0 transition and the chain can be destroyed now.
467 	 *
468 	 * We still have the core spinlock, and core's chain_count is 0.
469 	 * Any parent spinlock is gone.
470 	 */
471 	hammer2_spin_unex(&chain->core.spin);
472 	KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
473 		 chain->core.chain_count == 0);
474 
475 	/*
476 	 * All spin locks are gone, finish freeing stuff.
477 	 */
478 	KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
479 				  HAMMER2_CHAIN_MODIFIED)) == 0);
480 	hammer2_chain_drop_data(chain, 1);
481 
482 	KKASSERT(chain->dio == NULL);
483 
484 	/*
485 	 * Once chain resources are gone we can use the now dead chain
486 	 * structure to placehold what might otherwise require a recursive
487 	 * drop, because we have potentially two things to drop and can only
488 	 * return one directly.
489 	 */
490 	if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
491 		chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
492 		chain->hmp = NULL;
493 		kfree(chain, hmp->mchain);
494 	}
495 
496 	/*
497 	 * Possible chaining loop when parent re-drop needed.
498 	 */
499 	return(rdrop);
500 }
501 
502 /*
503  * On either last lock release or last drop
504  */
505 static void
506 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
507 {
508 	/*hammer2_dev_t *hmp = chain->hmp;*/
509 
510 	switch(chain->bref.type) {
511 	case HAMMER2_BREF_TYPE_VOLUME:
512 	case HAMMER2_BREF_TYPE_FREEMAP:
513 		if (lastdrop)
514 			chain->data = NULL;
515 		break;
516 	default:
517 		KKASSERT(chain->data == NULL);
518 		break;
519 	}
520 }
521 
522 /*
523  * Lock a referenced chain element, acquiring its data with I/O if necessary,
524  * and specify how you would like the data to be resolved.
525  *
526  * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
527  *
528  * The lock is allowed to recurse, multiple locking ops will aggregate
529  * the requested resolve types.  Once data is assigned it will not be
530  * removed until the last unlock.
531  *
532  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
533  *			   (typically used to avoid device/logical buffer
534  *			    aliasing for data)
535  *
536  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
537  *			   the INITIAL-create state (indirect blocks only).
538  *
539  *			   Do not resolve data elements for DATA chains.
540  *			   (typically used to avoid device/logical buffer
541  *			    aliasing for data)
542  *
543  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
544  *
545  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
546  *			   it will be locked exclusive.
547  *
548  * NOTE: Embedded elements (volume header, inodes) are always resolved
549  *	 regardless.
550  *
551  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
552  *	 element will instantiate and zero its buffer, and flush it on
553  *	 release.
554  *
555  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
556  *	 so as not to instantiate a device buffer, which could alias against
557  *	 a logical file buffer.  However, if ALWAYS is specified the
558  *	 device buffer will be instantiated anyway.
559  *
560  * WARNING! This function blocks on I/O if data needs to be fetched.  This
561  *	    blocking can run concurrent with other compatible lock holders
562  *	    who do not need data returning.  The lock is not upgraded to
563  *	    exclusive during a data fetch, a separate bit is used to
564  *	    interlock I/O.  However, an exclusive lock holder can still count
565  *	    on being interlocked against an I/O fetch managed by a shared
566  *	    lock holder.
567  */
568 void
569 hammer2_chain_lock(hammer2_chain_t *chain, int how)
570 {
571 	/*
572 	 * Ref and lock the element.  Recursive locks are allowed.
573 	 */
574 	KKASSERT(chain->refs > 0);
575 	atomic_add_int(&chain->lockcnt, 1);
576 
577 	/*
578 	 * Get the appropriate lock.
579 	 */
580 	if (how & HAMMER2_RESOLVE_SHARED)
581 		hammer2_mtx_sh(&chain->lock);
582 	else
583 		hammer2_mtx_ex(&chain->lock);
584 
585 	/*
586 	 * If we already have a valid data pointer no further action is
587 	 * necessary.
588 	 */
589 	if (chain->data)
590 		return;
591 
592 	/*
593 	 * Do we have to resolve the data?
594 	 */
595 	switch(how & HAMMER2_RESOLVE_MASK) {
596 	case HAMMER2_RESOLVE_NEVER:
597 		return;
598 	case HAMMER2_RESOLVE_MAYBE:
599 		if (chain->flags & HAMMER2_CHAIN_INITIAL)
600 			return;
601 		if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
602 			return;
603 #if 0
604 		if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
605 			return;
606 		if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
607 			return;
608 #endif
609 		/* fall through */
610 	case HAMMER2_RESOLVE_ALWAYS:
611 	default:
612 		break;
613 	}
614 
615 	/*
616 	 * Caller requires data
617 	 */
618 	hammer2_chain_load_data(chain);
619 }
620 
621 /*
622  * Issue I/O and install chain->data.  Caller must hold a chain lock, lock
623  * may be of any type.
624  *
625  * Once chain->data is set it cannot be disposed of until all locks are
626  * released.
627  */
628 void
629 hammer2_chain_load_data(hammer2_chain_t *chain)
630 {
631 	hammer2_blockref_t *bref;
632 	hammer2_dev_t *hmp;
633 	char *bdata;
634 	int error;
635 
636 	/*
637 	 * Degenerate case, data already present.
638 	 */
639 	if (chain->data)
640 		return;
641 
642 	hmp = chain->hmp;
643 	KKASSERT(hmp != NULL);
644 
645 	/*
646 	 * Gain the IOINPROG bit, interlocked block.
647 	 */
648 	for (;;) {
649 		u_int oflags;
650 		u_int nflags;
651 
652 		oflags = chain->flags;
653 		cpu_ccfence();
654 		if (oflags & HAMMER2_CHAIN_IOINPROG) {
655 			nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
656 			tsleep_interlock(&chain->flags, 0);
657 			if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
658 				tsleep(&chain->flags, PINTERLOCKED,
659 					"h2iocw", 0);
660 			}
661 			/* retry */
662 		} else {
663 			nflags = oflags | HAMMER2_CHAIN_IOINPROG;
664 			if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
665 				break;
666 			}
667 			/* retry */
668 		}
669 	}
670 
671 	/*
672 	 * We own CHAIN_IOINPROG
673 	 *
674 	 * Degenerate case if we raced another load.
675 	 */
676 	if (chain->data)
677 		goto done;
678 
679 	/*
680 	 * We must resolve to a device buffer, either by issuing I/O or
681 	 * by creating a zero-fill element.  We do not mark the buffer
682 	 * dirty when creating a zero-fill element (the hammer2_chain_modify()
683 	 * API must still be used to do that).
684 	 *
685 	 * The device buffer is variable-sized in powers of 2 down
686 	 * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
687 	 * chunk always contains buffers of the same size. (XXX)
688 	 *
689 	 * The minimum physical IO size may be larger than the variable
690 	 * block size.
691 	 */
692 	bref = &chain->bref;
693 
694 	/*
695 	 * The getblk() optimization can only be used on newly created
696 	 * elements if the physical block size matches the request.
697 	 */
698 	if (chain->flags & HAMMER2_CHAIN_INITIAL) {
699 		error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
700 					&chain->dio);
701 	} else {
702 		error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
703 					 &chain->dio);
704 		hammer2_adjreadcounter(&chain->bref, chain->bytes);
705 	}
706 	if (error) {
707 		chain->error = HAMMER2_ERROR_IO;
708 		kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
709 			(intmax_t)bref->data_off, error);
710 		hammer2_io_bqrelse(&chain->dio);
711 		goto done;
712 	}
713 	chain->error = 0;
714 
715 	/*
716 	 * NOTE: A locked chain's data cannot be modified without first
717 	 *	 calling hammer2_chain_modify().
718 	 */
719 
720 	/*
721 	 * Clear INITIAL.  In this case we used io_new() and the buffer has
722 	 * been zero'd and marked dirty.
723 	 */
724 	bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
725 	if (chain->flags & HAMMER2_CHAIN_INITIAL) {
726 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
727 		chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
728 	} else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
729 		/*
730 		 * check data not currently synchronized due to
731 		 * modification.  XXX assumes data stays in the buffer
732 		 * cache, which might not be true (need biodep on flush
733 		 * to calculate crc?  or simple crc?).
734 		 */
735 	} else {
736 		if (hammer2_chain_testcheck(chain, bdata) == 0) {
737 			kprintf("chain %016jx.%02x meth=%02x "
738 				"CHECK FAIL %08x (flags=%08x)\n",
739 				chain->bref.data_off,
740 				chain->bref.type,
741 				chain->bref.methods,
742 				hammer2_icrc32(bdata, chain->bytes),
743 				chain->flags);
744 			chain->error = HAMMER2_ERROR_CHECK;
745 		}
746 	}
747 
748 	/*
749 	 * Setup the data pointer, either pointing it to an embedded data
750 	 * structure and copying the data from the buffer, or pointing it
751 	 * into the buffer.
752 	 *
753 	 * The buffer is not retained when copying to an embedded data
754 	 * structure in order to avoid potential deadlocks or recursions
755 	 * on the same physical buffer.
756 	 *
757 	 * WARNING! Other threads can start using the data the instant we
758 	 *	    set chain->data non-NULL.
759 	 */
760 	switch (bref->type) {
761 	case HAMMER2_BREF_TYPE_VOLUME:
762 	case HAMMER2_BREF_TYPE_FREEMAP:
763 		/*
764 		 * Copy data from bp to embedded buffer
765 		 */
766 		panic("hammer2_chain_lock: called on unresolved volume header");
767 		break;
768 	case HAMMER2_BREF_TYPE_INODE:
769 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
770 	case HAMMER2_BREF_TYPE_INDIRECT:
771 	case HAMMER2_BREF_TYPE_DATA:
772 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
773 	default:
774 		/*
775 		 * Point data at the device buffer and leave dio intact.
776 		 */
777 		chain->data = (void *)bdata;
778 		break;
779 	}
780 
781 	/*
782 	 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
783 	 */
784 done:
785 	for (;;) {
786 		u_int oflags;
787 		u_int nflags;
788 
789 		oflags = chain->flags;
790 		nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
791 				    HAMMER2_CHAIN_IOSIGNAL);
792 		KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
793 		if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
794 			if (oflags & HAMMER2_CHAIN_IOSIGNAL)
795 				wakeup(&chain->flags);
796 			break;
797 		}
798 	}
799 }
800 
801 /*
802  * Unlock and deref a chain element.
803  *
804  * On the last lock release any non-embedded data (chain->dio) will be
805  * retired.
806  */
807 void
808 hammer2_chain_unlock(hammer2_chain_t *chain)
809 {
810 	hammer2_mtx_state_t ostate;
811 	long *counterp;
812 	u_int lockcnt;
813 
814 	/*
815 	 * If multiple locks are present (or being attempted) on this
816 	 * particular chain we can just unlock, drop refs, and return.
817 	 *
818 	 * Otherwise fall-through on the 1->0 transition.
819 	 */
820 	for (;;) {
821 		lockcnt = chain->lockcnt;
822 		KKASSERT(lockcnt > 0);
823 		cpu_ccfence();
824 		if (lockcnt > 1) {
825 			if (atomic_cmpset_int(&chain->lockcnt,
826 					      lockcnt, lockcnt - 1)) {
827 				hammer2_mtx_unlock(&chain->lock);
828 				return;
829 			}
830 		} else {
831 			if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
832 				break;
833 		}
834 		/* retry */
835 	}
836 
837 	/*
838 	 * On the 1->0 transition we upgrade the core lock (if necessary)
839 	 * to exclusive for terminal processing.  If after upgrading we find
840 	 * that lockcnt is non-zero, another thread is racing us and will
841 	 * handle the unload for us later on, so just cleanup and return
842 	 * leaving the data/io intact
843 	 *
844 	 * Otherwise if lockcnt is still 0 it is possible for it to become
845 	 * non-zero and race, but since we hold the core->lock exclusively
846 	 * all that will happen is that the chain will be reloaded after we
847 	 * unload it.
848 	 */
849 	ostate = hammer2_mtx_upgrade(&chain->lock);
850 	if (chain->lockcnt) {
851 		hammer2_mtx_unlock(&chain->lock);
852 		return;
853 	}
854 
855 	/*
856 	 * Shortcut the case if the data is embedded or not resolved.
857 	 *
858 	 * Do NOT NULL out chain->data (e.g. inode data), it might be
859 	 * dirty.
860 	 */
861 	if (chain->dio == NULL) {
862 		if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
863 			hammer2_chain_drop_data(chain, 0);
864 		hammer2_mtx_unlock(&chain->lock);
865 		return;
866 	}
867 
868 	/*
869 	 * Statistics
870 	 */
871 	if (hammer2_io_isdirty(chain->dio)) {
872 		switch(chain->bref.type) {
873 		case HAMMER2_BREF_TYPE_DATA:
874 			counterp = &hammer2_iod_file_write;
875 			break;
876 		case HAMMER2_BREF_TYPE_INODE:
877 			counterp = &hammer2_iod_meta_write;
878 			break;
879 		case HAMMER2_BREF_TYPE_INDIRECT:
880 			counterp = &hammer2_iod_indr_write;
881 			break;
882 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
883 		case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
884 			counterp = &hammer2_iod_fmap_write;
885 			break;
886 		default:
887 			counterp = &hammer2_iod_volu_write;
888 			break;
889 		}
890 		*counterp += chain->bytes;
891 	}
892 
893 	/*
894 	 * Clean out the dio.
895 	 *
896 	 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
897 	 *	 is possible.
898 	 */
899 	chain->data = NULL;
900 	hammer2_io_bqrelse(&chain->dio);
901 	hammer2_mtx_unlock(&chain->lock);
902 }
903 
904 /*
905  * This counts the number of live blockrefs in a block array and
906  * also calculates the point at which all remaining blockrefs are empty.
907  * This routine can only be called on a live chain (DUPLICATED flag not set).
908  *
909  * NOTE: Flag is not set until after the count is complete, allowing
910  *	 callers to test the flag without holding the spinlock.
911  *
912  * NOTE: If base is NULL the related chain is still in the INITIAL
913  *	 state and there are no blockrefs to count.
914  *
915  * NOTE: live_count may already have some counts accumulated due to
916  *	 creation and deletion and could even be initially negative.
917  */
918 void
919 hammer2_chain_countbrefs(hammer2_chain_t *chain,
920 			 hammer2_blockref_t *base, int count)
921 {
922 	hammer2_spin_ex(&chain->core.spin);
923         if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
924 		if (base) {
925 			while (--count >= 0) {
926 				if (base[count].type)
927 					break;
928 			}
929 			chain->core.live_zero = count + 1;
930 			while (count >= 0) {
931 				if (base[count].type)
932 					atomic_add_int(&chain->core.live_count,
933 						       1);
934 				--count;
935 			}
936 		} else {
937 			chain->core.live_zero = 0;
938 		}
939 		/* else do not modify live_count */
940 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
941 	}
942 	hammer2_spin_unex(&chain->core.spin);
943 }
944 
945 /*
946  * Resize the chain's physical storage allocation in-place.  This function does
947  * not adjust the data pointer and must be followed by (typically) a
948  * hammer2_chain_modify() call to copy any old data over and adjust the
949  * data pointer.
950  *
951  * Chains can be resized smaller without reallocating the storage.  Resizing
952  * larger will reallocate the storage.  Excess or prior storage is reclaimed
953  * asynchronously at a later time.
954  *
955  * Must be passed an exclusively locked parent and chain.
956  *
957  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
958  * to avoid instantiating a device buffer that conflicts with the vnode data
959  * buffer.  However, because H2 can compress or encrypt data, the chain may
960  * have a dio assigned to it in those situations, and they do not conflict.
961  *
962  * XXX return error if cannot resize.
963  */
964 void
965 hammer2_chain_resize(hammer2_inode_t *ip,
966 		     hammer2_chain_t *parent, hammer2_chain_t *chain,
967 		     hammer2_tid_t mtid, hammer2_off_t dedup_off,
968 		     int nradix, int flags)
969 {
970 	hammer2_dev_t *hmp;
971 	size_t obytes;
972 	size_t nbytes;
973 
974 	hmp = chain->hmp;
975 
976 	/*
977 	 * Only data and indirect blocks can be resized for now.
978 	 * (The volu root, inodes, and freemap elements use a fixed size).
979 	 */
980 	KKASSERT(chain != &hmp->vchain);
981 	KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
982 		 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
983 	KKASSERT(chain->parent == parent);
984 
985 	/*
986 	 * Nothing to do if the element is already the proper size
987 	 */
988 	obytes = chain->bytes;
989 	nbytes = 1U << nradix;
990 	if (obytes == nbytes)
991 		return;
992 
993 	/*
994 	 * Make sure the old data is instantiated so we can copy it.  If this
995 	 * is a data block, the device data may be superfluous since the data
996 	 * might be in a logical block, but compressed or encrypted data is
997 	 * another matter.
998 	 *
999 	 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1000 	 */
1001 	hammer2_chain_modify(chain, mtid, dedup_off, 0);
1002 
1003 	/*
1004 	 * Relocate the block, even if making it smaller (because different
1005 	 * block sizes may be in different regions).
1006 	 *
1007 	 * (data blocks only, we aren't copying the storage here).
1008 	 */
1009 	hammer2_freemap_alloc(chain, nbytes);
1010 	chain->bytes = nbytes;
1011 	/*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1012 
1013 	/*
1014 	 * We don't want the followup chain_modify() to try to copy data
1015 	 * from the old (wrong-sized) buffer.  It won't know how much to
1016 	 * copy.  This case should only occur during writes when the
1017 	 * originator already has the data to write in-hand.
1018 	 */
1019 	if (chain->dio) {
1020 		KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1021 		hammer2_io_brelse(&chain->dio);
1022 		chain->data = NULL;
1023 	}
1024 }
1025 
1026 /*
1027  * Set the chain modified so its data can be changed by the caller.
1028  *
1029  * Sets bref.modify_tid to mtid only if mtid != 0.  Note that bref.modify_tid
1030  * is a CLC (cluster level change) field and is not updated by parent
1031  * propagation during a flush.
1032  *
1033  * If the caller passes a non-zero dedup_off we assign data_off to that
1034  * instead of allocating a ne block.  Caller must not modify the data already
1035  * present at the target offset.
1036  */
1037 void
1038 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1039 		     hammer2_off_t dedup_off, int flags)
1040 {
1041 	hammer2_blockref_t obref;
1042 	hammer2_dev_t *hmp;
1043 	hammer2_io_t *dio;
1044 	int error;
1045 	int wasinitial;
1046 	int newmod;
1047 	char *bdata;
1048 
1049 	hmp = chain->hmp;
1050 	obref = chain->bref;
1051 	KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1052 
1053 	/*
1054 	 * Data is not optional for freemap chains (we must always be sure
1055 	 * to copy the data on COW storage allocations).
1056 	 */
1057 	if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1058 	    chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1059 		KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1060 			 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1061 	}
1062 
1063 	/*
1064 	 * Data must be resolved if already assigned, unless explicitly
1065 	 * flagged otherwise.
1066 	 */
1067 	if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1068 	    (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1069 		hammer2_chain_load_data(chain);
1070 	}
1071 
1072 	/*
1073 	 * Set MODIFIED to indicate that the chain has been modified.
1074 	 * Set UPDATE to ensure that the blockref is updated in the parent.
1075 	 */
1076 	if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1077 	    (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1078 		newmod = 1;
1079 	} else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1080 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1081 		hammer2_chain_ref(chain);
1082 		hammer2_pfs_memory_inc(chain->pmp);	/* can be NULL */
1083 		newmod = 1;
1084 	} else {
1085 		newmod = 0;
1086 	}
1087 	if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1088 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1089 		hammer2_chain_ref(chain);
1090 	}
1091 	atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1092 
1093 	/*
1094 	 * The modification or re-modification requires an allocation and
1095 	 * possible COW.
1096 	 *
1097 	 * If dedup_off is non-zero, caller already has a data offset
1098 	 * containing the caller's desired data.  The dedup offset is
1099 	 * allowed to be in a partially free state and we must be sure
1100 	 * to reset it to a fully allocated state to force two bulkfree
1101 	 * passes to free it again.
1102 	 *
1103 	 * XXX can a chain already be marked MODIFIED without a data
1104 	 * assignment?  If not, assert here instead of testing the case.
1105 	 */
1106 	if (chain != &hmp->vchain && chain != &hmp->fchain) {
1107 		if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1108 		     newmod
1109 		) {
1110 			if (dedup_off) {
1111 				chain->bref.data_off = dedup_off;
1112 				atomic_set_int(&chain->flags,
1113 					       HAMMER2_CHAIN_DEDUP);
1114 				hammer2_freemap_adjust(hmp, &chain->bref,
1115 						HAMMER2_FREEMAP_DORECOVER);
1116 			} else {
1117 				hammer2_freemap_alloc(chain, chain->bytes);
1118 			}
1119 			/* XXX failed allocation */
1120 		}
1121 	}
1122 
1123 	/*
1124 	 * Update mirror_tid and modify_tid.  modify_tid is only updated
1125 	 * if not passed as zero (during flushes, parent propagation passes
1126 	 * the value 0).
1127 	 *
1128 	 * NOTE: chain->pmp could be the device spmp.
1129 	 */
1130 	chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1131 	if (mtid)
1132 		chain->bref.modify_tid = mtid;
1133 
1134 	/*
1135 	 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1136 	 * requires updating as well as to tell the delete code that the
1137 	 * chain's blockref might not exactly match (in terms of physical size
1138 	 * or block offset) the one in the parent's blocktable.  The base key
1139 	 * of course will still match.
1140 	 */
1141 	if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1142 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1143 
1144 	/*
1145 	 * Short-cut data blocks which the caller does not need an actual
1146 	 * data reference to (aka OPTDATA), as long as the chain does not
1147 	 * already have a data pointer to the data.  This generally means
1148 	 * that the modifications are being done via the logical buffer cache.
1149 	 * The INITIAL flag relates only to the device data buffer and thus
1150 	 * remains unchange in this situation.
1151 	 */
1152 	if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1153 	    (flags & HAMMER2_MODIFY_OPTDATA) &&
1154 	    chain->data == NULL) {
1155 		goto skip2;
1156 	}
1157 
1158 	/*
1159 	 * Clearing the INITIAL flag (for indirect blocks) indicates that
1160 	 * we've processed the uninitialized storage allocation.
1161 	 *
1162 	 * If this flag is already clear we are likely in a copy-on-write
1163 	 * situation but we have to be sure NOT to bzero the storage if
1164 	 * no data is present.
1165 	 */
1166 	if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1167 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1168 		wasinitial = 1;
1169 	} else {
1170 		wasinitial = 0;
1171 	}
1172 
1173 	/*
1174 	 * Instantiate data buffer and possibly execute COW operation
1175 	 */
1176 	switch(chain->bref.type) {
1177 	case HAMMER2_BREF_TYPE_VOLUME:
1178 	case HAMMER2_BREF_TYPE_FREEMAP:
1179 		/*
1180 		 * The data is embedded, no copy-on-write operation is
1181 		 * needed.
1182 		 */
1183 		KKASSERT(chain->dio == NULL);
1184 		break;
1185 	case HAMMER2_BREF_TYPE_INODE:
1186 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1187 	case HAMMER2_BREF_TYPE_DATA:
1188 	case HAMMER2_BREF_TYPE_INDIRECT:
1189 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1190 		/*
1191 		 * Perform the copy-on-write operation
1192 		 *
1193 		 * zero-fill or copy-on-write depending on whether
1194 		 * chain->data exists or not and set the dirty state for
1195 		 * the new buffer.  hammer2_io_new() will handle the
1196 		 * zero-fill.
1197 		 *
1198 		 * If a dedup_off was supplied this is an existing block
1199 		 * and no COW, copy, or further modification is required.
1200 		 */
1201 		KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1202 
1203 		if (wasinitial && dedup_off == 0) {
1204 			error = hammer2_io_new(hmp, chain->bref.data_off,
1205 					       chain->bytes, &dio);
1206 		} else {
1207 			error = hammer2_io_bread(hmp, chain->bref.data_off,
1208 						 chain->bytes, &dio);
1209 		}
1210 		hammer2_adjreadcounter(&chain->bref, chain->bytes);
1211 
1212 		/*
1213 		 * If an I/O error occurs make sure callers cannot accidently
1214 		 * modify the old buffer's contents and corrupt the filesystem.
1215 		 */
1216 		if (error) {
1217 			kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1218 				hmp);
1219 			chain->error = HAMMER2_ERROR_IO;
1220 			hammer2_io_brelse(&dio);
1221 			hammer2_io_brelse(&chain->dio);
1222 			chain->data = NULL;
1223 			break;
1224 		}
1225 		chain->error = 0;
1226 		bdata = hammer2_io_data(dio, chain->bref.data_off);
1227 
1228 		if (chain->data) {
1229 			/*
1230 			 * COW (unless a dedup).
1231 			 */
1232 			KKASSERT(chain->dio != NULL);
1233 			if (chain->data != (void *)bdata && dedup_off == 0) {
1234 				bcopy(chain->data, bdata, chain->bytes);
1235 			}
1236 		} else if (wasinitial == 0) {
1237 			/*
1238 			 * We have a problem.  We were asked to COW but
1239 			 * we don't have any data to COW with!
1240 			 */
1241 			panic("hammer2_chain_modify: having a COW %p\n",
1242 			      chain);
1243 		}
1244 
1245 		/*
1246 		 * Retire the old buffer, replace with the new.  Dirty or
1247 		 * redirty the new buffer.
1248 		 *
1249 		 * WARNING! The system buffer cache may have already flushed
1250 		 *	    the buffer, so we must be sure to [re]dirty it
1251 		 *	    for further modification.
1252 		 *
1253 		 *	    If dedup_off was supplied, the caller is not
1254 		 *	    expected to make any further modification to the
1255 		 *	    buffer.
1256 		 */
1257 		if (chain->dio)
1258 			hammer2_io_bqrelse(&chain->dio);
1259 		chain->data = (void *)bdata;
1260 		chain->dio = dio;
1261 		if (dedup_off == 0)
1262 			hammer2_io_setdirty(dio);
1263 		break;
1264 	default:
1265 		panic("hammer2_chain_modify: illegal non-embedded type %d",
1266 		      chain->bref.type);
1267 		break;
1268 
1269 	}
1270 skip2:
1271 	/*
1272 	 * setflush on parent indicating that the parent must recurse down
1273 	 * to us.  Do not call on chain itself which might already have it
1274 	 * set.
1275 	 */
1276 	if (chain->parent)
1277 		hammer2_chain_setflush(chain->parent);
1278 }
1279 
1280 /*
1281  * Modify the chain associated with an inode.
1282  */
1283 void
1284 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1285 			hammer2_tid_t mtid, int flags)
1286 {
1287 	hammer2_inode_modify(ip);
1288 	hammer2_chain_modify(chain, mtid, 0, flags);
1289 }
1290 
1291 /*
1292  * Volume header data locks
1293  */
1294 void
1295 hammer2_voldata_lock(hammer2_dev_t *hmp)
1296 {
1297 	lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1298 }
1299 
1300 void
1301 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1302 {
1303 	lockmgr(&hmp->vollk, LK_RELEASE);
1304 }
1305 
1306 void
1307 hammer2_voldata_modify(hammer2_dev_t *hmp)
1308 {
1309 	if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1310 		atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1311 		hammer2_chain_ref(&hmp->vchain);
1312 		hammer2_pfs_memory_inc(hmp->vchain.pmp);
1313 	}
1314 }
1315 
1316 /*
1317  * This function returns the chain at the nearest key within the specified
1318  * range.  The returned chain will be referenced but not locked.
1319  *
1320  * This function will recurse through chain->rbtree as necessary and will
1321  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1322  * the iteration value is less than the current value of *key_nextp.
1323  *
1324  * The caller should use (*key_nextp) to calculate the actual range of
1325  * the returned element, which will be (key_beg to *key_nextp - 1), because
1326  * there might be another element which is superior to the returned element
1327  * and overlaps it.
1328  *
1329  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1330  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1331  * it will wind up being (key_end + 1).
1332  *
1333  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
1334  *	     held through the operation.
1335  */
1336 struct hammer2_chain_find_info {
1337 	hammer2_chain_t		*best;
1338 	hammer2_key_t		key_beg;
1339 	hammer2_key_t		key_end;
1340 	hammer2_key_t		key_next;
1341 };
1342 
1343 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1344 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1345 
1346 static
1347 hammer2_chain_t *
1348 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1349 			  hammer2_key_t key_beg, hammer2_key_t key_end)
1350 {
1351 	struct hammer2_chain_find_info info;
1352 
1353 	info.best = NULL;
1354 	info.key_beg = key_beg;
1355 	info.key_end = key_end;
1356 	info.key_next = *key_nextp;
1357 
1358 	RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1359 		hammer2_chain_find_cmp, hammer2_chain_find_callback,
1360 		&info);
1361 	*key_nextp = info.key_next;
1362 #if 0
1363 	kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1364 		parent, key_beg, key_end, *key_nextp);
1365 #endif
1366 
1367 	return (info.best);
1368 }
1369 
1370 static
1371 int
1372 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1373 {
1374 	struct hammer2_chain_find_info *info = data;
1375 	hammer2_key_t child_beg;
1376 	hammer2_key_t child_end;
1377 
1378 	child_beg = child->bref.key;
1379 	child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1380 
1381 	if (child_end < info->key_beg)
1382 		return(-1);
1383 	if (child_beg > info->key_end)
1384 		return(1);
1385 	return(0);
1386 }
1387 
1388 static
1389 int
1390 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1391 {
1392 	struct hammer2_chain_find_info *info = data;
1393 	hammer2_chain_t *best;
1394 	hammer2_key_t child_end;
1395 
1396 	/*
1397 	 * WARNING! Do not discard DUPLICATED chains, it is possible that
1398 	 *	    we are catching an insertion half-way done.  If a
1399 	 *	    duplicated chain turns out to be the best choice the
1400 	 *	    caller will re-check its flags after locking it.
1401 	 *
1402 	 * WARNING! Layerq is scanned forwards, exact matches should keep
1403 	 *	    the existing info->best.
1404 	 */
1405 	if ((best = info->best) == NULL) {
1406 		/*
1407 		 * No previous best.  Assign best
1408 		 */
1409 		info->best = child;
1410 	} else if (best->bref.key <= info->key_beg &&
1411 		   child->bref.key <= info->key_beg) {
1412 		/*
1413 		 * Illegal overlap.
1414 		 */
1415 		KKASSERT(0);
1416 		/*info->best = child;*/
1417 	} else if (child->bref.key < best->bref.key) {
1418 		/*
1419 		 * Child has a nearer key and best is not flush with key_beg.
1420 		 * Set best to child.  Truncate key_next to the old best key.
1421 		 */
1422 		info->best = child;
1423 		if (info->key_next > best->bref.key || info->key_next == 0)
1424 			info->key_next = best->bref.key;
1425 	} else if (child->bref.key == best->bref.key) {
1426 		/*
1427 		 * If our current best is flush with the child then this
1428 		 * is an illegal overlap.
1429 		 *
1430 		 * key_next will automatically be limited to the smaller of
1431 		 * the two end-points.
1432 		 */
1433 		KKASSERT(0);
1434 		info->best = child;
1435 	} else {
1436 		/*
1437 		 * Keep the current best but truncate key_next to the child's
1438 		 * base.
1439 		 *
1440 		 * key_next will also automatically be limited to the smaller
1441 		 * of the two end-points (probably not necessary for this case
1442 		 * but we do it anyway).
1443 		 */
1444 		if (info->key_next > child->bref.key || info->key_next == 0)
1445 			info->key_next = child->bref.key;
1446 	}
1447 
1448 	/*
1449 	 * Always truncate key_next based on child's end-of-range.
1450 	 */
1451 	child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1452 	if (child_end && (info->key_next > child_end || info->key_next == 0))
1453 		info->key_next = child_end;
1454 
1455 	return(0);
1456 }
1457 
1458 /*
1459  * Retrieve the specified chain from a media blockref, creating the
1460  * in-memory chain structure which reflects it.
1461  *
1462  * To handle insertion races pass the INSERT_RACE flag along with the
1463  * generation number of the core.  NULL will be returned if the generation
1464  * number changes before we have a chance to insert the chain.  Insert
1465  * races can occur because the parent might be held shared.
1466  *
1467  * Caller must hold the parent locked shared or exclusive since we may
1468  * need the parent's bref array to find our block.
1469  *
1470  * WARNING! chain->pmp is always set to NULL for any chain representing
1471  *	    part of the super-root topology.
1472  */
1473 hammer2_chain_t *
1474 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1475 		  hammer2_blockref_t *bref)
1476 {
1477 	hammer2_dev_t *hmp = parent->hmp;
1478 	hammer2_chain_t *chain;
1479 	int error;
1480 
1481 	/*
1482 	 * Allocate a chain structure representing the existing media
1483 	 * entry.  Resulting chain has one ref and is not locked.
1484 	 */
1485 	if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1486 		chain = hammer2_chain_alloc(hmp, NULL, bref);
1487 	else
1488 		chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1489 	/* ref'd chain returned */
1490 
1491 	/*
1492 	 * Flag that the chain is in the parent's blockmap so delete/flush
1493 	 * knows what to do with it.
1494 	 */
1495 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1496 
1497 	/*
1498 	 * Link the chain into its parent.  A spinlock is required to safely
1499 	 * access the RBTREE, and it is possible to collide with another
1500 	 * hammer2_chain_get() operation because the caller might only hold
1501 	 * a shared lock on the parent.
1502 	 */
1503 	KKASSERT(parent->refs > 0);
1504 	error = hammer2_chain_insert(parent, chain,
1505 				     HAMMER2_CHAIN_INSERT_SPIN |
1506 				     HAMMER2_CHAIN_INSERT_RACE,
1507 				     generation);
1508 	if (error) {
1509 		KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1510 		kprintf("chain %p get race\n", chain);
1511 		hammer2_chain_drop(chain);
1512 		chain = NULL;
1513 	} else {
1514 		KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1515 	}
1516 
1517 	/*
1518 	 * Return our new chain referenced but not locked, or NULL if
1519 	 * a race occurred.
1520 	 */
1521 	return (chain);
1522 }
1523 
1524 /*
1525  * Lookup initialization/completion API
1526  */
1527 hammer2_chain_t *
1528 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1529 {
1530 	hammer2_chain_ref(parent);
1531 	if (flags & HAMMER2_LOOKUP_SHARED) {
1532 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1533 					   HAMMER2_RESOLVE_SHARED);
1534 	} else {
1535 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1536 	}
1537 	return (parent);
1538 }
1539 
1540 void
1541 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1542 {
1543 	if (parent) {
1544 		hammer2_chain_unlock(parent);
1545 		hammer2_chain_drop(parent);
1546 	}
1547 }
1548 
1549 hammer2_chain_t *
1550 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1551 {
1552 	hammer2_chain_t *oparent;
1553 	hammer2_chain_t *nparent;
1554 
1555 	/*
1556 	 * Be careful of order, oparent must be unlocked before nparent
1557 	 * is locked below to avoid a deadlock.
1558 	 */
1559 	oparent = *parentp;
1560 	hammer2_spin_ex(&oparent->core.spin);
1561 	nparent = oparent->parent;
1562 	hammer2_chain_ref(nparent);
1563 	hammer2_spin_unex(&oparent->core.spin);
1564 	if (oparent) {
1565 		hammer2_chain_unlock(oparent);
1566 		hammer2_chain_drop(oparent);
1567 		oparent = NULL;
1568 	}
1569 
1570 	hammer2_chain_lock(nparent, how);
1571 	*parentp = nparent;
1572 
1573 	return (nparent);
1574 }
1575 
1576 /*
1577  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1578  * (*parentp) typically points to an inode but can also point to a related
1579  * indirect block and this function will recurse upwards and find the inode
1580  * again.
1581  *
1582  * (*parentp) must be exclusively locked and referenced and can be an inode
1583  * or an existing indirect block within the inode.
1584  *
1585  * On return (*parentp) will be modified to point at the deepest parent chain
1586  * element encountered during the search, as a helper for an insertion or
1587  * deletion.   The new (*parentp) will be locked and referenced and the old
1588  * will be unlocked and dereferenced (no change if they are both the same).
1589  *
1590  * The matching chain will be returned exclusively locked.  If NOLOCK is
1591  * requested the chain will be returned only referenced.  Note that the
1592  * parent chain must always be locked shared or exclusive, matching the
1593  * HAMMER2_LOOKUP_SHARED flag.  We can conceivably lock it SHARED temporarily
1594  * when NOLOCK is specified but that complicates matters if *parentp must
1595  * inherit the chain.
1596  *
1597  * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1598  * data pointer or can otherwise be in flux.
1599  *
1600  * NULL is returned if no match was found, but (*parentp) will still
1601  * potentially be adjusted.
1602  *
1603  * If a fatal error occurs (typically an I/O error), a dummy chain is
1604  * returned with chain->error and error-identifying information set.  This
1605  * chain will assert if you try to do anything fancy with it.
1606  *
1607  * XXX Depending on where the error occurs we should allow continued iteration.
1608  *
1609  * On return (*key_nextp) will point to an iterative value for key_beg.
1610  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1611  *
1612  * This function will also recurse up the chain if the key is not within the
1613  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1614  * can simply allow (*parentp) to float inside the loop.
1615  *
1616  * NOTE!  chain->data is not always resolved.  By default it will not be
1617  *	  resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1618  *	  HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1619  *	  BREF_TYPE_DATA as the device buffer can alias the logical file
1620  *	  buffer).
1621  */
1622 hammer2_chain_t *
1623 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1624 		     hammer2_key_t key_beg, hammer2_key_t key_end,
1625 		     int *cache_indexp, int flags)
1626 {
1627 	hammer2_dev_t *hmp;
1628 	hammer2_chain_t *parent;
1629 	hammer2_chain_t *chain;
1630 	hammer2_blockref_t *base;
1631 	hammer2_blockref_t *bref;
1632 	hammer2_blockref_t bcopy;
1633 	hammer2_key_t scan_beg;
1634 	hammer2_key_t scan_end;
1635 	int count = 0;
1636 	int how_always = HAMMER2_RESOLVE_ALWAYS;
1637 	int how_maybe = HAMMER2_RESOLVE_MAYBE;
1638 	int how;
1639 	int generation;
1640 	int maxloops = 300000;
1641 
1642 	if (flags & HAMMER2_LOOKUP_ALWAYS) {
1643 		how_maybe = how_always;
1644 		how = HAMMER2_RESOLVE_ALWAYS;
1645 	} else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1646 		how = HAMMER2_RESOLVE_NEVER;
1647 	} else {
1648 		how = HAMMER2_RESOLVE_MAYBE;
1649 	}
1650 	if (flags & HAMMER2_LOOKUP_SHARED) {
1651 		how_maybe |= HAMMER2_RESOLVE_SHARED;
1652 		how_always |= HAMMER2_RESOLVE_SHARED;
1653 		how |= HAMMER2_RESOLVE_SHARED;
1654 	}
1655 
1656 	/*
1657 	 * Recurse (*parentp) upward if necessary until the parent completely
1658 	 * encloses the key range or we hit the inode.
1659 	 *
1660 	 * This function handles races against the flusher doing a delete-
1661 	 * duplicate above us and re-homes the parent to the duplicate in
1662 	 * that case, otherwise we'd wind up recursing down a stale chain.
1663 	 */
1664 	parent = *parentp;
1665 	hmp = parent->hmp;
1666 
1667 	while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1668 	       parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1669 		scan_beg = parent->bref.key;
1670 		scan_end = scan_beg +
1671 			   ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1672 		if (key_beg >= scan_beg && key_end <= scan_end)
1673 			break;
1674 		parent = hammer2_chain_getparent(parentp, how_maybe);
1675 	}
1676 
1677 again:
1678 	if (--maxloops == 0)
1679 		panic("hammer2_chain_lookup: maxloops");
1680 	/*
1681 	 * Locate the blockref array.  Currently we do a fully associative
1682 	 * search through the array.
1683 	 */
1684 	switch(parent->bref.type) {
1685 	case HAMMER2_BREF_TYPE_INODE:
1686 		/*
1687 		 * Special shortcut for embedded data returns the inode
1688 		 * itself.  Callers must detect this condition and access
1689 		 * the embedded data (the strategy code does this for us).
1690 		 *
1691 		 * This is only applicable to regular files and softlinks.
1692 		 */
1693 		if (parent->data->ipdata.meta.op_flags &
1694 		    HAMMER2_OPFLAG_DIRECTDATA) {
1695 			if (flags & HAMMER2_LOOKUP_NODIRECT) {
1696 				chain = NULL;
1697 				*key_nextp = key_end + 1;
1698 				goto done;
1699 			}
1700 			hammer2_chain_ref(parent);
1701 			if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1702 				hammer2_chain_lock(parent, how_always);
1703 			*key_nextp = key_end + 1;
1704 			return (parent);
1705 		}
1706 		base = &parent->data->ipdata.u.blockset.blockref[0];
1707 		count = HAMMER2_SET_COUNT;
1708 		break;
1709 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1710 	case HAMMER2_BREF_TYPE_INDIRECT:
1711 		/*
1712 		 * Handle MATCHIND on the parent
1713 		 */
1714 		if (flags & HAMMER2_LOOKUP_MATCHIND) {
1715 			scan_beg = parent->bref.key;
1716 			scan_end = scan_beg +
1717 			       ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1718 			if (key_beg == scan_beg && key_end == scan_end) {
1719 				chain = parent;
1720 				hammer2_chain_ref(chain);
1721 				hammer2_chain_lock(chain, how_maybe);
1722 				*key_nextp = scan_end + 1;
1723 				goto done;
1724 			}
1725 		}
1726 		/*
1727 		 * Optimize indirect blocks in the INITIAL state to avoid
1728 		 * I/O.
1729 		 */
1730 		if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1731 			base = NULL;
1732 		} else {
1733 			if (parent->data == NULL)
1734 				panic("parent->data is NULL");
1735 			base = &parent->data->npdata[0];
1736 		}
1737 		count = parent->bytes / sizeof(hammer2_blockref_t);
1738 		break;
1739 	case HAMMER2_BREF_TYPE_VOLUME:
1740 		base = &parent->data->voldata.sroot_blockset.blockref[0];
1741 		count = HAMMER2_SET_COUNT;
1742 		break;
1743 	case HAMMER2_BREF_TYPE_FREEMAP:
1744 		base = &parent->data->blkset.blockref[0];
1745 		count = HAMMER2_SET_COUNT;
1746 		break;
1747 	default:
1748 		kprintf("hammer2_chain_lookup: unrecognized "
1749 			"blockref(B) type: %d",
1750 			parent->bref.type);
1751 		while (1)
1752 			tsleep(&base, 0, "dead", 0);
1753 		panic("hammer2_chain_lookup: unrecognized "
1754 		      "blockref(B) type: %d",
1755 		      parent->bref.type);
1756 		base = NULL;	/* safety */
1757 		count = 0;	/* safety */
1758 	}
1759 
1760 	/*
1761 	 * Merged scan to find next candidate.
1762 	 *
1763 	 * hammer2_base_*() functions require the parent->core.live_* fields
1764 	 * to be synchronized.
1765 	 *
1766 	 * We need to hold the spinlock to access the block array and RB tree
1767 	 * and to interlock chain creation.
1768 	 */
1769 	if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1770 		hammer2_chain_countbrefs(parent, base, count);
1771 
1772 	/*
1773 	 * Combined search
1774 	 */
1775 	hammer2_spin_ex(&parent->core.spin);
1776 	chain = hammer2_combined_find(parent, base, count,
1777 				      cache_indexp, key_nextp,
1778 				      key_beg, key_end,
1779 				      &bref);
1780 	generation = parent->core.generation;
1781 
1782 	/*
1783 	 * Exhausted parent chain, iterate.
1784 	 */
1785 	if (bref == NULL) {
1786 		hammer2_spin_unex(&parent->core.spin);
1787 		if (key_beg == key_end)	/* short cut single-key case */
1788 			return (NULL);
1789 
1790 		/*
1791 		 * Stop if we reached the end of the iteration.
1792 		 */
1793 		if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1794 		    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1795 			return (NULL);
1796 		}
1797 
1798 		/*
1799 		 * Calculate next key, stop if we reached the end of the
1800 		 * iteration, otherwise go up one level and loop.
1801 		 */
1802 		key_beg = parent->bref.key +
1803 			  ((hammer2_key_t)1 << parent->bref.keybits);
1804 		if (key_beg == 0 || key_beg > key_end)
1805 			return (NULL);
1806 		parent = hammer2_chain_getparent(parentp, how_maybe);
1807 		goto again;
1808 	}
1809 
1810 	/*
1811 	 * Selected from blockref or in-memory chain.
1812 	 */
1813 	if (chain == NULL) {
1814 		bcopy = *bref;
1815 		hammer2_spin_unex(&parent->core.spin);
1816 		chain = hammer2_chain_get(parent, generation,
1817 					  &bcopy);
1818 		if (chain == NULL) {
1819 			kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1820 				parent, key_beg, key_end);
1821 			goto again;
1822 		}
1823 		if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1824 			hammer2_chain_drop(chain);
1825 			goto again;
1826 		}
1827 	} else {
1828 		hammer2_chain_ref(chain);
1829 		hammer2_spin_unex(&parent->core.spin);
1830 	}
1831 
1832 	/*
1833 	 * chain is referenced but not locked.  We must lock the chain
1834 	 * to obtain definitive DUPLICATED/DELETED state
1835 	 */
1836 	if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1837 	    chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1838 		hammer2_chain_lock(chain, how_maybe);
1839 	} else {
1840 		hammer2_chain_lock(chain, how);
1841 	}
1842 
1843 	/*
1844 	 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1845 	 *
1846 	 * NOTE: Chain's key range is not relevant as there might be
1847 	 *	 one-offs within the range that are not deleted.
1848 	 *
1849 	 * NOTE: Lookups can race delete-duplicate because
1850 	 *	 delete-duplicate does not lock the parent's core
1851 	 *	 (they just use the spinlock on the core).  We must
1852 	 *	 check for races by comparing the DUPLICATED flag before
1853 	 *	 releasing the spinlock with the flag after locking the
1854 	 *	 chain.
1855 	 */
1856 	if (chain->flags & HAMMER2_CHAIN_DELETED) {
1857 		hammer2_chain_unlock(chain);
1858 		hammer2_chain_drop(chain);
1859 		key_beg = *key_nextp;
1860 		if (key_beg == 0 || key_beg > key_end)
1861 			return(NULL);
1862 		goto again;
1863 	}
1864 
1865 	/*
1866 	 * If the chain element is an indirect block it becomes the new
1867 	 * parent and we loop on it.  We must maintain our top-down locks
1868 	 * to prevent the flusher from interfering (i.e. doing a
1869 	 * delete-duplicate and leaving us recursing down a deleted chain).
1870 	 *
1871 	 * The parent always has to be locked with at least RESOLVE_MAYBE
1872 	 * so we can access its data.  It might need a fixup if the caller
1873 	 * passed incompatible flags.  Be careful not to cause a deadlock
1874 	 * as a data-load requires an exclusive lock.
1875 	 *
1876 	 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1877 	 * range is within the requested key range we return the indirect
1878 	 * block and do NOT loop.  This is usually only used to acquire
1879 	 * freemap nodes.
1880 	 */
1881 	if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1882 	    chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1883 		hammer2_chain_unlock(parent);
1884 		hammer2_chain_drop(parent);
1885 		*parentp = parent = chain;
1886 		goto again;
1887 	}
1888 done:
1889 	/*
1890 	 * All done, return the chain.
1891 	 *
1892 	 * If the caller does not want a locked chain, replace the lock with
1893 	 * a ref.  Perhaps this can eventually be optimized to not obtain the
1894 	 * lock in the first place for situations where the data does not
1895 	 * need to be resolved.
1896 	 */
1897 	if (chain) {
1898 		if (flags & HAMMER2_LOOKUP_NOLOCK)
1899 			hammer2_chain_unlock(chain);
1900 	}
1901 
1902 	return (chain);
1903 }
1904 
1905 /*
1906  * After having issued a lookup we can iterate all matching keys.
1907  *
1908  * If chain is non-NULL we continue the iteration from just after it's index.
1909  *
1910  * If chain is NULL we assume the parent was exhausted and continue the
1911  * iteration at the next parent.
1912  *
1913  * If a fatal error occurs (typically an I/O error), a dummy chain is
1914  * returned with chain->error and error-identifying information set.  This
1915  * chain will assert if you try to do anything fancy with it.
1916  *
1917  * XXX Depending on where the error occurs we should allow continued iteration.
1918  *
1919  * parent must be locked on entry and remains locked throughout.  chain's
1920  * lock status must match flags.  Chain is always at least referenced.
1921  *
1922  * WARNING!  The MATCHIND flag does not apply to this function.
1923  */
1924 hammer2_chain_t *
1925 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1926 		   hammer2_key_t *key_nextp,
1927 		   hammer2_key_t key_beg, hammer2_key_t key_end,
1928 		   int *cache_indexp, int flags)
1929 {
1930 	hammer2_chain_t *parent;
1931 	int how_maybe;
1932 
1933 	/*
1934 	 * Calculate locking flags for upward recursion.
1935 	 */
1936 	how_maybe = HAMMER2_RESOLVE_MAYBE;
1937 	if (flags & HAMMER2_LOOKUP_SHARED)
1938 		how_maybe |= HAMMER2_RESOLVE_SHARED;
1939 
1940 	parent = *parentp;
1941 
1942 	/*
1943 	 * Calculate the next index and recalculate the parent if necessary.
1944 	 */
1945 	if (chain) {
1946 		key_beg = chain->bref.key +
1947 			  ((hammer2_key_t)1 << chain->bref.keybits);
1948 		if ((flags & (HAMMER2_LOOKUP_NOLOCK |
1949 			      HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
1950 			hammer2_chain_unlock(chain);
1951 		}
1952 		hammer2_chain_drop(chain);
1953 
1954 		/*
1955 		 * chain invalid past this point, but we can still do a
1956 		 * pointer comparison w/parent.
1957 		 *
1958 		 * Any scan where the lookup returned degenerate data embedded
1959 		 * in the inode has an invalid index and must terminate.
1960 		 */
1961 		if (chain == parent)
1962 			return(NULL);
1963 		if (key_beg == 0 || key_beg > key_end)
1964 			return(NULL);
1965 		chain = NULL;
1966 	} else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1967 		   parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1968 		/*
1969 		 * We reached the end of the iteration.
1970 		 */
1971 		return (NULL);
1972 	} else {
1973 		/*
1974 		 * Continue iteration with next parent unless the current
1975 		 * parent covers the range.
1976 		 */
1977 		key_beg = parent->bref.key +
1978 			  ((hammer2_key_t)1 << parent->bref.keybits);
1979 		if (key_beg == 0 || key_beg > key_end)
1980 			return (NULL);
1981 		parent = hammer2_chain_getparent(parentp, how_maybe);
1982 	}
1983 
1984 	/*
1985 	 * And execute
1986 	 */
1987 	return (hammer2_chain_lookup(parentp, key_nextp,
1988 				     key_beg, key_end,
1989 				     cache_indexp, flags));
1990 }
1991 
1992 /*
1993  * The raw scan function is similar to lookup/next but does not seek to a key.
1994  * Blockrefs are iterated via first_bref = (parent, NULL) and
1995  * next_chain = (parent, bref).
1996  *
1997  * The passed-in parent must be locked and its data resolved.  The function
1998  * nominally returns a locked and referenced *chainp != NULL for chains
1999  * the caller might need to recurse on (and will dipose of any *chainp passed
2000  * in).  The caller must check the chain->bref.type either way.
2001  *
2002  * *chainp is not set for leaf elements.
2003  *
2004  * This function takes a pointer to a stack-based bref structure whos
2005  * contents is updated for each iteration.  The same pointer is returned,
2006  * or NULL when the iteration is complete.  *firstp must be set to 1 for
2007  * the first ieration.  This function will set it to 0.
2008  */
2009 hammer2_blockref_t *
2010 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2011 		   hammer2_blockref_t *bref, int *firstp,
2012 		   int *cache_indexp, int flags)
2013 {
2014 	hammer2_dev_t *hmp;
2015 	hammer2_blockref_t *base;
2016 	hammer2_blockref_t *bref_ptr;
2017 	hammer2_key_t key;
2018 	hammer2_key_t next_key;
2019 	hammer2_chain_t *chain = NULL;
2020 	int count = 0;
2021 	int how_always = HAMMER2_RESOLVE_ALWAYS;
2022 	int how_maybe = HAMMER2_RESOLVE_MAYBE;
2023 	int how;
2024 	int generation;
2025 	int maxloops = 300000;
2026 
2027 	hmp = parent->hmp;
2028 
2029 	/*
2030 	 * Scan flags borrowed from lookup.
2031 	 */
2032 	if (flags & HAMMER2_LOOKUP_ALWAYS) {
2033 		how_maybe = how_always;
2034 		how = HAMMER2_RESOLVE_ALWAYS;
2035 	} else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2036 		how = HAMMER2_RESOLVE_NEVER;
2037 	} else {
2038 		how = HAMMER2_RESOLVE_MAYBE;
2039 	}
2040 	if (flags & HAMMER2_LOOKUP_SHARED) {
2041 		how_maybe |= HAMMER2_RESOLVE_SHARED;
2042 		how_always |= HAMMER2_RESOLVE_SHARED;
2043 		how |= HAMMER2_RESOLVE_SHARED;
2044 	}
2045 
2046 	/*
2047 	 * Calculate key to locate first/next element, unlocking the previous
2048 	 * element as we go.  Be careful, the key calculation can overflow.
2049 	 *
2050 	 * (also reset bref to NULL)
2051 	 */
2052 	if (*firstp) {
2053 		key = 0;
2054 		*firstp = 0;
2055 	} else {
2056 		key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2057 		if ((chain = *chainp) != NULL) {
2058 			*chainp = NULL;
2059 			hammer2_chain_unlock(chain);
2060 			hammer2_chain_drop(chain);
2061 			chain = NULL;
2062 		}
2063 		if (key == 0) {
2064 			bref = NULL;
2065 			goto done;
2066 		}
2067 	}
2068 
2069 again:
2070 	KKASSERT(parent->error == 0);	/* XXX case not handled yet */
2071 	if (--maxloops == 0)
2072 		panic("hammer2_chain_scan: maxloops");
2073 	/*
2074 	 * Locate the blockref array.  Currently we do a fully associative
2075 	 * search through the array.
2076 	 */
2077 	switch(parent->bref.type) {
2078 	case HAMMER2_BREF_TYPE_INODE:
2079 		/*
2080 		 * An inode with embedded data has no sub-chains.
2081 		 *
2082 		 * WARNING! Bulk scan code may pass a static chain marked
2083 		 *	    as BREF_TYPE_INODE with a copy of the volume
2084 		 *	    root blockset to snapshot the volume.
2085 		 */
2086 		if (parent->data->ipdata.meta.op_flags &
2087 		    HAMMER2_OPFLAG_DIRECTDATA) {
2088 			bref = NULL;
2089 			goto done;
2090 		}
2091 		base = &parent->data->ipdata.u.blockset.blockref[0];
2092 		count = HAMMER2_SET_COUNT;
2093 		break;
2094 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2095 	case HAMMER2_BREF_TYPE_INDIRECT:
2096 		/*
2097 		 * Optimize indirect blocks in the INITIAL state to avoid
2098 		 * I/O.
2099 		 */
2100 		if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2101 			base = NULL;
2102 		} else {
2103 			if (parent->data == NULL)
2104 				panic("parent->data is NULL");
2105 			base = &parent->data->npdata[0];
2106 		}
2107 		count = parent->bytes / sizeof(hammer2_blockref_t);
2108 		break;
2109 	case HAMMER2_BREF_TYPE_VOLUME:
2110 		base = &parent->data->voldata.sroot_blockset.blockref[0];
2111 		count = HAMMER2_SET_COUNT;
2112 		break;
2113 	case HAMMER2_BREF_TYPE_FREEMAP:
2114 		base = &parent->data->blkset.blockref[0];
2115 		count = HAMMER2_SET_COUNT;
2116 		break;
2117 	default:
2118 		panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2119 		      parent->bref.type);
2120 		base = NULL;	/* safety */
2121 		count = 0;	/* safety */
2122 	}
2123 
2124 	/*
2125 	 * Merged scan to find next candidate.
2126 	 *
2127 	 * hammer2_base_*() functions require the parent->core.live_* fields
2128 	 * to be synchronized.
2129 	 *
2130 	 * We need to hold the spinlock to access the block array and RB tree
2131 	 * and to interlock chain creation.
2132 	 */
2133 	if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2134 		hammer2_chain_countbrefs(parent, base, count);
2135 
2136 	next_key = 0;
2137 	bref_ptr = NULL;
2138 	hammer2_spin_ex(&parent->core.spin);
2139 	chain = hammer2_combined_find(parent, base, count,
2140 				      cache_indexp, &next_key,
2141 				      key, HAMMER2_KEY_MAX,
2142 				      &bref_ptr);
2143 	generation = parent->core.generation;
2144 
2145 	/*
2146 	 * Exhausted parent chain, we're done.
2147 	 */
2148 	if (bref_ptr == NULL) {
2149 		hammer2_spin_unex(&parent->core.spin);
2150 		KKASSERT(chain == NULL);
2151 		bref = NULL;
2152 		goto done;
2153 	}
2154 
2155 	/*
2156 	 * Copy into the supplied stack-based blockref.
2157 	 */
2158 	*bref = *bref_ptr;
2159 
2160 	/*
2161 	 * Selected from blockref or in-memory chain.
2162 	 */
2163 	if (chain == NULL) {
2164 		switch(bref->type) {
2165 		case HAMMER2_BREF_TYPE_INODE:
2166 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2167 		case HAMMER2_BREF_TYPE_INDIRECT:
2168 		case HAMMER2_BREF_TYPE_VOLUME:
2169 		case HAMMER2_BREF_TYPE_FREEMAP:
2170 			/*
2171 			 * Recursion, always get the chain
2172 			 */
2173 			hammer2_spin_unex(&parent->core.spin);
2174 			chain = hammer2_chain_get(parent, generation, bref);
2175 			if (chain == NULL) {
2176 				kprintf("retry scan parent %p keys %016jx\n",
2177 					parent, key);
2178 				goto again;
2179 			}
2180 			if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2181 				hammer2_chain_drop(chain);
2182 				chain = NULL;
2183 				goto again;
2184 			}
2185 			break;
2186 		default:
2187 			/*
2188 			 * No recursion, do not waste time instantiating
2189 			 * a chain, just iterate using the bref.
2190 			 */
2191 			hammer2_spin_unex(&parent->core.spin);
2192 			break;
2193 		}
2194 	} else {
2195 		/*
2196 		 * Recursion or not we need the chain in order to supply
2197 		 * the bref.
2198 		 */
2199 		hammer2_chain_ref(chain);
2200 		hammer2_spin_unex(&parent->core.spin);
2201 	}
2202 
2203 	/*
2204 	 * chain is referenced but not locked.  We must lock the chain
2205 	 * to obtain definitive DUPLICATED/DELETED state
2206 	 */
2207 	if (chain)
2208 		hammer2_chain_lock(chain, how);
2209 
2210 	/*
2211 	 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2212 	 *
2213 	 * NOTE: chain's key range is not relevant as there might be
2214 	 *	 one-offs within the range that are not deleted.
2215 	 *
2216 	 * NOTE: XXX this could create problems with scans used in
2217 	 *	 situations other than mount-time recovery.
2218 	 *
2219 	 * NOTE: Lookups can race delete-duplicate because
2220 	 *	 delete-duplicate does not lock the parent's core
2221 	 *	 (they just use the spinlock on the core).  We must
2222 	 *	 check for races by comparing the DUPLICATED flag before
2223 	 *	 releasing the spinlock with the flag after locking the
2224 	 *	 chain.
2225 	 */
2226 	if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2227 		hammer2_chain_unlock(chain);
2228 		hammer2_chain_drop(chain);
2229 		chain = NULL;
2230 
2231 		key = next_key;
2232 		if (key == 0) {
2233 			bref = NULL;
2234 			goto done;
2235 		}
2236 		goto again;
2237 	}
2238 
2239 done:
2240 	/*
2241 	 * All done, return the bref or NULL, supply chain if necessary.
2242 	 */
2243 	if (chain)
2244 		*chainp = chain;
2245 	return (bref);
2246 }
2247 
2248 /*
2249  * Create and return a new hammer2 system memory structure of the specified
2250  * key, type and size and insert it under (*parentp).  This is a full
2251  * insertion, based on the supplied key/keybits, and may involve creating
2252  * indirect blocks and moving other chains around via delete/duplicate.
2253  *
2254  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2255  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2256  * FULL.  This typically means that the caller is creating the chain after
2257  * doing a hammer2_chain_lookup().
2258  *
2259  * (*parentp) must be exclusive locked and may be replaced on return
2260  * depending on how much work the function had to do.
2261  *
2262  * (*parentp) must not be errored or this function will assert.
2263  *
2264  * (*chainp) usually starts out NULL and returns the newly created chain,
2265  * but if the caller desires the caller may allocate a disconnected chain
2266  * and pass it in instead.
2267  *
2268  * This function should NOT be used to insert INDIRECT blocks.  It is
2269  * typically used to create/insert inodes and data blocks.
2270  *
2271  * Caller must pass-in an exclusively locked parent the new chain is to
2272  * be inserted under, and optionally pass-in a disconnected, exclusively
2273  * locked chain to insert (else we create a new chain).  The function will
2274  * adjust (*parentp) as necessary, create or connect the chain, and
2275  * return an exclusively locked chain in *chainp.
2276  *
2277  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2278  * and will be reassigned.
2279  */
2280 int
2281 hammer2_chain_create(hammer2_chain_t **parentp,
2282 		     hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2283 		     hammer2_key_t key, int keybits, int type, size_t bytes,
2284 		     hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2285 {
2286 	hammer2_dev_t *hmp;
2287 	hammer2_chain_t *chain;
2288 	hammer2_chain_t *parent;
2289 	hammer2_blockref_t *base;
2290 	hammer2_blockref_t dummy;
2291 	int allocated = 0;
2292 	int error = 0;
2293 	int count;
2294 	int maxloops = 300000;
2295 
2296 	/*
2297 	 * Topology may be crossing a PFS boundary.
2298 	 */
2299 	parent = *parentp;
2300 	KKASSERT(hammer2_mtx_owned(&parent->lock));
2301 	KKASSERT(parent->error == 0);
2302 	hmp = parent->hmp;
2303 	chain = *chainp;
2304 
2305 	if (chain == NULL) {
2306 		/*
2307 		 * First allocate media space and construct the dummy bref,
2308 		 * then allocate the in-memory chain structure.  Set the
2309 		 * INITIAL flag for fresh chains which do not have embedded
2310 		 * data.
2311 		 *
2312 		 * XXX for now set the check mode of the child based on
2313 		 *     the parent or, if the parent is an inode, the
2314 		 *     specification in the inode.
2315 		 */
2316 		bzero(&dummy, sizeof(dummy));
2317 		dummy.type = type;
2318 		dummy.key = key;
2319 		dummy.keybits = keybits;
2320 		dummy.data_off = hammer2_getradix(bytes);
2321 		dummy.methods = parent->bref.methods;
2322 		if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2323 		    parent->data) {
2324 			dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2325 			dummy.methods |= HAMMER2_ENC_CHECK(
2326 					  parent->data->ipdata.meta.check_algo);
2327 		}
2328 
2329 		chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2330 
2331 		/*
2332 		 * Lock the chain manually, chain_lock will load the chain
2333 		 * which we do NOT want to do.  (note: chain->refs is set
2334 		 * to 1 by chain_alloc() for us, but lockcnt is not).
2335 		 */
2336 		chain->lockcnt = 1;
2337 		hammer2_mtx_ex(&chain->lock);
2338 		allocated = 1;
2339 
2340 		/*
2341 		 * Set INITIAL to optimize I/O.  The flag will generally be
2342 		 * processed when we call hammer2_chain_modify().
2343 		 *
2344 		 * Recalculate bytes to reflect the actual media block
2345 		 * allocation.
2346 		 */
2347 		bytes = (hammer2_off_t)1 <<
2348 			(int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2349 		chain->bytes = bytes;
2350 
2351 		switch(type) {
2352 		case HAMMER2_BREF_TYPE_VOLUME:
2353 		case HAMMER2_BREF_TYPE_FREEMAP:
2354 			panic("hammer2_chain_create: called with volume type");
2355 			break;
2356 		case HAMMER2_BREF_TYPE_INDIRECT:
2357 			panic("hammer2_chain_create: cannot be used to"
2358 			      "create indirect block");
2359 			break;
2360 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2361 			panic("hammer2_chain_create: cannot be used to"
2362 			      "create freemap root or node");
2363 			break;
2364 		case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2365 			KKASSERT(bytes == sizeof(chain->data->bmdata));
2366 			/* fall through */
2367 		case HAMMER2_BREF_TYPE_INODE:
2368 		case HAMMER2_BREF_TYPE_DATA:
2369 		default:
2370 			/*
2371 			 * leave chain->data NULL, set INITIAL
2372 			 */
2373 			KKASSERT(chain->data == NULL);
2374 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2375 			break;
2376 		}
2377 	} else {
2378 		/*
2379 		 * We are reattaching a previously deleted chain, possibly
2380 		 * under a new parent and possibly with a new key/keybits.
2381 		 * The chain does not have to be in a modified state.  The
2382 		 * UPDATE flag will be set later on in this routine.
2383 		 *
2384 		 * Do NOT mess with the current state of the INITIAL flag.
2385 		 */
2386 		chain->bref.key = key;
2387 		chain->bref.keybits = keybits;
2388 		if (chain->flags & HAMMER2_CHAIN_DELETED)
2389 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2390 		KKASSERT(chain->parent == NULL);
2391 	}
2392 	if (flags & HAMMER2_INSERT_PFSROOT)
2393 		chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2394 	else
2395 		chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2396 
2397 	/*
2398 	 * Calculate how many entries we have in the blockref array and
2399 	 * determine if an indirect block is required.
2400 	 */
2401 again:
2402 	if (--maxloops == 0)
2403 		panic("hammer2_chain_create: maxloops");
2404 
2405 	switch(parent->bref.type) {
2406 	case HAMMER2_BREF_TYPE_INODE:
2407 		KKASSERT((parent->data->ipdata.meta.op_flags &
2408 			  HAMMER2_OPFLAG_DIRECTDATA) == 0);
2409 		KKASSERT(parent->data != NULL);
2410 		base = &parent->data->ipdata.u.blockset.blockref[0];
2411 		count = HAMMER2_SET_COUNT;
2412 		break;
2413 	case HAMMER2_BREF_TYPE_INDIRECT:
2414 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2415 		if (parent->flags & HAMMER2_CHAIN_INITIAL)
2416 			base = NULL;
2417 		else
2418 			base = &parent->data->npdata[0];
2419 		count = parent->bytes / sizeof(hammer2_blockref_t);
2420 		break;
2421 	case HAMMER2_BREF_TYPE_VOLUME:
2422 		KKASSERT(parent->data != NULL);
2423 		base = &parent->data->voldata.sroot_blockset.blockref[0];
2424 		count = HAMMER2_SET_COUNT;
2425 		break;
2426 	case HAMMER2_BREF_TYPE_FREEMAP:
2427 		KKASSERT(parent->data != NULL);
2428 		base = &parent->data->blkset.blockref[0];
2429 		count = HAMMER2_SET_COUNT;
2430 		break;
2431 	default:
2432 		panic("hammer2_chain_create: unrecognized blockref type: %d",
2433 		      parent->bref.type);
2434 		base = NULL;
2435 		count = 0;
2436 		break;
2437 	}
2438 
2439 	/*
2440 	 * Make sure we've counted the brefs
2441 	 */
2442 	if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2443 		hammer2_chain_countbrefs(parent, base, count);
2444 
2445 	KKASSERT(parent->core.live_count >= 0 &&
2446 		 parent->core.live_count <= count);
2447 
2448 	/*
2449 	 * If no free blockref could be found we must create an indirect
2450 	 * block and move a number of blockrefs into it.  With the parent
2451 	 * locked we can safely lock each child in order to delete+duplicate
2452 	 * it without causing a deadlock.
2453 	 *
2454 	 * This may return the new indirect block or the old parent depending
2455 	 * on where the key falls.  NULL is returned on error.
2456 	 */
2457 	if (parent->core.live_count == count) {
2458 		hammer2_chain_t *nparent;
2459 
2460 		nparent = hammer2_chain_create_indirect(parent, key, keybits,
2461 							mtid, type, &error);
2462 		if (nparent == NULL) {
2463 			if (allocated)
2464 				hammer2_chain_drop(chain);
2465 			chain = NULL;
2466 			goto done;
2467 		}
2468 		if (parent != nparent) {
2469 			hammer2_chain_unlock(parent);
2470 			hammer2_chain_drop(parent);
2471 			parent = *parentp = nparent;
2472 		}
2473 		goto again;
2474 	}
2475 
2476 	/*
2477 	 * Link the chain into its parent.
2478 	 */
2479 	if (chain->parent != NULL)
2480 		panic("hammer2: hammer2_chain_create: chain already connected");
2481 	KKASSERT(chain->parent == NULL);
2482 	hammer2_chain_insert(parent, chain,
2483 			     HAMMER2_CHAIN_INSERT_SPIN |
2484 			     HAMMER2_CHAIN_INSERT_LIVE,
2485 			     0);
2486 
2487 	if (allocated) {
2488 		/*
2489 		 * Mark the newly created chain modified.  This will cause
2490 		 * UPDATE to be set and process the INITIAL flag.
2491 		 *
2492 		 * Device buffers are not instantiated for DATA elements
2493 		 * as these are handled by logical buffers.
2494 		 *
2495 		 * Indirect and freemap node indirect blocks are handled
2496 		 * by hammer2_chain_create_indirect() and not by this
2497 		 * function.
2498 		 *
2499 		 * Data for all other bref types is expected to be
2500 		 * instantiated (INODE, LEAF).
2501 		 */
2502 		switch(chain->bref.type) {
2503 		case HAMMER2_BREF_TYPE_DATA:
2504 		case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2505 		case HAMMER2_BREF_TYPE_INODE:
2506 			hammer2_chain_modify(chain, mtid, dedup_off,
2507 					     HAMMER2_MODIFY_OPTDATA);
2508 			break;
2509 		default:
2510 			/*
2511 			 * Remaining types are not supported by this function.
2512 			 * In particular, INDIRECT and LEAF_NODE types are
2513 			 * handled by create_indirect().
2514 			 */
2515 			panic("hammer2_chain_create: bad type: %d",
2516 			      chain->bref.type);
2517 			/* NOT REACHED */
2518 			break;
2519 		}
2520 	} else {
2521 		/*
2522 		 * When reconnecting a chain we must set UPDATE and
2523 		 * setflush so the flush recognizes that it must update
2524 		 * the bref in the parent.
2525 		 */
2526 		if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2527 			hammer2_chain_ref(chain);
2528 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2529 		}
2530 	}
2531 
2532 	/*
2533 	 * We must setflush(parent) to ensure that it recurses through to
2534 	 * chain.  setflush(chain) might not work because ONFLUSH is possibly
2535 	 * already set in the chain (so it won't recurse up to set it in the
2536 	 * parent).
2537 	 */
2538 	hammer2_chain_setflush(parent);
2539 
2540 done:
2541 	*chainp = chain;
2542 
2543 	return (error);
2544 }
2545 
2546 /*
2547  * Move the chain from its old parent to a new parent.  The chain must have
2548  * already been deleted or already disconnected (or never associated) with
2549  * a parent.  The chain is reassociated with the new parent and the deleted
2550  * flag will be cleared (no longer deleted).  The chain's modification state
2551  * is not altered.
2552  *
2553  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2554  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2555  * FULL.  This typically means that the caller is creating the chain after
2556  * doing a hammer2_chain_lookup().
2557  *
2558  * A non-NULL bref is typically passed when key and keybits must be overridden.
2559  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2560  * from a passed-in bref and uses the old chain's bref for everything else.
2561  *
2562  * Neither (parent) or (chain) can be errored.
2563  *
2564  * If (parent) is non-NULL then the new duplicated chain is inserted under
2565  * the parent.
2566  *
2567  * If (parent) is NULL then the newly duplicated chain is not inserted
2568  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2569  * passing into hammer2_chain_create() after this function returns).
2570  *
2571  * WARNING! This function calls create which means it can insert indirect
2572  *	    blocks.  This can cause other unrelated chains in the parent to
2573  *	    be moved to a newly inserted indirect block in addition to the
2574  *	    specific chain.
2575  */
2576 void
2577 hammer2_chain_rename(hammer2_blockref_t *bref,
2578 		     hammer2_chain_t **parentp, hammer2_chain_t *chain,
2579 		     hammer2_tid_t mtid, int flags)
2580 {
2581 	hammer2_dev_t *hmp;
2582 	hammer2_chain_t *parent;
2583 	size_t bytes;
2584 
2585 	/*
2586 	 * WARNING!  We should never resolve DATA to device buffers
2587 	 *	     (XXX allow it if the caller did?), and since
2588 	 *	     we currently do not have the logical buffer cache
2589 	 *	     buffer in-hand to fix its cached physical offset
2590 	 *	     we also force the modify code to not COW it. XXX
2591 	 */
2592 	hmp = chain->hmp;
2593 	KKASSERT(chain->parent == NULL);
2594 	KKASSERT(chain->error == 0);
2595 
2596 	/*
2597 	 * Now create a duplicate of the chain structure, associating
2598 	 * it with the same core, making it the same size, pointing it
2599 	 * to the same bref (the same media block).
2600 	 */
2601 	if (bref == NULL)
2602 		bref = &chain->bref;
2603 	bytes = (hammer2_off_t)1 <<
2604 		(int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2605 
2606 	/*
2607 	 * If parent is not NULL the duplicated chain will be entered under
2608 	 * the parent and the UPDATE bit set to tell flush to update
2609 	 * the blockref.
2610 	 *
2611 	 * We must setflush(parent) to ensure that it recurses through to
2612 	 * chain.  setflush(chain) might not work because ONFLUSH is possibly
2613 	 * already set in the chain (so it won't recurse up to set it in the
2614 	 * parent).
2615 	 *
2616 	 * Having both chains locked is extremely important for atomicy.
2617 	 */
2618 	if (parentp && (parent = *parentp) != NULL) {
2619 		KKASSERT(hammer2_mtx_owned(&parent->lock));
2620 		KKASSERT(parent->refs > 0);
2621 		KKASSERT(parent->error == 0);
2622 
2623 		hammer2_chain_create(parentp, &chain, chain->pmp,
2624 				     bref->key, bref->keybits, bref->type,
2625 				     chain->bytes, mtid, 0, flags);
2626 		KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2627 		hammer2_chain_setflush(*parentp);
2628 	}
2629 }
2630 
2631 /*
2632  * Helper function for deleting chains.
2633  *
2634  * The chain is removed from the live view (the RBTREE) as well as the parent's
2635  * blockmap.  Both chain and its parent must be locked.
2636  *
2637  * parent may not be errored.  chain can be errored.
2638  */
2639 static void
2640 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2641 			     hammer2_tid_t mtid, int flags)
2642 {
2643 	hammer2_dev_t *hmp;
2644 
2645 	KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2646 				  HAMMER2_CHAIN_FICTITIOUS)) == 0);
2647 	KKASSERT(chain->parent == parent);
2648 	hmp = chain->hmp;
2649 
2650 	if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2651 		/*
2652 		 * Chain is blockmapped, so there must be a parent.
2653 		 * Atomically remove the chain from the parent and remove
2654 		 * the blockmap entry.
2655 		 */
2656 		hammer2_blockref_t *base;
2657 		int count;
2658 
2659 		KKASSERT(parent != NULL);
2660 		KKASSERT(parent->error == 0);
2661 		KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2662 		hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2663 
2664 		/*
2665 		 * Calculate blockmap pointer
2666 		 */
2667 		KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2668 		hammer2_spin_ex(&parent->core.spin);
2669 
2670 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2671 		atomic_add_int(&parent->core.live_count, -1);
2672 		++parent->core.generation;
2673 		RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2674 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2675 		--parent->core.chain_count;
2676 		chain->parent = NULL;
2677 
2678 		switch(parent->bref.type) {
2679 		case HAMMER2_BREF_TYPE_INODE:
2680 			/*
2681 			 * Access the inode's block array.  However, there
2682 			 * is no block array if the inode is flagged
2683 			 * DIRECTDATA.  The DIRECTDATA case typicaly only
2684 			 * occurs when a hardlink has been shifted up the
2685 			 * tree and the original inode gets replaced with
2686 			 * an OBJTYPE_HARDLINK placeholding inode.
2687 			 */
2688 			if (parent->data &&
2689 			    (parent->data->ipdata.meta.op_flags &
2690 			     HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2691 				base =
2692 				   &parent->data->ipdata.u.blockset.blockref[0];
2693 			} else {
2694 				base = NULL;
2695 			}
2696 			count = HAMMER2_SET_COUNT;
2697 			break;
2698 		case HAMMER2_BREF_TYPE_INDIRECT:
2699 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2700 			if (parent->data)
2701 				base = &parent->data->npdata[0];
2702 			else
2703 				base = NULL;
2704 			count = parent->bytes / sizeof(hammer2_blockref_t);
2705 			break;
2706 		case HAMMER2_BREF_TYPE_VOLUME:
2707 			base = &parent->data->voldata.
2708 					sroot_blockset.blockref[0];
2709 			count = HAMMER2_SET_COUNT;
2710 			break;
2711 		case HAMMER2_BREF_TYPE_FREEMAP:
2712 			base = &parent->data->blkset.blockref[0];
2713 			count = HAMMER2_SET_COUNT;
2714 			break;
2715 		default:
2716 			base = NULL;
2717 			count = 0;
2718 			panic("hammer2_flush_pass2: "
2719 			      "unrecognized blockref type: %d",
2720 			      parent->bref.type);
2721 		}
2722 
2723 		/*
2724 		 * delete blockmapped chain from its parent.
2725 		 *
2726 		 * The parent is not affected by any statistics in chain
2727 		 * which are pending synchronization.  That is, there is
2728 		 * nothing to undo in the parent since they have not yet
2729 		 * been incorporated into the parent.
2730 		 *
2731 		 * The parent is affected by statistics stored in inodes.
2732 		 * Those have already been synchronized, so they must be
2733 		 * undone.  XXX split update possible w/delete in middle?
2734 		 */
2735 		if (base) {
2736 			int cache_index = -1;
2737 			hammer2_base_delete(parent, base, count,
2738 					    &cache_index, chain);
2739 		}
2740 		hammer2_spin_unex(&parent->core.spin);
2741 	} else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2742 		/*
2743 		 * Chain is not blockmapped but a parent is present.
2744 		 * Atomically remove the chain from the parent.  There is
2745 		 * no blockmap entry to remove.
2746 		 *
2747 		 * Because chain was associated with a parent but not
2748 		 * synchronized, the chain's *_count_up fields contain
2749 		 * inode adjustment statistics which must be undone.
2750 		 */
2751 		hammer2_spin_ex(&parent->core.spin);
2752 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2753 		atomic_add_int(&parent->core.live_count, -1);
2754 		++parent->core.generation;
2755 		RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2756 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2757 		--parent->core.chain_count;
2758 		chain->parent = NULL;
2759 		hammer2_spin_unex(&parent->core.spin);
2760 	} else {
2761 		/*
2762 		 * Chain is not blockmapped and has no parent.  This
2763 		 * is a degenerate case.
2764 		 */
2765 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2766 	}
2767 }
2768 
2769 /*
2770  * Create an indirect block that covers one or more of the elements in the
2771  * current parent.  Either returns the existing parent with no locking or
2772  * ref changes or returns the new indirect block locked and referenced
2773  * and leaving the original parent lock/ref intact as well.
2774  *
2775  * If an error occurs, NULL is returned and *errorp is set to the error.
2776  *
2777  * The returned chain depends on where the specified key falls.
2778  *
2779  * The key/keybits for the indirect mode only needs to follow three rules:
2780  *
2781  * (1) That all elements underneath it fit within its key space and
2782  *
2783  * (2) That all elements outside it are outside its key space.
2784  *
2785  * (3) When creating the new indirect block any elements in the current
2786  *     parent that fit within the new indirect block's keyspace must be
2787  *     moved into the new indirect block.
2788  *
2789  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2790  *     keyspace the the current parent, but lookup/iteration rules will
2791  *     ensure (and must ensure) that rule (2) for all parents leading up
2792  *     to the nearest inode or the root volume header is adhered to.  This
2793  *     is accomplished by always recursing through matching keyspaces in
2794  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
2795  *
2796  * The current implementation calculates the current worst-case keyspace by
2797  * iterating the current parent and then divides it into two halves, choosing
2798  * whichever half has the most elements (not necessarily the half containing
2799  * the requested key).
2800  *
2801  * We can also opt to use the half with the least number of elements.  This
2802  * causes lower-numbered keys (aka logical file offsets) to recurse through
2803  * fewer indirect blocks and higher-numbered keys to recurse through more.
2804  * This also has the risk of not moving enough elements to the new indirect
2805  * block and being forced to create several indirect blocks before the element
2806  * can be inserted.
2807  *
2808  * Must be called with an exclusively locked parent.
2809  */
2810 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2811 				hammer2_key_t *keyp, int keybits,
2812 				hammer2_blockref_t *base, int count);
2813 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2814 				hammer2_key_t *keyp, int keybits,
2815 				hammer2_blockref_t *base, int count);
2816 static
2817 hammer2_chain_t *
2818 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2819 			      hammer2_key_t create_key, int create_bits,
2820 			      hammer2_tid_t mtid, int for_type, int *errorp)
2821 {
2822 	hammer2_dev_t *hmp;
2823 	hammer2_blockref_t *base;
2824 	hammer2_blockref_t *bref;
2825 	hammer2_blockref_t bcopy;
2826 	hammer2_chain_t *chain;
2827 	hammer2_chain_t *ichain;
2828 	hammer2_chain_t dummy;
2829 	hammer2_key_t key = create_key;
2830 	hammer2_key_t key_beg;
2831 	hammer2_key_t key_end;
2832 	hammer2_key_t key_next;
2833 	int keybits = create_bits;
2834 	int count;
2835 	int nbytes;
2836 	int cache_index;
2837 	int loops;
2838 	int reason;
2839 	int generation;
2840 	int maxloops = 300000;
2841 
2842 	/*
2843 	 * Calculate the base blockref pointer or NULL if the chain
2844 	 * is known to be empty.  We need to calculate the array count
2845 	 * for RB lookups either way.
2846 	 */
2847 	hmp = parent->hmp;
2848 	*errorp = 0;
2849 	KKASSERT(hammer2_mtx_owned(&parent->lock));
2850 
2851 	/*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2852 	if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2853 		base = NULL;
2854 
2855 		switch(parent->bref.type) {
2856 		case HAMMER2_BREF_TYPE_INODE:
2857 			count = HAMMER2_SET_COUNT;
2858 			break;
2859 		case HAMMER2_BREF_TYPE_INDIRECT:
2860 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2861 			count = parent->bytes / sizeof(hammer2_blockref_t);
2862 			break;
2863 		case HAMMER2_BREF_TYPE_VOLUME:
2864 			count = HAMMER2_SET_COUNT;
2865 			break;
2866 		case HAMMER2_BREF_TYPE_FREEMAP:
2867 			count = HAMMER2_SET_COUNT;
2868 			break;
2869 		default:
2870 			panic("hammer2_chain_create_indirect: "
2871 			      "unrecognized blockref type: %d",
2872 			      parent->bref.type);
2873 			count = 0;
2874 			break;
2875 		}
2876 	} else {
2877 		switch(parent->bref.type) {
2878 		case HAMMER2_BREF_TYPE_INODE:
2879 			base = &parent->data->ipdata.u.blockset.blockref[0];
2880 			count = HAMMER2_SET_COUNT;
2881 			break;
2882 		case HAMMER2_BREF_TYPE_INDIRECT:
2883 		case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2884 			base = &parent->data->npdata[0];
2885 			count = parent->bytes / sizeof(hammer2_blockref_t);
2886 			break;
2887 		case HAMMER2_BREF_TYPE_VOLUME:
2888 			base = &parent->data->voldata.
2889 					sroot_blockset.blockref[0];
2890 			count = HAMMER2_SET_COUNT;
2891 			break;
2892 		case HAMMER2_BREF_TYPE_FREEMAP:
2893 			base = &parent->data->blkset.blockref[0];
2894 			count = HAMMER2_SET_COUNT;
2895 			break;
2896 		default:
2897 			panic("hammer2_chain_create_indirect: "
2898 			      "unrecognized blockref type: %d",
2899 			      parent->bref.type);
2900 			count = 0;
2901 			break;
2902 		}
2903 	}
2904 
2905 	/*
2906 	 * dummy used in later chain allocation (no longer used for lookups).
2907 	 */
2908 	bzero(&dummy, sizeof(dummy));
2909 
2910 	/*
2911 	 * When creating an indirect block for a freemap node or leaf
2912 	 * the key/keybits must be fitted to static radix levels because
2913 	 * particular radix levels use particular reserved blocks in the
2914 	 * related zone.
2915 	 *
2916 	 * This routine calculates the key/radix of the indirect block
2917 	 * we need to create, and whether it is on the high-side or the
2918 	 * low-side.
2919 	 */
2920 	if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2921 	    for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2922 		keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2923 						       base, count);
2924 	} else {
2925 		keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2926 						      base, count);
2927 	}
2928 
2929 	/*
2930 	 * Normalize the key for the radix being represented, keeping the
2931 	 * high bits and throwing away the low bits.
2932 	 */
2933 	key &= ~(((hammer2_key_t)1 << keybits) - 1);
2934 
2935 	/*
2936 	 * How big should our new indirect block be?  It has to be at least
2937 	 * as large as its parent.
2938 	 *
2939 	 * The freemap uses a specific indirect block size.
2940 	 *
2941 	 * The first indirect block level down from an inode typically
2942 	 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
2943 	 */
2944 	if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2945 	    for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2946 		nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
2947 	} else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
2948 		nbytes = HAMMER2_IND_BYTES_MIN;
2949 	} else {
2950 		nbytes = HAMMER2_IND_BYTES_MAX;
2951 	}
2952 	if (nbytes < count * sizeof(hammer2_blockref_t)) {
2953 		KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2954 			 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
2955 		nbytes = count * sizeof(hammer2_blockref_t);
2956 	}
2957 
2958 	/*
2959 	 * Ok, create our new indirect block
2960 	 */
2961 	if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2962 	    for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2963 		dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2964 	} else {
2965 		dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2966 	}
2967 	dummy.bref.key = key;
2968 	dummy.bref.keybits = keybits;
2969 	dummy.bref.data_off = hammer2_getradix(nbytes);
2970 	dummy.bref.methods = parent->bref.methods;
2971 
2972 	ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
2973 	atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2974 	hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2975 	/* ichain has one ref at this point */
2976 
2977 	/*
2978 	 * We have to mark it modified to allocate its block, but use
2979 	 * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
2980 	 * it won't be acted upon by the flush code.
2981 	 */
2982 	hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2983 
2984 	/*
2985 	 * Iterate the original parent and move the matching brefs into
2986 	 * the new indirect block.
2987 	 *
2988 	 * XXX handle flushes.
2989 	 */
2990 	key_beg = 0;
2991 	key_end = HAMMER2_KEY_MAX;
2992 	cache_index = 0;
2993 	hammer2_spin_ex(&parent->core.spin);
2994 	loops = 0;
2995 	reason = 0;
2996 
2997 	for (;;) {
2998 		if (++loops > 100000) {
2999 		    hammer2_spin_unex(&parent->core.spin);
3000 		    panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3001 			  reason, parent, base, count, key_next);
3002 		}
3003 
3004 		/*
3005 		 * NOTE: spinlock stays intact, returned chain (if not NULL)
3006 		 *	 is not referenced or locked which means that we
3007 		 *	 cannot safely check its flagged / deletion status
3008 		 *	 until we lock it.
3009 		 */
3010 		chain = hammer2_combined_find(parent, base, count,
3011 					      &cache_index, &key_next,
3012 					      key_beg, key_end,
3013 					      &bref);
3014 		generation = parent->core.generation;
3015 		if (bref == NULL)
3016 			break;
3017 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3018 
3019 		/*
3020 		 * Skip keys that are not within the key/radix of the new
3021 		 * indirect block.  They stay in the parent.
3022 		 */
3023 		if ((~(((hammer2_key_t)1 << keybits) - 1) &
3024 		    (key ^ bref->key)) != 0) {
3025 			goto next_key_spinlocked;
3026 		}
3027 
3028 		/*
3029 		 * Load the new indirect block by acquiring the related
3030 		 * chains (potentially from media as it might not be
3031 		 * in-memory).  Then move it to the new parent (ichain)
3032 		 * via DELETE-DUPLICATE.
3033 		 *
3034 		 * chain is referenced but not locked.  We must lock the
3035 		 * chain to obtain definitive DUPLICATED/DELETED state
3036 		 */
3037 		if (chain) {
3038 			/*
3039 			 * Use chain already present in the RBTREE
3040 			 */
3041 			hammer2_chain_ref(chain);
3042 			hammer2_spin_unex(&parent->core.spin);
3043 			hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3044 		} else {
3045 			/*
3046 			 * Get chain for blockref element.  _get returns NULL
3047 			 * on insertion race.
3048 			 */
3049 			bcopy = *bref;
3050 			hammer2_spin_unex(&parent->core.spin);
3051 			chain = hammer2_chain_get(parent, generation, &bcopy);
3052 			if (chain == NULL) {
3053 				reason = 1;
3054 				hammer2_spin_ex(&parent->core.spin);
3055 				continue;
3056 			}
3057 			if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3058 				kprintf("REASON 2\n");
3059 				reason = 2;
3060 				hammer2_chain_drop(chain);
3061 				hammer2_spin_ex(&parent->core.spin);
3062 				continue;
3063 			}
3064 			hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3065 		}
3066 
3067 		/*
3068 		 * This is always live so if the chain has been deleted
3069 		 * we raced someone and we have to retry.
3070 		 *
3071 		 * NOTE: Lookups can race delete-duplicate because
3072 		 *	 delete-duplicate does not lock the parent's core
3073 		 *	 (they just use the spinlock on the core).  We must
3074 		 *	 check for races by comparing the DUPLICATED flag before
3075 		 *	 releasing the spinlock with the flag after locking the
3076 		 *	 chain.
3077 		 *
3078 		 *	 (note reversed logic for this one)
3079 		 */
3080 		if (chain->flags & HAMMER2_CHAIN_DELETED) {
3081 			hammer2_chain_unlock(chain);
3082 			hammer2_chain_drop(chain);
3083 			goto next_key;
3084 		}
3085 
3086 		/*
3087 		 * Shift the chain to the indirect block.
3088 		 *
3089 		 * WARNING! No reason for us to load chain data, pass NOSTATS
3090 		 *	    to prevent delete/insert from trying to access
3091 		 *	    inode stats (and thus asserting if there is no
3092 		 *	    chain->data loaded).
3093 		 */
3094 		hammer2_chain_delete(parent, chain, mtid, 0);
3095 		hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3096 		hammer2_chain_unlock(chain);
3097 		hammer2_chain_drop(chain);
3098 		KKASSERT(parent->refs > 0);
3099 		chain = NULL;
3100 next_key:
3101 		hammer2_spin_ex(&parent->core.spin);
3102 next_key_spinlocked:
3103 		if (--maxloops == 0)
3104 			panic("hammer2_chain_create_indirect: maxloops");
3105 		reason = 4;
3106 		if (key_next == 0 || key_next > key_end)
3107 			break;
3108 		key_beg = key_next;
3109 		/* loop */
3110 	}
3111 	hammer2_spin_unex(&parent->core.spin);
3112 
3113 	/*
3114 	 * Insert the new indirect block into the parent now that we've
3115 	 * cleared out some entries in the parent.  We calculated a good
3116 	 * insertion index in the loop above (ichain->index).
3117 	 *
3118 	 * We don't have to set UPDATE here because we mark ichain
3119 	 * modified down below (so the normal modified -> flush -> set-moved
3120 	 * sequence applies).
3121 	 *
3122 	 * The insertion shouldn't race as this is a completely new block
3123 	 * and the parent is locked.
3124 	 */
3125 	KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3126 	hammer2_chain_insert(parent, ichain,
3127 			     HAMMER2_CHAIN_INSERT_SPIN |
3128 			     HAMMER2_CHAIN_INSERT_LIVE,
3129 			     0);
3130 
3131 	/*
3132 	 * Make sure flushes propogate after our manual insertion.
3133 	 */
3134 	hammer2_chain_setflush(ichain);
3135 	hammer2_chain_setflush(parent);
3136 
3137 	/*
3138 	 * Figure out what to return.
3139 	 */
3140 	if (~(((hammer2_key_t)1 << keybits) - 1) &
3141 		   (create_key ^ key)) {
3142 		/*
3143 		 * Key being created is outside the key range,
3144 		 * return the original parent.
3145 		 */
3146 		hammer2_chain_unlock(ichain);
3147 		hammer2_chain_drop(ichain);
3148 	} else {
3149 		/*
3150 		 * Otherwise its in the range, return the new parent.
3151 		 * (leave both the new and old parent locked).
3152 		 */
3153 		parent = ichain;
3154 	}
3155 
3156 	return(parent);
3157 }
3158 
3159 /*
3160  * Calculate the keybits and highside/lowside of the freemap node the
3161  * caller is creating.
3162  *
3163  * This routine will specify the next higher-level freemap key/radix
3164  * representing the lowest-ordered set.  By doing so, eventually all
3165  * low-ordered sets will be moved one level down.
3166  *
3167  * We have to be careful here because the freemap reserves a limited
3168  * number of blocks for a limited number of levels.  So we can't just
3169  * push indiscriminately.
3170  */
3171 int
3172 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3173 			     int keybits, hammer2_blockref_t *base, int count)
3174 {
3175 	hammer2_chain_t *chain;
3176 	hammer2_blockref_t *bref;
3177 	hammer2_key_t key;
3178 	hammer2_key_t key_beg;
3179 	hammer2_key_t key_end;
3180 	hammer2_key_t key_next;
3181 	int cache_index;
3182 	int locount;
3183 	int hicount;
3184 	int maxloops = 300000;
3185 
3186 	key = *keyp;
3187 	locount = 0;
3188 	hicount = 0;
3189 	keybits = 64;
3190 
3191 	/*
3192 	 * Calculate the range of keys in the array being careful to skip
3193 	 * slots which are overridden with a deletion.
3194 	 */
3195 	key_beg = 0;
3196 	key_end = HAMMER2_KEY_MAX;
3197 	cache_index = 0;
3198 	hammer2_spin_ex(&parent->core.spin);
3199 
3200 	for (;;) {
3201 		if (--maxloops == 0) {
3202 			panic("indkey_freemap shit %p %p:%d\n",
3203 			      parent, base, count);
3204 		}
3205 		chain = hammer2_combined_find(parent, base, count,
3206 					      &cache_index, &key_next,
3207 					      key_beg, key_end,
3208 					      &bref);
3209 
3210 		/*
3211 		 * Exhausted search
3212 		 */
3213 		if (bref == NULL)
3214 			break;
3215 
3216 		/*
3217 		 * Skip deleted chains.
3218 		 */
3219 		if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3220 			if (key_next == 0 || key_next > key_end)
3221 				break;
3222 			key_beg = key_next;
3223 			continue;
3224 		}
3225 
3226 		/*
3227 		 * Use the full live (not deleted) element for the scan
3228 		 * iteration.  HAMMER2 does not allow partial replacements.
3229 		 *
3230 		 * XXX should be built into hammer2_combined_find().
3231 		 */
3232 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3233 
3234 		if (keybits > bref->keybits) {
3235 			key = bref->key;
3236 			keybits = bref->keybits;
3237 		} else if (keybits == bref->keybits && bref->key < key) {
3238 			key = bref->key;
3239 		}
3240 		if (key_next == 0)
3241 			break;
3242 		key_beg = key_next;
3243 	}
3244 	hammer2_spin_unex(&parent->core.spin);
3245 
3246 	/*
3247 	 * Return the keybits for a higher-level FREEMAP_NODE covering
3248 	 * this node.
3249 	 */
3250 	switch(keybits) {
3251 	case HAMMER2_FREEMAP_LEVEL0_RADIX:
3252 		keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3253 		break;
3254 	case HAMMER2_FREEMAP_LEVEL1_RADIX:
3255 		keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3256 		break;
3257 	case HAMMER2_FREEMAP_LEVEL2_RADIX:
3258 		keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3259 		break;
3260 	case HAMMER2_FREEMAP_LEVEL3_RADIX:
3261 		keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3262 		break;
3263 	case HAMMER2_FREEMAP_LEVEL4_RADIX:
3264 		keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3265 		break;
3266 	case HAMMER2_FREEMAP_LEVEL5_RADIX:
3267 		panic("hammer2_chain_indkey_freemap: level too high");
3268 		break;
3269 	default:
3270 		panic("hammer2_chain_indkey_freemap: bad radix");
3271 		break;
3272 	}
3273 	*keyp = key;
3274 
3275 	return (keybits);
3276 }
3277 
3278 /*
3279  * Calculate the keybits and highside/lowside of the indirect block the
3280  * caller is creating.
3281  */
3282 static int
3283 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3284 			    int keybits, hammer2_blockref_t *base, int count)
3285 {
3286 	hammer2_blockref_t *bref;
3287 	hammer2_chain_t	*chain;
3288 	hammer2_key_t key_beg;
3289 	hammer2_key_t key_end;
3290 	hammer2_key_t key_next;
3291 	hammer2_key_t key;
3292 	int nkeybits;
3293 	int locount;
3294 	int hicount;
3295 	int cache_index;
3296 	int maxloops = 300000;
3297 
3298 	key = *keyp;
3299 	locount = 0;
3300 	hicount = 0;
3301 
3302 	/*
3303 	 * Calculate the range of keys in the array being careful to skip
3304 	 * slots which are overridden with a deletion.  Once the scan
3305 	 * completes we will cut the key range in half and shift half the
3306 	 * range into the new indirect block.
3307 	 */
3308 	key_beg = 0;
3309 	key_end = HAMMER2_KEY_MAX;
3310 	cache_index = 0;
3311 	hammer2_spin_ex(&parent->core.spin);
3312 
3313 	for (;;) {
3314 		if (--maxloops == 0) {
3315 			panic("indkey_freemap shit %p %p:%d\n",
3316 			      parent, base, count);
3317 		}
3318 		chain = hammer2_combined_find(parent, base, count,
3319 					      &cache_index, &key_next,
3320 					      key_beg, key_end,
3321 					      &bref);
3322 
3323 		/*
3324 		 * Exhausted search
3325 		 */
3326 		if (bref == NULL)
3327 			break;
3328 
3329 		/*
3330 		 * NOTE: No need to check DUPLICATED here because we do
3331 		 *	 not release the spinlock.
3332 		 */
3333 		if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3334 			if (key_next == 0 || key_next > key_end)
3335 				break;
3336 			key_beg = key_next;
3337 			continue;
3338 		}
3339 
3340 		/*
3341 		 * Use the full live (not deleted) element for the scan
3342 		 * iteration.  HAMMER2 does not allow partial replacements.
3343 		 *
3344 		 * XXX should be built into hammer2_combined_find().
3345 		 */
3346 		key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3347 
3348 		/*
3349 		 * Expand our calculated key range (key, keybits) to fit
3350 		 * the scanned key.  nkeybits represents the full range
3351 		 * that we will later cut in half (two halves @ nkeybits - 1).
3352 		 */
3353 		nkeybits = keybits;
3354 		if (nkeybits < bref->keybits) {
3355 			if (bref->keybits > 64) {
3356 				kprintf("bad bref chain %p bref %p\n",
3357 					chain, bref);
3358 				Debugger("fubar");
3359 			}
3360 			nkeybits = bref->keybits;
3361 		}
3362 		while (nkeybits < 64 &&
3363 		       (~(((hammer2_key_t)1 << nkeybits) - 1) &
3364 		        (key ^ bref->key)) != 0) {
3365 			++nkeybits;
3366 		}
3367 
3368 		/*
3369 		 * If the new key range is larger we have to determine
3370 		 * which side of the new key range the existing keys fall
3371 		 * under by checking the high bit, then collapsing the
3372 		 * locount into the hicount or vise-versa.
3373 		 */
3374 		if (keybits != nkeybits) {
3375 			if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3376 				hicount += locount;
3377 				locount = 0;
3378 			} else {
3379 				locount += hicount;
3380 				hicount = 0;
3381 			}
3382 			keybits = nkeybits;
3383 		}
3384 
3385 		/*
3386 		 * The newly scanned key will be in the lower half or the
3387 		 * upper half of the (new) key range.
3388 		 */
3389 		if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3390 			++hicount;
3391 		else
3392 			++locount;
3393 
3394 		if (key_next == 0)
3395 			break;
3396 		key_beg = key_next;
3397 	}
3398 	hammer2_spin_unex(&parent->core.spin);
3399 	bref = NULL;	/* now invalid (safety) */
3400 
3401 	/*
3402 	 * Adjust keybits to represent half of the full range calculated
3403 	 * above (radix 63 max)
3404 	 */
3405 	--keybits;
3406 
3407 	/*
3408 	 * Select whichever half contains the most elements.  Theoretically
3409 	 * we can select either side as long as it contains at least one
3410 	 * element (in order to ensure that a free slot is present to hold
3411 	 * the indirect block).
3412 	 */
3413 	if (hammer2_indirect_optimize) {
3414 		/*
3415 		 * Insert node for least number of keys, this will arrange
3416 		 * the first few blocks of a large file or the first few
3417 		 * inodes in a directory with fewer indirect blocks when
3418 		 * created linearly.
3419 		 */
3420 		if (hicount < locount && hicount != 0)
3421 			key |= (hammer2_key_t)1 << keybits;
3422 		else
3423 			key &= ~(hammer2_key_t)1 << keybits;
3424 	} else {
3425 		/*
3426 		 * Insert node for most number of keys, best for heavily
3427 		 * fragmented files.
3428 		 */
3429 		if (hicount > locount)
3430 			key |= (hammer2_key_t)1 << keybits;
3431 		else
3432 			key &= ~(hammer2_key_t)1 << keybits;
3433 	}
3434 	*keyp = key;
3435 
3436 	return (keybits);
3437 }
3438 
3439 /*
3440  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3441  * it exists.
3442  *
3443  * Both parent and chain must be locked exclusively.
3444  *
3445  * This function will modify the parent if the blockref requires removal
3446  * from the parent's block table.
3447  *
3448  * This function is NOT recursive.  Any entity already pushed into the
3449  * chain (such as an inode) may still need visibility into its contents,
3450  * as well as the ability to read and modify the contents.  For example,
3451  * for an unlinked file which is still open.
3452  */
3453 void
3454 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3455 		     hammer2_tid_t mtid, int flags)
3456 {
3457 	KKASSERT(hammer2_mtx_owned(&chain->lock));
3458 
3459 	/*
3460 	 * Nothing to do if already marked.
3461 	 *
3462 	 * We need the spinlock on the core whos RBTREE contains chain
3463 	 * to protect against races.
3464 	 */
3465 	if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3466 		KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3467 			 chain->parent == parent);
3468 		_hammer2_chain_delete_helper(parent, chain, mtid, flags);
3469 	}
3470 
3471 	/*
3472 	 * To avoid losing track of a permanent deletion we add the chain
3473 	 * to the delayed flush queue.  If were to flush it right now the
3474 	 * parent would end up in a modified state and generate I/O.
3475 	 * The delayed queue gives the parent a chance to be deleted to
3476 	 * (e.g. rm -rf).
3477 	 */
3478 	if (flags & HAMMER2_DELETE_PERMANENT) {
3479 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3480 		hammer2_delayed_flush(chain);
3481 	} else {
3482 		/* XXX might not be needed */
3483 		hammer2_chain_setflush(chain);
3484 	}
3485 }
3486 
3487 /*
3488  * Returns the index of the nearest element in the blockref array >= elm.
3489  * Returns (count) if no element could be found.
3490  *
3491  * Sets *key_nextp to the next key for loop purposes but does not modify
3492  * it if the next key would be higher than the current value of *key_nextp.
3493  * Note that *key_nexp can overflow to 0, which should be tested by the
3494  * caller.
3495  *
3496  * (*cache_indexp) is a heuristic and can be any value without effecting
3497  * the result.
3498  *
3499  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3500  *	     held through the operation.
3501  */
3502 static int
3503 hammer2_base_find(hammer2_chain_t *parent,
3504 		  hammer2_blockref_t *base, int count,
3505 		  int *cache_indexp, hammer2_key_t *key_nextp,
3506 		  hammer2_key_t key_beg, hammer2_key_t key_end)
3507 {
3508 	hammer2_blockref_t *scan;
3509 	hammer2_key_t scan_end;
3510 	int i;
3511 	int limit;
3512 
3513 	/*
3514 	 * Require the live chain's already have their core's counted
3515 	 * so we can optimize operations.
3516 	 */
3517         KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3518 
3519 	/*
3520 	 * Degenerate case
3521 	 */
3522 	if (count == 0 || base == NULL)
3523 		return(count);
3524 
3525 	/*
3526 	 * Sequential optimization using *cache_indexp.  This is the most
3527 	 * likely scenario.
3528 	 *
3529 	 * We can avoid trailing empty entries on live chains, otherwise
3530 	 * we might have to check the whole block array.
3531 	 */
3532 	i = *cache_indexp;
3533 	cpu_ccfence();
3534 	limit = parent->core.live_zero;
3535 	if (i >= limit)
3536 		i = limit - 1;
3537 	if (i < 0)
3538 		i = 0;
3539 	KKASSERT(i < count);
3540 
3541 	/*
3542 	 * Search backwards
3543 	 */
3544 	scan = &base[i];
3545 	while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3546 		--scan;
3547 		--i;
3548 	}
3549 	*cache_indexp = i;
3550 
3551 	/*
3552 	 * Search forwards, stop when we find a scan element which
3553 	 * encloses the key or until we know that there are no further
3554 	 * elements.
3555 	 */
3556 	while (i < count) {
3557 		if (scan->type != 0) {
3558 			scan_end = scan->key +
3559 				   ((hammer2_key_t)1 << scan->keybits) - 1;
3560 			if (scan->key > key_beg || scan_end >= key_beg)
3561 				break;
3562 		}
3563 		if (i >= limit)
3564 			return (count);
3565 		++scan;
3566 		++i;
3567 	}
3568 	if (i != count) {
3569 		*cache_indexp = i;
3570 		if (i >= limit) {
3571 			i = count;
3572 		} else {
3573 			scan_end = scan->key +
3574 				   ((hammer2_key_t)1 << scan->keybits);
3575 			if (scan_end && (*key_nextp > scan_end ||
3576 					 *key_nextp == 0)) {
3577 				*key_nextp = scan_end;
3578 			}
3579 		}
3580 	}
3581 	return (i);
3582 }
3583 
3584 /*
3585  * Do a combined search and return the next match either from the blockref
3586  * array or from the in-memory chain.  Sets *bresp to the returned bref in
3587  * both cases, or sets it to NULL if the search exhausted.  Only returns
3588  * a non-NULL chain if the search matched from the in-memory chain.
3589  *
3590  * When no in-memory chain has been found and a non-NULL bref is returned
3591  * in *bresp.
3592  *
3593  *
3594  * The returned chain is not locked or referenced.  Use the returned bref
3595  * to determine if the search exhausted or not.  Iterate if the base find
3596  * is chosen but matches a deleted chain.
3597  *
3598  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3599  *	     held through the operation.
3600  */
3601 static hammer2_chain_t *
3602 hammer2_combined_find(hammer2_chain_t *parent,
3603 		      hammer2_blockref_t *base, int count,
3604 		      int *cache_indexp, hammer2_key_t *key_nextp,
3605 		      hammer2_key_t key_beg, hammer2_key_t key_end,
3606 		      hammer2_blockref_t **bresp)
3607 {
3608 	hammer2_blockref_t *bref;
3609 	hammer2_chain_t *chain;
3610 	int i;
3611 
3612 	/*
3613 	 * Lookup in block array and in rbtree.
3614 	 */
3615 	*key_nextp = key_end + 1;
3616 	i = hammer2_base_find(parent, base, count, cache_indexp,
3617 			      key_nextp, key_beg, key_end);
3618 	chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3619 
3620 	/*
3621 	 * Neither matched
3622 	 */
3623 	if (i == count && chain == NULL) {
3624 		*bresp = NULL;
3625 		return(NULL);
3626 	}
3627 
3628 	/*
3629 	 * Only chain matched.
3630 	 */
3631 	if (i == count) {
3632 		bref = &chain->bref;
3633 		goto found;
3634 	}
3635 
3636 	/*
3637 	 * Only blockref matched.
3638 	 */
3639 	if (chain == NULL) {
3640 		bref = &base[i];
3641 		goto found;
3642 	}
3643 
3644 	/*
3645 	 * Both in-memory and blockref matched, select the nearer element.
3646 	 *
3647 	 * If both are flush with the left-hand side or both are the
3648 	 * same distance away, select the chain.  In this situation the
3649 	 * chain must have been loaded from the matching blockmap.
3650 	 */
3651 	if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3652 	    chain->bref.key == base[i].key) {
3653 		KKASSERT(chain->bref.key == base[i].key);
3654 		bref = &chain->bref;
3655 		goto found;
3656 	}
3657 
3658 	/*
3659 	 * Select the nearer key
3660 	 */
3661 	if (chain->bref.key < base[i].key) {
3662 		bref = &chain->bref;
3663 	} else {
3664 		bref = &base[i];
3665 		chain = NULL;
3666 	}
3667 
3668 	/*
3669 	 * If the bref is out of bounds we've exhausted our search.
3670 	 */
3671 found:
3672 	if (bref->key > key_end) {
3673 		*bresp = NULL;
3674 		chain = NULL;
3675 	} else {
3676 		*bresp = bref;
3677 	}
3678 	return(chain);
3679 }
3680 
3681 /*
3682  * Locate the specified block array element and delete it.  The element
3683  * must exist.
3684  *
3685  * The spin lock on the related chain must be held.
3686  *
3687  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3688  *	 need to be adjusted when we commit the media change.
3689  */
3690 void
3691 hammer2_base_delete(hammer2_chain_t *parent,
3692 		    hammer2_blockref_t *base, int count,
3693 		    int *cache_indexp, hammer2_chain_t *chain)
3694 {
3695 	hammer2_blockref_t *elm = &chain->bref;
3696 	hammer2_key_t key_next;
3697 	int i;
3698 
3699 	/*
3700 	 * Delete element.  Expect the element to exist.
3701 	 *
3702 	 * XXX see caller, flush code not yet sophisticated enough to prevent
3703 	 *     re-flushed in some cases.
3704 	 */
3705 	key_next = 0; /* max range */
3706 	i = hammer2_base_find(parent, base, count, cache_indexp,
3707 			      &key_next, elm->key, elm->key);
3708 	if (i == count || base[i].type == 0 ||
3709 	    base[i].key != elm->key ||
3710 	    ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3711 	     base[i].keybits != elm->keybits)) {
3712 		hammer2_spin_unex(&parent->core.spin);
3713 		panic("delete base %p element not found at %d/%d elm %p\n",
3714 		      base, i, count, elm);
3715 		return;
3716 	}
3717 
3718 	/*
3719 	 * Update stats and zero the entry
3720 	 */
3721 	parent->bref.data_count -= base[i].data_count;
3722 	parent->bref.data_count -= (hammer2_off_t)1 <<
3723 			(int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3724 	parent->bref.inode_count -= base[i].inode_count;
3725 	if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3726 		parent->bref.inode_count -= 1;
3727 
3728 	bzero(&base[i], sizeof(*base));
3729 
3730 	/*
3731 	 * We can only optimize parent->core.live_zero for live chains.
3732 	 */
3733 	if (parent->core.live_zero == i + 1) {
3734 		while (--i >= 0 && base[i].type == 0)
3735 			;
3736 		parent->core.live_zero = i + 1;
3737 	}
3738 
3739 	/*
3740 	 * Clear appropriate blockmap flags in chain.
3741 	 */
3742 	atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3743 					HAMMER2_CHAIN_BMAPUPD);
3744 }
3745 
3746 /*
3747  * Insert the specified element.  The block array must not already have the
3748  * element and must have space available for the insertion.
3749  *
3750  * The spin lock on the related chain must be held.
3751  *
3752  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3753  *	 need to be adjusted when we commit the media change.
3754  */
3755 void
3756 hammer2_base_insert(hammer2_chain_t *parent,
3757 		    hammer2_blockref_t *base, int count,
3758 		    int *cache_indexp, hammer2_chain_t *chain)
3759 {
3760 	hammer2_blockref_t *elm = &chain->bref;
3761 	hammer2_key_t key_next;
3762 	hammer2_key_t xkey;
3763 	int i;
3764 	int j;
3765 	int k;
3766 	int l;
3767 	int u = 1;
3768 
3769 	/*
3770 	 * Insert new element.  Expect the element to not already exist
3771 	 * unless we are replacing it.
3772 	 *
3773 	 * XXX see caller, flush code not yet sophisticated enough to prevent
3774 	 *     re-flushed in some cases.
3775 	 */
3776 	key_next = 0; /* max range */
3777 	i = hammer2_base_find(parent, base, count, cache_indexp,
3778 			      &key_next, elm->key, elm->key);
3779 
3780 	/*
3781 	 * Shortcut fill optimization, typical ordered insertion(s) may not
3782 	 * require a search.
3783 	 */
3784 	KKASSERT(i >= 0 && i <= count);
3785 
3786 	/*
3787 	 * Set appropriate blockmap flags in chain.
3788 	 */
3789 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3790 
3791 	/*
3792 	 * Update stats and zero the entry
3793 	 */
3794 	parent->bref.data_count += elm->data_count;
3795 	parent->bref.data_count += (hammer2_off_t)1 <<
3796 			(int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3797 	parent->bref.inode_count += elm->inode_count;
3798 	if (elm->type == HAMMER2_BREF_TYPE_INODE)
3799 		parent->bref.inode_count += 1;
3800 
3801 
3802 	/*
3803 	 * We can only optimize parent->core.live_zero for live chains.
3804 	 */
3805 	if (i == count && parent->core.live_zero < count) {
3806 		i = parent->core.live_zero++;
3807 		base[i] = *elm;
3808 		return;
3809 	}
3810 
3811 	xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3812 	if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3813 		hammer2_spin_unex(&parent->core.spin);
3814 		panic("insert base %p overlapping elements at %d elm %p\n",
3815 		      base, i, elm);
3816 	}
3817 
3818 	/*
3819 	 * Try to find an empty slot before or after.
3820 	 */
3821 	j = i;
3822 	k = i;
3823 	while (j > 0 || k < count) {
3824 		--j;
3825 		if (j >= 0 && base[j].type == 0) {
3826 			if (j == i - 1) {
3827 				base[j] = *elm;
3828 			} else {
3829 				bcopy(&base[j+1], &base[j],
3830 				      (i - j - 1) * sizeof(*base));
3831 				base[i - 1] = *elm;
3832 			}
3833 			goto validate;
3834 		}
3835 		++k;
3836 		if (k < count && base[k].type == 0) {
3837 			bcopy(&base[i], &base[i+1],
3838 			      (k - i) * sizeof(hammer2_blockref_t));
3839 			base[i] = *elm;
3840 
3841 			/*
3842 			 * We can only update parent->core.live_zero for live
3843 			 * chains.
3844 			 */
3845 			if (parent->core.live_zero <= k)
3846 				parent->core.live_zero = k + 1;
3847 			u = 2;
3848 			goto validate;
3849 		}
3850 	}
3851 	panic("hammer2_base_insert: no room!");
3852 
3853 	/*
3854 	 * Debugging
3855 	 */
3856 validate:
3857 	key_next = 0;
3858 	for (l = 0; l < count; ++l) {
3859 		if (base[l].type) {
3860 			key_next = base[l].key +
3861 				   ((hammer2_key_t)1 << base[l].keybits) - 1;
3862 			break;
3863 		}
3864 	}
3865 	while (++l < count) {
3866 		if (base[l].type) {
3867 			if (base[l].key <= key_next)
3868 				panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3869 			key_next = base[l].key +
3870 				   ((hammer2_key_t)1 << base[l].keybits) - 1;
3871 
3872 		}
3873 	}
3874 
3875 }
3876 
3877 #if 0
3878 
3879 /*
3880  * Sort the blockref array for the chain.  Used by the flush code to
3881  * sort the blockref[] array.
3882  *
3883  * The chain must be exclusively locked AND spin-locked.
3884  */
3885 typedef hammer2_blockref_t *hammer2_blockref_p;
3886 
3887 static
3888 int
3889 hammer2_base_sort_callback(const void *v1, const void *v2)
3890 {
3891 	hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3892 	hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3893 
3894 	/*
3895 	 * Make sure empty elements are placed at the end of the array
3896 	 */
3897 	if (bref1->type == 0) {
3898 		if (bref2->type == 0)
3899 			return(0);
3900 		return(1);
3901 	} else if (bref2->type == 0) {
3902 		return(-1);
3903 	}
3904 
3905 	/*
3906 	 * Sort by key
3907 	 */
3908 	if (bref1->key < bref2->key)
3909 		return(-1);
3910 	if (bref1->key > bref2->key)
3911 		return(1);
3912 	return(0);
3913 }
3914 
3915 void
3916 hammer2_base_sort(hammer2_chain_t *chain)
3917 {
3918 	hammer2_blockref_t *base;
3919 	int count;
3920 
3921 	switch(chain->bref.type) {
3922 	case HAMMER2_BREF_TYPE_INODE:
3923 		/*
3924 		 * Special shortcut for embedded data returns the inode
3925 		 * itself.  Callers must detect this condition and access
3926 		 * the embedded data (the strategy code does this for us).
3927 		 *
3928 		 * This is only applicable to regular files and softlinks.
3929 		 */
3930 		if (chain->data->ipdata.meta.op_flags &
3931 		    HAMMER2_OPFLAG_DIRECTDATA) {
3932 			return;
3933 		}
3934 		base = &chain->data->ipdata.u.blockset.blockref[0];
3935 		count = HAMMER2_SET_COUNT;
3936 		break;
3937 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3938 	case HAMMER2_BREF_TYPE_INDIRECT:
3939 		/*
3940 		 * Optimize indirect blocks in the INITIAL state to avoid
3941 		 * I/O.
3942 		 */
3943 		KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3944 		base = &chain->data->npdata[0];
3945 		count = chain->bytes / sizeof(hammer2_blockref_t);
3946 		break;
3947 	case HAMMER2_BREF_TYPE_VOLUME:
3948 		base = &chain->data->voldata.sroot_blockset.blockref[0];
3949 		count = HAMMER2_SET_COUNT;
3950 		break;
3951 	case HAMMER2_BREF_TYPE_FREEMAP:
3952 		base = &chain->data->blkset.blockref[0];
3953 		count = HAMMER2_SET_COUNT;
3954 		break;
3955 	default:
3956 		kprintf("hammer2_chain_lookup: unrecognized "
3957 			"blockref(A) type: %d",
3958 		        chain->bref.type);
3959 		while (1)
3960 			tsleep(&base, 0, "dead", 0);
3961 		panic("hammer2_chain_lookup: unrecognized "
3962 		      "blockref(A) type: %d",
3963 		      chain->bref.type);
3964 		base = NULL;	/* safety */
3965 		count = 0;	/* safety */
3966 	}
3967 	kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3968 }
3969 
3970 #endif
3971 
3972 /*
3973  * Chain memory management
3974  */
3975 void
3976 hammer2_chain_wait(hammer2_chain_t *chain)
3977 {
3978 	tsleep(chain, 0, "chnflw", 1);
3979 }
3980 
3981 const hammer2_media_data_t *
3982 hammer2_chain_rdata(hammer2_chain_t *chain)
3983 {
3984 	KKASSERT(chain->data != NULL);
3985 	return (chain->data);
3986 }
3987 
3988 hammer2_media_data_t *
3989 hammer2_chain_wdata(hammer2_chain_t *chain)
3990 {
3991 	KKASSERT(chain->data != NULL);
3992 	return (chain->data);
3993 }
3994 
3995 /*
3996  * Set the check data for a chain.  This can be a heavy-weight operation
3997  * and typically only runs on-flush.  For file data check data is calculated
3998  * when the logical buffers are flushed.
3999  */
4000 void
4001 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4002 {
4003 	chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4004 
4005 	switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4006 	case HAMMER2_CHECK_NONE:
4007 		break;
4008 	case HAMMER2_CHECK_DISABLED:
4009 		break;
4010 	case HAMMER2_CHECK_ISCSI32:
4011 		chain->bref.check.iscsi32.value =
4012 			hammer2_icrc32(bdata, chain->bytes);
4013 		break;
4014 	case HAMMER2_CHECK_CRC64:
4015 		chain->bref.check.crc64.value = 0;
4016 		/* XXX */
4017 		break;
4018 	case HAMMER2_CHECK_SHA192:
4019 		{
4020 			SHA256_CTX hash_ctx;
4021 			union {
4022 				uint8_t digest[SHA256_DIGEST_LENGTH];
4023 				uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4024 			} u;
4025 
4026 			SHA256_Init(&hash_ctx);
4027 			SHA256_Update(&hash_ctx, bdata, chain->bytes);
4028 			SHA256_Final(u.digest, &hash_ctx);
4029 			u.digest64[2] ^= u.digest64[3];
4030 			bcopy(u.digest,
4031 			      chain->bref.check.sha192.data,
4032 			      sizeof(chain->bref.check.sha192.data));
4033 		}
4034 		break;
4035 	case HAMMER2_CHECK_FREEMAP:
4036 		chain->bref.check.freemap.icrc32 =
4037 			hammer2_icrc32(bdata, chain->bytes);
4038 		break;
4039 	default:
4040 		kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4041 			chain->bref.methods);
4042 		break;
4043 	}
4044 }
4045 
4046 int
4047 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4048 {
4049 	int r;
4050 
4051 	if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4052 		return 1;
4053 
4054 	switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4055 	case HAMMER2_CHECK_NONE:
4056 		r = 1;
4057 		break;
4058 	case HAMMER2_CHECK_DISABLED:
4059 		r = 1;
4060 		break;
4061 	case HAMMER2_CHECK_ISCSI32:
4062 		r = (chain->bref.check.iscsi32.value ==
4063 		     hammer2_icrc32(bdata, chain->bytes));
4064 		break;
4065 	case HAMMER2_CHECK_CRC64:
4066 		r = (chain->bref.check.crc64.value == 0);
4067 		/* XXX */
4068 		break;
4069 	case HAMMER2_CHECK_SHA192:
4070 		{
4071 			SHA256_CTX hash_ctx;
4072 			union {
4073 				uint8_t digest[SHA256_DIGEST_LENGTH];
4074 				uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4075 			} u;
4076 
4077 			SHA256_Init(&hash_ctx);
4078 			SHA256_Update(&hash_ctx, bdata, chain->bytes);
4079 			SHA256_Final(u.digest, &hash_ctx);
4080 			u.digest64[2] ^= u.digest64[3];
4081 			if (bcmp(u.digest,
4082 				 chain->bref.check.sha192.data,
4083 			         sizeof(chain->bref.check.sha192.data)) == 0) {
4084 				r = 1;
4085 			} else {
4086 				r = 0;
4087 			}
4088 		}
4089 		break;
4090 	case HAMMER2_CHECK_FREEMAP:
4091 		r = (chain->bref.check.freemap.icrc32 ==
4092 		     hammer2_icrc32(bdata, chain->bytes));
4093 		if (r == 0) {
4094 			kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4095 				chain->bref.check.freemap.icrc32,
4096 				hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4097 			if (chain->dio)
4098 				kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4099 					chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4100 		}
4101 
4102 		break;
4103 	default:
4104 		kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4105 			chain->bref.methods);
4106 		r = 1;
4107 		break;
4108 	}
4109 	return r;
4110 }
4111 
4112 /*
4113  * The caller presents a shared-locked (parent, chain) where the chain
4114  * is of type HAMMER2_OBJTYPE_HARDLINK.  The caller must hold the ip
4115  * structure representing the inode locked to prevent
4116  * consolidation/deconsolidation races.
4117  *
4118  * We locate the hardlink in the current or a common parent directory.
4119  *
4120  * If we are unable to locate the hardlink, EIO is returned and
4121  * (*chainp) is unlocked and dropped.
4122  */
4123 int
4124 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4125 			hammer2_chain_t **parentp,
4126 			hammer2_chain_t **chainp,
4127 			int flags)
4128 {
4129 	hammer2_chain_t *parent;
4130 	hammer2_chain_t *rchain;
4131 	hammer2_key_t key_dummy;
4132 	hammer2_key_t lhc;
4133 	int cache_index = -1;
4134 
4135 	/*
4136 	 * Obtain the key for the hardlink from *chainp.
4137 	 */
4138 	rchain = *chainp;
4139 	lhc = rchain->data->ipdata.meta.inum;
4140 	hammer2_chain_unlock(rchain);
4141 	hammer2_chain_drop(rchain);
4142 	rchain = NULL;
4143 
4144 	for (;;) {
4145 		int nloops;
4146 		rchain = hammer2_chain_lookup(parentp, &key_dummy,
4147 					      lhc, lhc,
4148 					      &cache_index, flags);
4149 		if (rchain)
4150 			break;
4151 
4152 		/*
4153 		 * Iterate parents, handle parent rename races by retrying
4154 		 * the operation.
4155 		 */
4156 		nloops = -1;
4157 		while (nloops) {
4158 			--nloops;
4159 			parent = *parentp;
4160 			if (nloops < 0 &&
4161 			    parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4162 				nloops = 1;
4163 			}
4164 			if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4165 				goto done;
4166 			if (parent->parent == NULL)
4167 				goto done;
4168 			parent = parent->parent;
4169 			hammer2_chain_ref(parent);
4170 			hammer2_chain_unlock(*parentp);
4171 			hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4172 						   flags);
4173 			if ((*parentp)->parent == parent) {
4174 				hammer2_chain_drop(*parentp);
4175 				*parentp = parent;
4176 			} else {
4177 				hammer2_chain_unlock(parent);
4178 				hammer2_chain_drop(parent);
4179 				hammer2_chain_lock(*parentp,
4180 						   HAMMER2_RESOLVE_ALWAYS |
4181 						   flags);
4182 				parent = NULL;	/* safety */
4183 				/* retry */
4184 			}
4185 		}
4186 	}
4187 done:
4188 
4189 	*chainp = rchain;
4190 	return (rchain ? EINVAL : 0);
4191 }
4192 
4193 /*
4194  * Used by the bulkscan code to snapshot the synchronized storage for
4195  * a volume, allowing it to be scanned concurrently against normal
4196  * operation.
4197  */
4198 hammer2_chain_t *
4199 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4200 {
4201 	hammer2_chain_t *copy;
4202 
4203 	copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4204 	switch(chain->bref.type) {
4205 	case HAMMER2_BREF_TYPE_VOLUME:
4206 		copy->data = kmalloc(sizeof(copy->data->voldata),
4207 				     chain->hmp->mchain,
4208 				     M_WAITOK | M_ZERO);
4209 		hammer2_spin_ex(&chain->core.spin);
4210 		copy->data->voldata = chain->data->voldata;
4211 		hammer2_spin_unex(&chain->core.spin);
4212 		break;
4213 	case HAMMER2_BREF_TYPE_FREEMAP:
4214 		copy->data = kmalloc(sizeof(hammer2_blockset_t),
4215 				     chain->hmp->mchain,
4216 				     M_WAITOK | M_ZERO);
4217 		hammer2_spin_ex(&chain->core.spin);
4218 		copy->data->blkset = chain->data->blkset;
4219 		hammer2_spin_unex(&chain->core.spin);
4220 		break;
4221 	default:
4222 		break;
4223 	}
4224 	return copy;
4225 }
4226 
4227 void
4228 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4229 {
4230 	switch(copy->bref.type) {
4231 	case HAMMER2_BREF_TYPE_VOLUME:
4232 	case HAMMER2_BREF_TYPE_FREEMAP:
4233 		KKASSERT(copy->data);
4234 		kfree(copy->data, copy->hmp->mchain);
4235 		copy->data = NULL;
4236 	default:
4237 		break;
4238 	}
4239 	hammer2_chain_drop(copy);
4240 }
4241 
4242 /*
4243  * Create a snapshot of the specified {parent, ochain} with the specified
4244  * label.  The originating hammer2_inode must be exclusively locked for
4245  * safety.
4246  *
4247  * The ioctl code has already synced the filesystem.
4248  */
4249 int
4250 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4251 		       hammer2_tid_t mtid)
4252 {
4253 	hammer2_dev_t *hmp;
4254 	const hammer2_inode_data_t *ripdata;
4255 	hammer2_inode_data_t *wipdata;
4256 	hammer2_chain_t *nchain;
4257 	hammer2_inode_t *nip;
4258 	size_t name_len;
4259 	hammer2_key_t lhc;
4260 	struct vattr vat;
4261 #if 0
4262 	uuid_t opfs_clid;
4263 #endif
4264 	int error;
4265 
4266 	kprintf("snapshot %s\n", pmp->name);
4267 
4268 	name_len = strlen(pmp->name);
4269 	lhc = hammer2_dirhash(pmp->name, name_len);
4270 
4271 	/*
4272 	 * Get the clid
4273 	 */
4274 	ripdata = &chain->data->ipdata;
4275 #if 0
4276 	opfs_clid = ripdata->meta.pfs_clid;
4277 #endif
4278 	hmp = chain->hmp;
4279 
4280 	/*
4281 	 * Create the snapshot directory under the super-root
4282 	 *
4283 	 * Set PFS type, generate a unique filesystem id, and generate
4284 	 * a cluster id.  Use the same clid when snapshotting a PFS root,
4285 	 * which theoretically allows the snapshot to be used as part of
4286 	 * the same cluster (perhaps as a cache).
4287 	 *
4288 	 * Copy the (flushed) blockref array.  Theoretically we could use
4289 	 * chain_duplicate() but it becomes difficult to disentangle
4290 	 * the shared core so for now just brute-force it.
4291 	 */
4292 	VATTR_NULL(&vat);
4293 	vat.va_type = VDIR;
4294 	vat.va_mode = 0755;
4295 	nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4296 				   pmp->name, name_len, 0,
4297 				   1, 0, 0,
4298 				   HAMMER2_INSERT_PFSROOT, &error);
4299 
4300 	if (nip) {
4301 		hammer2_inode_modify(nip);
4302 		nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4303 		hammer2_chain_modify(nchain, mtid, 0, 0);
4304 		wipdata = &nchain->data->ipdata;
4305 
4306 		nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4307 		nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4308 		nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4309 		kern_uuidgen(&nip->meta.pfs_fsid, 1);
4310 
4311 		/*
4312 		 * Give the snapshot its own private cluster id.  As a
4313 		 * snapshot no further synchronization with the original
4314 		 * cluster will be done.
4315 		 */
4316 #if 0
4317 		if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4318 			nip->meta.pfs_clid = opfs_clid;
4319 		else
4320 			kern_uuidgen(&nip->meta.pfs_clid, 1);
4321 #endif
4322 		kern_uuidgen(&nip->meta.pfs_clid, 1);
4323 		nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4324 
4325 		/* XXX hack blockset copy */
4326 		/* XXX doesn't work with real cluster */
4327 		wipdata->meta = nip->meta;
4328 		wipdata->u.blockset = ripdata->u.blockset;
4329 		hammer2_flush(nchain, 1);
4330 		hammer2_chain_unlock(nchain);
4331 		hammer2_chain_drop(nchain);
4332 		hammer2_inode_unlock(nip);
4333 	}
4334 	return (error);
4335 }
4336