xref: /dragonfly/sys/vfs/hammer2/hammer2_vfsops.c (revision d8d5b238)
1 /*
2  * Copyright (c) 2011-2018 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 	int pass;
73 };
74 
75 TAILQ_HEAD(hammer2_mntlist, hammer2_dev);
76 static struct hammer2_mntlist hammer2_mntlist;
77 
78 struct hammer2_pfslist hammer2_pfslist;
79 struct hammer2_pfslist hammer2_spmplist;
80 struct lock hammer2_mntlk;
81 
82 int hammer2_supported_version = HAMMER2_VOL_VERSION_DEFAULT;
83 int hammer2_debug;
84 int hammer2_xopgroups;
85 long hammer2_debug_inode;
86 int hammer2_cluster_meta_read = 1;	/* physical read-ahead */
87 int hammer2_cluster_data_read = 4;	/* physical read-ahead */
88 int hammer2_cluster_write = 0;		/* physical write clustering */
89 int hammer2_dedup_enable = 1;
90 int hammer2_always_compress = 0;	/* always try to compress */
91 int hammer2_inval_enable = 0;
92 int hammer2_flush_pipe = 100;
93 int hammer2_dio_count;
94 int hammer2_dio_limit = 256;
95 int hammer2_bulkfree_tps = 5000;
96 int hammer2_worker_rmask = 3;
97 long hammer2_chain_allocs;
98 long hammer2_chain_frees;
99 long hammer2_limit_dirty_chains;
100 long hammer2_limit_dirty_inodes;
101 long hammer2_count_modified_chains;
102 long hammer2_iod_invals;
103 long hammer2_iod_file_read;
104 long hammer2_iod_meta_read;
105 long hammer2_iod_indr_read;
106 long hammer2_iod_fmap_read;
107 long hammer2_iod_volu_read;
108 long hammer2_iod_file_write;
109 long hammer2_iod_file_wembed;
110 long hammer2_iod_file_wzero;
111 long hammer2_iod_file_wdedup;
112 long hammer2_iod_meta_write;
113 long hammer2_iod_indr_write;
114 long hammer2_iod_fmap_write;
115 long hammer2_iod_volu_write;
116 long hammer2_iod_inode_creates;
117 long hammer2_iod_inode_deletes;
118 
119 MALLOC_DECLARE(M_HAMMER2_CBUFFER);
120 MALLOC_DEFINE(M_HAMMER2_CBUFFER, "HAMMER2-compbuffer",
121 		"Buffer used for compression.");
122 
123 MALLOC_DECLARE(M_HAMMER2_DEBUFFER);
124 MALLOC_DEFINE(M_HAMMER2_DEBUFFER, "HAMMER2-decompbuffer",
125 		"Buffer used for decompression.");
126 
127 SYSCTL_NODE(_vfs, OID_AUTO, hammer2, CTLFLAG_RW, 0, "HAMMER2 filesystem");
128 
129 SYSCTL_INT(_vfs_hammer2, OID_AUTO, supported_version, CTLFLAG_RD,
130 	   &hammer2_supported_version, 0, "");
131 SYSCTL_INT(_vfs_hammer2, OID_AUTO, debug, CTLFLAG_RW,
132 	   &hammer2_debug, 0, "");
133 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, debug_inode, CTLFLAG_RW,
134 	   &hammer2_debug_inode, 0, "");
135 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_meta_read, CTLFLAG_RW,
136 	   &hammer2_cluster_meta_read, 0, "");
137 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_data_read, CTLFLAG_RW,
138 	   &hammer2_cluster_data_read, 0, "");
139 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_write, CTLFLAG_RW,
140 	   &hammer2_cluster_write, 0, "");
141 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dedup_enable, CTLFLAG_RW,
142 	   &hammer2_dedup_enable, 0, "");
143 SYSCTL_INT(_vfs_hammer2, OID_AUTO, always_compress, CTLFLAG_RW,
144 	   &hammer2_always_compress, 0, "");
145 SYSCTL_INT(_vfs_hammer2, OID_AUTO, inval_enable, CTLFLAG_RW,
146 	   &hammer2_inval_enable, 0, "");
147 SYSCTL_INT(_vfs_hammer2, OID_AUTO, flush_pipe, CTLFLAG_RW,
148 	   &hammer2_flush_pipe, 0, "");
149 SYSCTL_INT(_vfs_hammer2, OID_AUTO, worker_rmask, CTLFLAG_RW,
150 	   &hammer2_worker_rmask, 0, "");
151 SYSCTL_INT(_vfs_hammer2, OID_AUTO, bulkfree_tps, CTLFLAG_RW,
152 	   &hammer2_bulkfree_tps, 0, "");
153 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, chain_allocs, CTLFLAG_RW,
154 	   &hammer2_chain_allocs, 0, "");
155 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, chain_frees, CTLFLAG_RW,
156 	   &hammer2_chain_frees, 0, "");
157 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, limit_dirty_chains, CTLFLAG_RW,
158 	   &hammer2_limit_dirty_chains, 0, "");
159 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, limit_dirty_inodes, CTLFLAG_RW,
160 	   &hammer2_limit_dirty_inodes, 0, "");
161 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, count_modified_chains, CTLFLAG_RW,
162 	   &hammer2_count_modified_chains, 0, "");
163 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dio_count, CTLFLAG_RD,
164 	   &hammer2_dio_count, 0, "");
165 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dio_limit, CTLFLAG_RW,
166 	   &hammer2_dio_limit, 0, "");
167 
168 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_invals, CTLFLAG_RW,
169 	   &hammer2_iod_invals, 0, "");
170 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_read, CTLFLAG_RW,
171 	   &hammer2_iod_file_read, 0, "");
172 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_read, CTLFLAG_RW,
173 	   &hammer2_iod_meta_read, 0, "");
174 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_read, CTLFLAG_RW,
175 	   &hammer2_iod_indr_read, 0, "");
176 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_read, CTLFLAG_RW,
177 	   &hammer2_iod_fmap_read, 0, "");
178 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_read, CTLFLAG_RW,
179 	   &hammer2_iod_volu_read, 0, "");
180 
181 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_write, CTLFLAG_RW,
182 	   &hammer2_iod_file_write, 0, "");
183 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_wembed, CTLFLAG_RW,
184 	   &hammer2_iod_file_wembed, 0, "");
185 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_wzero, CTLFLAG_RW,
186 	   &hammer2_iod_file_wzero, 0, "");
187 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_wdedup, CTLFLAG_RW,
188 	   &hammer2_iod_file_wdedup, 0, "");
189 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_write, CTLFLAG_RW,
190 	   &hammer2_iod_meta_write, 0, "");
191 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_write, CTLFLAG_RW,
192 	   &hammer2_iod_indr_write, 0, "");
193 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_write, CTLFLAG_RW,
194 	   &hammer2_iod_fmap_write, 0, "");
195 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_write, CTLFLAG_RW,
196 	   &hammer2_iod_volu_write, 0, "");
197 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_inode_creates, CTLFLAG_RW,
198 	   &hammer2_iod_inode_creates, 0, "");
199 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_inode_deletes, CTLFLAG_RW,
200 	   &hammer2_iod_inode_deletes, 0, "");
201 
202 long hammer2_process_icrc32;
203 long hammer2_process_xxhash64;
204 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, process_icrc32, CTLFLAG_RW,
205 	   &hammer2_process_icrc32, 0, "");
206 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, process_xxhash64, CTLFLAG_RW,
207 	   &hammer2_process_xxhash64, 0, "");
208 
209 static int hammer2_vfs_init(struct vfsconf *conf);
210 static int hammer2_vfs_uninit(struct vfsconf *vfsp);
211 static int hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
212 				struct ucred *cred);
213 static int hammer2_remount(hammer2_dev_t *, struct mount *, char *,
214 				struct vnode *, struct ucred *);
215 static int hammer2_recovery(hammer2_dev_t *hmp);
216 static int hammer2_vfs_unmount(struct mount *mp, int mntflags);
217 static int hammer2_vfs_root(struct mount *mp, struct vnode **vpp);
218 static int hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp,
219 				struct ucred *cred);
220 static int hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp,
221 				struct ucred *cred);
222 static int hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
223 				struct fid *fhp, struct vnode **vpp);
224 static int hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp);
225 static int hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
226 				int *exflagsp, struct ucred **credanonp);
227 static void hammer2_vfs_modifying(struct mount *mp);
228 
229 static int hammer2_install_volume_header(hammer2_dev_t *hmp);
230 #if 0
231 static int hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data);
232 #endif
233 
234 static void hammer2_update_pmps(hammer2_dev_t *hmp);
235 
236 static void hammer2_mount_helper(struct mount *mp, hammer2_pfs_t *pmp);
237 static void hammer2_unmount_helper(struct mount *mp, hammer2_pfs_t *pmp,
238 				hammer2_dev_t *hmp);
239 static int hammer2_fixup_pfses(hammer2_dev_t *hmp);
240 
241 /*
242  * HAMMER2 vfs operations.
243  */
244 static struct vfsops hammer2_vfsops = {
245 	.vfs_init	= hammer2_vfs_init,
246 	.vfs_uninit	= hammer2_vfs_uninit,
247 	.vfs_sync	= hammer2_vfs_sync,
248 	.vfs_mount	= hammer2_vfs_mount,
249 	.vfs_unmount	= hammer2_vfs_unmount,
250 	.vfs_root 	= hammer2_vfs_root,
251 	.vfs_statfs	= hammer2_vfs_statfs,
252 	.vfs_statvfs	= hammer2_vfs_statvfs,
253 	.vfs_vget	= hammer2_vfs_vget,
254 	.vfs_vptofh	= hammer2_vfs_vptofh,
255 	.vfs_fhtovp	= hammer2_vfs_fhtovp,
256 	.vfs_checkexp	= hammer2_vfs_checkexp,
257 	.vfs_modifying	= hammer2_vfs_modifying
258 };
259 
260 MALLOC_DEFINE(M_HAMMER2, "HAMMER2-mount", "");
261 
262 VFS_SET(hammer2_vfsops, hammer2, VFCF_MPSAFE);
263 MODULE_VERSION(hammer2, 1);
264 
265 static
266 int
267 hammer2_vfs_init(struct vfsconf *conf)
268 {
269 	static struct objcache_malloc_args margs_read;
270 	static struct objcache_malloc_args margs_write;
271 	static struct objcache_malloc_args margs_vop;
272 
273 	int error;
274 
275 	error = 0;
276 	kmalloc_raise_limit(M_HAMMER2, 0);	/* unlimited */
277 
278 	/*
279 	 * hammer2_xopgroups must be even and is most optimal if
280 	 * 2 x ncpus so strategy functions can be queued to the same
281 	 * cpu.
282 	 */
283 	hammer2_xopgroups = HAMMER2_XOPGROUPS_MIN;
284 	if (hammer2_xopgroups < ncpus * 2)
285 		hammer2_xopgroups = ncpus * 2;
286 
287 	/*
288 	 * A large DIO cache is needed to retain dedup enablement masks.
289 	 * The bulkfree code clears related masks as part of the disk block
290 	 * recycling algorithm, preventing it from being used for a later
291 	 * dedup.
292 	 *
293 	 * NOTE: A large buffer cache can actually interfere with dedup
294 	 *	 operation because we dedup based on media physical buffers
295 	 *	 and not logical buffers.  Try to make the DIO case large
296 	 *	 enough to avoid this problem, but also cap it.
297 	 */
298 	hammer2_dio_limit = nbuf * 2;
299 	if (hammer2_dio_limit > 100000)
300 		hammer2_dio_limit = 100000;
301 
302 	if (HAMMER2_BLOCKREF_BYTES != sizeof(struct hammer2_blockref))
303 		error = EINVAL;
304 	if (HAMMER2_INODE_BYTES != sizeof(struct hammer2_inode_data))
305 		error = EINVAL;
306 	if (HAMMER2_VOLUME_BYTES != sizeof(struct hammer2_volume_data))
307 		error = EINVAL;
308 
309 	if (error)
310 		kprintf("HAMMER2 structure size mismatch; cannot continue.\n");
311 
312 	margs_read.objsize = 65536;
313 	margs_read.mtype = M_HAMMER2_DEBUFFER;
314 
315 	margs_write.objsize = 32768;
316 	margs_write.mtype = M_HAMMER2_CBUFFER;
317 
318 	margs_vop.objsize = sizeof(hammer2_xop_t);
319 	margs_vop.mtype = M_HAMMER2;
320 
321 	/*
322 	 * Note thaht for the XOPS cache we want backing store allocations
323 	 * to use M_ZERO.  This is not allowed in objcache_get() (to avoid
324 	 * confusion), so use the backing store function that does it.  This
325 	 * means that initial XOPS objects are zerod but REUSED objects are
326 	 * not.  So we are responsible for cleaning the object up sufficiently
327 	 * for our needs before objcache_put()ing it back (typically just the
328 	 * FIFO indices).
329 	 */
330 	cache_buffer_read = objcache_create(margs_read.mtype->ks_shortdesc,
331 				0, 1, NULL, NULL, NULL,
332 				objcache_malloc_alloc,
333 				objcache_malloc_free,
334 				&margs_read);
335 	cache_buffer_write = objcache_create(margs_write.mtype->ks_shortdesc,
336 				0, 1, NULL, NULL, NULL,
337 				objcache_malloc_alloc,
338 				objcache_malloc_free,
339 				&margs_write);
340 	cache_xops = objcache_create(margs_vop.mtype->ks_shortdesc,
341 				0, 1, NULL, NULL, NULL,
342 				objcache_malloc_alloc_zero,
343 				objcache_malloc_free,
344 				&margs_vop);
345 
346 
347 	lockinit(&hammer2_mntlk, "mntlk", 0, 0);
348 	TAILQ_INIT(&hammer2_mntlist);
349 	TAILQ_INIT(&hammer2_pfslist);
350 	TAILQ_INIT(&hammer2_spmplist);
351 
352 	hammer2_limit_dirty_chains = maxvnodes / 10;
353 	if (hammer2_limit_dirty_chains > HAMMER2_LIMIT_DIRTY_CHAINS)
354 		hammer2_limit_dirty_chains = HAMMER2_LIMIT_DIRTY_CHAINS;
355 	if (hammer2_limit_dirty_chains < 1000)
356 		hammer2_limit_dirty_chains = 1000;
357 
358 	hammer2_limit_dirty_inodes = maxvnodes / 25;
359 	if (hammer2_limit_dirty_inodes < 100)
360 		hammer2_limit_dirty_inodes = 100;
361 	if (hammer2_limit_dirty_inodes > HAMMER2_LIMIT_DIRTY_INODES)
362 		hammer2_limit_dirty_inodes = HAMMER2_LIMIT_DIRTY_INODES;
363 
364 	return (error);
365 }
366 
367 static
368 int
369 hammer2_vfs_uninit(struct vfsconf *vfsp __unused)
370 {
371 	objcache_destroy(cache_buffer_read);
372 	objcache_destroy(cache_buffer_write);
373 	objcache_destroy(cache_xops);
374 	return 0;
375 }
376 
377 /*
378  * Core PFS allocator.  Used to allocate or reference the pmp structure
379  * for PFS cluster mounts and the spmp structure for media (hmp) structures.
380  * The pmp can be passed in or loaded by this function using the chain and
381  * inode data.
382  *
383  * pmp->modify_tid tracks new modify_tid transaction ids for front-end
384  * transactions.  Note that synchronization does not use this field.
385  * (typically frontend operations and synchronization cannot run on the
386  * same PFS node at the same time).
387  *
388  * XXX check locking
389  */
390 hammer2_pfs_t *
391 hammer2_pfsalloc(hammer2_chain_t *chain,
392 		 const hammer2_inode_data_t *ripdata,
393 		 hammer2_tid_t modify_tid, hammer2_dev_t *force_local)
394 {
395 	hammer2_pfs_t *pmp;
396 	hammer2_inode_t *iroot;
397 	int count;
398 	int i;
399 	int j;
400 
401 	pmp = NULL;
402 
403 	/*
404 	 * Locate or create the PFS based on the cluster id.  If ripdata
405 	 * is NULL this is a spmp which is unique and is always allocated.
406 	 *
407 	 * If the device is mounted in local mode all PFSs are considered
408 	 * independent and not part of any cluster (for debugging only).
409 	 */
410 	if (ripdata) {
411 		TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
412 			if (force_local != pmp->force_local)
413 				continue;
414 			if (force_local == NULL &&
415 			    bcmp(&pmp->pfs_clid, &ripdata->meta.pfs_clid,
416 				 sizeof(pmp->pfs_clid)) == 0) {
417 					break;
418 			} else if (force_local && pmp->pfs_names[0] &&
419 			    strcmp(pmp->pfs_names[0], ripdata->filename) == 0) {
420 					break;
421 			}
422 		}
423 	}
424 
425 	if (pmp == NULL) {
426 		pmp = kmalloc(sizeof(*pmp), M_HAMMER2, M_WAITOK | M_ZERO);
427 		pmp->force_local = force_local;
428 		hammer2_trans_manage_init(pmp);
429 		kmalloc_create(&pmp->minode, "HAMMER2-inodes");
430 		kmalloc_create(&pmp->mmsg, "HAMMER2-pfsmsg");
431 		lockinit(&pmp->lock, "pfslk", 0, 0);
432 		lockinit(&pmp->lock_nlink, "h2nlink", 0, 0);
433 		spin_init(&pmp->inum_spin, "hm2pfsalloc_inum");
434 		spin_init(&pmp->xop_spin, "h2xop");
435 		spin_init(&pmp->lru_spin, "h2lru");
436 		RB_INIT(&pmp->inum_tree);
437 		TAILQ_INIT(&pmp->syncq);
438 		TAILQ_INIT(&pmp->depq);
439 		TAILQ_INIT(&pmp->lru_list);
440 		spin_init(&pmp->list_spin, "h2pfsalloc_list");
441 
442 		/*
443 		 * Save the last media transaction id for the flusher.  Set
444 		 * initial
445 		 */
446 		if (ripdata) {
447 			pmp->pfs_clid = ripdata->meta.pfs_clid;
448 			TAILQ_INSERT_TAIL(&hammer2_pfslist, pmp, mntentry);
449 		} else {
450 			pmp->flags |= HAMMER2_PMPF_SPMP;
451 			TAILQ_INSERT_TAIL(&hammer2_spmplist, pmp, mntentry);
452 		}
453 
454 		/*
455 		 * The synchronization thread may start too early, make
456 		 * sure it stays frozen until we are ready to let it go.
457 		 * XXX
458 		 */
459 		/*
460 		pmp->primary_thr.flags = HAMMER2_THREAD_FROZEN |
461 					 HAMMER2_THREAD_REMASTER;
462 		*/
463 	}
464 
465 	/*
466 	 * Create the PFS's root inode and any missing XOP helper threads.
467 	 */
468 	if ((iroot = pmp->iroot) == NULL) {
469 		iroot = hammer2_inode_get(pmp, NULL, 1, -1);
470 		if (ripdata)
471 			iroot->meta = ripdata->meta;
472 		pmp->iroot = iroot;
473 		hammer2_inode_ref(iroot);
474 		hammer2_inode_unlock(iroot);
475 	}
476 
477 	/*
478 	 * Stop here if no chain is passed in.
479 	 */
480 	if (chain == NULL)
481 		goto done;
482 
483 	/*
484 	 * When a chain is passed in we must add it to the PFS's root
485 	 * inode, update pmp->pfs_types[], and update the syncronization
486 	 * threads.
487 	 *
488 	 * When forcing local mode, mark the PFS as a MASTER regardless.
489 	 *
490 	 * At the moment empty spots can develop due to removals or failures.
491 	 * Ultimately we want to re-fill these spots but doing so might
492 	 * confused running code. XXX
493 	 */
494 	hammer2_inode_ref(iroot);
495 	hammer2_mtx_ex(&iroot->lock);
496 	j = iroot->cluster.nchains;
497 
498 	if (j == HAMMER2_MAXCLUSTER) {
499 		kprintf("hammer2_mount: cluster full!\n");
500 		/* XXX fatal error? */
501 	} else {
502 		KKASSERT(chain->pmp == NULL);
503 		chain->pmp = pmp;
504 		hammer2_chain_ref(chain);
505 		iroot->cluster.array[j].chain = chain;
506 		if (force_local)
507 			pmp->pfs_types[j] = HAMMER2_PFSTYPE_MASTER;
508 		else
509 			pmp->pfs_types[j] = ripdata->meta.pfs_type;
510 		pmp->pfs_names[j] = kstrdup(ripdata->filename, M_HAMMER2);
511 		pmp->pfs_hmps[j] = chain->hmp;
512 		hammer2_spin_ex(&pmp->inum_spin);
513 		pmp->pfs_iroot_blocksets[j] = chain->data->ipdata.u.blockset;
514 		hammer2_spin_unex(&pmp->inum_spin);
515 
516 		/*
517 		 * If the PFS is already mounted we must account
518 		 * for the mount_count here.
519 		 */
520 		if (pmp->mp)
521 			++chain->hmp->mount_count;
522 
523 		/*
524 		 * May have to fixup dirty chain tracking.  Previous
525 		 * pmp was NULL so nothing to undo.
526 		 */
527 		if (chain->flags & HAMMER2_CHAIN_MODIFIED)
528 			hammer2_pfs_memory_inc(pmp);
529 		++j;
530 	}
531 	iroot->cluster.nchains = j;
532 
533 	/*
534 	 * Update nmasters from any PFS inode which is part of the cluster.
535 	 * It is possible that this will result in a value which is too
536 	 * high.  MASTER PFSs are authoritative for pfs_nmasters and will
537 	 * override this value later on.
538 	 *
539 	 * (This informs us of masters that might not currently be
540 	 *  discoverable by this mount).
541 	 */
542 	if (ripdata && pmp->pfs_nmasters < ripdata->meta.pfs_nmasters) {
543 		pmp->pfs_nmasters = ripdata->meta.pfs_nmasters;
544 	}
545 
546 	/*
547 	 * Count visible masters.  Masters are usually added with
548 	 * ripdata->meta.pfs_nmasters set to 1.  This detects when there
549 	 * are more (XXX and must update the master inodes).
550 	 */
551 	count = 0;
552 	for (i = 0; i < iroot->cluster.nchains; ++i) {
553 		if (pmp->pfs_types[i] == HAMMER2_PFSTYPE_MASTER)
554 			++count;
555 	}
556 	if (pmp->pfs_nmasters < count)
557 		pmp->pfs_nmasters = count;
558 
559 	/*
560 	 * Create missing synchronization and support threads.
561 	 *
562 	 * Single-node masters (including snapshots) have nothing to
563 	 * synchronize and do not require this thread.
564 	 *
565 	 * Multi-node masters or any number of soft masters, slaves, copy,
566 	 * or other PFS types need the thread.
567 	 *
568 	 * Each thread is responsible for its particular cluster index.
569 	 * We use independent threads so stalls or mismatches related to
570 	 * any given target do not affect other targets.
571 	 */
572 	for (i = 0; i < iroot->cluster.nchains; ++i) {
573 		/*
574 		 * Single-node masters (including snapshots) have nothing
575 		 * to synchronize and will make direct xops support calls,
576 		 * thus they do not require this thread.
577 		 *
578 		 * Note that there can be thousands of snapshots.  We do not
579 		 * want to create thousands of threads.
580 		 */
581 		if (pmp->pfs_nmasters <= 1 &&
582 		    pmp->pfs_types[i] == HAMMER2_PFSTYPE_MASTER) {
583 			continue;
584 		}
585 
586 		/*
587 		 * Sync support thread
588 		 */
589 		if (pmp->sync_thrs[i].td == NULL) {
590 			hammer2_thr_create(&pmp->sync_thrs[i], pmp, NULL,
591 					   "h2nod", i, -1,
592 					   hammer2_primary_sync_thread);
593 		}
594 	}
595 
596 	/*
597 	 * Create missing Xop threads
598 	 *
599 	 * NOTE: We create helper threads for all mounted PFSs or any
600 	 *	 PFSs with 2+ nodes (so the sync thread can update them,
601 	 *	 even if not mounted).
602 	 */
603 	if (pmp->mp || iroot->cluster.nchains >= 2)
604 		hammer2_xop_helper_create(pmp);
605 
606 	hammer2_mtx_unlock(&iroot->lock);
607 	hammer2_inode_drop(iroot);
608 done:
609 	return pmp;
610 }
611 
612 /*
613  * Deallocate an element of a probed PFS.  If destroying and this is a
614  * MASTER, adjust nmasters.
615  *
616  * This function does not physically destroy the PFS element in its device
617  * under the super-root  (see hammer2_ioctl_pfs_delete()).
618  */
619 void
620 hammer2_pfsdealloc(hammer2_pfs_t *pmp, int clindex, int destroying)
621 {
622 	hammer2_inode_t *iroot;
623 	hammer2_chain_t *chain;
624 	int j;
625 
626 	/*
627 	 * Cleanup our reference on iroot.  iroot is (should) not be needed
628 	 * by the flush code.
629 	 */
630 	iroot = pmp->iroot;
631 	if (iroot) {
632 		/*
633 		 * Stop synchronizing
634 		 *
635 		 * XXX flush after acquiring the iroot lock.
636 		 * XXX clean out the cluster index from all inode structures.
637 		 */
638 		hammer2_thr_delete(&pmp->sync_thrs[clindex]);
639 
640 		/*
641 		 * Remove the cluster index from the group.  If destroying
642 		 * the PFS and this is a master, adjust pfs_nmasters.
643 		 */
644 		hammer2_mtx_ex(&iroot->lock);
645 		chain = iroot->cluster.array[clindex].chain;
646 		iroot->cluster.array[clindex].chain = NULL;
647 
648 		switch(pmp->pfs_types[clindex]) {
649 		case HAMMER2_PFSTYPE_MASTER:
650 			if (destroying && pmp->pfs_nmasters > 0)
651 				--pmp->pfs_nmasters;
652 			/* XXX adjust ripdata->meta.pfs_nmasters */
653 			break;
654 		default:
655 			break;
656 		}
657 		pmp->pfs_types[clindex] = HAMMER2_PFSTYPE_NONE;
658 
659 		hammer2_mtx_unlock(&iroot->lock);
660 
661 		/*
662 		 * Release the chain.
663 		 */
664 		if (chain) {
665 			atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
666 			hammer2_chain_drop(chain);
667 		}
668 
669 		/*
670 		 * Terminate all XOP threads for the cluster index.
671 		 */
672 		if (pmp->xop_groups) {
673 			for (j = 0; j < hammer2_xopgroups; ++j) {
674 				hammer2_thr_delete(
675 					&pmp->xop_groups[j].thrs[clindex]);
676 			}
677 		}
678 	}
679 }
680 
681 /*
682  * Destroy a PFS, typically only occurs after the last mount on a device
683  * has gone away.
684  */
685 static void
686 hammer2_pfsfree(hammer2_pfs_t *pmp)
687 {
688 	hammer2_inode_t *iroot;
689 	hammer2_chain_t *chain;
690 	int chains_still_present = 0;
691 	int i;
692 	int j;
693 
694 	/*
695 	 * Cleanup our reference on iroot.  iroot is (should) not be needed
696 	 * by the flush code.
697 	 */
698 	if (pmp->flags & HAMMER2_PMPF_SPMP)
699 		TAILQ_REMOVE(&hammer2_spmplist, pmp, mntentry);
700 	else
701 		TAILQ_REMOVE(&hammer2_pfslist, pmp, mntentry);
702 
703 	/*
704 	 * Cleanup chains remaining on LRU list.
705 	 */
706 	hammer2_spin_ex(&pmp->lru_spin);
707 	while ((chain = TAILQ_FIRST(&pmp->lru_list)) != NULL) {
708 		KKASSERT(chain->flags & HAMMER2_CHAIN_ONLRU);
709 		atomic_add_int(&pmp->lru_count, -1);
710 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
711 		TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
712 		hammer2_chain_ref(chain);
713 		hammer2_spin_unex(&pmp->lru_spin);
714 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
715 		hammer2_chain_drop(chain);
716 		hammer2_spin_ex(&pmp->lru_spin);
717 	}
718 	hammer2_spin_unex(&pmp->lru_spin);
719 
720 	/*
721 	 * Clean up iroot
722 	 */
723 	iroot = pmp->iroot;
724 	if (iroot) {
725 		for (i = 0; i < iroot->cluster.nchains; ++i) {
726 			hammer2_thr_delete(&pmp->sync_thrs[i]);
727 			if (pmp->xop_groups) {
728 				for (j = 0; j < hammer2_xopgroups; ++j)
729 					hammer2_thr_delete(
730 						&pmp->xop_groups[j].thrs[i]);
731 			}
732 			chain = iroot->cluster.array[i].chain;
733 			if (chain && !RB_EMPTY(&chain->core.rbtree)) {
734 				kprintf("hammer2: Warning pmp %p still "
735 					"has active chains\n", pmp);
736 				chains_still_present = 1;
737 			}
738 		}
739 #if REPORT_REFS_ERRORS
740 		if (iroot->refs != 1)
741 			kprintf("PMP->IROOT %p REFS WRONG %d\n",
742 				iroot, iroot->refs);
743 #else
744 		KKASSERT(iroot->refs == 1);
745 #endif
746 		/* ref for iroot */
747 		hammer2_inode_drop(iroot);
748 		pmp->iroot = NULL;
749 	}
750 
751 	/*
752 	 * Free remaining pmp resources
753 	 */
754 	if (chains_still_present) {
755 		kprintf("hammer2: cannot free pmp %p, still in use\n", pmp);
756 	} else {
757 		kmalloc_destroy(&pmp->mmsg);
758 		kmalloc_destroy(&pmp->minode);
759 		kfree(pmp, M_HAMMER2);
760 	}
761 }
762 
763 /*
764  * Remove all references to hmp from the pfs list.  Any PFS which becomes
765  * empty is terminated and freed.
766  *
767  * XXX inefficient.
768  */
769 static void
770 hammer2_pfsfree_scan(hammer2_dev_t *hmp, int which)
771 {
772 	hammer2_pfs_t *pmp;
773 	hammer2_inode_t *iroot;
774 	hammer2_chain_t *rchain;
775 	int i;
776 	int j;
777 	struct hammer2_pfslist *wlist;
778 
779 	if (which == 0)
780 		wlist = &hammer2_pfslist;
781 	else
782 		wlist = &hammer2_spmplist;
783 again:
784 	TAILQ_FOREACH(pmp, wlist, mntentry) {
785 		if ((iroot = pmp->iroot) == NULL)
786 			continue;
787 
788 		/*
789 		 * Determine if this PFS is affected.  If it is we must
790 		 * freeze all management threads and lock its iroot.
791 		 *
792 		 * Freezing a management thread forces it idle, operations
793 		 * in-progress will be aborted and it will have to start
794 		 * over again when unfrozen, or exit if told to exit.
795 		 */
796 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
797 			if (pmp->pfs_hmps[i] == hmp)
798 				break;
799 		}
800 		if (i == HAMMER2_MAXCLUSTER)
801 			continue;
802 
803 		hammer2_vfs_sync_pmp(pmp, MNT_WAIT);
804 
805 		/*
806 		 * Make sure all synchronization threads are locked
807 		 * down.
808 		 */
809 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
810 			if (pmp->pfs_hmps[i] == NULL)
811 				continue;
812 			hammer2_thr_freeze_async(&pmp->sync_thrs[i]);
813 			if (pmp->xop_groups) {
814 				for (j = 0; j < hammer2_xopgroups; ++j) {
815 					hammer2_thr_freeze_async(
816 						&pmp->xop_groups[j].thrs[i]);
817 				}
818 			}
819 		}
820 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
821 			if (pmp->pfs_hmps[i] == NULL)
822 				continue;
823 			hammer2_thr_freeze(&pmp->sync_thrs[i]);
824 			if (pmp->xop_groups) {
825 				for (j = 0; j < hammer2_xopgroups; ++j) {
826 					hammer2_thr_freeze(
827 						&pmp->xop_groups[j].thrs[i]);
828 				}
829 			}
830 		}
831 
832 		/*
833 		 * Lock the inode and clean out matching chains.
834 		 * Note that we cannot use hammer2_inode_lock_*()
835 		 * here because that would attempt to validate the
836 		 * cluster that we are in the middle of ripping
837 		 * apart.
838 		 *
839 		 * WARNING! We are working directly on the inodes
840 		 *	    embedded cluster.
841 		 */
842 		hammer2_mtx_ex(&iroot->lock);
843 
844 		/*
845 		 * Remove the chain from matching elements of the PFS.
846 		 */
847 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
848 			if (pmp->pfs_hmps[i] != hmp)
849 				continue;
850 			hammer2_thr_delete(&pmp->sync_thrs[i]);
851 			if (pmp->xop_groups) {
852 				for (j = 0; j < hammer2_xopgroups; ++j) {
853 					hammer2_thr_delete(
854 						&pmp->xop_groups[j].thrs[i]);
855 				}
856 			}
857 			rchain = iroot->cluster.array[i].chain;
858 			iroot->cluster.array[i].chain = NULL;
859 			pmp->pfs_types[i] = 0;
860 			if (pmp->pfs_names[i]) {
861 				kfree(pmp->pfs_names[i], M_HAMMER2);
862 				pmp->pfs_names[i] = NULL;
863 			}
864 			if (rchain) {
865 				hammer2_chain_drop(rchain);
866 				/* focus hint */
867 				if (iroot->cluster.focus == rchain)
868 					iroot->cluster.focus = NULL;
869 			}
870 			pmp->pfs_hmps[i] = NULL;
871 		}
872 		hammer2_mtx_unlock(&iroot->lock);
873 
874 		/*
875 		 * Cleanup trailing chains.  Gaps may remain.
876 		 */
877 		for (i = HAMMER2_MAXCLUSTER - 1; i >= 0; --i) {
878 			if (pmp->pfs_hmps[i])
879 				break;
880 		}
881 		iroot->cluster.nchains = i + 1;
882 
883 		/*
884 		 * If the PMP has no elements remaining we can destroy it.
885 		 * (this will transition management threads from frozen->exit).
886 		 */
887 		if (iroot->cluster.nchains == 0) {
888 			/*
889 			 * If this was the hmp's spmp, we need to clean
890 			 * a little more stuff out.
891 			 */
892 			if (hmp->spmp == pmp) {
893 				hmp->spmp = NULL;
894 				hmp->vchain.pmp = NULL;
895 				hmp->fchain.pmp = NULL;
896 			}
897 
898 			/*
899 			 * Free the pmp and restart the loop
900 			 */
901 			KKASSERT(TAILQ_EMPTY(&pmp->syncq));
902 			KKASSERT(TAILQ_EMPTY(&pmp->depq));
903 			hammer2_pfsfree(pmp);
904 			goto again;
905 		}
906 
907 		/*
908 		 * If elements still remain we need to set the REMASTER
909 		 * flag and unfreeze it.
910 		 */
911 		for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
912 			if (pmp->pfs_hmps[i] == NULL)
913 				continue;
914 			hammer2_thr_remaster(&pmp->sync_thrs[i]);
915 			hammer2_thr_unfreeze(&pmp->sync_thrs[i]);
916 			if (pmp->xop_groups) {
917 				for (j = 0; j < hammer2_xopgroups; ++j) {
918 					hammer2_thr_remaster(
919 						&pmp->xop_groups[j].thrs[i]);
920 					hammer2_thr_unfreeze(
921 						&pmp->xop_groups[j].thrs[i]);
922 				}
923 			}
924 		}
925 	}
926 }
927 
928 /*
929  * Mount or remount HAMMER2 fileystem from physical media
930  *
931  *	mountroot
932  *		mp		mount point structure
933  *		path		NULL
934  *		data		<unused>
935  *		cred		<unused>
936  *
937  *	mount
938  *		mp		mount point structure
939  *		path		path to mount point
940  *		data		pointer to argument structure in user space
941  *			volume	volume path (device@LABEL form)
942  *			hflags	user mount flags
943  *		cred		user credentials
944  *
945  * RETURNS:	0	Success
946  *		!0	error number
947  */
948 static
949 int
950 hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
951 		  struct ucred *cred)
952 {
953 	struct hammer2_mount_info info;
954 	hammer2_pfs_t *pmp;
955 	hammer2_pfs_t *spmp;
956 	hammer2_dev_t *hmp;
957 	hammer2_dev_t *force_local;
958 	hammer2_key_t key_next;
959 	hammer2_key_t key_dummy;
960 	hammer2_key_t lhc;
961 	struct vnode *devvp;
962 	struct nlookupdata nd;
963 	hammer2_chain_t *parent;
964 	hammer2_chain_t *chain;
965 	const hammer2_inode_data_t *ripdata;
966 	hammer2_blockref_t bref;
967 	struct file *fp;
968 	char devstr[MNAMELEN];
969 	size_t size;
970 	size_t done;
971 	char *dev;
972 	char *label;
973 	int ronly = 1;
974 	int error;
975 	int i;
976 
977 	hmp = NULL;
978 	pmp = NULL;
979 	dev = NULL;
980 	label = NULL;
981 	devvp = NULL;
982 
983 	if (path == NULL) {
984 		/*
985 		 * Root mount
986 		 */
987 		bzero(&info, sizeof(info));
988 		info.cluster_fd = -1;
989 		ksnprintf(devstr, sizeof(devstr), "%s",
990 			  mp->mnt_stat.f_mntfromname);
991 		kprintf("hammer2_mount: root '%s'\n", devstr);
992 		done = strlen(devstr) + 1;
993 	} else {
994 		/*
995 		 * Non-root mount or updating a mount
996 		 */
997 		error = copyin(data, &info, sizeof(info));
998 		if (error)
999 			return (error);
1000 
1001 		error = copyinstr(info.volume, devstr, MNAMELEN - 1, &done);
1002 		if (error)
1003 			return (error);
1004 		kprintf("hammer2_mount: '%s'\n", devstr);
1005 	}
1006 
1007 	/*
1008 	 * Extract device and label, automatically mount @BOOT, @ROOT, or @DATA
1009 	 * if no label specified, based on the partition id.  Error out if no
1010 	 * label or device (with partition id) is specified.  This is strictly
1011 	 * a convenience to match the default label created by newfs_hammer2,
1012 	 * our preference is that a label always be specified.
1013 	 *
1014 	 * NOTE: We allow 'mount @LABEL <blah>'... that is, a mount command
1015 	 *	 that does not specify a device, as long as some H2 label
1016 	 *	 has already been mounted from that device.  This makes
1017 	 *	 mounting snapshots a lot easier.
1018 	 */
1019 	dev = devstr;
1020 	label = strchr(devstr, '@');
1021 	if (label && ((label + 1) - dev) > done) {
1022 		kprintf("hammer2: mount: bad label %s/%zd\n",
1023 			devstr, done);
1024 		return (EINVAL);
1025 	}
1026 	if (label == NULL || label[1] == 0) {
1027 		char slice;
1028 
1029 		if (label == NULL)
1030 			label = devstr + strlen(devstr);
1031 		else
1032 			*label = '\0';		/* clean up trailing @ */
1033 
1034 		slice = label[-1];
1035 		switch(slice) {
1036 		case 'a':
1037 			label = "BOOT";
1038 			break;
1039 		case 'd':
1040 			label = "ROOT";
1041 			break;
1042 		default:
1043 			label = "DATA";
1044 			break;
1045 		}
1046 	} else {
1047 		*label = '\0';
1048 		label++;
1049 	}
1050 
1051 	kprintf("hammer2_mount: dev=\"%s\" label=\"%s\" rdonly=%d\n",
1052 		dev, label, (mp->mnt_flag & MNT_RDONLY));
1053 
1054 	if (mp->mnt_flag & MNT_UPDATE) {
1055 		/*
1056 		 * Update mount.  Note that pmp->iroot->cluster is
1057 		 * an inode-embedded cluster and thus cannot be
1058 		 * directly locked.
1059 		 *
1060 		 * XXX HAMMER2 needs to implement NFS export via
1061 		 *     mountctl.
1062 		 */
1063 		hammer2_cluster_t *cluster;
1064 
1065 		pmp = MPTOPMP(mp);
1066 		pmp->hflags = info.hflags;
1067 		cluster = &pmp->iroot->cluster;
1068 		for (i = 0; i < cluster->nchains; ++i) {
1069 			if (cluster->array[i].chain == NULL)
1070 				continue;
1071 			hmp = cluster->array[i].chain->hmp;
1072 			devvp = hmp->devvp;
1073 			error = hammer2_remount(hmp, mp, path,
1074 						devvp, cred);
1075 			if (error)
1076 				break;
1077 		}
1078 
1079 		return error;
1080 	}
1081 
1082 	/*
1083 	 * HMP device mount
1084 	 *
1085 	 * If a path is specified and dev is not an empty string, lookup the
1086 	 * name and verify that it referes to a block device.
1087 	 *
1088 	 * If a path is specified and dev is an empty string we fall through
1089 	 * and locate the label in the hmp search.
1090 	 */
1091 	if (path && *dev != 0) {
1092 		error = nlookup_init(&nd, dev, UIO_SYSSPACE, NLC_FOLLOW);
1093 		if (error == 0)
1094 			error = nlookup(&nd);
1095 		if (error == 0)
1096 			error = cache_vref(&nd.nl_nch, nd.nl_cred, &devvp);
1097 		nlookup_done(&nd);
1098 	} else if (path == NULL) {
1099 		/* root mount */
1100 		cdev_t cdev = kgetdiskbyname(dev);
1101 		error = bdevvp(cdev, &devvp);
1102 		if (error)
1103 			kprintf("hammer2: cannot find '%s'\n", dev);
1104 	} else {
1105 		/*
1106 		 * We will locate the hmp using the label in the hmp loop.
1107 		 */
1108 		error = 0;
1109 	}
1110 
1111 	/*
1112 	 * Make sure its a block device.  Do not check to see if it is
1113 	 * already mounted until we determine that its a fresh H2 device.
1114 	 */
1115 	if (error == 0 && devvp) {
1116 		vn_isdisk(devvp, &error);
1117 	}
1118 
1119 	/*
1120 	 * Determine if the device has already been mounted.  After this
1121 	 * check hmp will be non-NULL if we are doing the second or more
1122 	 * hammer2 mounts from the same device.
1123 	 */
1124 	lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1125 	if (devvp) {
1126 		/*
1127 		 * Match the device.  Due to the way devfs works,
1128 		 * we may not be able to directly match the vnode pointer,
1129 		 * so also check to see if the underlying device matches.
1130 		 */
1131 		TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
1132 			if (hmp->devvp == devvp)
1133 				break;
1134 			if (devvp->v_rdev &&
1135 			    hmp->devvp->v_rdev == devvp->v_rdev) {
1136 				break;
1137 			}
1138 		}
1139 
1140 		/*
1141 		 * If no match this may be a fresh H2 mount, make sure
1142 		 * the device is not mounted on anything else.
1143 		 */
1144 		if (hmp == NULL)
1145 			error = vfs_mountedon(devvp);
1146 	} else if (error == 0) {
1147 		/*
1148 		 * Match the label to a pmp already probed.
1149 		 */
1150 		TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
1151 			for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
1152 				if (pmp->pfs_names[i] &&
1153 				    strcmp(pmp->pfs_names[i], label) == 0) {
1154 					hmp = pmp->pfs_hmps[i];
1155 					break;
1156 				}
1157 			}
1158 			if (hmp)
1159 				break;
1160 		}
1161 		if (hmp == NULL)
1162 			error = ENOENT;
1163 	}
1164 
1165 	/*
1166 	 * Open the device if this isn't a secondary mount and construct
1167 	 * the H2 device mount (hmp).
1168 	 */
1169 	if (hmp == NULL) {
1170 		hammer2_chain_t *schain;
1171 		hammer2_xid_t xid;
1172 		hammer2_xop_head_t xop;
1173 
1174 		if (error == 0 && vcount(devvp) > 0) {
1175 			kprintf("Primary device already has references\n");
1176 			error = EBUSY;
1177 		}
1178 
1179 		/*
1180 		 * Now open the device
1181 		 */
1182 		if (error == 0) {
1183 			ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
1184 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1185 			error = vinvalbuf(devvp, V_SAVE, 0, 0);
1186 			if (error == 0) {
1187 				error = VOP_OPEN(devvp,
1188 					     (ronly ? FREAD : FREAD | FWRITE),
1189 					     FSCRED, NULL);
1190 			}
1191 			vn_unlock(devvp);
1192 		}
1193 		if (error && devvp) {
1194 			vrele(devvp);
1195 			devvp = NULL;
1196 		}
1197 		if (error) {
1198 			lockmgr(&hammer2_mntlk, LK_RELEASE);
1199 			return error;
1200 		}
1201 		hmp = kmalloc(sizeof(*hmp), M_HAMMER2, M_WAITOK | M_ZERO);
1202 		ksnprintf(hmp->devrepname, sizeof(hmp->devrepname), "%s", dev);
1203 		hmp->ronly = ronly;
1204 		hmp->devvp = devvp;
1205 		hmp->hflags = info.hflags & HMNT2_DEVFLAGS;
1206 		kmalloc_create(&hmp->mchain, "HAMMER2-chains");
1207 		TAILQ_INSERT_TAIL(&hammer2_mntlist, hmp, mntentry);
1208 		RB_INIT(&hmp->iotree);
1209 		spin_init(&hmp->io_spin, "h2mount_io");
1210 		spin_init(&hmp->list_spin, "h2mount_list");
1211 
1212 		lockinit(&hmp->vollk, "h2vol", 0, 0);
1213 		lockinit(&hmp->bulklk, "h2bulk", 0, 0);
1214 		lockinit(&hmp->bflock, "h2bflk", 0, 0);
1215 
1216 		/*
1217 		 * vchain setup. vchain.data is embedded.
1218 		 * vchain.refs is initialized and will never drop to 0.
1219 		 *
1220 		 * NOTE! voldata is not yet loaded.
1221 		 */
1222 		hmp->vchain.hmp = hmp;
1223 		hmp->vchain.refs = 1;
1224 		hmp->vchain.data = (void *)&hmp->voldata;
1225 		hmp->vchain.bref.type = HAMMER2_BREF_TYPE_VOLUME;
1226 		hmp->vchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
1227 		hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
1228 
1229 		hammer2_chain_core_init(&hmp->vchain);
1230 		/* hmp->vchain.u.xxx is left NULL */
1231 
1232 		/*
1233 		 * fchain setup.  fchain.data is embedded.
1234 		 * fchain.refs is initialized and will never drop to 0.
1235 		 *
1236 		 * The data is not used but needs to be initialized to
1237 		 * pass assertion muster.  We use this chain primarily
1238 		 * as a placeholder for the freemap's top-level RBTREE
1239 		 * so it does not interfere with the volume's topology
1240 		 * RBTREE.
1241 		 */
1242 		hmp->fchain.hmp = hmp;
1243 		hmp->fchain.refs = 1;
1244 		hmp->fchain.data = (void *)&hmp->voldata.freemap_blockset;
1245 		hmp->fchain.bref.type = HAMMER2_BREF_TYPE_FREEMAP;
1246 		hmp->fchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
1247 		hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
1248 		hmp->fchain.bref.methods =
1249 			HAMMER2_ENC_CHECK(HAMMER2_CHECK_FREEMAP) |
1250 			HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
1251 
1252 		hammer2_chain_core_init(&hmp->fchain);
1253 		/* hmp->fchain.u.xxx is left NULL */
1254 
1255 		/*
1256 		 * Install the volume header and initialize fields from
1257 		 * voldata.
1258 		 */
1259 		error = hammer2_install_volume_header(hmp);
1260 		if (error) {
1261 			hammer2_unmount_helper(mp, NULL, hmp);
1262 			lockmgr(&hammer2_mntlk, LK_RELEASE);
1263 			hammer2_vfs_unmount(mp, MNT_FORCE);
1264 			return error;
1265 		}
1266 
1267 		/*
1268 		 * Really important to get these right or the flush and
1269 		 * teardown code will get confused.
1270 		 */
1271 		hmp->spmp = hammer2_pfsalloc(NULL, NULL, 0, NULL);
1272 		spmp = hmp->spmp;
1273 		spmp->pfs_hmps[0] = hmp;
1274 
1275 		/*
1276 		 * Dummy-up vchain and fchain's modify_tid.  mirror_tid
1277 		 * is inherited from the volume header.
1278 		 */
1279 		xid = 0;
1280 		hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
1281 		hmp->vchain.bref.modify_tid = hmp->vchain.bref.mirror_tid;
1282 		hmp->vchain.pmp = spmp;
1283 		hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
1284 		hmp->fchain.bref.modify_tid = hmp->fchain.bref.mirror_tid;
1285 		hmp->fchain.pmp = spmp;
1286 
1287 		/*
1288 		 * First locate the super-root inode, which is key 0
1289 		 * relative to the volume header's blockset.
1290 		 *
1291 		 * Then locate the root inode by scanning the directory keyspace
1292 		 * represented by the label.
1293 		 */
1294 		parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
1295 		schain = hammer2_chain_lookup(&parent, &key_dummy,
1296 				      HAMMER2_SROOT_KEY, HAMMER2_SROOT_KEY,
1297 				      &error, 0);
1298 		hammer2_chain_lookup_done(parent);
1299 		if (schain == NULL) {
1300 			kprintf("hammer2_mount: invalid super-root\n");
1301 			hammer2_unmount_helper(mp, NULL, hmp);
1302 			lockmgr(&hammer2_mntlk, LK_RELEASE);
1303 			hammer2_vfs_unmount(mp, MNT_FORCE);
1304 			return EINVAL;
1305 		}
1306 		if (schain->error) {
1307 			kprintf("hammer2_mount: error %s reading super-root\n",
1308 				hammer2_error_str(schain->error));
1309 			hammer2_chain_unlock(schain);
1310 			hammer2_chain_drop(schain);
1311 			schain = NULL;
1312 			hammer2_unmount_helper(mp, NULL, hmp);
1313 			lockmgr(&hammer2_mntlk, LK_RELEASE);
1314 			hammer2_vfs_unmount(mp, MNT_FORCE);
1315 			return EINVAL;
1316 		}
1317 
1318 		/*
1319 		 * The super-root always uses an inode_tid of 1 when
1320 		 * creating PFSs.
1321 		 */
1322 		spmp->inode_tid = 1;
1323 		spmp->modify_tid = schain->bref.modify_tid + 1;
1324 
1325 		/*
1326 		 * Sanity-check schain's pmp and finish initialization.
1327 		 * Any chain belonging to the super-root topology should
1328 		 * have a NULL pmp (not even set to spmp).
1329 		 */
1330 		ripdata = &hammer2_chain_rdata(schain)->ipdata;
1331 		KKASSERT(schain->pmp == NULL);
1332 		spmp->pfs_clid = ripdata->meta.pfs_clid;
1333 
1334 		/*
1335 		 * Replace the dummy spmp->iroot with a real one.  It's
1336 		 * easier to just do a wholesale replacement than to try
1337 		 * to update the chain and fixup the iroot fields.
1338 		 *
1339 		 * The returned inode is locked with the supplied cluster.
1340 		 */
1341 		hammer2_dummy_xop_from_chain(&xop, schain);
1342 		hammer2_inode_drop(spmp->iroot);
1343 		spmp->iroot = NULL;
1344 		spmp->iroot = hammer2_inode_get(spmp, &xop, -1, -1);
1345 		spmp->spmp_hmp = hmp;
1346 		spmp->pfs_types[0] = ripdata->meta.pfs_type;
1347 		spmp->pfs_hmps[0] = hmp;
1348 		hammer2_inode_ref(spmp->iroot);
1349 		hammer2_inode_unlock(spmp->iroot);
1350 		hammer2_cluster_unlock(&xop.cluster);
1351 		hammer2_chain_drop(schain);
1352 		/* do not call hammer2_cluster_drop() on an embedded cluster */
1353 		schain = NULL;	/* now invalid */
1354 		/* leave spmp->iroot with one ref */
1355 
1356 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1357 			error = hammer2_recovery(hmp);
1358 			if (error == 0)
1359 				error |= hammer2_fixup_pfses(hmp);
1360 			/* XXX do something with error */
1361 		}
1362 		hammer2_update_pmps(hmp);
1363 		hammer2_iocom_init(hmp);
1364 		hammer2_bulkfree_init(hmp);
1365 
1366 		/*
1367 		 * Ref the cluster management messaging descriptor.  The mount
1368 		 * program deals with the other end of the communications pipe.
1369 		 *
1370 		 * Root mounts typically do not supply one.
1371 		 */
1372 		if (info.cluster_fd >= 0) {
1373 			fp = holdfp(curthread, info.cluster_fd, -1);
1374 			if (fp) {
1375 				hammer2_cluster_reconnect(hmp, fp);
1376 			} else {
1377 				kprintf("hammer2_mount: bad cluster_fd!\n");
1378 			}
1379 		}
1380 	} else {
1381 		spmp = hmp->spmp;
1382 		if (info.hflags & HMNT2_DEVFLAGS) {
1383 			kprintf("hammer2: Warning: mount flags pertaining "
1384 				"to the whole device may only be specified "
1385 				"on the first mount of the device: %08x\n",
1386 				info.hflags & HMNT2_DEVFLAGS);
1387 		}
1388 	}
1389 
1390 	/*
1391 	 * Force local mount (disassociate all PFSs from their clusters).
1392 	 * Used primarily for debugging.
1393 	 */
1394 	force_local = (hmp->hflags & HMNT2_LOCAL) ? hmp : NULL;
1395 
1396 	/*
1397 	 * Lookup the mount point under the media-localized super-root.
1398 	 * Scanning hammer2_pfslist doesn't help us because it represents
1399 	 * PFS cluster ids which can aggregate several named PFSs together.
1400 	 *
1401 	 * cluster->pmp will incorrectly point to spmp and must be fixed
1402 	 * up later on.
1403 	 */
1404 	hammer2_inode_lock(spmp->iroot, 0);
1405 	parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
1406 	lhc = hammer2_dirhash(label, strlen(label));
1407 	chain = hammer2_chain_lookup(&parent, &key_next,
1408 				     lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1409 				     &error, 0);
1410 	while (chain) {
1411 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1412 		    strcmp(label, chain->data->ipdata.filename) == 0) {
1413 			break;
1414 		}
1415 		chain = hammer2_chain_next(&parent, chain, &key_next,
1416 					    key_next,
1417 					    lhc + HAMMER2_DIRHASH_LOMASK,
1418 					    &error, 0);
1419 	}
1420 	if (parent) {
1421 		hammer2_chain_unlock(parent);
1422 		hammer2_chain_drop(parent);
1423 	}
1424 	hammer2_inode_unlock(spmp->iroot);
1425 
1426 	/*
1427 	 * PFS could not be found?
1428 	 */
1429 	if (chain == NULL) {
1430 		if (error)
1431 			kprintf("hammer2_mount: PFS label I/O error\n");
1432 		else
1433 			kprintf("hammer2_mount: PFS label not found\n");
1434 		hammer2_unmount_helper(mp, NULL, hmp);
1435 		lockmgr(&hammer2_mntlk, LK_RELEASE);
1436 		hammer2_vfs_unmount(mp, MNT_FORCE);
1437 
1438 		return EINVAL;
1439 	}
1440 
1441 	/*
1442 	 * Acquire the pmp structure (it should have already been allocated
1443 	 * via hammer2_update_pmps() so do not pass cluster in to add to
1444 	 * available chains).
1445 	 *
1446 	 * Check if the cluster has already been mounted.  A cluster can
1447 	 * only be mounted once, use null mounts to mount additional copies.
1448 	 */
1449 	if (chain->error) {
1450 		kprintf("hammer2_mount: PFS label I/O error\n");
1451 	} else {
1452 		ripdata = &chain->data->ipdata;
1453 		bref = chain->bref;
1454 		pmp = hammer2_pfsalloc(NULL, ripdata,
1455 				       bref.modify_tid, force_local);
1456 	}
1457 	hammer2_chain_unlock(chain);
1458 	hammer2_chain_drop(chain);
1459 
1460 	/*
1461 	 * Finish the mount
1462 	 */
1463         kprintf("hammer2_mount hmp=%p pmp=%p\n", hmp, pmp);
1464 
1465 	if (pmp->mp) {
1466 		kprintf("hammer2_mount: PFS already mounted!\n");
1467 		hammer2_unmount_helper(mp, NULL, hmp);
1468 		lockmgr(&hammer2_mntlk, LK_RELEASE);
1469 		hammer2_vfs_unmount(mp, MNT_FORCE);
1470 
1471 		return EBUSY;
1472 	}
1473 
1474 	pmp->hflags = info.hflags;
1475         mp->mnt_flag |= MNT_LOCAL;
1476         mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;   /* all entry pts are SMP */
1477         mp->mnt_kern_flag |= MNTK_THR_SYNC;     /* new vsyncscan semantics */
1478 
1479         /*
1480          * required mount structure initializations
1481          */
1482         mp->mnt_stat.f_iosize = HAMMER2_PBUFSIZE;
1483         mp->mnt_stat.f_bsize = HAMMER2_PBUFSIZE;
1484 
1485         mp->mnt_vstat.f_frsize = HAMMER2_PBUFSIZE;
1486         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1487 
1488         /*
1489          * Optional fields
1490          */
1491         mp->mnt_iosize_max = MAXPHYS;
1492 
1493 	/*
1494 	 * Connect up mount pointers.
1495 	 */
1496 	hammer2_mount_helper(mp, pmp);
1497 
1498         lockmgr(&hammer2_mntlk, LK_RELEASE);
1499 
1500 	/*
1501 	 * Finish setup
1502 	 */
1503 	vfs_getnewfsid(mp);
1504 	vfs_add_vnodeops(mp, &hammer2_vnode_vops, &mp->mnt_vn_norm_ops);
1505 	vfs_add_vnodeops(mp, &hammer2_spec_vops, &mp->mnt_vn_spec_ops);
1506 	vfs_add_vnodeops(mp, &hammer2_fifo_vops, &mp->mnt_vn_fifo_ops);
1507 
1508 	if (path) {
1509 		copyinstr(info.volume, mp->mnt_stat.f_mntfromname,
1510 			  MNAMELEN - 1, &size);
1511 		bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
1512 	} /* else root mount, already in there */
1513 
1514 	bzero(mp->mnt_stat.f_mntonname, sizeof(mp->mnt_stat.f_mntonname));
1515 	if (path) {
1516 		copyinstr(path, mp->mnt_stat.f_mntonname,
1517 			  sizeof(mp->mnt_stat.f_mntonname) - 1,
1518 			  &size);
1519 	} else {
1520 		/* root mount */
1521 		mp->mnt_stat.f_mntonname[0] = '/';
1522 	}
1523 
1524 	/*
1525 	 * Initial statfs to prime mnt_stat.
1526 	 */
1527 	hammer2_vfs_statfs(mp, &mp->mnt_stat, cred);
1528 
1529 	return 0;
1530 }
1531 
1532 /*
1533  * Scan PFSs under the super-root and create hammer2_pfs structures.
1534  */
1535 static
1536 void
1537 hammer2_update_pmps(hammer2_dev_t *hmp)
1538 {
1539 	const hammer2_inode_data_t *ripdata;
1540 	hammer2_chain_t *parent;
1541 	hammer2_chain_t *chain;
1542 	hammer2_blockref_t bref;
1543 	hammer2_dev_t *force_local;
1544 	hammer2_pfs_t *spmp;
1545 	hammer2_pfs_t *pmp;
1546 	hammer2_key_t key_next;
1547 	int error;
1548 
1549 	/*
1550 	 * Force local mount (disassociate all PFSs from their clusters).
1551 	 * Used primarily for debugging.
1552 	 */
1553 	force_local = (hmp->hflags & HMNT2_LOCAL) ? hmp : NULL;
1554 
1555 	/*
1556 	 * Lookup mount point under the media-localized super-root.
1557 	 *
1558 	 * cluster->pmp will incorrectly point to spmp and must be fixed
1559 	 * up later on.
1560 	 */
1561 	spmp = hmp->spmp;
1562 	hammer2_inode_lock(spmp->iroot, 0);
1563 	parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
1564 	chain = hammer2_chain_lookup(&parent, &key_next,
1565 					 HAMMER2_KEY_MIN, HAMMER2_KEY_MAX,
1566 					 &error, 0);
1567 	while (chain) {
1568 		if (chain->bref.type != HAMMER2_BREF_TYPE_INODE)
1569 			continue;
1570 		if (chain->error) {
1571 			kprintf("I/O error scanning PFS labels\n");
1572 		} else {
1573 			ripdata = &chain->data->ipdata;
1574 			bref = chain->bref;
1575 
1576 			pmp = hammer2_pfsalloc(chain, ripdata,
1577 					       bref.modify_tid, force_local);
1578 		}
1579 		chain = hammer2_chain_next(&parent, chain, &key_next,
1580 					   key_next, HAMMER2_KEY_MAX,
1581 					   &error, 0);
1582 	}
1583 	if (parent) {
1584 		hammer2_chain_unlock(parent);
1585 		hammer2_chain_drop(parent);
1586 	}
1587 	hammer2_inode_unlock(spmp->iroot);
1588 }
1589 
1590 static
1591 int
1592 hammer2_remount(hammer2_dev_t *hmp, struct mount *mp, char *path __unused,
1593 		struct vnode *devvp, struct ucred *cred)
1594 {
1595 	int error;
1596 
1597 	if (hmp->ronly && (mp->mnt_kern_flag & MNTK_WANTRDWR)) {
1598 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1599 		VOP_OPEN(devvp, FREAD | FWRITE, FSCRED, NULL);
1600 		vn_unlock(devvp);
1601 		error = hammer2_recovery(hmp);
1602 		if (error == 0)
1603 			error |= hammer2_fixup_pfses(hmp);
1604 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1605 		if (error == 0) {
1606 			VOP_CLOSE(devvp, FREAD, NULL);
1607 			hmp->ronly = 0;
1608 		} else {
1609 			VOP_CLOSE(devvp, FREAD | FWRITE, NULL);
1610 		}
1611 		vn_unlock(devvp);
1612 	} else {
1613 		error = 0;
1614 	}
1615 	return error;
1616 }
1617 
1618 static
1619 int
1620 hammer2_vfs_unmount(struct mount *mp, int mntflags)
1621 {
1622 	hammer2_pfs_t *pmp;
1623 	int flags;
1624 	int error = 0;
1625 
1626 	pmp = MPTOPMP(mp);
1627 
1628 	if (pmp == NULL)
1629 		return(0);
1630 
1631 	lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1632 
1633 	/*
1634 	 * If mount initialization proceeded far enough we must flush
1635 	 * its vnodes and sync the underlying mount points.  Three syncs
1636 	 * are required to fully flush the filesystem (freemap updates lag
1637 	 * by one flush, and one extra for safety).
1638 	 */
1639 	if (mntflags & MNT_FORCE)
1640 		flags = FORCECLOSE;
1641 	else
1642 		flags = 0;
1643 	if (pmp->iroot) {
1644 		error = vflush(mp, 0, flags);
1645 		if (error)
1646 			goto failed;
1647 		hammer2_vfs_sync(mp, MNT_WAIT);
1648 		hammer2_vfs_sync(mp, MNT_WAIT);
1649 		hammer2_vfs_sync(mp, MNT_WAIT);
1650 	}
1651 
1652 	/*
1653 	 * Cleanup the frontend support XOPS threads
1654 	 */
1655 	hammer2_xop_helper_cleanup(pmp);
1656 
1657 	if (pmp->mp)
1658 		hammer2_unmount_helper(mp, pmp, NULL);
1659 
1660 	error = 0;
1661 failed:
1662 	lockmgr(&hammer2_mntlk, LK_RELEASE);
1663 
1664 	return (error);
1665 }
1666 
1667 /*
1668  * Mount helper, hook the system mount into our PFS.
1669  * The mount lock is held.
1670  *
1671  * We must bump the mount_count on related devices for any
1672  * mounted PFSs.
1673  */
1674 static
1675 void
1676 hammer2_mount_helper(struct mount *mp, hammer2_pfs_t *pmp)
1677 {
1678 	hammer2_cluster_t *cluster;
1679 	hammer2_chain_t *rchain;
1680 	int i;
1681 
1682         mp->mnt_data = (qaddr_t)pmp;
1683 	pmp->mp = mp;
1684 
1685 	/*
1686 	 * After pmp->mp is set we have to adjust hmp->mount_count.
1687 	 */
1688 	cluster = &pmp->iroot->cluster;
1689 	for (i = 0; i < cluster->nchains; ++i) {
1690 		rchain = cluster->array[i].chain;
1691 		if (rchain == NULL)
1692 			continue;
1693 		++rchain->hmp->mount_count;
1694 	}
1695 
1696 	/*
1697 	 * Create missing Xop threads
1698 	 */
1699 	hammer2_xop_helper_create(pmp);
1700 }
1701 
1702 /*
1703  * Mount helper, unhook the system mount from our PFS.
1704  * The mount lock is held.
1705  *
1706  * If hmp is supplied a mount responsible for being the first to open
1707  * the block device failed and the block device and all PFSs using the
1708  * block device must be cleaned up.
1709  *
1710  * If pmp is supplied multiple devices might be backing the PFS and each
1711  * must be disconnected.  This might not be the last PFS using some of the
1712  * underlying devices.  Also, we have to adjust our hmp->mount_count
1713  * accounting for the devices backing the pmp which is now undergoing an
1714  * unmount.
1715  */
1716 static
1717 void
1718 hammer2_unmount_helper(struct mount *mp, hammer2_pfs_t *pmp, hammer2_dev_t *hmp)
1719 {
1720 	hammer2_cluster_t *cluster;
1721 	hammer2_chain_t *rchain;
1722 	struct vnode *devvp;
1723 	int dumpcnt;
1724 	int ronly;
1725 	int i;
1726 
1727 	/*
1728 	 * If no device supplied this is a high-level unmount and we have to
1729 	 * to disconnect the mount, adjust mount_count, and locate devices
1730 	 * that might now have no mounts.
1731 	 */
1732 	if (pmp) {
1733 		KKASSERT(hmp == NULL);
1734 		KKASSERT((void *)(intptr_t)mp->mnt_data == pmp);
1735 		pmp->mp = NULL;
1736 		mp->mnt_data = NULL;
1737 
1738 		/*
1739 		 * After pmp->mp is cleared we have to account for
1740 		 * mount_count.
1741 		 */
1742 		cluster = &pmp->iroot->cluster;
1743 		for (i = 0; i < cluster->nchains; ++i) {
1744 			rchain = cluster->array[i].chain;
1745 			if (rchain == NULL)
1746 				continue;
1747 			--rchain->hmp->mount_count;
1748 			/* scrapping hmp now may invalidate the pmp */
1749 		}
1750 again:
1751 		TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
1752 			if (hmp->mount_count == 0) {
1753 				hammer2_unmount_helper(NULL, NULL, hmp);
1754 				goto again;
1755 			}
1756 		}
1757 		return;
1758 	}
1759 
1760 	/*
1761 	 * Try to terminate the block device.  We can't terminate it if
1762 	 * there are still PFSs referencing it.
1763 	 */
1764 	if (hmp->mount_count)
1765 		return;
1766 
1767 	/*
1768 	 * Decomission the network before we start messing with the
1769 	 * device and PFS.
1770 	 */
1771 	hammer2_iocom_uninit(hmp);
1772 
1773 	hammer2_bulkfree_uninit(hmp);
1774 	hammer2_pfsfree_scan(hmp, 0);
1775 #if 0
1776 	hammer2_dev_exlock(hmp);	/* XXX order */
1777 #endif
1778 
1779 	/*
1780 	 * Cycle the volume data lock as a safety (probably not needed any
1781 	 * more).  To ensure everything is out we need to flush at least
1782 	 * three times.  (1) The running of the sideq can dirty the
1783 	 * filesystem, (2) A normal flush can dirty the freemap, and
1784 	 * (3) ensure that the freemap is fully synchronized.
1785 	 *
1786 	 * The next mount's recovery scan can clean everything up but we want
1787 	 * to leave the filesystem in a 100% clean state on a normal unmount.
1788 	 */
1789 #if 0
1790 	hammer2_voldata_lock(hmp);
1791 	hammer2_voldata_unlock(hmp);
1792 #endif
1793 
1794 	/*
1795 	 * Flush whatever is left.  Unmounted but modified PFS's might still
1796 	 * have some dirty chains on them.
1797 	 */
1798 	hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
1799 	hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
1800 
1801 	if (hmp->fchain.flags & HAMMER2_CHAIN_FLUSH_MASK) {
1802 		hammer2_voldata_modify(hmp);
1803 		hammer2_flush(&hmp->fchain, HAMMER2_FLUSH_TOP |
1804 					    HAMMER2_FLUSH_ALL);
1805 	}
1806 	hammer2_chain_unlock(&hmp->fchain);
1807 
1808 	if (hmp->vchain.flags & HAMMER2_CHAIN_FLUSH_MASK) {
1809 		hammer2_flush(&hmp->vchain, HAMMER2_FLUSH_TOP |
1810 					    HAMMER2_FLUSH_ALL);
1811 	}
1812 	hammer2_chain_unlock(&hmp->vchain);
1813 
1814 	if ((hmp->vchain.flags | hmp->fchain.flags) &
1815 	    HAMMER2_CHAIN_FLUSH_MASK) {
1816 		kprintf("hammer2_unmount: chains left over "
1817 			"after final sync\n");
1818 		kprintf("    vchain %08x\n", hmp->vchain.flags);
1819 		kprintf("    fchain %08x\n", hmp->fchain.flags);
1820 
1821 		if (hammer2_debug & 0x0010)
1822 			Debugger("entered debugger");
1823 	}
1824 
1825 	hammer2_pfsfree_scan(hmp, 1);
1826 
1827 	KKASSERT(hmp->spmp == NULL);
1828 
1829 	/*
1830 	 * Finish up with the device vnode
1831 	 */
1832 	if ((devvp = hmp->devvp) != NULL) {
1833 		ronly = hmp->ronly;
1834 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1835 		kprintf("hammer2_unmount(A): devvp %s rbdirty %p ronly=%d\n",
1836 			hmp->devrepname, RB_ROOT(&devvp->v_rbdirty_tree),
1837 			ronly);
1838 		vinvalbuf(devvp, (ronly ? 0 : V_SAVE), 0, 0);
1839 		kprintf("hammer2_unmount(B): devvp %s rbdirty %p\n",
1840 			hmp->devrepname, RB_ROOT(&devvp->v_rbdirty_tree));
1841 		hmp->devvp = NULL;
1842 		VOP_CLOSE(devvp, (ronly ? FREAD : FREAD|FWRITE), NULL);
1843 		vn_unlock(devvp);
1844 		vrele(devvp);
1845 		devvp = NULL;
1846 	}
1847 
1848 	/*
1849 	 * Clear vchain/fchain flags that might prevent final cleanup
1850 	 * of these chains.
1851 	 */
1852 	if (hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) {
1853 		atomic_add_long(&hammer2_count_modified_chains, -1);
1854 		atomic_clear_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1855 		hammer2_pfs_memory_wakeup(hmp->vchain.pmp);
1856 	}
1857 	if (hmp->vchain.flags & HAMMER2_CHAIN_UPDATE) {
1858 		atomic_clear_int(&hmp->vchain.flags, HAMMER2_CHAIN_UPDATE);
1859 	}
1860 
1861 	if (hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) {
1862 		atomic_add_long(&hammer2_count_modified_chains, -1);
1863 		atomic_clear_int(&hmp->fchain.flags, HAMMER2_CHAIN_MODIFIED);
1864 		hammer2_pfs_memory_wakeup(hmp->fchain.pmp);
1865 	}
1866 	if (hmp->fchain.flags & HAMMER2_CHAIN_UPDATE) {
1867 		atomic_clear_int(&hmp->fchain.flags, HAMMER2_CHAIN_UPDATE);
1868 	}
1869 
1870 	/*
1871 	 * Final drop of embedded freemap root chain to
1872 	 * clean up fchain.core (fchain structure is not
1873 	 * flagged ALLOCATED so it is cleaned out and then
1874 	 * left to rot).
1875 	 */
1876 	hammer2_chain_drop(&hmp->fchain);
1877 
1878 	/*
1879 	 * Final drop of embedded volume root chain to clean
1880 	 * up vchain.core (vchain structure is not flagged
1881 	 * ALLOCATED so it is cleaned out and then left to
1882 	 * rot).
1883 	 */
1884 	dumpcnt = 50;
1885 	hammer2_dump_chain(&hmp->vchain, 0, &dumpcnt, 'v', (u_int)-1);
1886 	dumpcnt = 50;
1887 	hammer2_dump_chain(&hmp->fchain, 0, &dumpcnt, 'f', (u_int)-1);
1888 #if 0
1889 	hammer2_dev_unlock(hmp);
1890 #endif
1891 	hammer2_chain_drop(&hmp->vchain);
1892 
1893 	hammer2_io_cleanup(hmp, &hmp->iotree);
1894 	if (hmp->iofree_count) {
1895 		kprintf("io_cleanup: %d I/O's left hanging\n",
1896 			hmp->iofree_count);
1897 	}
1898 
1899 	TAILQ_REMOVE(&hammer2_mntlist, hmp, mntentry);
1900 	kmalloc_destroy(&hmp->mchain);
1901 	kfree(hmp, M_HAMMER2);
1902 }
1903 
1904 int
1905 hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
1906 		 ino_t ino, struct vnode **vpp)
1907 {
1908 	hammer2_xop_lookup_t *xop;
1909 	hammer2_pfs_t *pmp;
1910 	hammer2_inode_t *ip;
1911 	hammer2_tid_t inum;
1912 	int error;
1913 
1914 	inum = (hammer2_tid_t)ino & HAMMER2_DIRHASH_USERMSK;
1915 
1916 	error = 0;
1917 	pmp = MPTOPMP(mp);
1918 
1919 	/*
1920 	 * Easy if we already have it cached
1921 	 */
1922 	ip = hammer2_inode_lookup(pmp, inum);
1923 	if (ip) {
1924 		hammer2_inode_lock(ip, HAMMER2_RESOLVE_SHARED);
1925 		*vpp = hammer2_igetv(ip, &error);
1926 		hammer2_inode_unlock(ip);
1927 		hammer2_inode_drop(ip);		/* from lookup */
1928 
1929 		return error;
1930 	}
1931 
1932 	/*
1933 	 * Otherwise we have to find the inode
1934 	 */
1935 	xop = hammer2_xop_alloc(pmp->iroot, 0);
1936 	xop->lhc = inum;
1937 	hammer2_xop_start(&xop->head, &hammer2_lookup_desc);
1938 	error = hammer2_xop_collect(&xop->head, 0);
1939 
1940 	if (error == 0)
1941 		ip = hammer2_inode_get(pmp, &xop->head, -1, -1);
1942 	hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1943 
1944 	if (ip) {
1945 		*vpp = hammer2_igetv(ip, &error);
1946 		hammer2_inode_unlock(ip);
1947 	} else {
1948 		*vpp = NULL;
1949 		error = ENOENT;
1950 	}
1951 	return (error);
1952 }
1953 
1954 static
1955 int
1956 hammer2_vfs_root(struct mount *mp, struct vnode **vpp)
1957 {
1958 	hammer2_pfs_t *pmp;
1959 	struct vnode *vp;
1960 	int error;
1961 
1962 	pmp = MPTOPMP(mp);
1963 	if (pmp->iroot == NULL) {
1964 		kprintf("hammer2 (%s): no root inode\n",
1965 			mp->mnt_stat.f_mntfromname);
1966 		*vpp = NULL;
1967 		return EINVAL;
1968 	}
1969 
1970 	error = 0;
1971 	hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
1972 
1973 	while (pmp->inode_tid == 0) {
1974 		hammer2_xop_ipcluster_t *xop;
1975 		const hammer2_inode_meta_t *meta;
1976 
1977 		xop = hammer2_xop_alloc(pmp->iroot, HAMMER2_XOP_MODIFYING);
1978 		hammer2_xop_start(&xop->head, &hammer2_ipcluster_desc);
1979 		error = hammer2_xop_collect(&xop->head, 0);
1980 
1981 		if (error == 0) {
1982 			meta = &hammer2_xop_gdata(&xop->head)->ipdata.meta;
1983 			pmp->iroot->meta = *meta;
1984 			pmp->inode_tid = meta->pfs_inum + 1;
1985 			hammer2_xop_pdata(&xop->head);
1986 			/* meta invalid */
1987 
1988 			if (pmp->inode_tid < HAMMER2_INODE_START)
1989 				pmp->inode_tid = HAMMER2_INODE_START;
1990 			pmp->modify_tid =
1991 				xop->head.cluster.focus->bref.modify_tid + 1;
1992 #if 0
1993 			kprintf("PFS: Starting inode %jd\n",
1994 				(intmax_t)pmp->inode_tid);
1995 			kprintf("PMP focus good set nextino=%ld mod=%016jx\n",
1996 				pmp->inode_tid, pmp->modify_tid);
1997 #endif
1998 			wakeup(&pmp->iroot);
1999 
2000 			hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
2001 
2002 			/*
2003 			 * Prime the mount info.
2004 			 */
2005 			hammer2_vfs_statfs(mp, &mp->mnt_stat, NULL);
2006 			break;
2007 		}
2008 
2009 		/*
2010 		 * Loop, try again
2011 		 */
2012 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
2013 		hammer2_inode_unlock(pmp->iroot);
2014 		error = tsleep(&pmp->iroot, PCATCH, "h2root", hz);
2015 		hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
2016 		if (error == EINTR)
2017 			break;
2018 	}
2019 
2020 	if (error) {
2021 		hammer2_inode_unlock(pmp->iroot);
2022 		*vpp = NULL;
2023 	} else {
2024 		vp = hammer2_igetv(pmp->iroot, &error);
2025 		hammer2_inode_unlock(pmp->iroot);
2026 		*vpp = vp;
2027 	}
2028 
2029 	return (error);
2030 }
2031 
2032 /*
2033  * Filesystem status
2034  *
2035  * XXX incorporate ipdata->meta.inode_quota and data_quota
2036  */
2037 static
2038 int
2039 hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred)
2040 {
2041 	hammer2_pfs_t *pmp;
2042 	hammer2_dev_t *hmp;
2043 	hammer2_blockref_t bref;
2044 	struct statfs tmp;
2045 	int i;
2046 
2047 	/*
2048 	 * NOTE: iroot might not have validated the cluster yet.
2049 	 */
2050 	pmp = MPTOPMP(mp);
2051 
2052 	bzero(&tmp, sizeof(tmp));
2053 
2054 	for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
2055 		hmp = pmp->pfs_hmps[i];
2056 		if (hmp == NULL)
2057 			continue;
2058 		if (pmp->iroot->cluster.array[i].chain)
2059 			bref = pmp->iroot->cluster.array[i].chain->bref;
2060 		else
2061 			bzero(&bref, sizeof(bref));
2062 
2063 		tmp.f_files = bref.embed.stats.inode_count;
2064 		tmp.f_ffree = 0;
2065 		tmp.f_blocks = hmp->voldata.allocator_size /
2066 			       mp->mnt_vstat.f_bsize;
2067 		tmp.f_bfree = hmp->voldata.allocator_free /
2068 			      mp->mnt_vstat.f_bsize;
2069 		tmp.f_bavail = tmp.f_bfree;
2070 
2071 		if (cred && cred->cr_uid != 0) {
2072 			uint64_t adj;
2073 
2074 			/* 5% */
2075 			adj = hmp->free_reserved / mp->mnt_vstat.f_bsize;
2076 			tmp.f_blocks -= adj;
2077 			tmp.f_bfree -= adj;
2078 			tmp.f_bavail -= adj;
2079 		}
2080 
2081 		mp->mnt_stat.f_blocks = tmp.f_blocks;
2082 		mp->mnt_stat.f_bfree = tmp.f_bfree;
2083 		mp->mnt_stat.f_bavail = tmp.f_bavail;
2084 		mp->mnt_stat.f_files = tmp.f_files;
2085 		mp->mnt_stat.f_ffree = tmp.f_ffree;
2086 
2087 		*sbp = mp->mnt_stat;
2088 	}
2089 	return (0);
2090 }
2091 
2092 static
2093 int
2094 hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp, struct ucred *cred)
2095 {
2096 	hammer2_pfs_t *pmp;
2097 	hammer2_dev_t *hmp;
2098 	hammer2_blockref_t bref;
2099 	struct statvfs tmp;
2100 	int i;
2101 
2102 	/*
2103 	 * NOTE: iroot might not have validated the cluster yet.
2104 	 */
2105 	pmp = MPTOPMP(mp);
2106 	bzero(&tmp, sizeof(tmp));
2107 
2108 	for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
2109 		hmp = pmp->pfs_hmps[i];
2110 		if (hmp == NULL)
2111 			continue;
2112 		if (pmp->iroot->cluster.array[i].chain)
2113 			bref = pmp->iroot->cluster.array[i].chain->bref;
2114 		else
2115 			bzero(&bref, sizeof(bref));
2116 
2117 		tmp.f_files = bref.embed.stats.inode_count;
2118 		tmp.f_ffree = 0;
2119 		tmp.f_blocks = hmp->voldata.allocator_size /
2120 			       mp->mnt_vstat.f_bsize;
2121 		tmp.f_bfree = hmp->voldata.allocator_free /
2122 			      mp->mnt_vstat.f_bsize;
2123 		tmp.f_bavail = tmp.f_bfree;
2124 
2125 		if (cred && cred->cr_uid != 0) {
2126 			uint64_t adj;
2127 
2128 			/* 5% */
2129 			adj = hmp->free_reserved / mp->mnt_vstat.f_bsize;
2130 			tmp.f_blocks -= adj;
2131 			tmp.f_bfree -= adj;
2132 			tmp.f_bavail -= adj;
2133 		}
2134 
2135 		mp->mnt_vstat.f_blocks = tmp.f_blocks;
2136 		mp->mnt_vstat.f_bfree = tmp.f_bfree;
2137 		mp->mnt_vstat.f_bavail = tmp.f_bavail;
2138 		mp->mnt_vstat.f_files = tmp.f_files;
2139 		mp->mnt_vstat.f_ffree = tmp.f_ffree;
2140 
2141 		*sbp = mp->mnt_vstat;
2142 	}
2143 	return (0);
2144 }
2145 
2146 /*
2147  * Mount-time recovery (RW mounts)
2148  *
2149  * Updates to the free block table are allowed to lag flushes by one
2150  * transaction.  In case of a crash, then on a fresh mount we must do an
2151  * incremental scan of the last committed transaction id and make sure that
2152  * all related blocks have been marked allocated.
2153  *
2154  * The super-root topology and each PFS has its own transaction id domain,
2155  * so we must track PFS boundary transitions.
2156  */
2157 struct hammer2_recovery_elm {
2158 	TAILQ_ENTRY(hammer2_recovery_elm) entry;
2159 	hammer2_chain_t *chain;
2160 	hammer2_tid_t sync_tid;
2161 };
2162 
2163 TAILQ_HEAD(hammer2_recovery_list, hammer2_recovery_elm);
2164 
2165 struct hammer2_recovery_info {
2166 	struct hammer2_recovery_list list;
2167 	hammer2_tid_t	mtid;
2168 	int	depth;
2169 };
2170 
2171 static int hammer2_recovery_scan(hammer2_dev_t *hmp,
2172 			hammer2_chain_t *parent,
2173 			struct hammer2_recovery_info *info,
2174 			hammer2_tid_t sync_tid);
2175 
2176 #define HAMMER2_RECOVERY_MAXDEPTH	10
2177 
2178 static
2179 int
2180 hammer2_recovery(hammer2_dev_t *hmp)
2181 {
2182 	struct hammer2_recovery_info info;
2183 	struct hammer2_recovery_elm *elm;
2184 	hammer2_chain_t *parent;
2185 	hammer2_tid_t sync_tid;
2186 	hammer2_tid_t mirror_tid;
2187 	int error;
2188 
2189 	hammer2_trans_init(hmp->spmp, 0);
2190 
2191 	sync_tid = hmp->voldata.freemap_tid;
2192 	mirror_tid = hmp->voldata.mirror_tid;
2193 
2194 	kprintf("hammer2 mount \"%s\": ", hmp->devrepname);
2195 	if (sync_tid >= mirror_tid) {
2196 		kprintf(" no recovery needed\n");
2197 	} else {
2198 		kprintf(" freemap recovery %016jx-%016jx\n",
2199 			sync_tid + 1, mirror_tid);
2200 	}
2201 
2202 	TAILQ_INIT(&info.list);
2203 	info.depth = 0;
2204 	parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
2205 	error = hammer2_recovery_scan(hmp, parent, &info, sync_tid);
2206 	hammer2_chain_lookup_done(parent);
2207 
2208 	while ((elm = TAILQ_FIRST(&info.list)) != NULL) {
2209 		TAILQ_REMOVE(&info.list, elm, entry);
2210 		parent = elm->chain;
2211 		sync_tid = elm->sync_tid;
2212 		kfree(elm, M_HAMMER2);
2213 
2214 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2215 		error |= hammer2_recovery_scan(hmp, parent, &info,
2216 					      hmp->voldata.freemap_tid);
2217 		hammer2_chain_unlock(parent);
2218 		hammer2_chain_drop(parent);	/* drop elm->chain ref */
2219 	}
2220 
2221 	hammer2_trans_done(hmp->spmp, 0);
2222 
2223 	return error;
2224 }
2225 
2226 static
2227 int
2228 hammer2_recovery_scan(hammer2_dev_t *hmp, hammer2_chain_t *parent,
2229 		      struct hammer2_recovery_info *info,
2230 		      hammer2_tid_t sync_tid)
2231 {
2232 	const hammer2_inode_data_t *ripdata;
2233 	hammer2_chain_t *chain;
2234 	hammer2_blockref_t bref;
2235 	int tmp_error;
2236 	int rup_error;
2237 	int error;
2238 	int first;
2239 
2240 	/*
2241 	 * Adjust freemap to ensure that the block(s) are marked allocated.
2242 	 */
2243 	if (parent->bref.type != HAMMER2_BREF_TYPE_VOLUME) {
2244 		hammer2_freemap_adjust(hmp, &parent->bref,
2245 				       HAMMER2_FREEMAP_DORECOVER);
2246 	}
2247 
2248 	/*
2249 	 * Check type for recursive scan
2250 	 */
2251 	switch(parent->bref.type) {
2252 	case HAMMER2_BREF_TYPE_VOLUME:
2253 		/* data already instantiated */
2254 		break;
2255 	case HAMMER2_BREF_TYPE_INODE:
2256 		/*
2257 		 * Must instantiate data for DIRECTDATA test and also
2258 		 * for recursion.
2259 		 */
2260 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2261 		ripdata = &hammer2_chain_rdata(parent)->ipdata;
2262 		if (ripdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2263 			/* not applicable to recovery scan */
2264 			hammer2_chain_unlock(parent);
2265 			return 0;
2266 		}
2267 		hammer2_chain_unlock(parent);
2268 		break;
2269 	case HAMMER2_BREF_TYPE_INDIRECT:
2270 		/*
2271 		 * Must instantiate data for recursion
2272 		 */
2273 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2274 		hammer2_chain_unlock(parent);
2275 		break;
2276 	case HAMMER2_BREF_TYPE_DIRENT:
2277 	case HAMMER2_BREF_TYPE_DATA:
2278 	case HAMMER2_BREF_TYPE_FREEMAP:
2279 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2280 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2281 		/* not applicable to recovery scan */
2282 		return 0;
2283 		break;
2284 	default:
2285 		return HAMMER2_ERROR_BADBREF;
2286 	}
2287 
2288 	/*
2289 	 * Defer operation if depth limit reached or if we are crossing a
2290 	 * PFS boundary.
2291 	 */
2292 	if (info->depth >= HAMMER2_RECOVERY_MAXDEPTH) {
2293 		struct hammer2_recovery_elm *elm;
2294 
2295 		elm = kmalloc(sizeof(*elm), M_HAMMER2, M_ZERO | M_WAITOK);
2296 		elm->chain = parent;
2297 		elm->sync_tid = sync_tid;
2298 		hammer2_chain_ref(parent);
2299 		TAILQ_INSERT_TAIL(&info->list, elm, entry);
2300 		/* unlocked by caller */
2301 
2302 		return(0);
2303 	}
2304 
2305 
2306 	/*
2307 	 * Recursive scan of the last flushed transaction only.  We are
2308 	 * doing this without pmp assignments so don't leave the chains
2309 	 * hanging around after we are done with them.
2310 	 *
2311 	 * error	Cumulative error this level only
2312 	 * rup_error	Cumulative error for recursion
2313 	 * tmp_error	Specific non-cumulative recursion error
2314 	 */
2315 	chain = NULL;
2316 	first = 1;
2317 	rup_error = 0;
2318 	error = 0;
2319 
2320 	for (;;) {
2321 		error |= hammer2_chain_scan(parent, &chain, &bref,
2322 					    &first,
2323 					    HAMMER2_LOOKUP_NODATA);
2324 
2325 		/*
2326 		 * Problem during scan or EOF
2327 		 */
2328 		if (error)
2329 			break;
2330 
2331 		/*
2332 		 * If this is a leaf
2333 		 */
2334 		if (chain == NULL) {
2335 			if (bref.mirror_tid > sync_tid) {
2336 				hammer2_freemap_adjust(hmp, &bref,
2337 						     HAMMER2_FREEMAP_DORECOVER);
2338 			}
2339 			continue;
2340 		}
2341 
2342 		/*
2343 		 * This may or may not be a recursive node.
2344 		 */
2345 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
2346 		if (bref.mirror_tid > sync_tid) {
2347 			++info->depth;
2348 			tmp_error = hammer2_recovery_scan(hmp, chain,
2349 							   info, sync_tid);
2350 			--info->depth;
2351 		} else {
2352 			tmp_error = 0;
2353 		}
2354 
2355 		/*
2356 		 * Flush the recovery at the PFS boundary to stage it for
2357 		 * the final flush of the super-root topology.
2358 		 */
2359 		if (tmp_error == 0 &&
2360 		    (bref.flags & HAMMER2_BREF_FLAG_PFSROOT) &&
2361 		    (chain->flags & HAMMER2_CHAIN_ONFLUSH)) {
2362 			hammer2_flush(chain, HAMMER2_FLUSH_TOP |
2363 					     HAMMER2_FLUSH_ALL);
2364 		}
2365 		rup_error |= tmp_error;
2366 	}
2367 	return ((error | rup_error) & ~HAMMER2_ERROR_EOF);
2368 }
2369 
2370 /*
2371  * This fixes up an error introduced in earlier H2 implementations where
2372  * moving a PFS inode into an indirect block wound up causing the
2373  * HAMMER2_BREF_FLAG_PFSROOT flag in the bref to get cleared.
2374  */
2375 static
2376 int
2377 hammer2_fixup_pfses(hammer2_dev_t *hmp)
2378 {
2379 	const hammer2_inode_data_t *ripdata;
2380 	hammer2_chain_t *parent;
2381 	hammer2_chain_t *chain;
2382 	hammer2_key_t key_next;
2383 	hammer2_pfs_t *spmp;
2384 	int error;
2385 
2386 	error = 0;
2387 
2388 	/*
2389 	 * Lookup mount point under the media-localized super-root.
2390 	 *
2391 	 * cluster->pmp will incorrectly point to spmp and must be fixed
2392 	 * up later on.
2393 	 */
2394 	spmp = hmp->spmp;
2395 	hammer2_inode_lock(spmp->iroot, 0);
2396 	parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
2397 	chain = hammer2_chain_lookup(&parent, &key_next,
2398 					 HAMMER2_KEY_MIN, HAMMER2_KEY_MAX,
2399 					 &error, 0);
2400 	while (chain) {
2401 		if (chain->bref.type != HAMMER2_BREF_TYPE_INODE)
2402 			continue;
2403 		if (chain->error) {
2404 			kprintf("I/O error scanning PFS labels\n");
2405 			error |= chain->error;
2406 		} else if ((chain->bref.flags &
2407 			    HAMMER2_BREF_FLAG_PFSROOT) == 0) {
2408 			int error2;
2409 
2410 			ripdata = &chain->data->ipdata;
2411 			hammer2_trans_init(hmp->spmp, 0);
2412 			error2 = hammer2_chain_modify(chain,
2413 						      chain->bref.modify_tid,
2414 						      0, 0);
2415 			if (error2 == 0) {
2416 				kprintf("hammer2: Correct mis-flagged PFS %s\n",
2417 					ripdata->filename);
2418 				chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2419 			} else {
2420 				error |= error2;
2421 			}
2422 			hammer2_flush(chain, HAMMER2_FLUSH_TOP |
2423 					     HAMMER2_FLUSH_ALL);
2424 			hammer2_trans_done(hmp->spmp, 0);
2425 		}
2426 		chain = hammer2_chain_next(&parent, chain, &key_next,
2427 					   key_next, HAMMER2_KEY_MAX,
2428 					   &error, 0);
2429 	}
2430 	if (parent) {
2431 		hammer2_chain_unlock(parent);
2432 		hammer2_chain_drop(parent);
2433 	}
2434 	hammer2_inode_unlock(spmp->iroot);
2435 
2436 	return error;
2437 }
2438 
2439 /*
2440  * Sync a mount point; this is called periodically on a per-mount basis from
2441  * the filesystem syncer, and whenever a user issues a sync.
2442  */
2443 int
2444 hammer2_vfs_sync(struct mount *mp, int waitfor)
2445 {
2446 	int error;
2447 
2448 	error = hammer2_vfs_sync_pmp(MPTOPMP(mp), waitfor);
2449 
2450 	return error;
2451 }
2452 
2453 /*
2454  * Because frontend operations lock vnodes before we get a chance to
2455  * lock the related inode, we can't just acquire a vnode lock without
2456  * risking a deadlock.  The frontend may be holding a vnode lock while
2457  * also blocked on our SYNCQ flag while trying to get the inode lock.
2458  *
2459  * To deal with this situation we can check the vnode lock situation
2460  * after locking the inode and perform a work-around.
2461  */
2462 int
2463 hammer2_vfs_sync_pmp(hammer2_pfs_t *pmp, int waitfor)
2464 {
2465 	struct mount *mp;
2466 	/*hammer2_xop_flush_t *xop;*/
2467 	/*struct hammer2_sync_info info;*/
2468 	hammer2_inode_t *ip;
2469 	hammer2_depend_t *depend;
2470 	hammer2_depend_t *depend_next;
2471 	struct vnode *vp;
2472 	uint32_t pass2;
2473 	int error;
2474 	int dorestart;
2475 
2476 	mp = pmp->mp;
2477 
2478 	/*
2479 	 * Move all inodes on sideq to syncq.  This will clear sideq.
2480 	 * This should represent all flushable inodes.  These inodes
2481 	 * will already have refs due to being on syncq or sideq.  We
2482 	 * must do this all at once with the spinlock held to ensure that
2483 	 * all inode dependencies are part of the same flush.
2484 	 *
2485 	 * We should be able to do this asynchronously from frontend
2486 	 * operations because we will be locking the inodes later on
2487 	 * to actually flush them, and that will partition any frontend
2488 	 * op using the same inode.  Either it has already locked the
2489 	 * inode and we will block, or it has not yet locked the inode
2490 	 * and it will block until we are finished flushing that inode.
2491 	 *
2492 	 * When restarting, only move the inodes flagged as PASS2 from
2493 	 * SIDEQ to SYNCQ.  PASS2 propagation by inode_lock4() and
2494 	 * inode_depend() are atomic with the spin-lock.
2495 	 */
2496 	hammer2_trans_init(pmp, HAMMER2_TRANS_ISFLUSH);
2497 #ifdef HAMMER2_DEBUG_SYNC
2498 	kprintf("FILESYSTEM SYNC BOUNDARY\n");
2499 #endif
2500 	dorestart = 0;
2501 
2502 	/*
2503 	 * Move inodes from depq to syncq, releasing the related
2504 	 * depend structures.
2505 	 */
2506 restart:
2507 #ifdef HAMMER2_DEBUG_SYNC
2508 	kprintf("FILESYSTEM SYNC RESTART (%d)\n", dorestart);
2509 #endif
2510 	hammer2_trans_setflags(pmp, 0/*HAMMER2_TRANS_COPYQ*/);
2511 	hammer2_trans_clearflags(pmp, HAMMER2_TRANS_RESCAN);
2512 
2513 	/*
2514 	 * Move inodes from depq to syncq.  When restarting, only depq's
2515 	 * marked pass2 are moved.
2516 	 */
2517 	hammer2_spin_ex(&pmp->list_spin);
2518 	depend_next = TAILQ_FIRST(&pmp->depq);
2519 
2520 	while ((depend = depend_next) != NULL) {
2521 		depend_next = TAILQ_NEXT(depend, entry);
2522 		if (dorestart && depend->pass2 == 0)
2523 			continue;
2524 		TAILQ_FOREACH(ip, &depend->sideq, entry) {
2525 			KKASSERT(ip->flags & HAMMER2_INODE_SIDEQ);
2526 			atomic_set_int(&ip->flags, HAMMER2_INODE_SYNCQ);
2527 			atomic_clear_int(&ip->flags, HAMMER2_INODE_SIDEQ);
2528 			ip->depend = NULL;
2529 		}
2530 		TAILQ_CONCAT(&pmp->syncq, &depend->sideq, entry);
2531 		pmp->sideq_count -= depend->count;
2532 		depend->count = 0;
2533 		depend->pass2 = 0;
2534 		TAILQ_REMOVE(&pmp->depq, depend, entry);
2535 	}
2536 
2537 	hammer2_spin_unex(&pmp->list_spin);
2538 	hammer2_trans_clearflags(pmp, /*HAMMER2_TRANS_COPYQ |*/
2539 				      HAMMER2_TRANS_WAITING);
2540 	dorestart = 0;
2541 
2542 	/*
2543 	 * sideq_count may have dropped enough to allow us to unstall
2544 	 * the frontend.
2545 	 */
2546 	hammer2_pfs_memory_inc(pmp);
2547 	hammer2_pfs_memory_wakeup(pmp);
2548 
2549 	/*
2550 	 * Now run through all inodes on syncq.
2551 	 *
2552 	 * Flush transactions only interlock with other flush transactions.
2553 	 * Any conflicting frontend operations will block on the inode, but
2554 	 * may hold a vnode lock while doing so.
2555 	 */
2556 	hammer2_spin_ex(&pmp->list_spin);
2557 	while ((ip = TAILQ_FIRST(&pmp->syncq)) != NULL) {
2558 		/*
2559 		 * Remove the inode from the SYNCQ, transfer the syncq ref
2560 		 * to us.  We must clear SYNCQ to allow any potential
2561 		 * front-end deadlock to proceed.  We must set PASS2 so
2562 		 * the dependency code knows what to do.
2563 		 */
2564 		pass2 = ip->flags;
2565 		cpu_ccfence();
2566 		if (atomic_cmpset_int(&ip->flags,
2567 			      pass2,
2568 			      (pass2 & ~(HAMMER2_INODE_SYNCQ |
2569 					 HAMMER2_INODE_SYNCQ_WAKEUP)) |
2570 			      HAMMER2_INODE_SYNCQ_PASS2) == 0) {
2571 			continue;
2572 		}
2573 		TAILQ_REMOVE(&pmp->syncq, ip, entry);
2574 		hammer2_spin_unex(&pmp->list_spin);
2575 		if (pass2 & HAMMER2_INODE_SYNCQ_WAKEUP)
2576 			wakeup(&ip->flags);
2577 
2578 		/*
2579 		 * Relock the inode, and we inherit a ref from the above.
2580 		 * We will check for a race after we acquire the vnode.
2581 		 */
2582 		hammer2_mtx_ex(&ip->lock);
2583 
2584 		/*
2585 		 * We need the vp in order to vfsync() dirty buffers, so if
2586 		 * one isn't attached we can skip it.
2587 		 *
2588 		 * Ordering the inode lock and then the vnode lock has the
2589 		 * potential to deadlock.  If we had left SYNCQ set that could
2590 		 * also deadlock us against the frontend even if we don't hold
2591 		 * any locks, but the latter is not a problem now since we
2592 		 * cleared it.  igetv will temporarily release the inode lock
2593 		 * in a safe manner to work-around the deadlock.
2594 		 *
2595 		 * Unfortunately it is still possible to deadlock when the
2596 		 * frontend obtains multiple inode locks, because all the
2597 		 * related vnodes are already locked (nor can the vnode locks
2598 		 * be released and reacquired without messing up RECLAIM and
2599 		 * INACTIVE sequencing).
2600 		 *
2601 		 * The solution for now is to move the vp back onto SIDEQ
2602 		 * and set dorestart, which will restart the flush after we
2603 		 * exhaust the current SYNCQ.  Note that additional
2604 		 * dependencies may build up, so we definitely need to move
2605 		 * the whole SIDEQ back to SYNCQ when we restart.
2606 		 */
2607 		vp = ip->vp;
2608 		if (vp) {
2609 			if (vget(vp, LK_EXCLUSIVE|LK_NOWAIT)) {
2610 				/*
2611 				 * Failed to get the vnode, requeue the inode
2612 				 * (PASS2 is already set so it will be found
2613 				 * again on the restart).
2614 				 *
2615 				 * Then unlock, possibly sleep, and retry
2616 				 * later.  We sleep if PASS2 was *previously*
2617 				 * set, before we set it again above.
2618 				 */
2619 				vp = NULL;
2620 				dorestart = 1;
2621 #ifdef HAMMER2_DEBUG_SYNC
2622 				kprintf("inum %ld (sync delayed by vnode)\n",
2623 					(long)ip->meta.inum);
2624 #endif
2625 				hammer2_inode_delayed_sideq(ip);
2626 
2627 				hammer2_mtx_unlock(&ip->lock);
2628 				hammer2_inode_drop(ip);
2629 
2630 				if (pass2 & HAMMER2_INODE_SYNCQ_PASS2) {
2631 					tsleep(&dorestart, 0, "h2syndel", 2);
2632 				}
2633 				hammer2_spin_ex(&pmp->list_spin);
2634 				continue;
2635 			}
2636 		} else {
2637 			vp = NULL;
2638 		}
2639 
2640 		/*
2641 		 * If the inode wound up on a SIDEQ again it will already be
2642 		 * prepped for another PASS2.  In this situation if we flush
2643 		 * it now we will just wind up flushing it again in the same
2644 		 * syncer run, so we might as well not flush it now.
2645 		 */
2646 		if (ip->flags & HAMMER2_INODE_SIDEQ) {
2647 			hammer2_mtx_unlock(&ip->lock);
2648 			hammer2_inode_drop(ip);
2649 			if (vp)
2650 				vput(vp);
2651 			dorestart = 1;
2652 			hammer2_spin_ex(&pmp->list_spin);
2653 			continue;
2654 		}
2655 
2656 		/*
2657 		 * Ok we have the inode exclusively locked and if vp is
2658 		 * not NULL that will also be exclusively locked.  Do the
2659 		 * meat of the flush.
2660 		 *
2661 		 * vp token needed for v_rbdirty_tree check / vclrisdirty
2662 		 * sequencing.  Though we hold the vnode exclusively so
2663 		 * we shouldn't need to hold the token also in this case.
2664 		 */
2665 		if (vp) {
2666 			vfsync(vp, MNT_WAIT, 1, NULL, NULL);
2667 			bio_track_wait(&vp->v_track_write, 0, 0); /* XXX */
2668 		}
2669 
2670 		/*
2671 		 * If the inode has not yet been inserted into the tree
2672 		 * we must do so.  Then sync and flush it.  The flush should
2673 		 * update the parent.
2674 		 */
2675 		if (ip->flags & HAMMER2_INODE_DELETING) {
2676 #ifdef HAMMER2_DEBUG_SYNC
2677 			kprintf("inum %ld destroy\n", (long)ip->meta.inum);
2678 #endif
2679 			hammer2_inode_chain_des(ip);
2680 			atomic_add_long(&hammer2_iod_inode_deletes, 1);
2681 		} else if (ip->flags & HAMMER2_INODE_CREATING) {
2682 #ifdef HAMMER2_DEBUG_SYNC
2683 			kprintf("inum %ld insert\n", (long)ip->meta.inum);
2684 #endif
2685 			hammer2_inode_chain_ins(ip);
2686 			atomic_add_long(&hammer2_iod_inode_creates, 1);
2687 		}
2688 #ifdef HAMMER2_DEBUG_SYNC
2689 		kprintf("inum %ld chain-sync\n", (long)ip->meta.inum);
2690 #endif
2691 
2692 		/*
2693 		 * Because I kinda messed up the design and index the inodes
2694 		 * under the root inode, along side the directory entries,
2695 		 * we can't flush the inode index under the iroot until the
2696 		 * end.  If we do it now we might miss effects created by
2697 		 * other inodes on the SYNCQ.
2698 		 *
2699 		 * Do a normal (non-FSSYNC) flush instead, which allows the
2700 		 * vnode code to work the same.  We don't want to force iroot
2701 		 * back onto the SIDEQ, and we also don't want the flush code
2702 		 * to update pfs_iroot_blocksets until the final flush later.
2703 		 *
2704 		 * XXX at the moment this will likely result in a double-flush
2705 		 * of the iroot chain.
2706 		 */
2707 		hammer2_inode_chain_sync(ip);
2708 		if (ip == pmp->iroot) {
2709 			hammer2_inode_chain_flush(ip, HAMMER2_XOP_INODE_STOP);
2710 		} else {
2711 			hammer2_inode_chain_flush(ip, HAMMER2_XOP_INODE_STOP |
2712 						      HAMMER2_XOP_FSSYNC);
2713 		}
2714 		if (vp) {
2715 			lwkt_gettoken(&vp->v_token);
2716 			if ((ip->flags & (HAMMER2_INODE_MODIFIED |
2717 					  HAMMER2_INODE_RESIZED |
2718 					  HAMMER2_INODE_DIRTYDATA)) == 0 &&
2719 			    RB_EMPTY(&vp->v_rbdirty_tree) &&
2720 			    !bio_track_active(&vp->v_track_write)) {
2721 				vclrisdirty(vp);
2722 			} else {
2723 				hammer2_inode_delayed_sideq(ip);
2724 			}
2725 			lwkt_reltoken(&vp->v_token);
2726 			vput(vp);
2727 			vp = NULL;	/* safety */
2728 		}
2729 		atomic_clear_int(&ip->flags, HAMMER2_INODE_SYNCQ_PASS2);
2730 		hammer2_inode_unlock(ip);	/* unlock+drop */
2731 		/* ip pointer invalid */
2732 
2733 		/*
2734 		 * If the inode got dirted after we dropped our locks,
2735 		 * it will have already been moved back to the SIDEQ.
2736 		 */
2737 		hammer2_spin_ex(&pmp->list_spin);
2738 	}
2739 	hammer2_spin_unex(&pmp->list_spin);
2740 	if (dorestart || (pmp->trans.flags & HAMMER2_TRANS_RESCAN)) {
2741 #ifdef HAMMER2_DEBUG_SYNC
2742 		kprintf("FILESYSTEM SYNC STAGE 1 RESTART\n");
2743 		/*tsleep(&dorestart, 0, "h2STG1-R", hz*20);*/
2744 #endif
2745 		dorestart = 1;
2746 		goto restart;
2747 	}
2748 #ifdef HAMMER2_DEBUG_SYNC
2749 	kprintf("FILESYSTEM SYNC STAGE 2 BEGIN\n");
2750 	/*tsleep(&dorestart, 0, "h2STG2", hz*20);*/
2751 #endif
2752 
2753 	/*
2754 	 * We have to flush the PFS root last, even if it does not appear to
2755 	 * be dirty, because all the inodes in the PFS are indexed under it.
2756 	 * The normal flushing of iroot above would only occur if directory
2757 	 * entries under the root were changed.
2758 	 *
2759 	 * Specifying VOLHDR will cause an additionl flush of hmp->spmp
2760 	 * for the media making up the cluster.
2761 	 */
2762 	if ((ip = pmp->iroot) != NULL) {
2763 		hammer2_inode_ref(ip);
2764 		hammer2_mtx_ex(&ip->lock);
2765 		hammer2_inode_chain_sync(ip);
2766 		hammer2_inode_chain_flush(ip, HAMMER2_XOP_INODE_STOP |
2767 					      HAMMER2_XOP_FSSYNC |
2768 					      HAMMER2_XOP_VOLHDR);
2769 		hammer2_inode_unlock(ip);	/* unlock+drop */
2770 	}
2771 #ifdef HAMMER2_DEBUG_SYNC
2772 	kprintf("FILESYSTEM SYNC STAGE 2 DONE\n");
2773 #endif
2774 
2775 	/*
2776 	 * device bioq sync
2777 	 */
2778 	hammer2_bioq_sync(pmp);
2779 
2780 #if 0
2781 	info.pass = 1;
2782 	info.waitfor = MNT_WAIT;
2783 	vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2784 
2785 	info.pass = 2;
2786 	info.waitfor = MNT_WAIT;
2787 	vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2788 #endif
2789 #if 0
2790 	/*
2791 	 * Generally speaking we now want to flush the media topology from
2792 	 * the iroot through to the inodes.  The flush stops at any inode
2793 	 * boundary, which allows the frontend to continue running concurrent
2794 	 * modifying operations on inodes (including kernel flushes of
2795 	 * buffers) without interfering with the main sync.
2796 	 *
2797 	 * Use the XOP interface to concurrently flush all nodes to
2798 	 * synchronize the PFSROOT subtopology to the media.  A standard
2799 	 * end-of-scan ENOENT error indicates cluster sufficiency.
2800 	 *
2801 	 * Note that this flush will not be visible on crash recovery until
2802 	 * we flush the super-root topology in the next loop.
2803 	 *
2804 	 * XXX For now wait for all flushes to complete.
2805 	 */
2806 	if (mp && (ip = pmp->iroot) != NULL) {
2807 		/*
2808 		 * If unmounting try to flush everything including any
2809 		 * sub-trees under inodes, just in case there is dangling
2810 		 * modified data, as a safety.  Otherwise just flush up to
2811 		 * the inodes in this stage.
2812 		 */
2813 		kprintf("MP & IROOT\n");
2814 #ifdef HAMMER2_DEBUG_SYNC
2815 		kprintf("FILESYSTEM SYNC STAGE 3 IROOT BEGIN\n");
2816 #endif
2817 		if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
2818 			xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING |
2819 						    HAMMER2_XOP_VOLHDR |
2820 						    HAMMER2_XOP_FSSYNC |
2821 						    HAMMER2_XOP_INODE_STOP);
2822 		} else {
2823 			xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING |
2824 						    HAMMER2_XOP_INODE_STOP |
2825 						    HAMMER2_XOP_VOLHDR |
2826 						    HAMMER2_XOP_FSSYNC |
2827 						    HAMMER2_XOP_INODE_STOP);
2828 		}
2829 		hammer2_xop_start(&xop->head, &hammer2_inode_flush_desc);
2830 		error = hammer2_xop_collect(&xop->head,
2831 					    HAMMER2_XOP_COLLECT_WAITALL);
2832 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
2833 #ifdef HAMMER2_DEBUG_SYNC
2834 		kprintf("FILESYSTEM SYNC STAGE 3 IROOT END\n");
2835 #endif
2836 		if (error == HAMMER2_ERROR_ENOENT)
2837 			error = 0;
2838 		else
2839 			error = hammer2_error_to_errno(error);
2840 	} else {
2841 		error = 0;
2842 	}
2843 #endif
2844 	error = 0;	/* XXX */
2845 	hammer2_trans_done(pmp, HAMMER2_TRANS_ISFLUSH);
2846 
2847 	return (error);
2848 }
2849 
2850 static
2851 int
2852 hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp)
2853 {
2854 	hammer2_inode_t *ip;
2855 
2856 	KKASSERT(MAXFIDSZ >= 16);
2857 	ip = VTOI(vp);
2858 	fhp->fid_len = offsetof(struct fid, fid_data[16]);
2859 	fhp->fid_ext = 0;
2860 	((hammer2_tid_t *)fhp->fid_data)[0] = ip->meta.inum;
2861 	((hammer2_tid_t *)fhp->fid_data)[1] = 0;
2862 
2863 	return 0;
2864 }
2865 
2866 static
2867 int
2868 hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
2869 	       struct fid *fhp, struct vnode **vpp)
2870 {
2871 	hammer2_pfs_t *pmp;
2872 	hammer2_tid_t inum;
2873 	int error;
2874 
2875 	pmp = MPTOPMP(mp);
2876 	inum = ((hammer2_tid_t *)fhp->fid_data)[0] & HAMMER2_DIRHASH_USERMSK;
2877 	if (vpp) {
2878 		if (inum == 1)
2879 			error = hammer2_vfs_root(mp, vpp);
2880 		else
2881 			error = hammer2_vfs_vget(mp, NULL, inum, vpp);
2882 	} else {
2883 		error = 0;
2884 	}
2885 	if (error)
2886 		kprintf("fhtovp: %016jx -> %p, %d\n", inum, *vpp, error);
2887 	return error;
2888 }
2889 
2890 static
2891 int
2892 hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
2893 		 int *exflagsp, struct ucred **credanonp)
2894 {
2895 	hammer2_pfs_t *pmp;
2896 	struct netcred *np;
2897 	int error;
2898 
2899 	pmp = MPTOPMP(mp);
2900 	np = vfs_export_lookup(mp, &pmp->export, nam);
2901 	if (np) {
2902 		*exflagsp = np->netc_exflags;
2903 		*credanonp = &np->netc_anon;
2904 		error = 0;
2905 	} else {
2906 		error = EACCES;
2907 	}
2908 	return error;
2909 }
2910 
2911 /*
2912  * Support code for hammer2_vfs_mount().  Read, verify, and install the volume
2913  * header into the HMP
2914  *
2915  * XXX read four volhdrs and use the one with the highest TID whos CRC
2916  *     matches.
2917  *
2918  * XXX check iCRCs.
2919  *
2920  * XXX For filesystems w/ less than 4 volhdrs, make sure to not write to
2921  *     nonexistant locations.
2922  *
2923  * XXX Record selected volhdr and ring updates to each of 4 volhdrs
2924  */
2925 static
2926 int
2927 hammer2_install_volume_header(hammer2_dev_t *hmp)
2928 {
2929 	hammer2_volume_data_t *vd;
2930 	struct buf *bp;
2931 	hammer2_crc32_t crc0, crc, bcrc0, bcrc;
2932 	int error_reported;
2933 	int error;
2934 	int valid;
2935 	int i;
2936 
2937 	error_reported = 0;
2938 	error = 0;
2939 	valid = 0;
2940 	bp = NULL;
2941 
2942 	/*
2943 	 * There are up to 4 copies of the volume header (syncs iterate
2944 	 * between them so there is no single master).  We don't trust the
2945 	 * volu_size field so we don't know precisely how large the filesystem
2946 	 * is, so depend on the OS to return an error if we go beyond the
2947 	 * block device's EOF.
2948 	 */
2949 	for (i = 0; i < HAMMER2_NUM_VOLHDRS; i++) {
2950 		error = bread(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2951 			      HAMMER2_VOLUME_BYTES, &bp);
2952 		if (error) {
2953 			brelse(bp);
2954 			bp = NULL;
2955 			continue;
2956 		}
2957 
2958 		vd = (struct hammer2_volume_data *) bp->b_data;
2959 		if ((vd->magic != HAMMER2_VOLUME_ID_HBO) &&
2960 		    (vd->magic != HAMMER2_VOLUME_ID_ABO)) {
2961 			brelse(bp);
2962 			bp = NULL;
2963 			continue;
2964 		}
2965 
2966 		if (vd->magic == HAMMER2_VOLUME_ID_ABO) {
2967 			/* XXX: Reversed-endianness filesystem */
2968 			kprintf("hammer2: reverse-endian filesystem detected");
2969 			brelse(bp);
2970 			bp = NULL;
2971 			continue;
2972 		}
2973 
2974 		crc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT0];
2975 		crc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC0_OFF,
2976 				      HAMMER2_VOLUME_ICRC0_SIZE);
2977 		bcrc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT1];
2978 		bcrc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC1_OFF,
2979 				       HAMMER2_VOLUME_ICRC1_SIZE);
2980 		if ((crc0 != crc) || (bcrc0 != bcrc)) {
2981 			kprintf("hammer2 volume header crc "
2982 				"mismatch copy #%d %08x/%08x\n",
2983 				i, crc0, crc);
2984 			error_reported = 1;
2985 			brelse(bp);
2986 			bp = NULL;
2987 			continue;
2988 		}
2989 		if (valid == 0 || hmp->voldata.mirror_tid < vd->mirror_tid) {
2990 			valid = 1;
2991 			hmp->voldata = *vd;
2992 			hmp->volhdrno = i;
2993 		}
2994 		brelse(bp);
2995 		bp = NULL;
2996 	}
2997 	if (valid) {
2998 		hmp->volsync = hmp->voldata;
2999 		hmp->free_reserved = hmp->voldata.allocator_size / 20;
3000 		error = 0;
3001 		if (error_reported || bootverbose || 1) { /* 1/DEBUG */
3002 			kprintf("hammer2: using volume header #%d\n",
3003 				hmp->volhdrno);
3004 		}
3005 	} else {
3006 		error = EINVAL;
3007 		kprintf("hammer2: no valid volume headers found!\n");
3008 	}
3009 	return (error);
3010 }
3011 
3012 /*
3013  * This handles hysteresis on regular file flushes.  Because the BIOs are
3014  * routed to a thread it is possible for an excessive number to build up
3015  * and cause long front-end stalls long before the runningbuffspace limit
3016  * is hit, so we implement hammer2_flush_pipe to control the
3017  * hysteresis.
3018  *
3019  * This is a particular problem when compression is used.
3020  */
3021 void
3022 hammer2_lwinprog_ref(hammer2_pfs_t *pmp)
3023 {
3024 	atomic_add_int(&pmp->count_lwinprog, 1);
3025 }
3026 
3027 void
3028 hammer2_lwinprog_drop(hammer2_pfs_t *pmp)
3029 {
3030 	int lwinprog;
3031 
3032 	lwinprog = atomic_fetchadd_int(&pmp->count_lwinprog, -1);
3033 	if ((lwinprog & HAMMER2_LWINPROG_WAITING) &&
3034 	    (lwinprog & HAMMER2_LWINPROG_MASK) <= hammer2_flush_pipe * 2 / 3) {
3035 		atomic_clear_int(&pmp->count_lwinprog,
3036 				 HAMMER2_LWINPROG_WAITING);
3037 		wakeup(&pmp->count_lwinprog);
3038 	}
3039 	if ((lwinprog & HAMMER2_LWINPROG_WAITING0) &&
3040 	    (lwinprog & HAMMER2_LWINPROG_MASK) <= 0) {
3041 		atomic_clear_int(&pmp->count_lwinprog,
3042 				 HAMMER2_LWINPROG_WAITING0);
3043 		wakeup(&pmp->count_lwinprog);
3044 	}
3045 }
3046 
3047 void
3048 hammer2_lwinprog_wait(hammer2_pfs_t *pmp, int flush_pipe)
3049 {
3050 	int lwinprog;
3051 	int lwflag = (flush_pipe) ? HAMMER2_LWINPROG_WAITING :
3052 				    HAMMER2_LWINPROG_WAITING0;
3053 
3054 	for (;;) {
3055 		lwinprog = pmp->count_lwinprog;
3056 		cpu_ccfence();
3057 		if ((lwinprog & HAMMER2_LWINPROG_MASK) <= flush_pipe)
3058 			break;
3059 		tsleep_interlock(&pmp->count_lwinprog, 0);
3060 		atomic_set_int(&pmp->count_lwinprog, lwflag);
3061 		lwinprog = pmp->count_lwinprog;
3062 		if ((lwinprog & HAMMER2_LWINPROG_MASK) <= flush_pipe)
3063 			break;
3064 		tsleep(&pmp->count_lwinprog, PINTERLOCKED, "h2wpipe", hz);
3065 	}
3066 }
3067 
3068 /*
3069  * It is possible for an excessive number of dirty chains or dirty inodes
3070  * to build up.  When this occurs we start an asynchronous filesystem sync.
3071  * If the level continues to build up, we stall, waiting for it to drop,
3072  * with some hysteresis.
3073  *
3074  * We limit the stall to two seconds per call.
3075  *
3076  * This relies on the kernel calling hammer2_vfs_modifying() prior to
3077  * obtaining any vnode locks before making a modifying VOP call.
3078  */
3079 static void
3080 hammer2_vfs_modifying(struct mount *mp)
3081 {
3082 	hammer2_pfs_memory_wait(MPTOPMP(mp));
3083 }
3084 
3085 /*
3086  * Initiate an asynchronous filesystem sync and, with hysteresis,
3087  * stall if the internal data structure count becomes too bloated.
3088  */
3089 void
3090 hammer2_pfs_memory_wait(hammer2_pfs_t *pmp)
3091 {
3092 	uint32_t waiting;
3093 	int loops;
3094 
3095 	if (pmp == NULL || pmp->mp == NULL)
3096 		return;
3097 
3098 	for (loops = 0; loops < 2; ++loops) {
3099 		waiting = pmp->inmem_dirty_chains & HAMMER2_DIRTYCHAIN_MASK;
3100 		cpu_ccfence();
3101 
3102 		/*
3103 		 * Start the syncer running at 1/2 the limit
3104 		 */
3105 		if (waiting > hammer2_limit_dirty_chains / 2 ||
3106 		    pmp->sideq_count > hammer2_limit_dirty_inodes / 2) {
3107 			trigger_syncer(pmp->mp);
3108 		}
3109 
3110 		/*
3111 		 * Stall at the limit waiting for the counts to drop.
3112 		 * This code will typically be woken up once the count
3113 		 * drops below 3/4 the limit, or in one second.
3114 		 */
3115 		if (waiting < hammer2_limit_dirty_chains &&
3116 		    pmp->sideq_count < hammer2_limit_dirty_inodes) {
3117 			break;
3118 		}
3119 		tsleep_interlock(&pmp->inmem_dirty_chains, 0);
3120 		atomic_set_int(&pmp->inmem_dirty_chains,
3121 			       HAMMER2_DIRTYCHAIN_WAITING);
3122 		if (waiting < hammer2_limit_dirty_chains &&
3123 		    pmp->sideq_count < hammer2_limit_dirty_inodes) {
3124 			break;
3125 		}
3126 		trigger_syncer(pmp->mp);
3127 		tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED, "h2memw", hz);
3128 #if 0
3129 		limit = pmp->mp->mnt_nvnodelistsize / 10;
3130 		if (limit < hammer2_limit_dirty_chains)
3131 			limit = hammer2_limit_dirty_chains;
3132 		if (limit < 1000)
3133 			limit = 1000;
3134 #endif
3135 	}
3136 }
3137 
3138 void
3139 hammer2_pfs_memory_inc(hammer2_pfs_t *pmp)
3140 {
3141 	if (pmp) {
3142 		atomic_add_int(&pmp->inmem_dirty_chains, 1);
3143 	}
3144 }
3145 
3146 void
3147 hammer2_pfs_memory_wakeup(hammer2_pfs_t *pmp)
3148 {
3149 	uint32_t waiting;
3150 
3151 	if (pmp) {
3152 		waiting = atomic_fetchadd_int(&pmp->inmem_dirty_chains, -1);
3153 		/* don't need --waiting to test flag */
3154 
3155 		if ((waiting & HAMMER2_DIRTYCHAIN_WAITING) &&
3156 		    (pmp->inmem_dirty_chains & HAMMER2_DIRTYCHAIN_MASK) <=
3157 		    hammer2_limit_dirty_chains * 2 / 3 &&
3158 		    pmp->sideq_count <= hammer2_limit_dirty_inodes * 2 / 3) {
3159 			atomic_clear_int(&pmp->inmem_dirty_chains,
3160 					 HAMMER2_DIRTYCHAIN_WAITING);
3161 			wakeup(&pmp->inmem_dirty_chains);
3162 		}
3163 	}
3164 }
3165 
3166 /*
3167  * Returns 0 if the filesystem has tons of free space
3168  * Returns 1 if the filesystem has less than 10% remaining
3169  * Returns 2 if the filesystem has less than 2%/5% (user/root) remaining.
3170  */
3171 int
3172 hammer2_vfs_enospace(hammer2_inode_t *ip, off_t bytes, struct ucred *cred)
3173 {
3174 	hammer2_pfs_t *pmp;
3175 	hammer2_dev_t *hmp;
3176 	hammer2_off_t free_reserved;
3177 	hammer2_off_t free_nominal;
3178 	int i;
3179 
3180 	pmp = ip->pmp;
3181 
3182 	if (pmp->free_ticks == 0 || pmp->free_ticks != ticks) {
3183 		free_reserved = HAMMER2_SEGSIZE;
3184 		free_nominal = 0x7FFFFFFFFFFFFFFFLLU;
3185 		for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
3186 			hmp = pmp->pfs_hmps[i];
3187 			if (hmp == NULL)
3188 				continue;
3189 			if (pmp->pfs_types[i] != HAMMER2_PFSTYPE_MASTER &&
3190 			    pmp->pfs_types[i] != HAMMER2_PFSTYPE_SOFT_MASTER)
3191 				continue;
3192 
3193 			if (free_nominal > hmp->voldata.allocator_free)
3194 				free_nominal = hmp->voldata.allocator_free;
3195 			if (free_reserved < hmp->free_reserved)
3196 				free_reserved = hmp->free_reserved;
3197 		}
3198 
3199 		/*
3200 		 * SMP races ok
3201 		 */
3202 		pmp->free_reserved = free_reserved;
3203 		pmp->free_nominal = free_nominal;
3204 		pmp->free_ticks = ticks;
3205 	} else {
3206 		free_reserved = pmp->free_reserved;
3207 		free_nominal = pmp->free_nominal;
3208 	}
3209 	if (cred && cred->cr_uid != 0) {
3210 		if ((int64_t)(free_nominal - bytes) <
3211 		    (int64_t)free_reserved) {
3212 			return 2;
3213 		}
3214 	} else {
3215 		if ((int64_t)(free_nominal - bytes) <
3216 		    (int64_t)free_reserved / 2) {
3217 			return 2;
3218 		}
3219 	}
3220 	if ((int64_t)(free_nominal - bytes) < (int64_t)free_reserved * 2)
3221 		return 1;
3222 	return 0;
3223 }
3224 
3225 /*
3226  * Debugging
3227  */
3228 void
3229 hammer2_dump_chain(hammer2_chain_t *chain, int tab, int *countp, char pfx,
3230 		   u_int flags)
3231 {
3232 	hammer2_chain_t *scan;
3233 	hammer2_chain_t *parent;
3234 
3235 	--*countp;
3236 	if (*countp == 0) {
3237 		kprintf("%*.*s...\n", tab, tab, "");
3238 		return;
3239 	}
3240 	if (*countp < 0)
3241 		return;
3242 	kprintf("%*.*s%c-chain %p.%d %016jx/%d mir=%016jx\n",
3243 		tab, tab, "", pfx,
3244 		chain, chain->bref.type,
3245 		chain->bref.key, chain->bref.keybits,
3246 		chain->bref.mirror_tid);
3247 
3248 	kprintf("%*.*s      [%08x] (%s) refs=%d",
3249 		tab, tab, "",
3250 		chain->flags,
3251 		((chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
3252 		chain->data) ?  (char *)chain->data->ipdata.filename : "?"),
3253 		chain->refs);
3254 
3255 	parent = chain->parent;
3256 	if (parent)
3257 		kprintf("\n%*.*s      p=%p [pflags %08x prefs %d",
3258 			tab, tab, "",
3259 			parent, parent->flags, parent->refs);
3260 	if (RB_EMPTY(&chain->core.rbtree)) {
3261 		kprintf("\n");
3262 	} else {
3263 		kprintf(" {\n");
3264 		RB_FOREACH(scan, hammer2_chain_tree, &chain->core.rbtree) {
3265 			if ((scan->flags & flags) || flags == (u_int)-1) {
3266 				hammer2_dump_chain(scan, tab + 4, countp, 'a',
3267 						   flags);
3268 			}
3269 		}
3270 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE && chain->data)
3271 			kprintf("%*.*s}(%s)\n", tab, tab, "",
3272 				chain->data->ipdata.filename);
3273 		else
3274 			kprintf("%*.*s}\n", tab, tab, "");
3275 	}
3276 }
3277