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