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