xref: /dragonfly/sys/vfs/hammer2/hammer2_vfsops.c (revision 38b720cd)
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@backplane.com>
6  * by Daniel Flores (GSOC 2013 - mentored by Matthew Dillon, compression)
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 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/nlookup.h>
39 #include <sys/vnode.h>
40 #include <sys/mount.h>
41 #include <sys/fcntl.h>
42 #include <sys/buf.h>
43 #include <sys/uuid.h>
44 #include <sys/vfsops.h>
45 #include <sys/sysctl.h>
46 #include <sys/socket.h>
47 #include <sys/objcache.h>
48 
49 #include <sys/proc.h>
50 #include <sys/namei.h>
51 #include <sys/mountctl.h>
52 #include <sys/dirent.h>
53 #include <sys/uio.h>
54 
55 #include <sys/mutex.h>
56 #include <sys/mutex2.h>
57 
58 #include "hammer2.h"
59 #include "hammer2_disk.h"
60 #include "hammer2_mount.h"
61 #include "hammer2_lz4.h"
62 
63 #include "zlib/hammer2_zlib.h"
64 
65 #define REPORT_REFS_ERRORS 1	/* XXX remove me */
66 
67 MALLOC_DEFINE(M_OBJCACHE, "objcache", "Object Cache");
68 
69 struct hammer2_sync_info {
70 	int error;
71 	int waitfor;
72 };
73 
74 TAILQ_HEAD(hammer2_mntlist, hammer2_dev);
75 TAILQ_HEAD(hammer2_pfslist, hammer2_pfs);
76 static struct hammer2_mntlist hammer2_mntlist;
77 static struct hammer2_pfslist hammer2_pfslist;
78 static struct lock hammer2_mntlk;
79 
80 int hammer2_debug;
81 int hammer2_cluster_read = 4;		/* physical read-ahead */
82 int hammer2_cluster_write = 0;		/* bdwrite() so later inval works */
83 int hammer2_dedup_enable = 1;
84 int hammer2_inval_enable = 0;
85 int hammer2_flush_pipe = 100;
86 int hammer2_synchronous_flush = 1;
87 int hammer2_dio_count;
88 long hammer2_chain_allocs;
89 long hammer2_chain_frees;
90 long hammer2_limit_dirty_chains;
91 long hammer2_count_modified_chains;
92 long hammer2_iod_invals;
93 long hammer2_iod_file_read;
94 long hammer2_iod_meta_read;
95 long hammer2_iod_indr_read;
96 long hammer2_iod_fmap_read;
97 long hammer2_iod_volu_read;
98 long hammer2_iod_file_write;
99 long hammer2_iod_file_wembed;
100 long hammer2_iod_file_wzero;
101 long hammer2_iod_file_wdedup;
102 long hammer2_iod_meta_write;
103 long hammer2_iod_indr_write;
104 long hammer2_iod_fmap_write;
105 long hammer2_iod_volu_write;
106 
107 MALLOC_DECLARE(M_HAMMER2_CBUFFER);
108 MALLOC_DEFINE(M_HAMMER2_CBUFFER, "HAMMER2-compbuffer",
109 		"Buffer used for compression.");
110 
111 MALLOC_DECLARE(M_HAMMER2_DEBUFFER);
112 MALLOC_DEFINE(M_HAMMER2_DEBUFFER, "HAMMER2-decompbuffer",
113 		"Buffer used for decompression.");
114 
115 SYSCTL_NODE(_vfs, OID_AUTO, hammer2, CTLFLAG_RW, 0, "HAMMER2 filesystem");
116 
117 SYSCTL_INT(_vfs_hammer2, OID_AUTO, debug, CTLFLAG_RW,
118 	   &hammer2_debug, 0, "");
119 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_read, CTLFLAG_RW,
120 	   &hammer2_cluster_read, 0, "");
121 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_write, CTLFLAG_RW,
122 	   &hammer2_cluster_write, 0, "");
123 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dedup_enable, CTLFLAG_RW,
124 	   &hammer2_dedup_enable, 0, "");
125 SYSCTL_INT(_vfs_hammer2, OID_AUTO, inval_enable, CTLFLAG_RW,
126 	   &hammer2_inval_enable, 0, "");
127 SYSCTL_INT(_vfs_hammer2, OID_AUTO, flush_pipe, CTLFLAG_RW,
128 	   &hammer2_flush_pipe, 0, "");
129 SYSCTL_INT(_vfs_hammer2, OID_AUTO, synchronous_flush, CTLFLAG_RW,
130 	   &hammer2_synchronous_flush, 0, "");
131 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, chain_allocs, CTLFLAG_RW,
132 	   &hammer2_chain_allocs, 0, "");
133 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, chain_frees, CTLFLAG_RW,
134 	   &hammer2_chain_frees, 0, "");
135 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, limit_dirty_chains, CTLFLAG_RW,
136 	   &hammer2_limit_dirty_chains, 0, "");
137 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, count_modified_chains, CTLFLAG_RW,
138 	   &hammer2_count_modified_chains, 0, "");
139 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dio_count, CTLFLAG_RD,
140 	   &hammer2_dio_count, 0, "");
141 
142 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_invals, CTLFLAG_RW,
143 	   &hammer2_iod_invals, 0, "");
144 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_read, CTLFLAG_RW,
145 	   &hammer2_iod_file_read, 0, "");
146 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_read, CTLFLAG_RW,
147 	   &hammer2_iod_meta_read, 0, "");
148 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_read, CTLFLAG_RW,
149 	   &hammer2_iod_indr_read, 0, "");
150 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_read, CTLFLAG_RW,
151 	   &hammer2_iod_fmap_read, 0, "");
152 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_read, CTLFLAG_RW,
153 	   &hammer2_iod_volu_read, 0, "");
154 
155 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_write, CTLFLAG_RW,
156 	   &hammer2_iod_file_write, 0, "");
157 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_wembed, CTLFLAG_RW,
158 	   &hammer2_iod_file_wembed, 0, "");
159 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_wzero, CTLFLAG_RW,
160 	   &hammer2_iod_file_wzero, 0, "");
161 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_wdedup, CTLFLAG_RW,
162 	   &hammer2_iod_file_wdedup, 0, "");
163 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_write, CTLFLAG_RW,
164 	   &hammer2_iod_meta_write, 0, "");
165 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_write, CTLFLAG_RW,
166 	   &hammer2_iod_indr_write, 0, "");
167 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_write, CTLFLAG_RW,
168 	   &hammer2_iod_fmap_write, 0, "");
169 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_write, CTLFLAG_RW,
170 	   &hammer2_iod_volu_write, 0, "");
171 
172 long hammer2_check_icrc32;
173 long hammer2_check_xxhash64;
174 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, check_icrc32, CTLFLAG_RW,
175 	   &hammer2_check_icrc32, 0, "");
176 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, check_xxhash64, CTLFLAG_RW,
177 	   &hammer2_check_xxhash64, 0, "");
178 
179 static int hammer2_vfs_init(struct vfsconf *conf);
180 static int hammer2_vfs_uninit(struct vfsconf *vfsp);
181 static int hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
182 				struct ucred *cred);
183 static int hammer2_remount(hammer2_dev_t *, struct mount *, char *,
184 				struct vnode *, struct ucred *);
185 static int hammer2_recovery(hammer2_dev_t *hmp);
186 static int hammer2_vfs_unmount(struct mount *mp, int mntflags);
187 static int hammer2_vfs_root(struct mount *mp, struct vnode **vpp);
188 static int hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp,
189 				struct ucred *cred);
190 static int hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp,
191 				struct ucred *cred);
192 static int hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
193 				struct fid *fhp, struct vnode **vpp);
194 static int hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp);
195 static int hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
196 				int *exflagsp, struct ucred **credanonp);
197 
198 static int hammer2_install_volume_header(hammer2_dev_t *hmp);
199 static int hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data);
200 
201 static void hammer2_update_pmps(hammer2_dev_t *hmp);
202 
203 static void hammer2_mount_helper(struct mount *mp, hammer2_pfs_t *pmp);
204 static void hammer2_unmount_helper(struct mount *mp, hammer2_pfs_t *pmp,
205 				hammer2_dev_t *hmp);
206 
207 /*
208  * HAMMER2 vfs operations.
209  */
210 static struct vfsops hammer2_vfsops = {
211 	.vfs_init	= hammer2_vfs_init,
212 	.vfs_uninit	= hammer2_vfs_uninit,
213 	.vfs_sync	= hammer2_vfs_sync,
214 	.vfs_mount	= hammer2_vfs_mount,
215 	.vfs_unmount	= hammer2_vfs_unmount,
216 	.vfs_root 	= hammer2_vfs_root,
217 	.vfs_statfs	= hammer2_vfs_statfs,
218 	.vfs_statvfs	= hammer2_vfs_statvfs,
219 	.vfs_vget	= hammer2_vfs_vget,
220 	.vfs_vptofh	= hammer2_vfs_vptofh,
221 	.vfs_fhtovp	= hammer2_vfs_fhtovp,
222 	.vfs_checkexp	= hammer2_vfs_checkexp
223 };
224 
225 MALLOC_DEFINE(M_HAMMER2, "HAMMER2-mount", "");
226 
227 VFS_SET(hammer2_vfsops, hammer2, 0);
228 MODULE_VERSION(hammer2, 1);
229 
230 static
231 int
232 hammer2_vfs_init(struct vfsconf *conf)
233 {
234 	static struct objcache_malloc_args margs_read;
235 	static struct objcache_malloc_args margs_write;
236 	static struct objcache_malloc_args margs_vop;
237 
238 	int error;
239 
240 	error = 0;
241 
242 	if (HAMMER2_BLOCKREF_BYTES != sizeof(struct hammer2_blockref))
243 		error = EINVAL;
244 	if (HAMMER2_INODE_BYTES != sizeof(struct hammer2_inode_data))
245 		error = EINVAL;
246 	if (HAMMER2_VOLUME_BYTES != sizeof(struct hammer2_volume_data))
247 		error = EINVAL;
248 
249 	if (error)
250 		kprintf("HAMMER2 structure size mismatch; cannot continue.\n");
251 
252 	margs_read.objsize = 65536;
253 	margs_read.mtype = M_HAMMER2_DEBUFFER;
254 
255 	margs_write.objsize = 32768;
256 	margs_write.mtype = M_HAMMER2_CBUFFER;
257 
258 	margs_vop.objsize = sizeof(hammer2_xop_t);
259 	margs_vop.mtype = M_HAMMER2;
260 
261 	/*
262 	 * Note thaht for the XOPS cache we want backing store allocations
263 	 * to use M_ZERO.  This is not allowed in objcache_get() (to avoid
264 	 * confusion), so use the backing store function that does it.  This
265 	 * means that initial XOPS objects are zerod but REUSED objects are
266 	 * not.  So we are responsible for cleaning the object up sufficiently
267 	 * for our needs before objcache_put()ing it back (typically just the
268 	 * FIFO indices).
269 	 */
270 	cache_buffer_read = objcache_create(margs_read.mtype->ks_shortdesc,
271 				0, 1, NULL, NULL, NULL,
272 				objcache_malloc_alloc,
273 				objcache_malloc_free,
274 				&margs_read);
275 	cache_buffer_write = objcache_create(margs_write.mtype->ks_shortdesc,
276 				0, 1, NULL, NULL, NULL,
277 				objcache_malloc_alloc,
278 				objcache_malloc_free,
279 				&margs_write);
280 	cache_xops = objcache_create(margs_vop.mtype->ks_shortdesc,
281 				0, 1, NULL, NULL, NULL,
282 				objcache_malloc_alloc_zero,
283 				objcache_malloc_free,
284 				&margs_vop);
285 
286 
287 	lockinit(&hammer2_mntlk, "mntlk", 0, 0);
288 	TAILQ_INIT(&hammer2_mntlist);
289 	TAILQ_INIT(&hammer2_pfslist);
290 
291 	hammer2_limit_dirty_chains = maxvnodes / 10;
292 	if (hammer2_limit_dirty_chains > HAMMER2_LIMIT_DIRTY_CHAINS)
293 		hammer2_limit_dirty_chains = HAMMER2_LIMIT_DIRTY_CHAINS;
294 
295 	return (error);
296 }
297 
298 static
299 int
300 hammer2_vfs_uninit(struct vfsconf *vfsp __unused)
301 {
302 	objcache_destroy(cache_buffer_read);
303 	objcache_destroy(cache_buffer_write);
304 	objcache_destroy(cache_xops);
305 	return 0;
306 }
307 
308 /*
309  * Core PFS allocator.  Used to allocate the pmp structure for PFS cluster
310  * mounts and the spmp structure for media (hmp) structures.
311  *
312  * pmp->modify_tid tracks new modify_tid transaction ids for front-end
313  * transactions.  Note that synchronization does not use this field.
314  * (typically frontend operations and synchronization cannot run on the
315  * same PFS node at the same time).
316  *
317  * XXX check locking
318  */
319 hammer2_pfs_t *
320 hammer2_pfsalloc(hammer2_chain_t *chain, const hammer2_inode_data_t *ripdata,
321 		 hammer2_tid_t modify_tid, hammer2_dev_t *force_local)
322 {
323 	hammer2_inode_t *iroot;
324 	hammer2_pfs_t *pmp;
325 	int count;
326 	int i;
327 	int j;
328 
329 	/*
330 	 * Locate or create the PFS based on the cluster id.  If ripdata
331 	 * is NULL this is a spmp which is unique and is always allocated.
332 	 *
333 	 * If the device is mounted in local mode all PFSs are considered
334 	 * independent and not part of any cluster (for debugging only).
335 	 */
336 	if (ripdata) {
337 		TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
338 			if (force_local != pmp->force_local)
339 				continue;
340 			if (force_local == NULL &&
341 			    bcmp(&pmp->pfs_clid, &ripdata->meta.pfs_clid,
342 				 sizeof(pmp->pfs_clid)) == 0) {
343 					break;
344 			} else if (force_local && pmp->pfs_names[0] &&
345 			    strcmp(pmp->pfs_names[0], ripdata->filename) == 0) {
346 					break;
347 			}
348 		}
349 	} else {
350 		pmp = NULL;
351 	}
352 
353 	if (pmp == NULL) {
354 		pmp = kmalloc(sizeof(*pmp), M_HAMMER2, M_WAITOK | M_ZERO);
355 		pmp->force_local = force_local;
356 		hammer2_trans_manage_init(pmp);
357 		kmalloc_create(&pmp->minode, "HAMMER2-inodes");
358 		kmalloc_create(&pmp->mmsg, "HAMMER2-pfsmsg");
359 		lockinit(&pmp->lock, "pfslk", 0, 0);
360 		lockinit(&pmp->lock_nlink, "h2nlink", 0, 0);
361 		spin_init(&pmp->inum_spin, "hm2pfsalloc_inum");
362 		spin_init(&pmp->xop_spin, "h2xop");
363 		spin_init(&pmp->lru_spin, "h2lru");
364 		RB_INIT(&pmp->inum_tree);
365 		TAILQ_INIT(&pmp->sideq);
366 		TAILQ_INIT(&pmp->lru_list);
367 		spin_init(&pmp->list_spin, "hm2pfsalloc_list");
368 
369 		/*
370 		 * Distribute backend operations to threads
371 		 */
372 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
373 			for (j = 0; j < HAMMER2_XOPGROUPS +
374 					HAMMER2_SPECTHREADS; ++j) {
375 				TAILQ_INIT(&pmp->xopq[i][j]);
376 			}
377 		}
378 		for (i = 0; i < HAMMER2_XOPGROUPS; ++i)
379 			hammer2_xop_group_init(pmp, &pmp->xop_groups[i]);
380 
381 		/*
382 		 * Save the last media transaction id for the flusher.  Set
383 		 * initial
384 		 */
385 		if (ripdata)
386 			pmp->pfs_clid = ripdata->meta.pfs_clid;
387 		TAILQ_INSERT_TAIL(&hammer2_pfslist, pmp, mntentry);
388 
389 		/*
390 		 * The synchronization thread may start too early, make
391 		 * sure it stays frozen until we are ready to let it go.
392 		 * XXX
393 		 */
394 		/*
395 		pmp->primary_thr.flags = HAMMER2_THREAD_FROZEN |
396 					 HAMMER2_THREAD_REMASTER;
397 		*/
398 	}
399 
400 	/*
401 	 * Create the PFS's root inode.
402 	 */
403 	if ((iroot = pmp->iroot) == NULL) {
404 		iroot = hammer2_inode_get(pmp, NULL, NULL, -1);
405 		pmp->iroot = iroot;
406 		hammer2_inode_ref(iroot);
407 		hammer2_inode_unlock(iroot);
408 	}
409 
410 	/*
411 	 * Stop here if no chain is passed in.
412 	 */
413 	if (chain == NULL)
414 		goto done;
415 
416 	/*
417 	 * When a chain is passed in we must add it to the PFS's root
418 	 * inode, update pmp->pfs_types[], and update the syncronization
419 	 * threads.
420 	 *
421 	 * When forcing local mode, mark the PFS as a MASTER regardless.
422 	 *
423 	 * At the moment empty spots can develop due to removals or failures.
424 	 * Ultimately we want to re-fill these spots but doing so might
425 	 * confused running code. XXX
426 	 */
427 	hammer2_inode_ref(iroot);
428 	hammer2_mtx_ex(&iroot->lock);
429 	j = iroot->cluster.nchains;
430 
431 	kprintf("add PFS to pmp %p[%d]\n", pmp, j);
432 
433 	if (j == HAMMER2_MAXCLUSTER) {
434 		kprintf("hammer2_mount: cluster full!\n");
435 		/* XXX fatal error? */
436 	} else {
437 		KKASSERT(chain->pmp == NULL);
438 		chain->pmp = pmp;
439 		hammer2_chain_ref(chain);
440 		iroot->cluster.array[j].chain = chain;
441 		if (force_local)
442 			pmp->pfs_types[j] = HAMMER2_PFSTYPE_MASTER;
443 		else
444 			pmp->pfs_types[j] = ripdata->meta.pfs_type;
445 		pmp->pfs_names[j] = kstrdup(ripdata->filename, M_HAMMER2);
446 		pmp->pfs_hmps[j] = chain->hmp;
447 
448 		/*
449 		 * If the PFS is already mounted we must account
450 		 * for the mount_count here.
451 		 */
452 		if (pmp->mp)
453 			++chain->hmp->mount_count;
454 
455 		/*
456 		 * May have to fixup dirty chain tracking.  Previous
457 		 * pmp was NULL so nothing to undo.
458 		 */
459 		if (chain->flags & HAMMER2_CHAIN_MODIFIED)
460 			hammer2_pfs_memory_inc(pmp);
461 		++j;
462 	}
463 	iroot->cluster.nchains = j;
464 
465 	/*
466 	 * Update nmasters from any PFS inode which is part of the cluster.
467 	 * It is possible that this will result in a value which is too
468 	 * high.  MASTER PFSs are authoritative for pfs_nmasters and will
469 	 * override this value later on.
470 	 *
471 	 * (This informs us of masters that might not currently be
472 	 *  discoverable by this mount).
473 	 */
474 	if (ripdata && pmp->pfs_nmasters < ripdata->meta.pfs_nmasters) {
475 		pmp->pfs_nmasters = ripdata->meta.pfs_nmasters;
476 	}
477 
478 	/*
479 	 * Count visible masters.  Masters are usually added with
480 	 * ripdata->meta.pfs_nmasters set to 1.  This detects when there
481 	 * are more (XXX and must update the master inodes).
482 	 */
483 	count = 0;
484 	for (i = 0; i < iroot->cluster.nchains; ++i) {
485 		if (pmp->pfs_types[i] == HAMMER2_PFSTYPE_MASTER)
486 			++count;
487 	}
488 	if (pmp->pfs_nmasters < count)
489 		pmp->pfs_nmasters = count;
490 
491 	/*
492 	 * Create missing synchronization and support threads.
493 	 *
494 	 * Single-node masters (including snapshots) have nothing to
495 	 * synchronize and do not require this thread.
496 	 *
497 	 * Multi-node masters or any number of soft masters, slaves, copy,
498 	 * or other PFS types need the thread.
499 	 *
500 	 * Each thread is responsible for its particular cluster index.
501 	 * We use independent threads so stalls or mismatches related to
502 	 * any given target do not affect other targets.
503 	 */
504 	for (i = 0; i < iroot->cluster.nchains; ++i) {
505 		/*
506 		 * Single-node masters (including snapshots) have nothing
507 		 * to synchronize and will make direct xops support calls,
508 		 * thus they do not require this thread.
509 		 *
510 		 * Note that there can be thousands of snapshots.  We do not
511 		 * want to create thousands of threads.
512 		 */
513 		if (pmp->pfs_nmasters <= 1 &&
514 		    pmp->pfs_types[i] == HAMMER2_PFSTYPE_MASTER) {
515 			continue;
516 		}
517 
518 		/*
519 		 * Sync support thread
520 		 */
521 		if (pmp->sync_thrs[i].td == NULL) {
522 			hammer2_thr_create(&pmp->sync_thrs[i], pmp,
523 					   "h2nod", i, -1,
524 					   hammer2_primary_sync_thread);
525 		}
526 	}
527 
528 	/*
529 	 * Create missing Xop threads
530 	 */
531 	if (pmp->mp)
532 		hammer2_xop_helper_create(pmp);
533 
534 	hammer2_mtx_unlock(&iroot->lock);
535 	hammer2_inode_drop(iroot);
536 done:
537 	return pmp;
538 }
539 
540 /*
541  * Destroy a PFS, typically only occurs after the last mount on a device
542  * has gone away.
543  */
544 static void
545 hammer2_pfsfree(hammer2_pfs_t *pmp)
546 {
547 	hammer2_inode_t *iroot;
548 	hammer2_chain_t *chain;
549 	int i;
550 	int j;
551 
552 	/*
553 	 * Cleanup our reference on iroot.  iroot is (should) not be needed
554 	 * by the flush code.
555 	 */
556 	TAILQ_REMOVE(&hammer2_pfslist, pmp, mntentry);
557 
558 	iroot = pmp->iroot;
559 	if (iroot) {
560 		for (i = 0; i < iroot->cluster.nchains; ++i) {
561 			hammer2_thr_delete(&pmp->sync_thrs[i]);
562 			for (j = 0; j < HAMMER2_XOPGROUPS; ++j)
563 				hammer2_thr_delete(&pmp->xop_groups[j].thrs[i]);
564 		}
565 #if REPORT_REFS_ERRORS
566 		if (pmp->iroot->refs != 1)
567 			kprintf("PMP->IROOT %p REFS WRONG %d\n",
568 				pmp->iroot, pmp->iroot->refs);
569 #else
570 		KKASSERT(pmp->iroot->refs == 1);
571 #endif
572 		/* ref for pmp->iroot */
573 		hammer2_inode_drop(pmp->iroot);
574 		pmp->iroot = NULL;
575 	}
576 
577 	/*
578 	 * Cleanup chains remaining on LRU list.
579 	 */
580 	kprintf("pfsfree: %p lrucount=%d\n", pmp, pmp->lru_count);
581 	while ((chain = TAILQ_FIRST(&pmp->lru_list)) != NULL) {
582 		hammer2_chain_ref(chain);
583 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
584 		hammer2_chain_drop(chain);
585 	}
586 
587 	/*
588 	 * Free remaining pmp resources
589 	 */
590 	kmalloc_destroy(&pmp->mmsg);
591 	kmalloc_destroy(&pmp->minode);
592 
593 	kfree(pmp, M_HAMMER2);
594 }
595 
596 /*
597  * Remove all references to hmp from the pfs list.  Any PFS which becomes
598  * empty is terminated and freed.
599  *
600  * XXX inefficient.
601  */
602 static void
603 hammer2_pfsfree_scan(hammer2_dev_t *hmp)
604 {
605 	hammer2_pfs_t *pmp;
606 	hammer2_inode_t *iroot;
607 	hammer2_chain_t *rchain;
608 	int didfreeze;
609 	int i;
610 	int j;
611 
612 again:
613 	TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
614 		if ((iroot = pmp->iroot) == NULL)
615 			continue;
616 		if (hmp->spmp == pmp) {
617 			kprintf("unmount hmp %p remove spmp %p\n",
618 				hmp, pmp);
619 			hmp->spmp = NULL;
620 		}
621 
622 		/*
623 		 * Determine if this PFS is affected.  If it is we must
624 		 * freeze all management threads and lock its iroot.
625 		 *
626 		 * Freezing a management thread forces it idle, operations
627 		 * in-progress will be aborted and it will have to start
628 		 * over again when unfrozen, or exit if told to exit.
629 		 */
630 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
631 			if (pmp->pfs_hmps[i] == hmp)
632 				break;
633 		}
634 		if (i != HAMMER2_MAXCLUSTER) {
635 			/*
636 			 * Make sure all synchronization threads are locked
637 			 * down.
638 			 */
639 			for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
640 				if (pmp->pfs_hmps[i] == NULL)
641 					continue;
642 				hammer2_thr_freeze_async(&pmp->sync_thrs[i]);
643 				for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
644 					hammer2_thr_freeze_async(
645 						&pmp->xop_groups[j].thrs[i]);
646 				}
647 			}
648 			for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
649 				if (pmp->pfs_hmps[i] == NULL)
650 					continue;
651 				hammer2_thr_freeze(&pmp->sync_thrs[i]);
652 				for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
653 					hammer2_thr_freeze(
654 						&pmp->xop_groups[j].thrs[i]);
655 				}
656 			}
657 
658 			/*
659 			 * Lock the inode and clean out matching chains.
660 			 * Note that we cannot use hammer2_inode_lock_*()
661 			 * here because that would attempt to validate the
662 			 * cluster that we are in the middle of ripping
663 			 * apart.
664 			 *
665 			 * WARNING! We are working directly on the inodes
666 			 *	    embedded cluster.
667 			 */
668 			hammer2_mtx_ex(&iroot->lock);
669 
670 			/*
671 			 * Remove the chain from matching elements of the PFS.
672 			 */
673 			for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
674 				if (pmp->pfs_hmps[i] != hmp)
675 					continue;
676 				hammer2_thr_delete(&pmp->sync_thrs[i]);
677 				for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
678 					hammer2_thr_delete(
679 						&pmp->xop_groups[j].thrs[i]);
680 				}
681 				rchain = iroot->cluster.array[i].chain;
682 				iroot->cluster.array[i].chain = NULL;
683 				pmp->pfs_types[i] = 0;
684 				if (pmp->pfs_names[i]) {
685 					kfree(pmp->pfs_names[i], M_HAMMER2);
686 					pmp->pfs_names[i] = NULL;
687 				}
688 				if (rchain) {
689 					hammer2_chain_drop(rchain);
690 					/* focus hint */
691 					if (iroot->cluster.focus == rchain)
692 						iroot->cluster.focus = NULL;
693 				}
694 				pmp->pfs_hmps[i] = NULL;
695 			}
696 			hammer2_mtx_unlock(&iroot->lock);
697 			didfreeze = 1;	/* remaster, unfreeze down below */
698 		} else {
699 			didfreeze = 0;
700 		}
701 
702 		/*
703 		 * Cleanup trailing chains.  Gaps may remain.
704 		 */
705 		for (i = HAMMER2_MAXCLUSTER - 1; i >= 0; --i) {
706 			if (pmp->pfs_hmps[i])
707 				break;
708 		}
709 		iroot->cluster.nchains = i + 1;
710 
711 		/*
712 		 * If the PMP has no elements remaining we can destroy it.
713 		 * (this will transition management threads from frozen->exit).
714 		 */
715 		if (iroot->cluster.nchains == 0) {
716 			kprintf("unmount hmp %p last ref to PMP=%p\n",
717 				hmp, pmp);
718 			hammer2_pfsfree(pmp);
719 			goto again;
720 		}
721 
722 		/*
723 		 * If elements still remain we need to set the REMASTER
724 		 * flag and unfreeze it.
725 		 */
726 		if (didfreeze) {
727 			for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
728 				if (pmp->pfs_hmps[i] == NULL)
729 					continue;
730 				hammer2_thr_remaster(&pmp->sync_thrs[i]);
731 				hammer2_thr_unfreeze(&pmp->sync_thrs[i]);
732 				for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
733 					hammer2_thr_remaster(
734 						&pmp->xop_groups[j].thrs[i]);
735 					hammer2_thr_unfreeze(
736 						&pmp->xop_groups[j].thrs[i]);
737 				}
738 			}
739 		}
740 	}
741 }
742 
743 /*
744  * Mount or remount HAMMER2 fileystem from physical media
745  *
746  *	mountroot
747  *		mp		mount point structure
748  *		path		NULL
749  *		data		<unused>
750  *		cred		<unused>
751  *
752  *	mount
753  *		mp		mount point structure
754  *		path		path to mount point
755  *		data		pointer to argument structure in user space
756  *			volume	volume path (device@LABEL form)
757  *			hflags	user mount flags
758  *		cred		user credentials
759  *
760  * RETURNS:	0	Success
761  *		!0	error number
762  */
763 static
764 int
765 hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
766 		  struct ucred *cred)
767 {
768 	struct hammer2_mount_info info;
769 	hammer2_pfs_t *pmp;
770 	hammer2_pfs_t *spmp;
771 	hammer2_dev_t *hmp;
772 	hammer2_dev_t *force_local;
773 	hammer2_key_t key_next;
774 	hammer2_key_t key_dummy;
775 	hammer2_key_t lhc;
776 	struct vnode *devvp;
777 	struct nlookupdata nd;
778 	hammer2_chain_t *parent;
779 	hammer2_chain_t *chain;
780 	hammer2_cluster_t *cluster;
781 	const hammer2_inode_data_t *ripdata;
782 	hammer2_blockref_t bref;
783 	struct file *fp;
784 	char devstr[MNAMELEN];
785 	size_t size;
786 	size_t done;
787 	char *dev;
788 	char *label;
789 	int ronly = 1;
790 	int error;
791 	int cache_index;
792 	int i;
793 
794 	hmp = NULL;
795 	pmp = NULL;
796 	dev = NULL;
797 	label = NULL;
798 	devvp = NULL;
799 	cache_index = -1;
800 
801 	kprintf("hammer2_mount\n");
802 
803 	if (path == NULL) {
804 		/*
805 		 * Root mount
806 		 */
807 		bzero(&info, sizeof(info));
808 		info.cluster_fd = -1;
809 		ksnprintf(devstr, sizeof(devstr), "%s",
810 			  mp->mnt_stat.f_mntfromname);
811 		kprintf("hammer2_mount: root '%s'\n", devstr);
812 	} else {
813 		/*
814 		 * Non-root mount or updating a mount
815 		 */
816 		error = copyin(data, &info, sizeof(info));
817 		if (error)
818 			return (error);
819 
820 		error = copyinstr(info.volume, devstr, MNAMELEN - 1, &done);
821 		if (error)
822 			return (error);
823 	}
824 
825 	/* Extract device and label */
826 	dev = devstr;
827 	label = strchr(devstr, '@');
828 	if (label == NULL ||
829 	    ((label + 1) - dev) > done) {
830 		return (EINVAL);
831 	}
832 	*label = '\0';
833 	label++;
834 	if (*label == '\0')
835 		return (EINVAL);
836 
837 	if (mp->mnt_flag & MNT_UPDATE) {
838 		/*
839 		 * Update mount.  Note that pmp->iroot->cluster is
840 		 * an inode-embedded cluster and thus cannot be
841 		 * directly locked.
842 		 *
843 		 * XXX HAMMER2 needs to implement NFS export via
844 		 *     mountctl.
845 		 */
846 		pmp = MPTOPMP(mp);
847 		pmp->hflags = info.hflags;
848 		cluster = &pmp->iroot->cluster;
849 		for (i = 0; i < cluster->nchains; ++i) {
850 			if (cluster->array[i].chain == NULL)
851 				continue;
852 			hmp = cluster->array[i].chain->hmp;
853 			devvp = hmp->devvp;
854 			error = hammer2_remount(hmp, mp, path,
855 						devvp, cred);
856 			if (error)
857 				break;
858 		}
859 
860 		return error;
861 	}
862 
863 	/*
864 	 * HMP device mount
865 	 *
866 	 * Lookup name and verify it refers to a block device.
867 	 */
868 	if (path) {
869 		error = nlookup_init(&nd, dev, UIO_SYSSPACE, NLC_FOLLOW);
870 		if (error == 0)
871 			error = nlookup(&nd);
872 		if (error == 0)
873 			error = cache_vref(&nd.nl_nch, nd.nl_cred, &devvp);
874 		nlookup_done(&nd);
875 	} else {
876 		/* root mount */
877 		cdev_t cdev = kgetdiskbyname(dev);
878 		error = bdevvp(cdev, &devvp);
879 		if (error)
880 			kprintf("hammer2: cannot find '%s'\n", dev);
881 	}
882 
883 	if (error == 0) {
884 		if (vn_isdisk(devvp, &error))
885 			error = vfs_mountedon(devvp);
886 	}
887 
888 	/*
889 	 * Determine if the device has already been mounted.  After this
890 	 * check hmp will be non-NULL if we are doing the second or more
891 	 * hammer2 mounts from the same device.
892 	 */
893 	lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
894 	TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
895 		if (hmp->devvp == devvp)
896 			break;
897 	}
898 
899 	/*
900 	 * Open the device if this isn't a secondary mount and construct
901 	 * the H2 device mount (hmp).
902 	 */
903 	if (hmp == NULL) {
904 		hammer2_chain_t *schain;
905 		hammer2_xid_t xid;
906 
907 		if (error == 0 && vcount(devvp) > 0)
908 			error = EBUSY;
909 
910 		/*
911 		 * Now open the device
912 		 */
913 		if (error == 0) {
914 			ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
915 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
916 			error = vinvalbuf(devvp, V_SAVE, 0, 0);
917 			if (error == 0) {
918 				error = VOP_OPEN(devvp,
919 						 ronly ? FREAD : FREAD | FWRITE,
920 						 FSCRED, NULL);
921 			}
922 			vn_unlock(devvp);
923 		}
924 		if (error && devvp) {
925 			vrele(devvp);
926 			devvp = NULL;
927 		}
928 		if (error) {
929 			lockmgr(&hammer2_mntlk, LK_RELEASE);
930 			return error;
931 		}
932 		hmp = kmalloc(sizeof(*hmp), M_HAMMER2, M_WAITOK | M_ZERO);
933 		ksnprintf(hmp->devrepname, sizeof(hmp->devrepname), "%s", dev);
934 		hmp->ronly = ronly;
935 		hmp->devvp = devvp;
936 		hmp->hflags = info.hflags & HMNT2_DEVFLAGS;
937 		kmalloc_create(&hmp->mchain, "HAMMER2-chains");
938 		TAILQ_INSERT_TAIL(&hammer2_mntlist, hmp, mntentry);
939 		RB_INIT(&hmp->iotree);
940 		spin_init(&hmp->io_spin, "hm2mount_io");
941 		spin_init(&hmp->list_spin, "hm2mount_list");
942 		TAILQ_INIT(&hmp->flushq);
943 
944 		lockinit(&hmp->vollk, "h2vol", 0, 0);
945 		lockinit(&hmp->bulklk, "h2bulk", 0, 0);
946 
947 		/*
948 		 * vchain setup. vchain.data is embedded.
949 		 * vchain.refs is initialized and will never drop to 0.
950 		 *
951 		 * NOTE! voldata is not yet loaded.
952 		 */
953 		hmp->vchain.hmp = hmp;
954 		hmp->vchain.refs = 1;
955 		hmp->vchain.data = (void *)&hmp->voldata;
956 		hmp->vchain.bref.type = HAMMER2_BREF_TYPE_VOLUME;
957 		hmp->vchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
958 		hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
959 
960 		hammer2_chain_core_init(&hmp->vchain);
961 		/* hmp->vchain.u.xxx is left NULL */
962 
963 		/*
964 		 * fchain setup.  fchain.data is embedded.
965 		 * fchain.refs is initialized and will never drop to 0.
966 		 *
967 		 * The data is not used but needs to be initialized to
968 		 * pass assertion muster.  We use this chain primarily
969 		 * as a placeholder for the freemap's top-level RBTREE
970 		 * so it does not interfere with the volume's topology
971 		 * RBTREE.
972 		 */
973 		hmp->fchain.hmp = hmp;
974 		hmp->fchain.refs = 1;
975 		hmp->fchain.data = (void *)&hmp->voldata.freemap_blockset;
976 		hmp->fchain.bref.type = HAMMER2_BREF_TYPE_FREEMAP;
977 		hmp->fchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
978 		hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
979 		hmp->fchain.bref.methods =
980 			HAMMER2_ENC_CHECK(HAMMER2_CHECK_FREEMAP) |
981 			HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
982 
983 		hammer2_chain_core_init(&hmp->fchain);
984 		/* hmp->fchain.u.xxx is left NULL */
985 
986 		/*
987 		 * Install the volume header and initialize fields from
988 		 * voldata.
989 		 */
990 		error = hammer2_install_volume_header(hmp);
991 		if (error) {
992 			hammer2_unmount_helper(mp, NULL, hmp);
993 			lockmgr(&hammer2_mntlk, LK_RELEASE);
994 			hammer2_vfs_unmount(mp, MNT_FORCE);
995 			return error;
996 		}
997 
998 		/*
999 		 * Really important to get these right or flush will get
1000 		 * confused.
1001 		 */
1002 		hmp->spmp = hammer2_pfsalloc(NULL, NULL, 0, NULL);
1003 		kprintf("alloc spmp %p tid %016jx\n",
1004 			hmp->spmp, hmp->voldata.mirror_tid);
1005 		spmp = hmp->spmp;
1006 
1007 		/*
1008 		 * Dummy-up vchain and fchain's modify_tid.  mirror_tid
1009 		 * is inherited from the volume header.
1010 		 */
1011 		xid = 0;
1012 		hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
1013 		hmp->vchain.bref.modify_tid = hmp->vchain.bref.mirror_tid;
1014 		hmp->vchain.pmp = spmp;
1015 		hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
1016 		hmp->fchain.bref.modify_tid = hmp->fchain.bref.mirror_tid;
1017 		hmp->fchain.pmp = spmp;
1018 
1019 		/*
1020 		 * First locate the super-root inode, which is key 0
1021 		 * relative to the volume header's blockset.
1022 		 *
1023 		 * Then locate the root inode by scanning the directory keyspace
1024 		 * represented by the label.
1025 		 */
1026 		parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
1027 		schain = hammer2_chain_lookup(&parent, &key_dummy,
1028 				      HAMMER2_SROOT_KEY, HAMMER2_SROOT_KEY,
1029 				      &cache_index, 0);
1030 		hammer2_chain_lookup_done(parent);
1031 		if (schain == NULL) {
1032 			kprintf("hammer2_mount: invalid super-root\n");
1033 			hammer2_unmount_helper(mp, NULL, hmp);
1034 			lockmgr(&hammer2_mntlk, LK_RELEASE);
1035 			hammer2_vfs_unmount(mp, MNT_FORCE);
1036 			return EINVAL;
1037 		}
1038 		if (schain->error) {
1039 			kprintf("hammer2_mount: error %s reading super-root\n",
1040 				hammer2_error_str(schain->error));
1041 			hammer2_chain_unlock(schain);
1042 			hammer2_chain_drop(schain);
1043 			schain = NULL;
1044 			hammer2_unmount_helper(mp, NULL, hmp);
1045 			lockmgr(&hammer2_mntlk, LK_RELEASE);
1046 			hammer2_vfs_unmount(mp, MNT_FORCE);
1047 			return EINVAL;
1048 		}
1049 
1050 		/*
1051 		 * The super-root always uses an inode_tid of 1 when
1052 		 * creating PFSs.
1053 		 */
1054 		spmp->inode_tid = 1;
1055 		spmp->modify_tid = schain->bref.modify_tid + 1;
1056 
1057 		/*
1058 		 * Sanity-check schain's pmp and finish initialization.
1059 		 * Any chain belonging to the super-root topology should
1060 		 * have a NULL pmp (not even set to spmp).
1061 		 */
1062 		ripdata = &hammer2_chain_rdata(schain)->ipdata;
1063 		KKASSERT(schain->pmp == NULL);
1064 		spmp->pfs_clid = ripdata->meta.pfs_clid;
1065 
1066 		/*
1067 		 * Replace the dummy spmp->iroot with a real one.  It's
1068 		 * easier to just do a wholesale replacement than to try
1069 		 * to update the chain and fixup the iroot fields.
1070 		 *
1071 		 * The returned inode is locked with the supplied cluster.
1072 		 */
1073 		cluster = hammer2_cluster_from_chain(schain);
1074 		hammer2_inode_drop(spmp->iroot);
1075 		spmp->iroot = NULL;
1076 		spmp->iroot = hammer2_inode_get(spmp, NULL, cluster, -1);
1077 		spmp->spmp_hmp = hmp;
1078 		spmp->pfs_types[0] = ripdata->meta.pfs_type;
1079 		spmp->pfs_hmps[0] = hmp;
1080 		hammer2_inode_ref(spmp->iroot);
1081 		hammer2_inode_unlock(spmp->iroot);
1082 		hammer2_cluster_unlock(cluster);
1083 		hammer2_cluster_drop(cluster);
1084 		schain = NULL;
1085 		/* leave spmp->iroot with one ref */
1086 
1087 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1088 			error = hammer2_recovery(hmp);
1089 			/* XXX do something with error */
1090 		}
1091 		hammer2_update_pmps(hmp);
1092 		hammer2_iocom_init(hmp);
1093 
1094 		/*
1095 		 * Ref the cluster management messaging descriptor.  The mount
1096 		 * program deals with the other end of the communications pipe.
1097 		 *
1098 		 * Root mounts typically do not supply one.
1099 		 */
1100 		if (info.cluster_fd >= 0) {
1101 			fp = holdfp(curproc->p_fd, info.cluster_fd, -1);
1102 			if (fp) {
1103 				hammer2_cluster_reconnect(hmp, fp);
1104 			} else {
1105 				kprintf("hammer2_mount: bad cluster_fd!\n");
1106 			}
1107 		}
1108 	} else {
1109 		spmp = hmp->spmp;
1110 		if (info.hflags & HMNT2_DEVFLAGS) {
1111 			kprintf("hammer2: Warning: mount flags pertaining "
1112 				"to the whole device may only be specified "
1113 				"on the first mount of the device: %08x\n",
1114 				info.hflags & HMNT2_DEVFLAGS);
1115 		}
1116 	}
1117 
1118 	/*
1119 	 * Force local mount (disassociate all PFSs from their clusters).
1120 	 * Used primarily for debugging.
1121 	 */
1122 	force_local = (hmp->hflags & HMNT2_LOCAL) ? hmp : NULL;
1123 
1124 	/*
1125 	 * Lookup the mount point under the media-localized super-root.
1126 	 * Scanning hammer2_pfslist doesn't help us because it represents
1127 	 * PFS cluster ids which can aggregate several named PFSs together.
1128 	 *
1129 	 * cluster->pmp will incorrectly point to spmp and must be fixed
1130 	 * up later on.
1131 	 */
1132 	hammer2_inode_lock(spmp->iroot, 0);
1133 	parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
1134 	lhc = hammer2_dirhash(label, strlen(label));
1135 	chain = hammer2_chain_lookup(&parent, &key_next,
1136 				     lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1137 				     &cache_index, 0);
1138 	while (chain) {
1139 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1140 		    strcmp(label, chain->data->ipdata.filename) == 0) {
1141 			break;
1142 		}
1143 		chain = hammer2_chain_next(&parent, chain, &key_next,
1144 					    key_next,
1145 					    lhc + HAMMER2_DIRHASH_LOMASK,
1146 					    &cache_index, 0);
1147 	}
1148 	if (parent) {
1149 		hammer2_chain_unlock(parent);
1150 		hammer2_chain_drop(parent);
1151 	}
1152 	hammer2_inode_unlock(spmp->iroot);
1153 
1154 	/*
1155 	 * PFS could not be found?
1156 	 */
1157 	if (chain == NULL) {
1158 		kprintf("hammer2_mount: PFS label not found\n");
1159 		hammer2_unmount_helper(mp, NULL, hmp);
1160 		lockmgr(&hammer2_mntlk, LK_RELEASE);
1161 		hammer2_vfs_unmount(mp, MNT_FORCE);
1162 
1163 		return EINVAL;
1164 	}
1165 
1166 	/*
1167 	 * Acquire the pmp structure (it should have already been allocated
1168 	 * via hammer2_update_pmps() so do not pass cluster in to add to
1169 	 * available chains).
1170 	 *
1171 	 * Check if the cluster has already been mounted.  A cluster can
1172 	 * only be mounted once, use null mounts to mount additional copies.
1173 	 */
1174 	ripdata = &chain->data->ipdata;
1175 	bref = chain->bref;
1176 	pmp = hammer2_pfsalloc(NULL, ripdata, bref.modify_tid, force_local);
1177 	hammer2_chain_unlock(chain);
1178 	hammer2_chain_drop(chain);
1179 
1180 	if (pmp->mp) {
1181 		kprintf("hammer2_mount: PFS already mounted!\n");
1182 		hammer2_unmount_helper(mp, NULL, hmp);
1183 		lockmgr(&hammer2_mntlk, LK_RELEASE);
1184 		hammer2_vfs_unmount(mp, MNT_FORCE);
1185 
1186 		return EBUSY;
1187 	}
1188 
1189 	/*
1190 	 * Finish the mount
1191 	 */
1192         kprintf("hammer2_mount hmp=%p pmp=%p\n", hmp, pmp);
1193 
1194 	pmp->hflags = info.hflags;
1195         mp->mnt_flag = MNT_LOCAL;
1196         mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;   /* all entry pts are SMP */
1197         mp->mnt_kern_flag |= MNTK_THR_SYNC;     /* new vsyncscan semantics */
1198 
1199         /*
1200          * required mount structure initializations
1201          */
1202         mp->mnt_stat.f_iosize = HAMMER2_PBUFSIZE;
1203         mp->mnt_stat.f_bsize = HAMMER2_PBUFSIZE;
1204 
1205         mp->mnt_vstat.f_frsize = HAMMER2_PBUFSIZE;
1206         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1207 
1208         /*
1209          * Optional fields
1210          */
1211         mp->mnt_iosize_max = MAXPHYS;
1212 
1213 	/*
1214 	 * Connect up mount pointers.
1215 	 */
1216 	hammer2_mount_helper(mp, pmp);
1217 
1218         lockmgr(&hammer2_mntlk, LK_RELEASE);
1219 
1220 	/*
1221 	 * Finish setup
1222 	 */
1223 	vfs_getnewfsid(mp);
1224 	vfs_add_vnodeops(mp, &hammer2_vnode_vops, &mp->mnt_vn_norm_ops);
1225 	vfs_add_vnodeops(mp, &hammer2_spec_vops, &mp->mnt_vn_spec_ops);
1226 	vfs_add_vnodeops(mp, &hammer2_fifo_vops, &mp->mnt_vn_fifo_ops);
1227 
1228 	if (path) {
1229 		copyinstr(info.volume, mp->mnt_stat.f_mntfromname,
1230 			  MNAMELEN - 1, &size);
1231 		bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
1232 	} /* else root mount, already in there */
1233 
1234 	bzero(mp->mnt_stat.f_mntonname, sizeof(mp->mnt_stat.f_mntonname));
1235 	if (path) {
1236 		copyinstr(path, mp->mnt_stat.f_mntonname,
1237 			  sizeof(mp->mnt_stat.f_mntonname) - 1,
1238 			  &size);
1239 	} else {
1240 		/* root mount */
1241 		mp->mnt_stat.f_mntonname[0] = '/';
1242 	}
1243 
1244 	/*
1245 	 * Initial statfs to prime mnt_stat.
1246 	 */
1247 	hammer2_vfs_statfs(mp, &mp->mnt_stat, cred);
1248 
1249 	return 0;
1250 }
1251 
1252 /*
1253  * Scan PFSs under the super-root and create hammer2_pfs structures.
1254  */
1255 static
1256 void
1257 hammer2_update_pmps(hammer2_dev_t *hmp)
1258 {
1259 	const hammer2_inode_data_t *ripdata;
1260 	hammer2_chain_t *parent;
1261 	hammer2_chain_t *chain;
1262 	hammer2_blockref_t bref;
1263 	hammer2_dev_t *force_local;
1264 	hammer2_pfs_t *spmp;
1265 	hammer2_pfs_t *pmp;
1266 	hammer2_key_t key_next;
1267 	int cache_index = -1;
1268 
1269 	/*
1270 	 * Force local mount (disassociate all PFSs from their clusters).
1271 	 * Used primarily for debugging.
1272 	 */
1273 	force_local = (hmp->hflags & HMNT2_LOCAL) ? hmp : NULL;
1274 
1275 	/*
1276 	 * Lookup mount point under the media-localized super-root.
1277 	 *
1278 	 * cluster->pmp will incorrectly point to spmp and must be fixed
1279 	 * up later on.
1280 	 */
1281 	spmp = hmp->spmp;
1282 	hammer2_inode_lock(spmp->iroot, 0);
1283 	parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
1284 	chain = hammer2_chain_lookup(&parent, &key_next,
1285 					 HAMMER2_KEY_MIN, HAMMER2_KEY_MAX,
1286 					 &cache_index, 0);
1287 	while (chain) {
1288 		if (chain->bref.type != HAMMER2_BREF_TYPE_INODE)
1289 			continue;
1290 		ripdata = &chain->data->ipdata;
1291 		bref = chain->bref;
1292 		kprintf("ADD LOCAL PFS: %s\n", ripdata->filename);
1293 
1294 		pmp = hammer2_pfsalloc(chain, ripdata,
1295 				       bref.modify_tid, force_local);
1296 		chain = hammer2_chain_next(&parent, chain, &key_next,
1297 					   key_next, HAMMER2_KEY_MAX,
1298 					   &cache_index, 0);
1299 	}
1300 	if (parent) {
1301 		hammer2_chain_unlock(parent);
1302 		hammer2_chain_drop(parent);
1303 	}
1304 	hammer2_inode_unlock(spmp->iroot);
1305 }
1306 
1307 static
1308 int
1309 hammer2_remount(hammer2_dev_t *hmp, struct mount *mp, char *path __unused,
1310 		struct vnode *devvp, struct ucred *cred)
1311 {
1312 	int error;
1313 
1314 	if (hmp->ronly && (mp->mnt_kern_flag & MNTK_WANTRDWR)) {
1315 		error = hammer2_recovery(hmp);
1316 	} else {
1317 		error = 0;
1318 	}
1319 	return error;
1320 }
1321 
1322 static
1323 int
1324 hammer2_vfs_unmount(struct mount *mp, int mntflags)
1325 {
1326 	hammer2_pfs_t *pmp;
1327 	int flags;
1328 	int error = 0;
1329 
1330 	pmp = MPTOPMP(mp);
1331 
1332 	if (pmp == NULL)
1333 		return(0);
1334 
1335 	lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1336 
1337 	/*
1338 	 * If mount initialization proceeded far enough we must flush
1339 	 * its vnodes and sync the underlying mount points.  Three syncs
1340 	 * are required to fully flush the filesystem (freemap updates lag
1341 	 * by one flush, and one extra for safety).
1342 	 */
1343 	if (mntflags & MNT_FORCE)
1344 		flags = FORCECLOSE;
1345 	else
1346 		flags = 0;
1347 	if (pmp->iroot) {
1348 		error = vflush(mp, 0, flags);
1349 		if (error)
1350 			goto failed;
1351 		hammer2_vfs_sync(mp, MNT_WAIT);
1352 		hammer2_vfs_sync(mp, MNT_WAIT);
1353 		hammer2_vfs_sync(mp, MNT_WAIT);
1354 	}
1355 
1356 	/*
1357 	 * Cleanup the frontend support XOPS threads
1358 	 */
1359 	hammer2_xop_helper_cleanup(pmp);
1360 
1361 	if (pmp->mp)
1362 		hammer2_unmount_helper(mp, pmp, NULL);
1363 
1364 	error = 0;
1365 failed:
1366 	lockmgr(&hammer2_mntlk, LK_RELEASE);
1367 
1368 	return (error);
1369 }
1370 
1371 /*
1372  * Mount helper, hook the system mount into our PFS.
1373  * The mount lock is held.
1374  *
1375  * We must bump the mount_count on related devices for any
1376  * mounted PFSs.
1377  */
1378 static
1379 void
1380 hammer2_mount_helper(struct mount *mp, hammer2_pfs_t *pmp)
1381 {
1382 	hammer2_cluster_t *cluster;
1383 	hammer2_chain_t *rchain;
1384 	int i;
1385 
1386         mp->mnt_data = (qaddr_t)pmp;
1387 	pmp->mp = mp;
1388 
1389 	/*
1390 	 * After pmp->mp is set we have to adjust hmp->mount_count.
1391 	 */
1392 	cluster = &pmp->iroot->cluster;
1393 	for (i = 0; i < cluster->nchains; ++i) {
1394 		rchain = cluster->array[i].chain;
1395 		if (rchain == NULL)
1396 			continue;
1397 		++rchain->hmp->mount_count;
1398 		kprintf("hammer2_mount hmp=%p ++mount_count=%d\n",
1399 			rchain->hmp, rchain->hmp->mount_count);
1400 	}
1401 
1402 	/*
1403 	 * Create missing Xop threads
1404 	 */
1405 	hammer2_xop_helper_create(pmp);
1406 }
1407 
1408 /*
1409  * Mount helper, unhook the system mount from our PFS.
1410  * The mount lock is held.
1411  *
1412  * If hmp is supplied a mount responsible for being the first to open
1413  * the block device failed and the block device and all PFSs using the
1414  * block device must be cleaned up.
1415  *
1416  * If pmp is supplied multiple devices might be backing the PFS and each
1417  * must be disconnected.  This might not be the last PFS using some of the
1418  * underlying devices.  Also, we have to adjust our hmp->mount_count
1419  * accounting for the devices backing the pmp which is now undergoing an
1420  * unmount.
1421  */
1422 static
1423 void
1424 hammer2_unmount_helper(struct mount *mp, hammer2_pfs_t *pmp, hammer2_dev_t *hmp)
1425 {
1426 	hammer2_cluster_t *cluster;
1427 	hammer2_chain_t *rchain;
1428 	struct vnode *devvp;
1429 	int dumpcnt;
1430 	int ronly = 0;
1431 	int i;
1432 
1433 	/*
1434 	 * If no device supplied this is a high-level unmount and we have to
1435 	 * to disconnect the mount, adjust mount_count, and locate devices
1436 	 * that might now have no mounts.
1437 	 */
1438 	if (pmp) {
1439 		KKASSERT(hmp == NULL);
1440 		KKASSERT((void *)(intptr_t)mp->mnt_data == pmp);
1441 		pmp->mp = NULL;
1442 		mp->mnt_data = NULL;
1443 
1444 		/*
1445 		 * After pmp->mp is cleared we have to account for
1446 		 * mount_count.
1447 		 */
1448 		cluster = &pmp->iroot->cluster;
1449 		for (i = 0; i < cluster->nchains; ++i) {
1450 			rchain = cluster->array[i].chain;
1451 			if (rchain == NULL)
1452 				continue;
1453 			--rchain->hmp->mount_count;
1454 			kprintf("hammer2_unmount hmp=%p --mount_count=%d\n",
1455 				rchain->hmp, rchain->hmp->mount_count);
1456 			/* scrapping hmp now may invalidate the pmp */
1457 		}
1458 again:
1459 		TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
1460 			if (hmp->mount_count == 0) {
1461 				hammer2_unmount_helper(NULL, NULL, hmp);
1462 				goto again;
1463 			}
1464 		}
1465 		return;
1466 	}
1467 
1468 	/*
1469 	 * Try to terminate the block device.  We can't terminate it if
1470 	 * there are still PFSs referencing it.
1471 	 */
1472 	kprintf("hammer2_unmount hmp=%p mount_count=%d\n",
1473 		hmp, hmp->mount_count);
1474 	if (hmp->mount_count)
1475 		return;
1476 
1477 	hammer2_pfsfree_scan(hmp);
1478 	hammer2_dev_exlock(hmp);	/* XXX order */
1479 
1480 	/*
1481 	 * Cycle the volume data lock as a safety (probably not needed any
1482 	 * more).  To ensure everything is out we need to flush at least
1483 	 * three times.  (1) The running of the sideq can dirty the
1484 	 * filesystem, (2) A normal flush can dirty the freemap, and
1485 	 * (3) ensure that the freemap is fully synchronized.
1486 	 *
1487 	 * The next mount's recovery scan can clean everything up but we want
1488 	 * to leave the filesystem in a 100% clean state on a normal unmount.
1489 	 */
1490 #if 0
1491 	hammer2_voldata_lock(hmp);
1492 	hammer2_voldata_unlock(hmp);
1493 #endif
1494 	hammer2_iocom_uninit(hmp);
1495 
1496 	if ((hmp->vchain.flags | hmp->fchain.flags) &
1497 	    HAMMER2_CHAIN_FLUSH_MASK) {
1498 		kprintf("hammer2_unmount: chains left over "
1499 			"after final sync\n");
1500 		kprintf("    vchain %08x\n", hmp->vchain.flags);
1501 		kprintf("    fchain %08x\n", hmp->fchain.flags);
1502 
1503 		if (hammer2_debug & 0x0010)
1504 			Debugger("entered debugger");
1505 	}
1506 
1507 	KKASSERT(hmp->spmp == NULL);
1508 
1509 	/*
1510 	 * Finish up with the device vnode
1511 	 */
1512 	if ((devvp = hmp->devvp) != NULL) {
1513 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1514 		vinvalbuf(devvp, (ronly ? 0 : V_SAVE), 0, 0);
1515 		hmp->devvp = NULL;
1516 		VOP_CLOSE(devvp, (ronly ? FREAD : FREAD|FWRITE), NULL);
1517 		vn_unlock(devvp);
1518 		vrele(devvp);
1519 		devvp = NULL;
1520 	}
1521 
1522 	/*
1523 	 * Clear vchain/fchain flags that might prevent final cleanup
1524 	 * of these chains.
1525 	 */
1526 	if (hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) {
1527 		atomic_add_long(&hammer2_count_modified_chains, -1);
1528 		atomic_clear_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1529 		hammer2_pfs_memory_wakeup(hmp->vchain.pmp);
1530 	}
1531 	if (hmp->vchain.flags & HAMMER2_CHAIN_UPDATE) {
1532 		atomic_clear_int(&hmp->vchain.flags, HAMMER2_CHAIN_UPDATE);
1533 	}
1534 
1535 	if (hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) {
1536 		atomic_add_long(&hammer2_count_modified_chains, -1);
1537 		atomic_clear_int(&hmp->fchain.flags, HAMMER2_CHAIN_MODIFIED);
1538 		hammer2_pfs_memory_wakeup(hmp->fchain.pmp);
1539 	}
1540 	if (hmp->fchain.flags & HAMMER2_CHAIN_UPDATE) {
1541 		atomic_clear_int(&hmp->fchain.flags, HAMMER2_CHAIN_UPDATE);
1542 	}
1543 
1544 	/*
1545 	 * Final drop of embedded freemap root chain to
1546 	 * clean up fchain.core (fchain structure is not
1547 	 * flagged ALLOCATED so it is cleaned out and then
1548 	 * left to rot).
1549 	 */
1550 	hammer2_chain_drop(&hmp->fchain);
1551 
1552 	/*
1553 	 * Final drop of embedded volume root chain to clean
1554 	 * up vchain.core (vchain structure is not flagged
1555 	 * ALLOCATED so it is cleaned out and then left to
1556 	 * rot).
1557 	 */
1558 	dumpcnt = 50;
1559 	hammer2_dump_chain(&hmp->vchain, 0, &dumpcnt, 'v');
1560 	dumpcnt = 50;
1561 	hammer2_dump_chain(&hmp->fchain, 0, &dumpcnt, 'f');
1562 	hammer2_dev_unlock(hmp);
1563 	hammer2_chain_drop(&hmp->vchain);
1564 
1565 	hammer2_io_cleanup(hmp, &hmp->iotree);
1566 	if (hmp->iofree_count) {
1567 		kprintf("io_cleanup: %d I/O's left hanging\n",
1568 			hmp->iofree_count);
1569 	}
1570 
1571 	TAILQ_REMOVE(&hammer2_mntlist, hmp, mntentry);
1572 	kmalloc_destroy(&hmp->mchain);
1573 	kfree(hmp, M_HAMMER2);
1574 }
1575 
1576 int
1577 hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
1578 		 ino_t ino, struct vnode **vpp)
1579 {
1580 	hammer2_xop_lookup_t *xop;
1581 	hammer2_pfs_t *pmp;
1582 	hammer2_inode_t *ip;
1583 	hammer2_tid_t inum;
1584 	int error;
1585 
1586 	inum = (hammer2_tid_t)ino & HAMMER2_DIRHASH_USERMSK;
1587 
1588 	error = 0;
1589 	pmp = MPTOPMP(mp);
1590 
1591 	/*
1592 	 * Easy if we already have it cached
1593 	 */
1594 	ip = hammer2_inode_lookup(pmp, inum);
1595 	if (ip) {
1596 		hammer2_inode_lock(ip, HAMMER2_RESOLVE_SHARED);
1597 		*vpp = hammer2_igetv(ip, &error);
1598 		hammer2_inode_unlock(ip);
1599 		hammer2_inode_drop(ip);		/* from lookup */
1600 
1601 		return error;
1602 	}
1603 
1604 	/*
1605 	 * Otherwise we have to find the inode
1606 	 */
1607 	xop = hammer2_xop_alloc(pmp->iroot, 0);
1608 	xop->lhc = inum;
1609 	hammer2_xop_start(&xop->head, hammer2_xop_lookup);
1610 	error = hammer2_xop_collect(&xop->head, 0);
1611 
1612 	if (error == 0) {
1613 		if (hammer2_cluster_rdata(&xop->head.cluster) == NULL) {
1614 			kprintf("vget: no collect error but also no rdata\n");
1615 			kprintf("xop %p\n", xop);
1616 			while ((hammer2_debug & 0x80000) == 0) {
1617 				tsleep(xop, PCATCH, "wait", hz * 10);
1618 			}
1619 			ip = NULL;
1620 		} else {
1621 			ip = hammer2_inode_get(pmp, NULL, &xop->head.cluster, -1);
1622 		}
1623 	}
1624 	hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1625 
1626 	if (ip) {
1627 		*vpp = hammer2_igetv(ip, &error);
1628 		hammer2_inode_unlock(ip);
1629 	} else {
1630 		*vpp = NULL;
1631 		error = ENOENT;
1632 	}
1633 	return (error);
1634 }
1635 
1636 static
1637 int
1638 hammer2_vfs_root(struct mount *mp, struct vnode **vpp)
1639 {
1640 	hammer2_pfs_t *pmp;
1641 	struct vnode *vp;
1642 	int error;
1643 
1644 	pmp = MPTOPMP(mp);
1645 	if (pmp->iroot == NULL) {
1646 		*vpp = NULL;
1647 		return EINVAL;
1648 	}
1649 
1650 	error = 0;
1651 	hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
1652 
1653 	while (pmp->inode_tid == 0) {
1654 		hammer2_xop_ipcluster_t *xop;
1655 		hammer2_inode_meta_t *meta;
1656 
1657 		xop = hammer2_xop_alloc(pmp->iroot, HAMMER2_XOP_MODIFYING);
1658 		hammer2_xop_start(&xop->head, hammer2_xop_ipcluster);
1659 		error = hammer2_xop_collect(&xop->head, 0);
1660 
1661 		if (error == 0) {
1662 			meta = &xop->head.cluster.focus->data->ipdata.meta;
1663 			pmp->iroot->meta = *meta;
1664 			pmp->inode_tid = meta->pfs_inum + 1;
1665 			if (pmp->inode_tid < HAMMER2_INODE_START)
1666 				pmp->inode_tid = HAMMER2_INODE_START;
1667 			pmp->modify_tid =
1668 				xop->head.cluster.focus->bref.modify_tid + 1;
1669 			kprintf("PFS: Starting inode %jd\n",
1670 				(intmax_t)pmp->inode_tid);
1671 			kprintf("PMP focus good set nextino=%ld mod=%016jx\n",
1672 				pmp->inode_tid, pmp->modify_tid);
1673 			wakeup(&pmp->iroot);
1674 
1675 			hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1676 
1677 			/*
1678 			 * Prime the mount info.
1679 			 */
1680 			hammer2_vfs_statfs(mp, &mp->mnt_stat, NULL);
1681 			break;
1682 		}
1683 
1684 		/*
1685 		 * Loop, try again
1686 		 */
1687 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1688 		hammer2_inode_unlock(pmp->iroot);
1689 		error = tsleep(&pmp->iroot, PCATCH, "h2root", hz);
1690 		hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
1691 		if (error == EINTR)
1692 			break;
1693 	}
1694 
1695 	if (error) {
1696 		hammer2_inode_unlock(pmp->iroot);
1697 		*vpp = NULL;
1698 	} else {
1699 		vp = hammer2_igetv(pmp->iroot, &error);
1700 		hammer2_inode_unlock(pmp->iroot);
1701 		*vpp = vp;
1702 	}
1703 
1704 	return (error);
1705 }
1706 
1707 /*
1708  * Filesystem status
1709  *
1710  * XXX incorporate ipdata->meta.inode_quota and data_quota
1711  */
1712 static
1713 int
1714 hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred)
1715 {
1716 	hammer2_pfs_t *pmp;
1717 	hammer2_dev_t *hmp;
1718 	hammer2_blockref_t bref;
1719 	int i;
1720 
1721 	/*
1722 	 * NOTE: iroot might not have validated the cluster yet.
1723 	 */
1724 	pmp = MPTOPMP(mp);
1725 
1726 	mp->mnt_stat.f_files = 0;
1727 	mp->mnt_stat.f_ffree = 0;
1728 	mp->mnt_stat.f_blocks = 0;
1729 	mp->mnt_stat.f_bfree = 0;
1730 	mp->mnt_stat.f_bavail = 0;
1731 
1732 	for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
1733 		hmp = pmp->pfs_hmps[i];
1734 		if (hmp == NULL)
1735 			continue;
1736 		if (pmp->iroot->cluster.array[i].chain)
1737 			bref = pmp->iroot->cluster.array[i].chain->bref;
1738 		else
1739 			bzero(&bref, sizeof(bref));
1740 
1741 		mp->mnt_stat.f_files = bref.inode_count;
1742 		mp->mnt_stat.f_ffree = 0;
1743 #if 0
1744 		mp->mnt_stat.f_blocks = (bref.data_count +
1745 					 hmp->voldata.allocator_free) /
1746 					mp->mnt_vstat.f_bsize;
1747 		mp->mnt_stat.f_bfree =  hmp->voldata.allocator_free /
1748 					mp->mnt_vstat.f_bsize;
1749 #endif
1750 		mp->mnt_stat.f_blocks = hmp->voldata.allocator_size /
1751 					mp->mnt_vstat.f_bsize;
1752 		mp->mnt_stat.f_bfree = hmp->voldata.allocator_free /
1753 					mp->mnt_vstat.f_bsize;
1754 		mp->mnt_stat.f_bavail = mp->mnt_stat.f_bfree;
1755 
1756 		*sbp = mp->mnt_stat;
1757 	}
1758 	return (0);
1759 }
1760 
1761 static
1762 int
1763 hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp, struct ucred *cred)
1764 {
1765 	hammer2_pfs_t *pmp;
1766 	hammer2_dev_t *hmp;
1767 	hammer2_blockref_t bref;
1768 	int i;
1769 
1770 	/*
1771 	 * NOTE: iroot might not have validated the cluster yet.
1772 	 */
1773 	pmp = MPTOPMP(mp);
1774 
1775 	mp->mnt_vstat.f_bsize = 0;
1776 	mp->mnt_vstat.f_files = 0;
1777 	mp->mnt_vstat.f_ffree = 0;
1778 	mp->mnt_vstat.f_blocks = 0;
1779 	mp->mnt_vstat.f_bfree = 0;
1780 	mp->mnt_vstat.f_bavail = 0;
1781 
1782 	for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
1783 		hmp = pmp->pfs_hmps[i];
1784 		if (hmp == NULL)
1785 			continue;
1786 		if (pmp->iroot->cluster.array[i].chain)
1787 			bref = pmp->iroot->cluster.array[i].chain->bref;
1788 		else
1789 			bzero(&bref, sizeof(bref));
1790 
1791 		mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1792 		mp->mnt_vstat.f_files = bref.inode_count;
1793 		mp->mnt_vstat.f_ffree = 0;
1794 #if 0
1795 		mp->mnt_vstat.f_blocks = (bref.data_count +
1796 					 hmp->voldata.allocator_free) /
1797 					mp->mnt_vstat.f_bsize;
1798 		mp->mnt_vstat.f_bfree = hmp->voldata.allocator_free /
1799 					mp->mnt_vstat.f_bsize;
1800 #endif
1801 		mp->mnt_vstat.f_blocks = hmp->voldata.allocator_size /
1802 					mp->mnt_vstat.f_bsize;
1803 		mp->mnt_vstat.f_bfree = hmp->voldata.allocator_free /
1804 					mp->mnt_vstat.f_bsize;
1805 		mp->mnt_vstat.f_bavail = mp->mnt_vstat.f_bfree;
1806 
1807 		*sbp = mp->mnt_vstat;
1808 	}
1809 	return (0);
1810 }
1811 
1812 /*
1813  * Mount-time recovery (RW mounts)
1814  *
1815  * Updates to the free block table are allowed to lag flushes by one
1816  * transaction.  In case of a crash, then on a fresh mount we must do an
1817  * incremental scan of the last committed transaction id and make sure that
1818  * all related blocks have been marked allocated.
1819  *
1820  * The super-root topology and each PFS has its own transaction id domain,
1821  * so we must track PFS boundary transitions.
1822  */
1823 struct hammer2_recovery_elm {
1824 	TAILQ_ENTRY(hammer2_recovery_elm) entry;
1825 	hammer2_chain_t *chain;
1826 	hammer2_tid_t sync_tid;
1827 };
1828 
1829 TAILQ_HEAD(hammer2_recovery_list, hammer2_recovery_elm);
1830 
1831 struct hammer2_recovery_info {
1832 	struct hammer2_recovery_list list;
1833 	hammer2_tid_t	mtid;
1834 	int	depth;
1835 };
1836 
1837 static int hammer2_recovery_scan(hammer2_dev_t *hmp,
1838 			hammer2_chain_t *parent,
1839 			struct hammer2_recovery_info *info,
1840 			hammer2_tid_t sync_tid);
1841 
1842 #define HAMMER2_RECOVERY_MAXDEPTH	10
1843 
1844 static
1845 int
1846 hammer2_recovery(hammer2_dev_t *hmp)
1847 {
1848 	struct hammer2_recovery_info info;
1849 	struct hammer2_recovery_elm *elm;
1850 	hammer2_chain_t *parent;
1851 	hammer2_tid_t sync_tid;
1852 	hammer2_tid_t mirror_tid;
1853 	int error;
1854 	int cumulative_error = 0;
1855 
1856 	hammer2_trans_init(hmp->spmp, 0);
1857 
1858 	sync_tid = hmp->voldata.freemap_tid;
1859 	mirror_tid = hmp->voldata.mirror_tid;
1860 
1861 	kprintf("hammer2 mount \"%s\": ", hmp->devrepname);
1862 	if (sync_tid >= mirror_tid) {
1863 		kprintf(" no recovery needed\n");
1864 	} else {
1865 		kprintf(" freemap recovery %016jx-%016jx\n",
1866 			sync_tid + 1, mirror_tid);
1867 	}
1868 
1869 	TAILQ_INIT(&info.list);
1870 	info.depth = 0;
1871 	parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
1872 	cumulative_error = hammer2_recovery_scan(hmp, parent, &info, sync_tid);
1873 	hammer2_chain_lookup_done(parent);
1874 
1875 	while ((elm = TAILQ_FIRST(&info.list)) != NULL) {
1876 		TAILQ_REMOVE(&info.list, elm, entry);
1877 		parent = elm->chain;
1878 		sync_tid = elm->sync_tid;
1879 		kfree(elm, M_HAMMER2);
1880 
1881 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1882 		error = hammer2_recovery_scan(hmp, parent, &info,
1883 					      hmp->voldata.freemap_tid);
1884 		hammer2_chain_unlock(parent);
1885 		hammer2_chain_drop(parent);	/* drop elm->chain ref */
1886 		if (error)
1887 			cumulative_error = error;
1888 	}
1889 	hammer2_trans_done(hmp->spmp);
1890 
1891 	return cumulative_error;
1892 }
1893 
1894 static
1895 int
1896 hammer2_recovery_scan(hammer2_dev_t *hmp, hammer2_chain_t *parent,
1897 		      struct hammer2_recovery_info *info,
1898 		      hammer2_tid_t sync_tid)
1899 {
1900 	const hammer2_inode_data_t *ripdata;
1901 	hammer2_chain_t *chain;
1902 	hammer2_blockref_t bref;
1903 	int cache_index;
1904 	int cumulative_error = 0;
1905 	int error;
1906 	int first;
1907 
1908 	/*
1909 	 * Adjust freemap to ensure that the block(s) are marked allocated.
1910 	 */
1911 	if (parent->bref.type != HAMMER2_BREF_TYPE_VOLUME) {
1912 		hammer2_freemap_adjust(hmp, &parent->bref,
1913 				       HAMMER2_FREEMAP_DORECOVER);
1914 	}
1915 
1916 	/*
1917 	 * Check type for recursive scan
1918 	 */
1919 	switch(parent->bref.type) {
1920 	case HAMMER2_BREF_TYPE_VOLUME:
1921 		/* data already instantiated */
1922 		break;
1923 	case HAMMER2_BREF_TYPE_INODE:
1924 		/*
1925 		 * Must instantiate data for DIRECTDATA test and also
1926 		 * for recursion.
1927 		 */
1928 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1929 		ripdata = &hammer2_chain_rdata(parent)->ipdata;
1930 		if (ripdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1931 			/* not applicable to recovery scan */
1932 			hammer2_chain_unlock(parent);
1933 			return 0;
1934 		}
1935 		hammer2_chain_unlock(parent);
1936 		break;
1937 	case HAMMER2_BREF_TYPE_INDIRECT:
1938 		/*
1939 		 * Must instantiate data for recursion
1940 		 */
1941 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1942 		hammer2_chain_unlock(parent);
1943 		break;
1944 	case HAMMER2_BREF_TYPE_DATA:
1945 	case HAMMER2_BREF_TYPE_FREEMAP:
1946 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1947 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1948 		/* not applicable to recovery scan */
1949 		return 0;
1950 		break;
1951 	default:
1952 		return EDOM;
1953 	}
1954 
1955 	/*
1956 	 * Defer operation if depth limit reached or if we are crossing a
1957 	 * PFS boundary.
1958 	 */
1959 	if (info->depth >= HAMMER2_RECOVERY_MAXDEPTH) {
1960 		struct hammer2_recovery_elm *elm;
1961 
1962 		elm = kmalloc(sizeof(*elm), M_HAMMER2, M_ZERO | M_WAITOK);
1963 		elm->chain = parent;
1964 		elm->sync_tid = sync_tid;
1965 		hammer2_chain_ref(parent);
1966 		TAILQ_INSERT_TAIL(&info->list, elm, entry);
1967 		/* unlocked by caller */
1968 
1969 		return(0);
1970 	}
1971 
1972 
1973 	/*
1974 	 * Recursive scan of the last flushed transaction only.  We are
1975 	 * doing this without pmp assignments so don't leave the chains
1976 	 * hanging around after we are done with them.
1977 	 */
1978 	cache_index = 0;
1979 	chain = NULL;
1980 	first = 1;
1981 
1982 	while (hammer2_chain_scan(parent, &chain, &bref,
1983 				  &first, &cache_index,
1984 				  HAMMER2_LOOKUP_NODATA) != NULL) {
1985 		/*
1986 		 * If this is a leaf
1987 		 */
1988 		if (chain == NULL) {
1989 			if (bref.mirror_tid > sync_tid) {
1990 				hammer2_freemap_adjust(hmp, &bref,
1991 						     HAMMER2_FREEMAP_DORECOVER);
1992 			}
1993 			continue;
1994 		}
1995 
1996 		/*
1997 		 * This may or may not be a recursive node.
1998 		 */
1999 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
2000 		if (bref.mirror_tid > sync_tid) {
2001 			++info->depth;
2002 			error = hammer2_recovery_scan(hmp, chain,
2003 						      info, sync_tid);
2004 			--info->depth;
2005 			if (error)
2006 				cumulative_error = error;
2007 		}
2008 
2009 		/*
2010 		 * Flush the recovery at the PFS boundary to stage it for
2011 		 * the final flush of the super-root topology.
2012 		 */
2013 		if ((bref.flags & HAMMER2_BREF_FLAG_PFSROOT) &&
2014 		    (chain->flags & HAMMER2_CHAIN_ONFLUSH)) {
2015 			hammer2_flush(chain, HAMMER2_FLUSH_TOP);
2016 		}
2017 	}
2018 
2019 	return cumulative_error;
2020 }
2021 
2022 /*
2023  * Sync a mount point; this is called on a per-mount basis from the
2024  * filesystem syncer process periodically and whenever a user issues
2025  * a sync.
2026  */
2027 int
2028 hammer2_vfs_sync(struct mount *mp, int waitfor)
2029 {
2030 	hammer2_xop_flush_t *xop;
2031 	struct hammer2_sync_info info;
2032 	hammer2_inode_t *iroot;
2033 	hammer2_pfs_t *pmp;
2034 	int flags;
2035 	int error;
2036 
2037 	pmp = MPTOPMP(mp);
2038 	iroot = pmp->iroot;
2039 	KKASSERT(iroot);
2040 	KKASSERT(iroot->pmp == pmp);
2041 
2042 	/*
2043 	 * We can't acquire locks on existing vnodes while in a transaction
2044 	 * without risking a deadlock.  This assumes that vfsync() can be
2045 	 * called without the vnode locked (which it can in DragonFly).
2046 	 * Otherwise we'd have to implement a multi-pass or flag the lock
2047 	 * failures and retry.
2048 	 *
2049 	 * The reclamation code interlocks with the sync list's token
2050 	 * (by removing the vnode from the scan list) before unlocking
2051 	 * the inode, giving us time to ref the inode.
2052 	 */
2053 	/*flags = VMSC_GETVP;*/
2054 	flags = 0;
2055 	if (waitfor & MNT_LAZY)
2056 		flags |= VMSC_ONEPASS;
2057 
2058 #if 1
2059 	/*
2060 	 * Preflush the vnodes using a normal transaction before interlocking
2061 	 * with a flush transaction.  We do this to try to run as much of
2062 	 * the compression as possible outside the flush transaction.
2063 	 */
2064 	hammer2_trans_init(pmp, 0);
2065 	info.error = 0;
2066 	info.waitfor = MNT_NOWAIT;
2067 	vsyncscan(mp, flags | VMSC_NOWAIT, hammer2_sync_scan2, &info);
2068 	hammer2_trans_done(pmp);
2069 #endif
2070 
2071 	/*
2072 	 * Start our flush transaction.  This does not return until all
2073 	 * concurrent transactions have completed and will prevent any
2074 	 * new transactions from running concurrently, except for the
2075 	 * buffer cache transactions.
2076 	 *
2077 	 * For efficiency do an async pass before making sure with a
2078 	 * synchronous pass on all related buffer cache buffers.  It
2079 	 * should theoretically not be possible for any new file buffers
2080 	 * to be instantiated during this sequence.
2081 	 */
2082 	hammer2_trans_init(pmp, HAMMER2_TRANS_ISFLUSH |
2083 			        HAMMER2_TRANS_PREFLUSH);
2084 	hammer2_inode_run_sideq(pmp);
2085 
2086 	info.error = 0;
2087 	info.waitfor = MNT_NOWAIT;
2088 	vsyncscan(mp, flags | VMSC_NOWAIT, hammer2_sync_scan2, &info);
2089 	info.waitfor = MNT_WAIT;
2090 	vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2091 
2092 	/*
2093 	 * Clear PREFLUSH.  This prevents (or asserts on) any new logical
2094 	 * buffer cache flushes which occur during the flush.  Device buffers
2095 	 * are not affected.
2096 	 */
2097 	hammer2_bioq_sync(pmp);
2098 	hammer2_trans_clear_preflush(pmp);
2099 
2100 	/*
2101 	 * Use the XOP interface to concurrently flush all nodes to
2102 	 * synchronize the PFSROOT subtopology to the media.  A standard
2103 	 * end-of-scan ENOENT error indicates cluster sufficiency.
2104 	 *
2105 	 * Note that this flush will not be visible on crash recovery until
2106 	 * we flush the super-root topology in the next loop.
2107 	 *
2108 	 * XXX For now wait for all flushes to complete.
2109 	 */
2110 	if (iroot) {
2111 		xop = hammer2_xop_alloc(iroot, HAMMER2_XOP_MODIFYING);
2112 		hammer2_xop_start(&xop->head, hammer2_inode_xop_flush);
2113 		error = hammer2_xop_collect(&xop->head,
2114 					    HAMMER2_XOP_COLLECT_WAITALL);
2115 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
2116 		if (error == ENOENT)
2117 			error = 0;
2118 	} else {
2119 		error = 0;
2120 	}
2121 	hammer2_trans_done(pmp);
2122 
2123 	return (error);
2124 }
2125 
2126 /*
2127  * Sync passes.
2128  *
2129  * Note that we ignore the tranasction mtid we got above.  Instead,
2130  * each vfsync below will ultimately get its own via TRANS_BUFCACHE
2131  * transactions.
2132  */
2133 static int
2134 hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data)
2135 {
2136 	struct hammer2_sync_info *info = data;
2137 	hammer2_inode_t *ip;
2138 	int error;
2139 
2140 	/*
2141 	 * Degenerate cases.  Note that ip == NULL typically means the
2142 	 * syncer vnode itself and we don't want to vclrisdirty() in that
2143 	 * situation.
2144 	 */
2145 	ip = VTOI(vp);
2146 	if (ip == NULL) {
2147 		return(0);
2148 	}
2149 	if (vp->v_type == VNON || vp->v_type == VBAD) {
2150 		vclrisdirty(vp);
2151 		return(0);
2152 	}
2153 
2154 	/*
2155 	 * VOP_FSYNC will start a new transaction so replicate some code
2156 	 * here to do it inline (see hammer2_vop_fsync()).
2157 	 *
2158 	 * WARNING: The vfsync interacts with the buffer cache and might
2159 	 *          block, we can't hold the inode lock at that time.
2160 	 *	    However, we MUST ref ip before blocking to ensure that
2161 	 *	    it isn't ripped out from under us (since we do not
2162 	 *	    hold a lock on the vnode).
2163 	 */
2164 	hammer2_inode_ref(ip);
2165 	if ((ip->flags & HAMMER2_INODE_MODIFIED) ||
2166 	    !RB_EMPTY(&vp->v_rbdirty_tree)) {
2167 		vfsync(vp, info->waitfor, 1, NULL, NULL);
2168 		if (ip->flags & (HAMMER2_INODE_RESIZED |
2169 				 HAMMER2_INODE_MODIFIED)) {
2170 			hammer2_inode_lock(ip, 0);
2171 			hammer2_inode_chain_sync(ip);
2172 			hammer2_inode_unlock(ip);
2173 		}
2174 	}
2175 	if ((ip->flags & HAMMER2_INODE_MODIFIED) == 0 &&
2176 	    RB_EMPTY(&vp->v_rbdirty_tree)) {
2177 		vclrisdirty(vp);
2178 	}
2179 
2180 	hammer2_inode_drop(ip);
2181 #if 1
2182 	error = 0;
2183 	if (error)
2184 		info->error = error;
2185 #endif
2186 	return(0);
2187 }
2188 
2189 static
2190 int
2191 hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp)
2192 {
2193 	hammer2_inode_t *ip;
2194 
2195 	KKASSERT(MAXFIDSZ >= 16);
2196 	ip = VTOI(vp);
2197 	fhp->fid_len = offsetof(struct fid, fid_data[16]);
2198 	fhp->fid_ext = 0;
2199 	((hammer2_tid_t *)fhp->fid_data)[0] = ip->meta.inum;
2200 	((hammer2_tid_t *)fhp->fid_data)[1] = 0;
2201 
2202 	return 0;
2203 }
2204 
2205 static
2206 int
2207 hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
2208 	       struct fid *fhp, struct vnode **vpp)
2209 {
2210 	hammer2_pfs_t *pmp;
2211 	hammer2_tid_t inum;
2212 	int error;
2213 
2214 	pmp = MPTOPMP(mp);
2215 	inum = ((hammer2_tid_t *)fhp->fid_data)[0] & HAMMER2_DIRHASH_USERMSK;
2216 	if (vpp) {
2217 		if (inum == 1)
2218 			error = hammer2_vfs_root(mp, vpp);
2219 		else
2220 			error = hammer2_vfs_vget(mp, NULL, inum, vpp);
2221 	} else {
2222 		error = 0;
2223 	}
2224 	if (error)
2225 		kprintf("fhtovp: %016jx -> %p, %d\n", inum, *vpp, error);
2226 	return error;
2227 }
2228 
2229 static
2230 int
2231 hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
2232 		 int *exflagsp, struct ucred **credanonp)
2233 {
2234 	hammer2_pfs_t *pmp;
2235 	struct netcred *np;
2236 	int error;
2237 
2238 	pmp = MPTOPMP(mp);
2239 	np = vfs_export_lookup(mp, &pmp->export, nam);
2240 	if (np) {
2241 		*exflagsp = np->netc_exflags;
2242 		*credanonp = &np->netc_anon;
2243 		error = 0;
2244 	} else {
2245 		error = EACCES;
2246 	}
2247 	return error;
2248 }
2249 
2250 /*
2251  * Support code for hammer2_vfs_mount().  Read, verify, and install the volume
2252  * header into the HMP
2253  *
2254  * XXX read four volhdrs and use the one with the highest TID whos CRC
2255  *     matches.
2256  *
2257  * XXX check iCRCs.
2258  *
2259  * XXX For filesystems w/ less than 4 volhdrs, make sure to not write to
2260  *     nonexistant locations.
2261  *
2262  * XXX Record selected volhdr and ring updates to each of 4 volhdrs
2263  */
2264 static
2265 int
2266 hammer2_install_volume_header(hammer2_dev_t *hmp)
2267 {
2268 	hammer2_volume_data_t *vd;
2269 	struct buf *bp;
2270 	hammer2_crc32_t crc0, crc, bcrc0, bcrc;
2271 	int error_reported;
2272 	int error;
2273 	int valid;
2274 	int i;
2275 
2276 	error_reported = 0;
2277 	error = 0;
2278 	valid = 0;
2279 	bp = NULL;
2280 
2281 	/*
2282 	 * There are up to 4 copies of the volume header (syncs iterate
2283 	 * between them so there is no single master).  We don't trust the
2284 	 * volu_size field so we don't know precisely how large the filesystem
2285 	 * is, so depend on the OS to return an error if we go beyond the
2286 	 * block device's EOF.
2287 	 */
2288 	for (i = 0; i < HAMMER2_NUM_VOLHDRS; i++) {
2289 		error = bread(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2290 			      HAMMER2_VOLUME_BYTES, &bp);
2291 		if (error) {
2292 			brelse(bp);
2293 			bp = NULL;
2294 			continue;
2295 		}
2296 
2297 		vd = (struct hammer2_volume_data *) bp->b_data;
2298 		if ((vd->magic != HAMMER2_VOLUME_ID_HBO) &&
2299 		    (vd->magic != HAMMER2_VOLUME_ID_ABO)) {
2300 			brelse(bp);
2301 			bp = NULL;
2302 			continue;
2303 		}
2304 
2305 		if (vd->magic == HAMMER2_VOLUME_ID_ABO) {
2306 			/* XXX: Reversed-endianness filesystem */
2307 			kprintf("hammer2: reverse-endian filesystem detected");
2308 			brelse(bp);
2309 			bp = NULL;
2310 			continue;
2311 		}
2312 
2313 		crc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT0];
2314 		crc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC0_OFF,
2315 				      HAMMER2_VOLUME_ICRC0_SIZE);
2316 		bcrc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT1];
2317 		bcrc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC1_OFF,
2318 				       HAMMER2_VOLUME_ICRC1_SIZE);
2319 		if ((crc0 != crc) || (bcrc0 != bcrc)) {
2320 			kprintf("hammer2 volume header crc "
2321 				"mismatch copy #%d %08x/%08x\n",
2322 				i, crc0, crc);
2323 			error_reported = 1;
2324 			brelse(bp);
2325 			bp = NULL;
2326 			continue;
2327 		}
2328 		if (valid == 0 || hmp->voldata.mirror_tid < vd->mirror_tid) {
2329 			valid = 1;
2330 			hmp->voldata = *vd;
2331 			hmp->volhdrno = i;
2332 		}
2333 		brelse(bp);
2334 		bp = NULL;
2335 	}
2336 	if (valid) {
2337 		hmp->volsync = hmp->voldata;
2338 		error = 0;
2339 		if (error_reported || bootverbose || 1) { /* 1/DEBUG */
2340 			kprintf("hammer2: using volume header #%d\n",
2341 				hmp->volhdrno);
2342 		}
2343 	} else {
2344 		error = EINVAL;
2345 		kprintf("hammer2: no valid volume headers found!\n");
2346 	}
2347 	return (error);
2348 }
2349 
2350 /*
2351  * This handles hysteresis on regular file flushes.  Because the BIOs are
2352  * routed to a thread it is possible for an excessive number to build up
2353  * and cause long front-end stalls long before the runningbuffspace limit
2354  * is hit, so we implement hammer2_flush_pipe to control the
2355  * hysteresis.
2356  *
2357  * This is a particular problem when compression is used.
2358  */
2359 void
2360 hammer2_lwinprog_ref(hammer2_pfs_t *pmp)
2361 {
2362 	atomic_add_int(&pmp->count_lwinprog, 1);
2363 }
2364 
2365 void
2366 hammer2_lwinprog_drop(hammer2_pfs_t *pmp)
2367 {
2368 	int lwinprog;
2369 
2370 	lwinprog = atomic_fetchadd_int(&pmp->count_lwinprog, -1);
2371 	if ((lwinprog & HAMMER2_LWINPROG_WAITING) &&
2372 	    (lwinprog & HAMMER2_LWINPROG_MASK) <= hammer2_flush_pipe * 2 / 3) {
2373 		atomic_clear_int(&pmp->count_lwinprog,
2374 				 HAMMER2_LWINPROG_WAITING);
2375 		wakeup(&pmp->count_lwinprog);
2376 	}
2377 	if ((lwinprog & HAMMER2_LWINPROG_WAITING0) &&
2378 	    (lwinprog & HAMMER2_LWINPROG_MASK) <= 0) {
2379 		atomic_clear_int(&pmp->count_lwinprog,
2380 				 HAMMER2_LWINPROG_WAITING0);
2381 		wakeup(&pmp->count_lwinprog);
2382 	}
2383 }
2384 
2385 void
2386 hammer2_lwinprog_wait(hammer2_pfs_t *pmp, int flush_pipe)
2387 {
2388 	int lwinprog;
2389 	int lwflag = (flush_pipe) ? HAMMER2_LWINPROG_WAITING :
2390 				    HAMMER2_LWINPROG_WAITING0;
2391 
2392 	for (;;) {
2393 		lwinprog = pmp->count_lwinprog;
2394 		cpu_ccfence();
2395 		if ((lwinprog & HAMMER2_LWINPROG_MASK) <= flush_pipe)
2396 			break;
2397 		tsleep_interlock(&pmp->count_lwinprog, 0);
2398 		atomic_set_int(&pmp->count_lwinprog, lwflag);
2399 		lwinprog = pmp->count_lwinprog;
2400 		if ((lwinprog & HAMMER2_LWINPROG_MASK) <= flush_pipe)
2401 			break;
2402 		tsleep(&pmp->count_lwinprog, PINTERLOCKED, "h2wpipe", hz);
2403 	}
2404 }
2405 
2406 /*
2407  * Manage excessive memory resource use for chain and related
2408  * structures.
2409  */
2410 void
2411 hammer2_pfs_memory_wait(hammer2_pfs_t *pmp)
2412 {
2413 	uint32_t waiting;
2414 	uint32_t count;
2415 	uint32_t limit;
2416 #if 0
2417 	static int zzticks;
2418 #endif
2419 
2420 	/*
2421 	 * Atomic check condition and wait.  Also do an early speedup of
2422 	 * the syncer to try to avoid hitting the wait.
2423 	 */
2424 	for (;;) {
2425 		waiting = pmp->inmem_dirty_chains;
2426 		cpu_ccfence();
2427 		count = waiting & HAMMER2_DIRTYCHAIN_MASK;
2428 
2429 		limit = pmp->mp->mnt_nvnodelistsize / 10;
2430 		if (limit < hammer2_limit_dirty_chains)
2431 			limit = hammer2_limit_dirty_chains;
2432 		if (limit < 1000)
2433 			limit = 1000;
2434 
2435 #if 0
2436 		if ((int)(ticks - zzticks) > hz) {
2437 			zzticks = ticks;
2438 			kprintf("count %ld %ld\n", count, limit);
2439 		}
2440 #endif
2441 
2442 		/*
2443 		 * Block if there are too many dirty chains present, wait
2444 		 * for the flush to clean some out.
2445 		 */
2446 		if (count > limit) {
2447 			tsleep_interlock(&pmp->inmem_dirty_chains, 0);
2448 			if (atomic_cmpset_int(&pmp->inmem_dirty_chains,
2449 					       waiting,
2450 				       waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
2451 				speedup_syncer(pmp->mp);
2452 				tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
2453 				       "chnmem", hz);
2454 			}
2455 			continue;	/* loop on success or fail */
2456 		}
2457 
2458 		/*
2459 		 * Try to start an early flush before we are forced to block.
2460 		 */
2461 		if (count > limit * 7 / 10)
2462 			speedup_syncer(pmp->mp);
2463 		break;
2464 	}
2465 }
2466 
2467 void
2468 hammer2_pfs_memory_inc(hammer2_pfs_t *pmp)
2469 {
2470 	if (pmp) {
2471 		atomic_add_int(&pmp->inmem_dirty_chains, 1);
2472 	}
2473 }
2474 
2475 void
2476 hammer2_pfs_memory_wakeup(hammer2_pfs_t *pmp)
2477 {
2478 	uint32_t waiting;
2479 
2480 	if (pmp == NULL)
2481 		return;
2482 
2483 	for (;;) {
2484 		waiting = pmp->inmem_dirty_chains;
2485 		cpu_ccfence();
2486 		if (atomic_cmpset_int(&pmp->inmem_dirty_chains,
2487 				       waiting,
2488 				       (waiting - 1) &
2489 					~HAMMER2_DIRTYCHAIN_WAITING)) {
2490 			break;
2491 		}
2492 	}
2493 
2494 	if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
2495 		wakeup(&pmp->inmem_dirty_chains);
2496 }
2497 
2498 /*
2499  * Debugging
2500  */
2501 void
2502 hammer2_dump_chain(hammer2_chain_t *chain, int tab, int *countp, char pfx)
2503 {
2504 	hammer2_chain_t *scan;
2505 	hammer2_chain_t *parent;
2506 
2507 	--*countp;
2508 	if (*countp == 0) {
2509 		kprintf("%*.*s...\n", tab, tab, "");
2510 		return;
2511 	}
2512 	if (*countp < 0)
2513 		return;
2514 	kprintf("%*.*s%c-chain %p.%d %016jx/%d mir=%016jx\n",
2515 		tab, tab, "", pfx,
2516 		chain, chain->bref.type,
2517 		chain->bref.key, chain->bref.keybits,
2518 		chain->bref.mirror_tid);
2519 
2520 	kprintf("%*.*s      [%08x] (%s) refs=%d",
2521 		tab, tab, "",
2522 		chain->flags,
2523 		((chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2524 		chain->data) ?  (char *)chain->data->ipdata.filename : "?"),
2525 		chain->refs);
2526 
2527 	parent = chain->parent;
2528 	if (parent)
2529 		kprintf("\n%*.*s      p=%p [pflags %08x prefs %d",
2530 			tab, tab, "",
2531 			parent, parent->flags, parent->refs);
2532 	if (RB_EMPTY(&chain->core.rbtree)) {
2533 		kprintf("\n");
2534 	} else {
2535 		kprintf(" {\n");
2536 		RB_FOREACH(scan, hammer2_chain_tree, &chain->core.rbtree)
2537 			hammer2_dump_chain(scan, tab + 4, countp, 'a');
2538 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE && chain->data)
2539 			kprintf("%*.*s}(%s)\n", tab, tab, "",
2540 				chain->data->ipdata.filename);
2541 		else
2542 			kprintf("%*.*s}\n", tab, tab, "");
2543 	}
2544 }
2545