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