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