xref: /dflybsd-src/sys/vfs/hammer2/hammer2_vfsops.c (revision e19e5bbc20dd1d64f1833c5d0ac7a605c8e9bfa0)
1 /*
2  * Copyright (c) 2011-2014 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * by Daniel Flores (GSOC 2013 - mentored by Matthew Dillon, compression)
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/nlookup.h>
39 #include <sys/vnode.h>
40 #include <sys/mount.h>
41 #include <sys/fcntl.h>
42 #include <sys/buf.h>
43 #include <sys/uuid.h>
44 #include <sys/vfsops.h>
45 #include <sys/sysctl.h>
46 #include <sys/socket.h>
47 #include <sys/objcache.h>
48 
49 #include <sys/proc.h>
50 #include <sys/namei.h>
51 #include <sys/mountctl.h>
52 #include <sys/dirent.h>
53 #include <sys/uio.h>
54 
55 #include <sys/mutex.h>
56 #include <sys/mutex2.h>
57 
58 #include "hammer2.h"
59 #include "hammer2_disk.h"
60 #include "hammer2_mount.h"
61 
62 #include "hammer2.h"
63 #include "hammer2_lz4.h"
64 
65 #include "zlib/hammer2_zlib.h"
66 
67 #define REPORT_REFS_ERRORS 1	/* XXX remove me */
68 
69 MALLOC_DEFINE(M_OBJCACHE, "objcache", "Object Cache");
70 
71 struct hammer2_sync_info {
72 	hammer2_trans_t trans;
73 	int error;
74 	int waitfor;
75 };
76 
77 TAILQ_HEAD(hammer2_mntlist, hammer2_mount);
78 TAILQ_HEAD(hammer2_pfslist, hammer2_pfsmount);
79 static struct hammer2_mntlist hammer2_mntlist;
80 static struct hammer2_pfslist hammer2_pfslist;
81 static struct lock hammer2_mntlk;
82 
83 int hammer2_debug;
84 int hammer2_cluster_enable = 1;
85 int hammer2_hardlink_enable = 1;
86 int hammer2_flush_pipe = 100;
87 int hammer2_synchronous_flush = 1;
88 int hammer2_dio_count;
89 long hammer2_limit_dirty_chains;
90 long hammer2_iod_file_read;
91 long hammer2_iod_meta_read;
92 long hammer2_iod_indr_read;
93 long hammer2_iod_fmap_read;
94 long hammer2_iod_volu_read;
95 long hammer2_iod_file_write;
96 long hammer2_iod_meta_write;
97 long hammer2_iod_indr_write;
98 long hammer2_iod_fmap_write;
99 long hammer2_iod_volu_write;
100 long hammer2_ioa_file_read;
101 long hammer2_ioa_meta_read;
102 long hammer2_ioa_indr_read;
103 long hammer2_ioa_fmap_read;
104 long hammer2_ioa_volu_read;
105 long hammer2_ioa_fmap_write;
106 long hammer2_ioa_file_write;
107 long hammer2_ioa_meta_write;
108 long hammer2_ioa_indr_write;
109 long hammer2_ioa_volu_write;
110 
111 MALLOC_DECLARE(C_BUFFER);
112 MALLOC_DEFINE(C_BUFFER, "compbuffer", "Buffer used for compression.");
113 
114 MALLOC_DECLARE(D_BUFFER);
115 MALLOC_DEFINE(D_BUFFER, "decompbuffer", "Buffer used for decompression.");
116 
117 SYSCTL_NODE(_vfs, OID_AUTO, hammer2, CTLFLAG_RW, 0, "HAMMER2 filesystem");
118 
119 SYSCTL_INT(_vfs_hammer2, OID_AUTO, debug, CTLFLAG_RW,
120 	   &hammer2_debug, 0, "");
121 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_enable, CTLFLAG_RW,
122 	   &hammer2_cluster_enable, 0, "");
123 SYSCTL_INT(_vfs_hammer2, OID_AUTO, hardlink_enable, CTLFLAG_RW,
124 	   &hammer2_hardlink_enable, 0, "");
125 SYSCTL_INT(_vfs_hammer2, OID_AUTO, flush_pipe, CTLFLAG_RW,
126 	   &hammer2_flush_pipe, 0, "");
127 SYSCTL_INT(_vfs_hammer2, OID_AUTO, synchronous_flush, CTLFLAG_RW,
128 	   &hammer2_synchronous_flush, 0, "");
129 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, limit_dirty_chains, CTLFLAG_RW,
130 	   &hammer2_limit_dirty_chains, 0, "");
131 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dio_count, CTLFLAG_RD,
132 	   &hammer2_dio_count, 0, "");
133 
134 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_read, CTLFLAG_RW,
135 	   &hammer2_iod_file_read, 0, "");
136 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_read, CTLFLAG_RW,
137 	   &hammer2_iod_meta_read, 0, "");
138 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_read, CTLFLAG_RW,
139 	   &hammer2_iod_indr_read, 0, "");
140 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_read, CTLFLAG_RW,
141 	   &hammer2_iod_fmap_read, 0, "");
142 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_read, CTLFLAG_RW,
143 	   &hammer2_iod_volu_read, 0, "");
144 
145 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_write, CTLFLAG_RW,
146 	   &hammer2_iod_file_write, 0, "");
147 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_write, CTLFLAG_RW,
148 	   &hammer2_iod_meta_write, 0, "");
149 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_write, CTLFLAG_RW,
150 	   &hammer2_iod_indr_write, 0, "");
151 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_write, CTLFLAG_RW,
152 	   &hammer2_iod_fmap_write, 0, "");
153 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_write, CTLFLAG_RW,
154 	   &hammer2_iod_volu_write, 0, "");
155 
156 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_file_read, CTLFLAG_RW,
157 	   &hammer2_ioa_file_read, 0, "");
158 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_meta_read, CTLFLAG_RW,
159 	   &hammer2_ioa_meta_read, 0, "");
160 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_indr_read, CTLFLAG_RW,
161 	   &hammer2_ioa_indr_read, 0, "");
162 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_fmap_read, CTLFLAG_RW,
163 	   &hammer2_ioa_fmap_read, 0, "");
164 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_volu_read, CTLFLAG_RW,
165 	   &hammer2_ioa_volu_read, 0, "");
166 
167 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_file_write, CTLFLAG_RW,
168 	   &hammer2_ioa_file_write, 0, "");
169 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_meta_write, CTLFLAG_RW,
170 	   &hammer2_ioa_meta_write, 0, "");
171 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_indr_write, CTLFLAG_RW,
172 	   &hammer2_ioa_indr_write, 0, "");
173 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_fmap_write, CTLFLAG_RW,
174 	   &hammer2_ioa_fmap_write, 0, "");
175 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_volu_write, CTLFLAG_RW,
176 	   &hammer2_ioa_volu_write, 0, "");
177 
178 static int hammer2_vfs_init(struct vfsconf *conf);
179 static int hammer2_vfs_uninit(struct vfsconf *vfsp);
180 static int hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
181 				struct ucred *cred);
182 static int hammer2_remount(hammer2_mount_t *, struct mount *, char *,
183 				struct vnode *, struct ucred *);
184 static int hammer2_recovery(hammer2_mount_t *hmp);
185 static int hammer2_vfs_unmount(struct mount *mp, int mntflags);
186 static int hammer2_vfs_root(struct mount *mp, struct vnode **vpp);
187 static int hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp,
188 				struct ucred *cred);
189 static int hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp,
190 				struct ucred *cred);
191 static int hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
192 				ino_t ino, struct vnode **vpp);
193 static int hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
194 				struct fid *fhp, struct vnode **vpp);
195 static int hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp);
196 static int hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
197 				int *exflagsp, struct ucred **credanonp);
198 
199 static int hammer2_install_volume_header(hammer2_mount_t *hmp);
200 static int hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data);
201 
202 static void hammer2_write_thread(void *arg);
203 
204 static void hammer2_vfs_unmount_hmp1(struct mount *mp, hammer2_mount_t *hmp);
205 static void hammer2_vfs_unmount_hmp2(struct mount *mp, hammer2_mount_t *hmp);
206 
207 /*
208  * Functions for compression in threads,
209  * from hammer2_vnops.c
210  */
211 static void hammer2_write_file_core(struct buf *bp, hammer2_trans_t *trans,
212 				hammer2_inode_t *ip,
213 				hammer2_inode_data_t *ipdata,
214 				hammer2_cluster_t *cparent,
215 				hammer2_key_t lbase, int ioflag, int pblksize,
216 				int *errorp);
217 static void hammer2_compress_and_write(struct buf *bp, hammer2_trans_t *trans,
218 				hammer2_inode_t *ip,
219 				const hammer2_inode_data_t *ipdata,
220 				hammer2_cluster_t *cparent,
221 				hammer2_key_t lbase, int ioflag,
222 				int pblksize, int *errorp, int comp_algo);
223 static void hammer2_zero_check_and_write(struct buf *bp,
224 				hammer2_trans_t *trans, hammer2_inode_t *ip,
225 				const hammer2_inode_data_t *ipdata,
226 				hammer2_cluster_t *cparent,
227 				hammer2_key_t lbase,
228 				int ioflag, int pblksize, int *errorp);
229 static int test_block_zeros(const char *buf, size_t bytes);
230 static void zero_write(struct buf *bp, hammer2_trans_t *trans,
231 				hammer2_inode_t *ip,
232 				const hammer2_inode_data_t *ipdata,
233 				hammer2_cluster_t *cparent,
234 				hammer2_key_t lbase,
235 				int *errorp);
236 static void hammer2_write_bp(hammer2_cluster_t *cluster, struct buf *bp,
237 				int ioflag, int pblksize, int *errorp);
238 
239 static int hammer2_rcvdmsg(kdmsg_msg_t *msg);
240 static void hammer2_autodmsg(kdmsg_msg_t *msg);
241 static int hammer2_lnk_span_reply(kdmsg_state_t *state, kdmsg_msg_t *msg);
242 
243 
244 /*
245  * HAMMER2 vfs operations.
246  */
247 static struct vfsops hammer2_vfsops = {
248 	.vfs_init	= hammer2_vfs_init,
249 	.vfs_uninit	= hammer2_vfs_uninit,
250 	.vfs_sync	= hammer2_vfs_sync,
251 	.vfs_mount	= hammer2_vfs_mount,
252 	.vfs_unmount	= hammer2_vfs_unmount,
253 	.vfs_root 	= hammer2_vfs_root,
254 	.vfs_statfs	= hammer2_vfs_statfs,
255 	.vfs_statvfs	= hammer2_vfs_statvfs,
256 	.vfs_vget	= hammer2_vfs_vget,
257 	.vfs_vptofh	= hammer2_vfs_vptofh,
258 	.vfs_fhtovp	= hammer2_vfs_fhtovp,
259 	.vfs_checkexp	= hammer2_vfs_checkexp
260 };
261 
262 MALLOC_DEFINE(M_HAMMER2, "HAMMER2-mount", "");
263 
264 VFS_SET(hammer2_vfsops, hammer2, 0);
265 MODULE_VERSION(hammer2, 1);
266 
267 static
268 int
269 hammer2_vfs_init(struct vfsconf *conf)
270 {
271 	static struct objcache_malloc_args margs_read;
272 	static struct objcache_malloc_args margs_write;
273 
274 	int error;
275 
276 	error = 0;
277 
278 	if (HAMMER2_BLOCKREF_BYTES != sizeof(struct hammer2_blockref))
279 		error = EINVAL;
280 	if (HAMMER2_INODE_BYTES != sizeof(struct hammer2_inode_data))
281 		error = EINVAL;
282 	if (HAMMER2_VOLUME_BYTES != sizeof(struct hammer2_volume_data))
283 		error = EINVAL;
284 
285 	if (error)
286 		kprintf("HAMMER2 structure size mismatch; cannot continue.\n");
287 
288 	margs_read.objsize = 65536;
289 	margs_read.mtype = D_BUFFER;
290 
291 	margs_write.objsize = 32768;
292 	margs_write.mtype = C_BUFFER;
293 
294 	cache_buffer_read = objcache_create(margs_read.mtype->ks_shortdesc,
295 				0, 1, NULL, NULL, NULL, objcache_malloc_alloc,
296 				objcache_malloc_free, &margs_read);
297 	cache_buffer_write = objcache_create(margs_write.mtype->ks_shortdesc,
298 				0, 1, NULL, NULL, NULL, objcache_malloc_alloc,
299 				objcache_malloc_free, &margs_write);
300 
301 	lockinit(&hammer2_mntlk, "mntlk", 0, 0);
302 	TAILQ_INIT(&hammer2_mntlist);
303 	TAILQ_INIT(&hammer2_pfslist);
304 
305 	hammer2_limit_dirty_chains = desiredvnodes / 10;
306 
307 	hammer2_trans_manage_init();
308 
309 	return (error);
310 }
311 
312 static
313 int
314 hammer2_vfs_uninit(struct vfsconf *vfsp __unused)
315 {
316 	objcache_destroy(cache_buffer_read);
317 	objcache_destroy(cache_buffer_write);
318 	return 0;
319 }
320 
321 /*
322  * Core PFS allocator.  Used to allocate the pmp structure for PFS cluster
323  * mounts and the spmp structure for media (hmp) structures.
324  */
325 static hammer2_pfsmount_t *
326 hammer2_pfsalloc(const hammer2_inode_data_t *ipdata, hammer2_tid_t alloc_tid)
327 {
328 	hammer2_pfsmount_t *pmp;
329 
330 	pmp = kmalloc(sizeof(*pmp), M_HAMMER2, M_WAITOK | M_ZERO);
331 	kmalloc_create(&pmp->minode, "HAMMER2-inodes");
332 	kmalloc_create(&pmp->mmsg, "HAMMER2-pfsmsg");
333 	lockinit(&pmp->lock, "pfslk", 0, 0);
334 	spin_init(&pmp->inum_spin);
335 	RB_INIT(&pmp->inum_tree);
336 	TAILQ_INIT(&pmp->unlinkq);
337 	spin_init(&pmp->unlinkq_spin);
338 
339 	pmp->alloc_tid = alloc_tid + 1;	  /* our first media transaction id */
340 	pmp->flush_tid = pmp->alloc_tid;
341 	if (ipdata) {
342 		pmp->inode_tid = ipdata->pfs_inum + 1;
343 		pmp->pfs_clid = ipdata->pfs_clid;
344 	}
345 	mtx_init(&pmp->wthread_mtx);
346 	bioq_init(&pmp->wthread_bioq);
347 
348 	return pmp;
349 }
350 
351 /*
352  * Mount or remount HAMMER2 fileystem from physical media
353  *
354  *	mountroot
355  *		mp		mount point structure
356  *		path		NULL
357  *		data		<unused>
358  *		cred		<unused>
359  *
360  *	mount
361  *		mp		mount point structure
362  *		path		path to mount point
363  *		data		pointer to argument structure in user space
364  *			volume	volume path (device@LABEL form)
365  *			hflags	user mount flags
366  *		cred		user credentials
367  *
368  * RETURNS:	0	Success
369  *		!0	error number
370  */
371 static
372 int
373 hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
374 		  struct ucred *cred)
375 {
376 	struct hammer2_mount_info info;
377 	hammer2_pfsmount_t *pmp;
378 	hammer2_pfsmount_t *spmp;
379 	hammer2_mount_t *hmp;
380 	hammer2_key_t key_next;
381 	hammer2_key_t key_dummy;
382 	hammer2_key_t lhc;
383 	struct vnode *devvp;
384 	struct nlookupdata nd;
385 	hammer2_chain_t *parent;
386 	hammer2_chain_t *rchain;
387 	hammer2_cluster_t *cluster;
388 	hammer2_cluster_t *cparent;
389 	const hammer2_inode_data_t *ipdata;
390 	hammer2_blockref_t bref;
391 	struct file *fp;
392 	char devstr[MNAMELEN];
393 	size_t size;
394 	size_t done;
395 	char *dev;
396 	char *label;
397 	int ronly = 1;
398 	int error;
399 	int cache_index;
400 	int ddflag;
401 	int i;
402 
403 	hmp = NULL;
404 	pmp = NULL;
405 	dev = NULL;
406 	label = NULL;
407 	devvp = NULL;
408 	cache_index = -1;
409 
410 	kprintf("hammer2_mount\n");
411 
412 	if (path == NULL) {
413 		/*
414 		 * Root mount
415 		 */
416 		bzero(&info, sizeof(info));
417 		info.cluster_fd = -1;
418 		return (EOPNOTSUPP);
419 	} else {
420 		/*
421 		 * Non-root mount or updating a mount
422 		 */
423 		error = copyin(data, &info, sizeof(info));
424 		if (error)
425 			return (error);
426 
427 		error = copyinstr(info.volume, devstr, MNAMELEN - 1, &done);
428 		if (error)
429 			return (error);
430 
431 		/* Extract device and label */
432 		dev = devstr;
433 		label = strchr(devstr, '@');
434 		if (label == NULL ||
435 		    ((label + 1) - dev) > done) {
436 			return (EINVAL);
437 		}
438 		*label = '\0';
439 		label++;
440 		if (*label == '\0')
441 			return (EINVAL);
442 
443 		if (mp->mnt_flag & MNT_UPDATE) {
444 			/* Update mount */
445 			/* HAMMER2 implements NFS export via mountctl */
446 			pmp = MPTOPMP(mp);
447 			for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
448 				hmp = pmp->iroot->cluster.array[i]->hmp;
449 				devvp = hmp->devvp;
450 				error = hammer2_remount(hmp, mp, path,
451 							devvp, cred);
452 				if (error)
453 					break;
454 			}
455 			/*hammer2_inode_install_hidden(pmp);*/
456 
457 			return error;
458 		}
459 	}
460 
461 	/*
462 	 * HMP device mount
463 	 *
464 	 * Lookup name and verify it refers to a block device.
465 	 */
466 	error = nlookup_init(&nd, dev, UIO_SYSSPACE, NLC_FOLLOW);
467 	if (error == 0)
468 		error = nlookup(&nd);
469 	if (error == 0)
470 		error = cache_vref(&nd.nl_nch, nd.nl_cred, &devvp);
471 	nlookup_done(&nd);
472 
473 	if (error == 0) {
474 		if (vn_isdisk(devvp, &error))
475 			error = vfs_mountedon(devvp);
476 	}
477 
478 	/*
479 	 * Determine if the device has already been mounted.  After this
480 	 * check hmp will be non-NULL if we are doing the second or more
481 	 * hammer2 mounts from the same device.
482 	 */
483 	lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
484 	TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
485 		if (hmp->devvp == devvp)
486 			break;
487 	}
488 
489 	/*
490 	 * Open the device if this isn't a secondary mount and construct
491 	 * the H2 device mount (hmp).
492 	 */
493 	if (hmp == NULL) {
494 		hammer2_chain_t *schain;
495 		hammer2_xid_t xid;
496 
497 		if (error == 0 && vcount(devvp) > 0)
498 			error = EBUSY;
499 
500 		/*
501 		 * Now open the device
502 		 */
503 		if (error == 0) {
504 			ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
505 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
506 			error = vinvalbuf(devvp, V_SAVE, 0, 0);
507 			if (error == 0) {
508 				error = VOP_OPEN(devvp,
509 						 ronly ? FREAD : FREAD | FWRITE,
510 						 FSCRED, NULL);
511 			}
512 			vn_unlock(devvp);
513 		}
514 		if (error && devvp) {
515 			vrele(devvp);
516 			devvp = NULL;
517 		}
518 		if (error) {
519 			lockmgr(&hammer2_mntlk, LK_RELEASE);
520 			return error;
521 		}
522 		hmp = kmalloc(sizeof(*hmp), M_HAMMER2, M_WAITOK | M_ZERO);
523 		hmp->ronly = ronly;
524 		hmp->devvp = devvp;
525 		kmalloc_create(&hmp->mchain, "HAMMER2-chains");
526 		TAILQ_INSERT_TAIL(&hammer2_mntlist, hmp, mntentry);
527 		RB_INIT(&hmp->iotree);
528 
529 		lockinit(&hmp->vollk, "h2vol", 0, 0);
530 
531 		/*
532 		 * vchain setup. vchain.data is embedded.
533 		 * vchain.refs is initialized and will never drop to 0.
534 		 *
535 		 * NOTE! voldata is not yet loaded.
536 		 */
537 		hmp->vchain.hmp = hmp;
538 		hmp->vchain.refs = 1;
539 		hmp->vchain.data = (void *)&hmp->voldata;
540 		hmp->vchain.bref.type = HAMMER2_BREF_TYPE_VOLUME;
541 		hmp->vchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
542 		hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
543 		hmp->vchain.delete_xid = HAMMER2_XID_MAX;
544 
545 		hammer2_chain_core_alloc(NULL, &hmp->vchain, NULL);
546 		/* hmp->vchain.u.xxx is left NULL */
547 
548 		/*
549 		 * fchain setup.  fchain.data is embedded.
550 		 * fchain.refs is initialized and will never drop to 0.
551 		 *
552 		 * The data is not used but needs to be initialized to
553 		 * pass assertion muster.  We use this chain primarily
554 		 * as a placeholder for the freemap's top-level RBTREE
555 		 * so it does not interfere with the volume's topology
556 		 * RBTREE.
557 		 */
558 		hmp->fchain.hmp = hmp;
559 		hmp->fchain.refs = 1;
560 		hmp->fchain.data = (void *)&hmp->voldata.freemap_blockset;
561 		hmp->fchain.bref.type = HAMMER2_BREF_TYPE_FREEMAP;
562 		hmp->fchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
563 		hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
564 		hmp->fchain.bref.methods =
565 			HAMMER2_ENC_CHECK(HAMMER2_CHECK_FREEMAP) |
566 			HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
567 		hmp->fchain.delete_xid = HAMMER2_XID_MAX;
568 
569 		hammer2_chain_core_alloc(NULL, &hmp->fchain, NULL);
570 		/* hmp->fchain.u.xxx is left NULL */
571 
572 		/*
573 		 * Install the volume header and initialize fields from
574 		 * voldata.
575 		 */
576 		error = hammer2_install_volume_header(hmp);
577 		if (error) {
578 			++hmp->pmp_count;
579 			hammer2_vfs_unmount_hmp1(mp, hmp);
580 			hammer2_vfs_unmount_hmp2(mp, hmp);
581 			hammer2_vfs_unmount(mp, MNT_FORCE);
582 			return error;
583 		}
584 
585 		/*
586 		 * Really important to get these right or flush will get
587 		 * confused.
588 		 */
589 		hmp->spmp = hammer2_pfsalloc(NULL, hmp->voldata.mirror_tid);
590 		kprintf("alloc spmp %p tid %016jx\n",
591 			hmp->spmp, hmp->voldata.mirror_tid);
592 		spmp = hmp->spmp;
593 		spmp->inode_tid = 1;
594 
595 		xid = 0;
596 		hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
597 		hmp->vchain.bref.modify_tid = hmp->vchain.bref.mirror_tid;
598 		hmp->vchain.modify_xid = xid;
599 		hmp->vchain.update_xlo = xid;
600 		hmp->vchain.update_xhi = xid;
601 		hmp->vchain.pmp = spmp;
602 		hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
603 		hmp->fchain.bref.modify_tid = hmp->fchain.bref.mirror_tid;
604 		hmp->fchain.modify_xid = xid;
605 		hmp->fchain.update_xlo = xid;
606 		hmp->fchain.update_xhi = xid;
607 		hmp->fchain.pmp = spmp;
608 
609 		/*
610 		 * First locate the super-root inode, which is key 0
611 		 * relative to the volume header's blockset.
612 		 *
613 		 * Then locate the root inode by scanning the directory keyspace
614 		 * represented by the label.
615 		 */
616 		parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
617 		schain = hammer2_chain_lookup(&parent, &key_dummy,
618 				      HAMMER2_SROOT_KEY, HAMMER2_SROOT_KEY,
619 				      &cache_index, 0, &ddflag);
620 		hammer2_chain_lookup_done(parent);
621 		if (schain == NULL) {
622 			kprintf("hammer2_mount: invalid super-root\n");
623 			++hmp->pmp_count;
624 			hammer2_vfs_unmount_hmp1(mp, hmp);
625 			hammer2_vfs_unmount_hmp2(mp, hmp);
626 			hammer2_vfs_unmount(mp, MNT_FORCE);
627 			return EINVAL;
628 		}
629 
630 		/*
631 		 * Sanity-check schain's pmp, finish initializing spmp.
632 		 */
633 		KKASSERT(schain->pmp == spmp);
634 		spmp->pfs_clid = schain->data->ipdata.pfs_clid;
635 
636 		/*
637 		 * NOTE: The CHAIN_PFSROOT is not set on the super-root inode.
638 		 * NOTE: inode_get sucks up schain's lock.
639 		 */
640 		cluster = hammer2_cluster_from_chain(schain);
641 		spmp->iroot = hammer2_inode_get(spmp, NULL, cluster);
642 		spmp->spmp_hmp = hmp;
643 		hammer2_inode_ref(spmp->iroot);
644 		hammer2_inode_unlock_ex(spmp->iroot, cluster);
645 		schain = NULL;
646 		/* leave spmp->iroot with one ref */
647 
648 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
649 			error = hammer2_recovery(hmp);
650 			/* XXX do something with error */
651 		}
652 		++hmp->pmp_count;
653 
654 		/*
655 		 * XXX RDONLY stuff is totally broken FIXME XXX
656 		 *
657 		 * Automatic LNK_CONN
658 		 * Automatic handling of received LNK_SPAN
659 		 * Automatic handling of received LNK_CIRC
660 		 * No automatic LNK_SPAN generation - we do this ourselves
661 		 * No automatic LNK_CIRC generation - we do this ourselves
662 		 */
663 		kdmsg_iocom_init(&hmp->iocom, hmp,
664 				 KDMSG_IOCOMF_AUTOCONN |
665 				 KDMSG_IOCOMF_AUTORXSPAN |
666 				 KDMSG_IOCOMF_AUTORXCIRC,
667 				 hmp->mchain, hammer2_rcvdmsg);
668 
669 		/*
670 		 * Ref the cluster management messaging descriptor.  The mount
671 		 * program deals with the other end of the communications pipe.
672 		 */
673 		fp = holdfp(curproc->p_fd, info.cluster_fd, -1);
674 		if (fp) {
675 			hammer2_cluster_reconnect(hmp, fp);
676 		} else {
677 			kprintf("hammer2_mount: bad cluster_fd!\n");
678 		}
679 	} else {
680 		spmp = hmp->spmp;
681 		++hmp->pmp_count;
682 	}
683 
684 	/*
685 	 * Lookup mount point under the media-localized super-root.
686 	 *
687 	 * cluster->pmp will incorrectly point to spmp and must be fixed
688 	 * up later on.
689 	 */
690 	cparent = hammer2_inode_lock_ex(spmp->iroot);
691 	lhc = hammer2_dirhash(label, strlen(label));
692 	cluster = hammer2_cluster_lookup(cparent, &key_next,
693 				      lhc, lhc + HAMMER2_DIRHASH_LOMASK,
694 				      0, &ddflag);
695 	while (cluster) {
696 		if (hammer2_cluster_type(cluster) == HAMMER2_BREF_TYPE_INODE &&
697 		    strcmp(label,
698 		       hammer2_cluster_data(cluster)->ipdata.filename) == 0) {
699 			break;
700 		}
701 		cluster = hammer2_cluster_next(cparent, cluster, &key_next,
702 					    key_next,
703 					    lhc + HAMMER2_DIRHASH_LOMASK, 0);
704 	}
705 	hammer2_inode_unlock_ex(spmp->iroot, cparent);
706 
707 	if (cluster == NULL) {
708 		kprintf("hammer2_mount: PFS label not found\n");
709 		hammer2_vfs_unmount_hmp1(mp, hmp);
710 		hammer2_vfs_unmount_hmp2(mp, hmp);
711 		lockmgr(&hammer2_mntlk, LK_RELEASE);
712 		hammer2_vfs_unmount(mp, MNT_FORCE);
713 		return EINVAL;
714 	}
715 
716 	for (i = 0; i < cluster->nchains; ++i) {
717 		rchain = cluster->array[i];
718 		KKASSERT(rchain->pmp == NULL);
719 		if (rchain->flags & HAMMER2_CHAIN_MOUNTED) {
720 			kprintf("hammer2_mount: PFS label already mounted!\n");
721 			hammer2_cluster_unlock(cluster);
722 			hammer2_vfs_unmount_hmp1(mp, hmp);
723 			hammer2_vfs_unmount_hmp2(mp, hmp);
724 			lockmgr(&hammer2_mntlk, LK_RELEASE);
725 			hammer2_vfs_unmount(mp, MNT_FORCE);
726 			return EBUSY;
727 		}
728 #if 0
729 		if (rchain->flags & HAMMER2_CHAIN_RECYCLE) {
730 			kprintf("hammer2_mount: PFS label is recycling\n");
731 			hammer2_cluster_unlock(cluster);
732 			hammer2_vfs_unmount_hmp1(mp, hmp);
733 			hammer2_vfs_unmount_hmp2(mp, hmp);
734 			lockmgr(&hammer2_mntlk, LK_RELEASE);
735 			hammer2_vfs_unmount(mp, MNT_FORCE);
736 			return EBUSY;
737 		}
738 #endif
739 	}
740 
741 	/*
742 	 * Check to see if the cluster id is already mounted at the mount
743 	 * point.  If it is, add us to the cluster.
744 	 */
745 	ipdata = &hammer2_cluster_data(cluster)->ipdata;
746 	hammer2_cluster_bref(cluster, &bref);
747 	TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
748 		if (pmp->spmp_hmp == NULL &&
749 		    bcmp(&pmp->pfs_clid, &ipdata->pfs_clid,
750 			 sizeof(pmp->pfs_clid)) == 0) {
751 			break;
752 		}
753 	}
754 
755 	if (pmp) {
756 		int i;
757 		int j;
758 
759 		hammer2_inode_ref(pmp->iroot);
760 		ccms_thread_lock(&pmp->iroot->topo_cst, CCMS_STATE_EXCLUSIVE);
761 
762 		if (pmp->iroot->cluster.nchains + cluster->nchains >
763 		    HAMMER2_MAXCLUSTER) {
764 			kprintf("hammer2_mount: cluster full!\n");
765 
766 			ccms_thread_unlock(&pmp->iroot->topo_cst);
767 			hammer2_inode_drop(pmp->iroot);
768 
769 			hammer2_cluster_unlock(cluster);
770 			hammer2_vfs_unmount_hmp1(mp, hmp);
771 			hammer2_vfs_unmount_hmp2(mp, hmp);
772 			lockmgr(&hammer2_mntlk, LK_RELEASE);
773 			hammer2_vfs_unmount(mp, MNT_FORCE);
774 			return EBUSY;
775 		}
776 		kprintf("hammer2_vfs_mount: Adding pfs to existing cluster\n");
777 		j = pmp->iroot->cluster.nchains;
778 		for (i = 0; i < cluster->nchains; ++i) {
779 			rchain = cluster->array[i];
780 			KKASSERT(rchain->pmp == NULL);
781 			rchain->pmp = pmp;
782 			hammer2_chain_ref(cluster->array[i]);
783 			pmp->iroot->cluster.array[j] = cluster->array[i];
784 			++j;
785 		}
786 		pmp->iroot->cluster.nchains = j;
787 		ccms_thread_unlock(&pmp->iroot->topo_cst);
788 		hammer2_inode_drop(pmp->iroot);
789 		hammer2_cluster_unlock(cluster);
790 		lockmgr(&hammer2_mntlk, LK_RELEASE);
791 
792 		kprintf("ok\n");
793 		hammer2_inode_install_hidden(pmp);
794 
795 		return ERANGE;
796 	}
797 
798 	/*
799 	 * Block device opened successfully, finish initializing the
800 	 * mount structure.
801 	 *
802 	 * From this point on we have to call hammer2_unmount() on failure.
803 	 */
804 	pmp = hammer2_pfsalloc(ipdata, bref.mirror_tid);
805 	kprintf("PMP mirror_tid is %016jx\n", bref.mirror_tid);
806 	for (i = 0; i < cluster->nchains; ++i) {
807 		rchain = cluster->array[i];
808 		KKASSERT(rchain->pmp == NULL);
809 		rchain->pmp = pmp;
810 		atomic_set_int(&rchain->flags, HAMMER2_CHAIN_MOUNTED);
811 	}
812 	cluster->pmp = pmp;
813 
814 	ccms_domain_init(&pmp->ccms_dom);
815 	TAILQ_INSERT_TAIL(&hammer2_pfslist, pmp, mntentry);
816 	lockmgr(&hammer2_mntlk, LK_RELEASE);
817 
818 	kprintf("hammer2_mount hmp=%p pmp=%p pmpcnt=%d\n",
819 		hmp, pmp, hmp->pmp_count);
820 
821 	mp->mnt_flag = MNT_LOCAL;
822 	mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;	/* all entry pts are SMP */
823 	mp->mnt_kern_flag |= MNTK_THR_SYNC;	/* new vsyncscan semantics */
824 
825 	/*
826 	 * required mount structure initializations
827 	 */
828 	mp->mnt_stat.f_iosize = HAMMER2_PBUFSIZE;
829 	mp->mnt_stat.f_bsize = HAMMER2_PBUFSIZE;
830 
831 	mp->mnt_vstat.f_frsize = HAMMER2_PBUFSIZE;
832 	mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
833 
834 	/*
835 	 * Optional fields
836 	 */
837 	mp->mnt_iosize_max = MAXPHYS;
838 	mp->mnt_data = (qaddr_t)pmp;
839 	pmp->mp = mp;
840 
841 	/*
842 	 * After this point hammer2_vfs_unmount() has visibility on hmp
843 	 * and manual hmp1/hmp2 calls are not needed on fatal errors.
844 	 */
845 	pmp->iroot = hammer2_inode_get(pmp, NULL, cluster);
846 	hammer2_inode_ref(pmp->iroot);		/* ref for pmp->iroot */
847 	hammer2_inode_unlock_ex(pmp->iroot, cluster);
848 
849 	/*
850 	 * The logical file buffer bio write thread handles things
851 	 * like physical block assignment and compression.
852 	 *
853 	 * (only applicable to pfs mounts, not applicable to spmp)
854 	 */
855 	pmp->wthread_destroy = 0;
856 	lwkt_create(hammer2_write_thread, pmp,
857 		    &pmp->wthread_td, NULL, 0, -1, "hwrite-%s", label);
858 
859 	/*
860 	 * With the cluster operational install ihidden.
861 	 * (only applicable to pfs mounts, not applicable to spmp)
862 	 */
863 	hammer2_inode_install_hidden(pmp);
864 
865 	/*
866 	 * Finish setup
867 	 */
868 	vfs_getnewfsid(mp);
869 	vfs_add_vnodeops(mp, &hammer2_vnode_vops, &mp->mnt_vn_norm_ops);
870 	vfs_add_vnodeops(mp, &hammer2_spec_vops, &mp->mnt_vn_spec_ops);
871 	vfs_add_vnodeops(mp, &hammer2_fifo_vops, &mp->mnt_vn_fifo_ops);
872 
873 	copyinstr(info.volume, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, &size);
874 	bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
875 	bzero(mp->mnt_stat.f_mntonname, sizeof(mp->mnt_stat.f_mntonname));
876 	copyinstr(path, mp->mnt_stat.f_mntonname,
877 		  sizeof(mp->mnt_stat.f_mntonname) - 1,
878 		  &size);
879 
880 	/*
881 	 * Initial statfs to prime mnt_stat.
882 	 */
883 	hammer2_vfs_statfs(mp, &mp->mnt_stat, cred);
884 
885 	return 0;
886 }
887 
888 /*
889  * Handle bioq for strategy write
890  */
891 static
892 void
893 hammer2_write_thread(void *arg)
894 {
895 	hammer2_pfsmount_t *pmp;
896 	struct bio *bio;
897 	struct buf *bp;
898 	hammer2_trans_t trans;
899 	struct vnode *vp;
900 	hammer2_inode_t *ip;
901 	hammer2_cluster_t *cparent;
902 	hammer2_inode_data_t *wipdata;
903 	hammer2_key_t lbase;
904 	int lblksize;
905 	int pblksize;
906 	int error;
907 
908 	pmp = arg;
909 
910 	mtx_lock(&pmp->wthread_mtx);
911 	while (pmp->wthread_destroy == 0) {
912 		if (bioq_first(&pmp->wthread_bioq) == NULL) {
913 			mtxsleep(&pmp->wthread_bioq, &pmp->wthread_mtx,
914 				 0, "h2bioqw", 0);
915 		}
916 		cparent = NULL;
917 
918 		hammer2_trans_init(&trans, pmp, HAMMER2_TRANS_BUFCACHE);
919 
920 		while ((bio = bioq_takefirst(&pmp->wthread_bioq)) != NULL) {
921 			/*
922 			 * dummy bio for synchronization.  The transaction
923 			 * must be reinitialized.
924 			 */
925 			if (bio->bio_buf == NULL) {
926 				bio->bio_flags |= BIO_DONE;
927 				wakeup(bio);
928 				hammer2_trans_done(&trans);
929 				hammer2_trans_init(&trans, pmp,
930 						   HAMMER2_TRANS_BUFCACHE);
931 				continue;
932 			}
933 
934 			/*
935 			 * else normal bio processing
936 			 */
937 			mtx_unlock(&pmp->wthread_mtx);
938 
939 			hammer2_lwinprog_drop(pmp);
940 
941 			error = 0;
942 			bp = bio->bio_buf;
943 			vp = bp->b_vp;
944 			ip = VTOI(vp);
945 
946 			/*
947 			 * Inode is modified, flush size and mtime changes
948 			 * to ensure that the file size remains consistent
949 			 * with the buffers being flushed.
950 			 *
951 			 * NOTE: The inode_fsync() call only flushes the
952 			 *	 inode's meta-data state, it doesn't try
953 			 *	 to flush underlying buffers or chains.
954 			 */
955 			cparent = hammer2_inode_lock_ex(ip);
956 			if (ip->flags & (HAMMER2_INODE_RESIZED |
957 					 HAMMER2_INODE_MTIME)) {
958 				hammer2_inode_fsync(&trans, ip, cparent);
959 			}
960 			wipdata = hammer2_cluster_modify_ip(&trans, ip,
961 							 cparent, 0);
962 			lblksize = hammer2_calc_logical(ip, bio->bio_offset,
963 							&lbase, NULL);
964 			pblksize = hammer2_calc_physical(ip, wipdata, lbase);
965 			hammer2_write_file_core(bp, &trans, ip, wipdata,
966 						cparent,
967 						lbase, IO_ASYNC,
968 						pblksize, &error);
969 			hammer2_cluster_modsync(cparent);
970 			hammer2_inode_unlock_ex(ip, cparent);
971 			if (error) {
972 				kprintf("hammer2: error in buffer write\n");
973 				bp->b_flags |= B_ERROR;
974 				bp->b_error = EIO;
975 			}
976 			biodone(bio);
977 			mtx_lock(&pmp->wthread_mtx);
978 		}
979 		hammer2_trans_done(&trans);
980 	}
981 	pmp->wthread_destroy = -1;
982 	wakeup(&pmp->wthread_destroy);
983 
984 	mtx_unlock(&pmp->wthread_mtx);
985 }
986 
987 void
988 hammer2_bioq_sync(hammer2_pfsmount_t *pmp)
989 {
990 	struct bio sync_bio;
991 
992 	bzero(&sync_bio, sizeof(sync_bio));	/* dummy with no bio_buf */
993 	mtx_lock(&pmp->wthread_mtx);
994 	if (pmp->wthread_destroy == 0 &&
995 	    TAILQ_FIRST(&pmp->wthread_bioq.queue)) {
996 		bioq_insert_tail(&pmp->wthread_bioq, &sync_bio);
997 		while ((sync_bio.bio_flags & BIO_DONE) == 0)
998 			mtxsleep(&sync_bio, &pmp->wthread_mtx, 0, "h2bioq", 0);
999 	}
1000 	mtx_unlock(&pmp->wthread_mtx);
1001 }
1002 
1003 /*
1004  * Return a chain suitable for I/O, creating the chain if necessary
1005  * and assigning its physical block.
1006  */
1007 static
1008 hammer2_cluster_t *
1009 hammer2_assign_physical(hammer2_trans_t *trans,
1010 			hammer2_inode_t *ip, hammer2_cluster_t *cparent,
1011 			hammer2_key_t lbase, int pblksize, int *errorp)
1012 {
1013 	hammer2_cluster_t *cluster;
1014 	hammer2_cluster_t *dparent;
1015 	hammer2_key_t key_dummy;
1016 	int pradix = hammer2_getradix(pblksize);
1017 	int ddflag;
1018 
1019 	/*
1020 	 * Locate the chain associated with lbase, return a locked chain.
1021 	 * However, do not instantiate any data reference (which utilizes a
1022 	 * device buffer) because we will be using direct IO via the
1023 	 * logical buffer cache buffer.
1024 	 */
1025 	*errorp = 0;
1026 	KKASSERT(pblksize >= HAMMER2_ALLOC_MIN);
1027 retry:
1028 	dparent = hammer2_cluster_lookup_init(cparent, 0);
1029 	cluster = hammer2_cluster_lookup(dparent, &key_dummy,
1030 				     lbase, lbase,
1031 				     HAMMER2_LOOKUP_NODATA, &ddflag);
1032 
1033 	if (cluster == NULL) {
1034 		/*
1035 		 * We found a hole, create a new chain entry.
1036 		 *
1037 		 * NOTE: DATA chains are created without device backing
1038 		 *	 store (nor do we want any).
1039 		 */
1040 		*errorp = hammer2_cluster_create(trans, dparent, &cluster,
1041 					       lbase, HAMMER2_PBUFRADIX,
1042 					       HAMMER2_BREF_TYPE_DATA,
1043 					       pblksize);
1044 		if (cluster == NULL) {
1045 			hammer2_cluster_lookup_done(dparent);
1046 			panic("hammer2_cluster_create: par=%p error=%d\n",
1047 				dparent->focus, *errorp);
1048 			goto retry;
1049 		}
1050 		/*ip->delta_dcount += pblksize;*/
1051 	} else {
1052 		switch (hammer2_cluster_type(cluster)) {
1053 		case HAMMER2_BREF_TYPE_INODE:
1054 			/*
1055 			 * The data is embedded in the inode.  The
1056 			 * caller is responsible for marking the inode
1057 			 * modified and copying the data to the embedded
1058 			 * area.
1059 			 */
1060 			break;
1061 		case HAMMER2_BREF_TYPE_DATA:
1062 			if (hammer2_cluster_bytes(cluster) != pblksize) {
1063 				hammer2_cluster_resize(trans, ip,
1064 						     dparent, cluster,
1065 						     pradix,
1066 						     HAMMER2_MODIFY_OPTDATA);
1067 			}
1068 			hammer2_cluster_modify(trans, cluster,
1069 					     HAMMER2_MODIFY_OPTDATA);
1070 			break;
1071 		default:
1072 			panic("hammer2_assign_physical: bad type");
1073 			/* NOT REACHED */
1074 			break;
1075 		}
1076 	}
1077 
1078 	/*
1079 	 * Cleanup.  If cluster wound up being the inode itself, i.e.
1080 	 * the DIRECTDATA case for offset 0, then we need to update cparent.
1081 	 * The caller expects cparent to not become stale.
1082 	 */
1083 	hammer2_cluster_lookup_done(dparent);
1084 	/* dparent = NULL; safety */
1085 	if (cluster && ddflag)
1086 		hammer2_cluster_replace_locked(cparent, cluster);
1087 	return (cluster);
1088 }
1089 
1090 /*
1091  * From hammer2_vnops.c.
1092  * The core write function which determines which path to take
1093  * depending on compression settings.
1094  */
1095 static
1096 void
1097 hammer2_write_file_core(struct buf *bp, hammer2_trans_t *trans,
1098 			hammer2_inode_t *ip, hammer2_inode_data_t *ipdata,
1099 			hammer2_cluster_t *cparent,
1100 			hammer2_key_t lbase, int ioflag, int pblksize,
1101 			int *errorp)
1102 {
1103 	hammer2_cluster_t *cluster;
1104 
1105 	switch(HAMMER2_DEC_COMP(ipdata->comp_algo)) {
1106 	case HAMMER2_COMP_NONE:
1107 		/*
1108 		 * We have to assign physical storage to the buffer
1109 		 * we intend to dirty or write now to avoid deadlocks
1110 		 * in the strategy code later.
1111 		 *
1112 		 * This can return NOOFFSET for inode-embedded data.
1113 		 * The strategy code will take care of it in that case.
1114 		 */
1115 		cluster = hammer2_assign_physical(trans, ip, cparent,
1116 						lbase, pblksize,
1117 						errorp);
1118 		hammer2_write_bp(cluster, bp, ioflag, pblksize, errorp);
1119 		if (cluster)
1120 			hammer2_cluster_unlock(cluster);
1121 		break;
1122 	case HAMMER2_COMP_AUTOZERO:
1123 		/*
1124 		 * Check for zero-fill only
1125 		 */
1126 		hammer2_zero_check_and_write(bp, trans, ip,
1127 				    ipdata, cparent, lbase,
1128 				    ioflag, pblksize, errorp);
1129 		break;
1130 	case HAMMER2_COMP_LZ4:
1131 	case HAMMER2_COMP_ZLIB:
1132 	default:
1133 		/*
1134 		 * Check for zero-fill and attempt compression.
1135 		 */
1136 		hammer2_compress_and_write(bp, trans, ip,
1137 					   ipdata, cparent,
1138 					   lbase, ioflag,
1139 					   pblksize, errorp,
1140 					   ipdata->comp_algo);
1141 		break;
1142 	}
1143 }
1144 
1145 /*
1146  * Generic function that will perform the compression in compression
1147  * write path. The compression algorithm is determined by the settings
1148  * obtained from inode.
1149  */
1150 static
1151 void
1152 hammer2_compress_and_write(struct buf *bp, hammer2_trans_t *trans,
1153 	hammer2_inode_t *ip, const hammer2_inode_data_t *ipdata,
1154 	hammer2_cluster_t *cparent,
1155 	hammer2_key_t lbase, int ioflag, int pblksize,
1156 	int *errorp, int comp_algo)
1157 {
1158 	hammer2_cluster_t *cluster;
1159 	hammer2_chain_t *chain;
1160 	int comp_size;
1161 	int comp_block_size;
1162 	int i;
1163 	char *comp_buffer;
1164 
1165 	if (test_block_zeros(bp->b_data, pblksize)) {
1166 		zero_write(bp, trans, ip, ipdata, cparent, lbase, errorp);
1167 		return;
1168 	}
1169 
1170 	comp_size = 0;
1171 	comp_buffer = NULL;
1172 
1173 	KKASSERT(pblksize / 2 <= 32768);
1174 
1175 	if (ip->comp_heuristic < 8 || (ip->comp_heuristic & 7) == 0) {
1176 		z_stream strm_compress;
1177 		int comp_level;
1178 		int ret;
1179 
1180 		switch(HAMMER2_DEC_COMP(comp_algo)) {
1181 		case HAMMER2_COMP_LZ4:
1182 			comp_buffer = objcache_get(cache_buffer_write,
1183 						   M_INTWAIT);
1184 			comp_size = LZ4_compress_limitedOutput(
1185 					bp->b_data,
1186 					&comp_buffer[sizeof(int)],
1187 					pblksize,
1188 					pblksize / 2 - sizeof(int));
1189 			/*
1190 			 * We need to prefix with the size, LZ4
1191 			 * doesn't do it for us.  Add the related
1192 			 * overhead.
1193 			 */
1194 			*(int *)comp_buffer = comp_size;
1195 			if (comp_size)
1196 				comp_size += sizeof(int);
1197 			break;
1198 		case HAMMER2_COMP_ZLIB:
1199 			comp_level = HAMMER2_DEC_LEVEL(comp_algo);
1200 			if (comp_level == 0)
1201 				comp_level = 6;	/* default zlib compression */
1202 			else if (comp_level < 6)
1203 				comp_level = 6;
1204 			else if (comp_level > 9)
1205 				comp_level = 9;
1206 			ret = deflateInit(&strm_compress, comp_level);
1207 			if (ret != Z_OK) {
1208 				kprintf("HAMMER2 ZLIB: fatal error "
1209 					"on deflateInit.\n");
1210 			}
1211 
1212 			comp_buffer = objcache_get(cache_buffer_write,
1213 						   M_INTWAIT);
1214 			strm_compress.next_in = bp->b_data;
1215 			strm_compress.avail_in = pblksize;
1216 			strm_compress.next_out = comp_buffer;
1217 			strm_compress.avail_out = pblksize / 2;
1218 			ret = deflate(&strm_compress, Z_FINISH);
1219 			if (ret == Z_STREAM_END) {
1220 				comp_size = pblksize / 2 -
1221 					    strm_compress.avail_out;
1222 			} else {
1223 				comp_size = 0;
1224 			}
1225 			ret = deflateEnd(&strm_compress);
1226 			break;
1227 		default:
1228 			kprintf("Error: Unknown compression method.\n");
1229 			kprintf("Comp_method = %d.\n", comp_algo);
1230 			break;
1231 		}
1232 	}
1233 
1234 	if (comp_size == 0) {
1235 		/*
1236 		 * compression failed or turned off
1237 		 */
1238 		comp_block_size = pblksize;	/* safety */
1239 		if (++ip->comp_heuristic > 128)
1240 			ip->comp_heuristic = 8;
1241 	} else {
1242 		/*
1243 		 * compression succeeded
1244 		 */
1245 		ip->comp_heuristic = 0;
1246 		if (comp_size <= 1024) {
1247 			comp_block_size = 1024;
1248 		} else if (comp_size <= 2048) {
1249 			comp_block_size = 2048;
1250 		} else if (comp_size <= 4096) {
1251 			comp_block_size = 4096;
1252 		} else if (comp_size <= 8192) {
1253 			comp_block_size = 8192;
1254 		} else if (comp_size <= 16384) {
1255 			comp_block_size = 16384;
1256 		} else if (comp_size <= 32768) {
1257 			comp_block_size = 32768;
1258 		} else {
1259 			panic("hammer2: WRITE PATH: "
1260 			      "Weird comp_size value.");
1261 			/* NOT REACHED */
1262 			comp_block_size = pblksize;
1263 		}
1264 	}
1265 
1266 	cluster = hammer2_assign_physical(trans, ip, cparent,
1267 					  lbase, comp_block_size,
1268 					  errorp);
1269 	ipdata = &hammer2_cluster_data(cparent)->ipdata;
1270 
1271 	if (*errorp) {
1272 		kprintf("WRITE PATH: An error occurred while "
1273 			"assigning physical space.\n");
1274 		KKASSERT(cluster == NULL);
1275 		goto done;
1276 	}
1277 
1278 	for (i = 0; i < cluster->nchains; ++i) {
1279 		hammer2_io_t *dio;
1280 		char *bdata;
1281 		int temp_check;
1282 
1283 		chain = cluster->array[i];
1284 		KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1285 
1286 		switch(chain->bref.type) {
1287 		case HAMMER2_BREF_TYPE_INODE:
1288 			KKASSERT(chain->data->ipdata.op_flags &
1289 				 HAMMER2_OPFLAG_DIRECTDATA);
1290 			KKASSERT(bp->b_loffset == 0);
1291 			bcopy(bp->b_data, chain->data->ipdata.u.data,
1292 			      HAMMER2_EMBEDDED_BYTES);
1293 			break;
1294 		case HAMMER2_BREF_TYPE_DATA:
1295 			temp_check = HAMMER2_DEC_CHECK(chain->bref.methods);
1296 
1297 			/*
1298 			 * Optimize out the read-before-write
1299 			 * if possible.
1300 			 */
1301 			*errorp = hammer2_io_newnz(chain->hmp,
1302 						   chain->bref.data_off,
1303 						   chain->bytes,
1304 						   &dio);
1305 			if (*errorp) {
1306 				hammer2_io_brelse(&dio);
1307 				kprintf("hammer2: WRITE PATH: "
1308 					"dbp bread error\n");
1309 				break;
1310 			}
1311 			bdata = hammer2_io_data(dio, chain->bref.data_off);
1312 
1313 			/*
1314 			 * When loading the block make sure we don't
1315 			 * leave garbage after the compressed data.
1316 			 */
1317 			if (comp_size) {
1318 				chain->bref.methods =
1319 					HAMMER2_ENC_COMP(comp_algo) +
1320 					HAMMER2_ENC_CHECK(temp_check);
1321 				bcopy(comp_buffer, bdata, comp_size);
1322 				if (comp_size != comp_block_size) {
1323 					bzero(bdata + comp_size,
1324 					      comp_block_size - comp_size);
1325 				}
1326 			} else {
1327 				chain->bref.methods =
1328 					HAMMER2_ENC_COMP(
1329 						HAMMER2_COMP_NONE) +
1330 					HAMMER2_ENC_CHECK(temp_check);
1331 				bcopy(bp->b_data, bdata, pblksize);
1332 			}
1333 
1334 			/*
1335 			 * Device buffer is now valid, chain is no
1336 			 * longer in the initial state.
1337 			 */
1338 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1339 
1340 			/* Now write the related bdp. */
1341 			if (ioflag & IO_SYNC) {
1342 				/*
1343 				 * Synchronous I/O requested.
1344 				 */
1345 				hammer2_io_bwrite(&dio);
1346 			/*
1347 			} else if ((ioflag & IO_DIRECT) &&
1348 				   loff + n == pblksize) {
1349 				hammer2_io_bdwrite(&dio);
1350 			*/
1351 			} else if (ioflag & IO_ASYNC) {
1352 				hammer2_io_bawrite(&dio);
1353 			} else {
1354 				hammer2_io_bdwrite(&dio);
1355 			}
1356 			break;
1357 		default:
1358 			panic("hammer2_write_bp: bad chain type %d\n",
1359 				chain->bref.type);
1360 			/* NOT REACHED */
1361 			break;
1362 		}
1363 	}
1364 done:
1365 	if (cluster)
1366 		hammer2_cluster_unlock(cluster);
1367 	if (comp_buffer)
1368 		objcache_put(cache_buffer_write, comp_buffer);
1369 }
1370 
1371 /*
1372  * Function that performs zero-checking and writing without compression,
1373  * it corresponds to default zero-checking path.
1374  */
1375 static
1376 void
1377 hammer2_zero_check_and_write(struct buf *bp, hammer2_trans_t *trans,
1378 	hammer2_inode_t *ip, const hammer2_inode_data_t *ipdata,
1379 	hammer2_cluster_t *cparent,
1380 	hammer2_key_t lbase, int ioflag, int pblksize, int *errorp)
1381 {
1382 	hammer2_cluster_t *cluster;
1383 
1384 	if (test_block_zeros(bp->b_data, pblksize)) {
1385 		zero_write(bp, trans, ip, ipdata, cparent, lbase, errorp);
1386 	} else {
1387 		cluster = hammer2_assign_physical(trans, ip, cparent,
1388 						  lbase, pblksize, errorp);
1389 		hammer2_write_bp(cluster, bp, ioflag, pblksize, errorp);
1390 		if (cluster)
1391 			hammer2_cluster_unlock(cluster);
1392 	}
1393 }
1394 
1395 /*
1396  * A function to test whether a block of data contains only zeros,
1397  * returns TRUE (non-zero) if the block is all zeros.
1398  */
1399 static
1400 int
1401 test_block_zeros(const char *buf, size_t bytes)
1402 {
1403 	size_t i;
1404 
1405 	for (i = 0; i < bytes; i += sizeof(long)) {
1406 		if (*(const long *)(buf + i) != 0)
1407 			return (0);
1408 	}
1409 	return (1);
1410 }
1411 
1412 /*
1413  * Function to "write" a block that contains only zeros.
1414  */
1415 static
1416 void
1417 zero_write(struct buf *bp, hammer2_trans_t *trans,
1418 	hammer2_inode_t *ip, const hammer2_inode_data_t *ipdata,
1419 	hammer2_cluster_t *cparent,
1420 	hammer2_key_t lbase, int *errorp __unused)
1421 {
1422 	hammer2_cluster_t *cluster;
1423 	hammer2_media_data_t *data;
1424 	hammer2_key_t key_dummy;
1425 	int ddflag;
1426 
1427 	cparent = hammer2_cluster_lookup_init(cparent, 0);
1428 	cluster = hammer2_cluster_lookup(cparent, &key_dummy, lbase, lbase,
1429 				     HAMMER2_LOOKUP_NODATA, &ddflag);
1430 	if (cluster) {
1431 		data = hammer2_cluster_wdata(cluster);
1432 
1433 		if (ddflag) {
1434 			KKASSERT(cluster->focus->flags &
1435 				 HAMMER2_CHAIN_MODIFIED);
1436 			bzero(data->ipdata.u.data, HAMMER2_EMBEDDED_BYTES);
1437 			hammer2_cluster_modsync(cluster);
1438 		} else {
1439 			hammer2_cluster_delete(trans, cluster, 0);
1440 		}
1441 		hammer2_cluster_unlock(cluster);
1442 	}
1443 	hammer2_cluster_lookup_done(cparent);
1444 }
1445 
1446 /*
1447  * Function to write the data as it is, without performing any sort of
1448  * compression. This function is used in path without compression and
1449  * default zero-checking path.
1450  */
1451 static
1452 void
1453 hammer2_write_bp(hammer2_cluster_t *cluster, struct buf *bp, int ioflag,
1454 				int pblksize, int *errorp)
1455 {
1456 	hammer2_chain_t *chain;
1457 	hammer2_io_t *dio;
1458 	char *bdata;
1459 	int error;
1460 	int i;
1461 	int temp_check;
1462 
1463 	error = 0;	/* XXX TODO below */
1464 
1465 	for (i = 0; i < cluster->nchains; ++i) {
1466 		chain = cluster->array[i];
1467 
1468 		temp_check = HAMMER2_DEC_CHECK(chain->bref.methods);
1469 
1470 		KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1471 
1472 		switch(chain->bref.type) {
1473 		case HAMMER2_BREF_TYPE_INODE:
1474 			KKASSERT(chain->data->ipdata.op_flags &
1475 				 HAMMER2_OPFLAG_DIRECTDATA);
1476 			KKASSERT(bp->b_loffset == 0);
1477 			bcopy(bp->b_data, chain->data->ipdata.u.data,
1478 			      HAMMER2_EMBEDDED_BYTES);
1479 			error = 0;
1480 			break;
1481 		case HAMMER2_BREF_TYPE_DATA:
1482 			error = hammer2_io_newnz(chain->hmp,
1483 						 chain->bref.data_off,
1484 						 chain->bytes, &dio);
1485 			if (error) {
1486 				hammer2_io_bqrelse(&dio);
1487 				kprintf("hammer2: WRITE PATH: "
1488 					"dbp bread error\n");
1489 				break;
1490 			}
1491 			bdata = hammer2_io_data(dio, chain->bref.data_off);
1492 
1493 			chain->bref.methods = HAMMER2_ENC_COMP(
1494 							HAMMER2_COMP_NONE) +
1495 					      HAMMER2_ENC_CHECK(temp_check);
1496 			bcopy(bp->b_data, bdata, chain->bytes);
1497 
1498 			/*
1499 			 * Device buffer is now valid, chain is no
1500 			 * longer in the initial state.
1501 			 */
1502 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1503 
1504 			if (ioflag & IO_SYNC) {
1505 				/*
1506 				 * Synchronous I/O requested.
1507 				 */
1508 				hammer2_io_bwrite(&dio);
1509 			/*
1510 			} else if ((ioflag & IO_DIRECT) &&
1511 				   loff + n == pblksize) {
1512 				hammer2_io_bdwrite(&dio);
1513 			*/
1514 			} else if (ioflag & IO_ASYNC) {
1515 				hammer2_io_bawrite(&dio);
1516 			} else {
1517 				hammer2_io_bdwrite(&dio);
1518 			}
1519 			break;
1520 		default:
1521 			panic("hammer2_write_bp: bad chain type %d\n",
1522 			      chain->bref.type);
1523 			/* NOT REACHED */
1524 			error = 0;
1525 			break;
1526 		}
1527 		KKASSERT(error == 0);	/* XXX TODO */
1528 	}
1529 	*errorp = error;
1530 }
1531 
1532 static
1533 int
1534 hammer2_remount(hammer2_mount_t *hmp, struct mount *mp, char *path,
1535 		struct vnode *devvp, struct ucred *cred)
1536 {
1537 	int error;
1538 
1539 	if (hmp->ronly && (mp->mnt_kern_flag & MNTK_WANTRDWR)) {
1540 		error = hammer2_recovery(hmp);
1541 	} else {
1542 		error = 0;
1543 	}
1544 	return error;
1545 }
1546 
1547 static
1548 int
1549 hammer2_vfs_unmount(struct mount *mp, int mntflags)
1550 {
1551 	hammer2_pfsmount_t *pmp;
1552 	hammer2_mount_t *hmp;
1553 	hammer2_chain_t *rchain;
1554 	hammer2_cluster_t *cluster;
1555 	int flags;
1556 	int error = 0;
1557 	int i;
1558 
1559 	pmp = MPTOPMP(mp);
1560 
1561 	if (pmp == NULL)
1562 		return(0);
1563 
1564 	lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1565 	TAILQ_REMOVE(&hammer2_pfslist, pmp, mntentry);
1566 
1567 	/*
1568 	 * If mount initialization proceeded far enough we must flush
1569 	 * its vnodes.
1570 	 */
1571 	if (mntflags & MNT_FORCE)
1572 		flags = FORCECLOSE;
1573 	else
1574 		flags = 0;
1575 	if (pmp->iroot) {
1576 		error = vflush(mp, 0, flags);
1577 		if (error)
1578 			goto failed;
1579 	}
1580 
1581 	ccms_domain_uninit(&pmp->ccms_dom);
1582 
1583 	if (pmp->wthread_td) {
1584 		mtx_lock(&pmp->wthread_mtx);
1585 		pmp->wthread_destroy = 1;
1586 		wakeup(&pmp->wthread_bioq);
1587 		while (pmp->wthread_destroy != -1) {
1588 			mtxsleep(&pmp->wthread_destroy,
1589 				&pmp->wthread_mtx, 0,
1590 				"umount-sleep",	0);
1591 		}
1592 		mtx_unlock(&pmp->wthread_mtx);
1593 		pmp->wthread_td = NULL;
1594 	}
1595 
1596 	/*
1597 	 * Cleanup our reference on ihidden.
1598 	 */
1599 	if (pmp->ihidden) {
1600 		hammer2_inode_drop(pmp->ihidden);
1601 		pmp->ihidden = NULL;
1602 	}
1603 
1604 	/*
1605 	 * Cleanup our reference on iroot.  iroot is (should) not be needed
1606 	 * by the flush code.
1607 	 */
1608 	if (pmp->iroot) {
1609 		cluster = &pmp->iroot->cluster;
1610 		for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
1611 			rchain = pmp->iroot->cluster.array[i];
1612 			if (rchain == NULL)
1613 				continue;
1614 			hmp = rchain->hmp;
1615 			hammer2_vfs_unmount_hmp1(mp, hmp);
1616 
1617 			atomic_clear_int(&rchain->flags, HAMMER2_CHAIN_MOUNTED);
1618 #if REPORT_REFS_ERRORS
1619 			if (rchain->refs != 1)
1620 				kprintf("PMP->RCHAIN %p REFS WRONG %d\n",
1621 					rchain, rchain->refs);
1622 #else
1623 			KKASSERT(rchain->refs == 1);
1624 #endif
1625 			hammer2_chain_drop(rchain);
1626 			cluster->array[i] = NULL;
1627 			hammer2_vfs_unmount_hmp2(mp, hmp);
1628 		}
1629 		cluster->focus = NULL;
1630 
1631 #if REPORT_REFS_ERRORS
1632 		if (pmp->iroot->refs != 1)
1633 			kprintf("PMP->IROOT %p REFS WRONG %d\n",
1634 				pmp->iroot, pmp->iroot->refs);
1635 #else
1636 		KKASSERT(pmp->iroot->refs == 1);
1637 #endif
1638 		/* ref for pmp->iroot */
1639 		hammer2_inode_drop(pmp->iroot);
1640 		pmp->iroot = NULL;
1641 	}
1642 
1643 	pmp->mp = NULL;
1644 	mp->mnt_data = NULL;
1645 
1646 	kmalloc_destroy(&pmp->mmsg);
1647 	kmalloc_destroy(&pmp->minode);
1648 
1649 	kfree(pmp, M_HAMMER2);
1650 	error = 0;
1651 
1652 failed:
1653 	lockmgr(&hammer2_mntlk, LK_RELEASE);
1654 
1655 	return (error);
1656 }
1657 
1658 static
1659 void
1660 hammer2_vfs_unmount_hmp1(struct mount *mp, hammer2_mount_t *hmp)
1661 {
1662 	hammer2_mount_exlock(hmp);
1663 	--hmp->pmp_count;
1664 
1665 	kprintf("hammer2_unmount hmp=%p pmpcnt=%d\n", hmp, hmp->pmp_count);
1666 
1667 	kdmsg_iocom_uninit(&hmp->iocom);	/* XXX chain depend deadlck? */
1668 
1669 	/*
1670 	 * Flush any left over chains.  The voldata lock is only used
1671 	 * to synchronize against HAMMER2_CHAIN_MODIFIED_AUX.
1672 	 *
1673 	 * Flush twice to ensure that the freemap is completely
1674 	 * synchronized.  If we only do it once the next mount's
1675 	 * recovery scan will have to do some fixups (which isn't
1676 	 * bad, but we don't want it to have to do it except when
1677 	 * recovering from a crash).
1678 	 */
1679 	hammer2_voldata_lock(hmp);
1680 	if (((hmp->vchain.flags | hmp->fchain.flags) &
1681 	     HAMMER2_CHAIN_MODIFIED) ||
1682 	    hmp->vchain.update_xhi > hmp->vchain.update_xlo ||
1683 	    hmp->fchain.update_xhi > hmp->fchain.update_xlo) {
1684 		hammer2_voldata_unlock(hmp);
1685 		hammer2_vfs_sync(mp, MNT_WAIT);
1686 		/*hammer2_vfs_sync(mp, MNT_WAIT);*/
1687 	} else {
1688 		hammer2_voldata_unlock(hmp);
1689 	}
1690 	if (hmp->pmp_count == 0) {
1691 		if (((hmp->vchain.flags | hmp->fchain.flags) &
1692 		     HAMMER2_CHAIN_MODIFIED) ||
1693 		    hmp->vchain.update_xhi > hmp->vchain.update_xlo ||
1694 		    hmp->fchain.update_xhi > hmp->fchain.update_xlo) {
1695 			kprintf("hammer2_unmount: chains left over "
1696 				"after final sync\n");
1697 			kprintf("    vchain %08x update_xlo/hi %08x/%08x\n",
1698 				hmp->vchain.flags,
1699 				hmp->vchain.update_xlo,
1700 				hmp->vchain.update_xhi);
1701 			kprintf("    fchain %08x update_xhi/hi %08x/%08x\n",
1702 				hmp->fchain.flags,
1703 				hmp->fchain.update_xlo,
1704 				hmp->fchain.update_xhi);
1705 
1706 			if (hammer2_debug & 0x0010)
1707 				Debugger("entered debugger");
1708 		}
1709 	}
1710 }
1711 
1712 static
1713 void
1714 hammer2_vfs_unmount_hmp2(struct mount *mp, hammer2_mount_t *hmp)
1715 {
1716 	hammer2_pfsmount_t *spmp;
1717 	struct vnode *devvp;
1718 	int dumpcnt;
1719 	int ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
1720 
1721 	/*
1722 	 * If no PFS's left drop the master hammer2_mount for the
1723 	 * device.
1724 	 */
1725 	if (hmp->pmp_count == 0) {
1726 		/*
1727 		 * Clean up SPMP and the super-root inode
1728 		 */
1729 		spmp = hmp->spmp;
1730 		if (spmp) {
1731 			if (spmp->iroot) {
1732 				hammer2_inode_drop(spmp->iroot);
1733 				spmp->iroot = NULL;
1734 			}
1735 			hmp->spmp = NULL;
1736 			kmalloc_destroy(&spmp->mmsg);
1737 			kmalloc_destroy(&spmp->minode);
1738 			kfree(spmp, M_HAMMER2);
1739 		}
1740 
1741 		/*
1742 		 * Finish up with the device vnode
1743 		 */
1744 		if ((devvp = hmp->devvp) != NULL) {
1745 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1746 			vinvalbuf(devvp, (ronly ? 0 : V_SAVE), 0, 0);
1747 			hmp->devvp = NULL;
1748 			VOP_CLOSE(devvp, (ronly ? FREAD : FREAD|FWRITE), NULL);
1749 			vn_unlock(devvp);
1750 			vrele(devvp);
1751 			devvp = NULL;
1752 		}
1753 
1754 		/*
1755 		 * Clear vchain/fchain flags that might prevent final cleanup
1756 		 * of these chains.
1757 		 */
1758 		if (hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) {
1759 			atomic_clear_int(&hmp->vchain.flags,
1760 					 HAMMER2_CHAIN_MODIFIED);
1761 			hammer2_chain_drop(&hmp->vchain);
1762 		}
1763 		if (hmp->vchain.flags & HAMMER2_CHAIN_FLUSH_CREATE) {
1764 			atomic_clear_int(&hmp->vchain.flags,
1765 					 HAMMER2_CHAIN_FLUSH_CREATE);
1766 			hammer2_chain_drop(&hmp->vchain);
1767 		}
1768 		if (hmp->vchain.flags & HAMMER2_CHAIN_FLUSH_DELETE) {
1769 			atomic_clear_int(&hmp->vchain.flags,
1770 					 HAMMER2_CHAIN_FLUSH_DELETE);
1771 			hammer2_chain_drop(&hmp->vchain);
1772 		}
1773 
1774 		if (hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) {
1775 			atomic_clear_int(&hmp->fchain.flags,
1776 					 HAMMER2_CHAIN_MODIFIED);
1777 			hammer2_chain_drop(&hmp->fchain);
1778 		}
1779 		if (hmp->fchain.flags & HAMMER2_CHAIN_FLUSH_CREATE) {
1780 			atomic_clear_int(&hmp->fchain.flags,
1781 					 HAMMER2_CHAIN_FLUSH_CREATE);
1782 			hammer2_chain_drop(&hmp->fchain);
1783 		}
1784 		if (hmp->fchain.flags & HAMMER2_CHAIN_FLUSH_DELETE) {
1785 			atomic_clear_int(&hmp->fchain.flags,
1786 					 HAMMER2_CHAIN_FLUSH_DELETE);
1787 			hammer2_chain_drop(&hmp->fchain);
1788 		}
1789 
1790 		/*
1791 		 * Final drop of embedded freemap root chain to
1792 		 * clean up fchain.core (fchain structure is not
1793 		 * flagged ALLOCATED so it is cleaned out and then
1794 		 * left to rot).
1795 		 */
1796 		hammer2_chain_drop(&hmp->fchain);
1797 
1798 		/*
1799 		 * Final drop of embedded volume root chain to clean
1800 		 * up vchain.core (vchain structure is not flagged
1801 		 * ALLOCATED so it is cleaned out and then left to
1802 		 * rot).
1803 		 */
1804 		dumpcnt = 50;
1805 		hammer2_dump_chain(&hmp->vchain, 0, &dumpcnt, 'v');
1806 		dumpcnt = 50;
1807 		hammer2_dump_chain(&hmp->fchain, 0, &dumpcnt, 'f');
1808 		hammer2_mount_unlock(hmp);
1809 		hammer2_chain_drop(&hmp->vchain);
1810 
1811 		hammer2_io_cleanup(hmp, &hmp->iotree);
1812 		if (hmp->iofree_count) {
1813 			kprintf("io_cleanup: %d I/O's left hanging\n",
1814 				hmp->iofree_count);
1815 		}
1816 
1817 		TAILQ_REMOVE(&hammer2_mntlist, hmp, mntentry);
1818 		kmalloc_destroy(&hmp->mchain);
1819 		kfree(hmp, M_HAMMER2);
1820 	} else {
1821 		hammer2_mount_unlock(hmp);
1822 	}
1823 }
1824 
1825 static
1826 int
1827 hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
1828 	     ino_t ino, struct vnode **vpp)
1829 {
1830 	kprintf("hammer2_vget\n");
1831 	return (EOPNOTSUPP);
1832 }
1833 
1834 static
1835 int
1836 hammer2_vfs_root(struct mount *mp, struct vnode **vpp)
1837 {
1838 	hammer2_pfsmount_t *pmp;
1839 	hammer2_cluster_t *cparent;
1840 	int error;
1841 	struct vnode *vp;
1842 
1843 	pmp = MPTOPMP(mp);
1844 	if (pmp->iroot == NULL) {
1845 		*vpp = NULL;
1846 		error = EINVAL;
1847 	} else {
1848 		cparent = hammer2_inode_lock_sh(pmp->iroot);
1849 		vp = hammer2_igetv(pmp->iroot, cparent, &error);
1850 		hammer2_inode_unlock_sh(pmp->iroot, cparent);
1851 		*vpp = vp;
1852 		if (vp == NULL)
1853 			kprintf("vnodefail\n");
1854 	}
1855 
1856 	return (error);
1857 }
1858 
1859 /*
1860  * Filesystem status
1861  *
1862  * XXX incorporate ipdata->inode_quota and data_quota
1863  */
1864 static
1865 int
1866 hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred)
1867 {
1868 	hammer2_pfsmount_t *pmp;
1869 	hammer2_mount_t *hmp;
1870 
1871 	pmp = MPTOPMP(mp);
1872 	KKASSERT(pmp->iroot->cluster.nchains >= 1);
1873 	hmp = pmp->iroot->cluster.focus->hmp;	/* XXX */
1874 
1875 	mp->mnt_stat.f_files = pmp->inode_count;
1876 	mp->mnt_stat.f_ffree = 0;
1877 	mp->mnt_stat.f_blocks = hmp->voldata.allocator_size / HAMMER2_PBUFSIZE;
1878 	mp->mnt_stat.f_bfree =  hmp->voldata.allocator_free / HAMMER2_PBUFSIZE;
1879 	mp->mnt_stat.f_bavail = mp->mnt_stat.f_bfree;
1880 
1881 	*sbp = mp->mnt_stat;
1882 	return (0);
1883 }
1884 
1885 static
1886 int
1887 hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp, struct ucred *cred)
1888 {
1889 	hammer2_pfsmount_t *pmp;
1890 	hammer2_mount_t *hmp;
1891 
1892 	pmp = MPTOPMP(mp);
1893 	KKASSERT(pmp->iroot->cluster.nchains >= 1);
1894 	hmp = pmp->iroot->cluster.focus->hmp;	/* XXX */
1895 
1896 	mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1897 	mp->mnt_vstat.f_files = pmp->inode_count;
1898 	mp->mnt_vstat.f_ffree = 0;
1899 	mp->mnt_vstat.f_blocks = hmp->voldata.allocator_size / HAMMER2_PBUFSIZE;
1900 	mp->mnt_vstat.f_bfree =  hmp->voldata.allocator_free / HAMMER2_PBUFSIZE;
1901 	mp->mnt_vstat.f_bavail = mp->mnt_vstat.f_bfree;
1902 
1903 	*sbp = mp->mnt_vstat;
1904 	return (0);
1905 }
1906 
1907 /*
1908  * Mount-time recovery (RW mounts)
1909  *
1910  * Updates to the free block table are allowed to lag flushes by one
1911  * transaction.  In case of a crash, then on a fresh mount we must do an
1912  * incremental scan of the last committed transaction id and make sure that
1913  * all related blocks have been marked allocated.
1914  *
1915  * The super-root topology and each PFS has its own transaction id domain,
1916  * so we must track PFS boundary transitions.
1917  */
1918 struct hammer2_recovery_elm {
1919 	TAILQ_ENTRY(hammer2_recovery_elm) entry;
1920 	hammer2_chain_t *chain;
1921 	hammer2_tid_t sync_tid;
1922 };
1923 
1924 TAILQ_HEAD(hammer2_recovery_list, hammer2_recovery_elm);
1925 
1926 struct hammer2_recovery_info {
1927 	struct hammer2_recovery_list list;
1928 	int	depth;
1929 };
1930 
1931 static int hammer2_recovery_scan(hammer2_trans_t *trans, hammer2_mount_t *hmp,
1932 			hammer2_chain_t *parent,
1933 			struct hammer2_recovery_info *info,
1934 			hammer2_tid_t sync_tid);
1935 
1936 #define HAMMER2_RECOVERY_MAXDEPTH	10
1937 
1938 static
1939 int
1940 hammer2_recovery(hammer2_mount_t *hmp)
1941 {
1942 	hammer2_trans_t trans;
1943 	struct hammer2_recovery_info info;
1944 	struct hammer2_recovery_elm *elm;
1945 	hammer2_chain_t *parent;
1946 	hammer2_tid_t sync_tid;
1947 	int error;
1948 	int cumulative_error = 0;
1949 
1950 	hammer2_trans_init(&trans, hmp->spmp, 0);
1951 
1952 	sync_tid = 0;
1953 	TAILQ_INIT(&info.list);
1954 	info.depth = 0;
1955 	parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
1956 	cumulative_error = hammer2_recovery_scan(&trans, hmp, parent,
1957 						 &info, sync_tid);
1958 	hammer2_chain_lookup_done(parent);
1959 
1960 	while ((elm = TAILQ_FIRST(&info.list)) != NULL) {
1961 		TAILQ_REMOVE(&info.list, elm, entry);
1962 		parent = elm->chain;
1963 		sync_tid = elm->sync_tid;
1964 		kfree(elm, M_HAMMER2);
1965 
1966 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1967 					   HAMMER2_RESOLVE_NOREF);
1968 		error = hammer2_recovery_scan(&trans, hmp, parent,
1969 					      &info, sync_tid);
1970 		hammer2_chain_unlock(parent);
1971 		if (error)
1972 			cumulative_error = error;
1973 	}
1974 	hammer2_trans_done(&trans);
1975 
1976 	return cumulative_error;
1977 }
1978 
1979 static
1980 int
1981 hammer2_recovery_scan(hammer2_trans_t *trans, hammer2_mount_t *hmp,
1982 		      hammer2_chain_t *parent,
1983 		      struct hammer2_recovery_info *info,
1984 		      hammer2_tid_t sync_tid)
1985 {
1986 	hammer2_chain_t *chain;
1987 	int cache_index;
1988 	int cumulative_error = 0;
1989 	int pfs_boundary = 0;
1990 	int error;
1991 
1992 	/*
1993 	 * Adjust freemap to ensure that the block(s) are marked allocated.
1994 	 */
1995 	if (parent->bref.type != HAMMER2_BREF_TYPE_VOLUME) {
1996 		hammer2_freemap_adjust(trans, hmp, &parent->bref,
1997 				       HAMMER2_FREEMAP_DORECOVER);
1998 	}
1999 
2000 	/*
2001 	 * Check type for recursive scan
2002 	 */
2003 	switch(parent->bref.type) {
2004 	case HAMMER2_BREF_TYPE_VOLUME:
2005 		/* data already instantiated */
2006 		break;
2007 	case HAMMER2_BREF_TYPE_INODE:
2008 		/*
2009 		 * Must instantiate data for DIRECTDATA test and also
2010 		 * for recursion.
2011 		 */
2012 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2013 		if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2014 			/* not applicable to recovery scan */
2015 			hammer2_chain_unlock(parent);
2016 			return 0;
2017 		}
2018 		if ((parent->data->ipdata.op_flags & HAMMER2_OPFLAG_PFSROOT) &&
2019 		    info->depth != 0) {
2020 			pfs_boundary = 1;
2021 			sync_tid = parent->bref.mirror_tid - 1;
2022 		}
2023 		hammer2_chain_unlock(parent);
2024 		break;
2025 	case HAMMER2_BREF_TYPE_INDIRECT:
2026 		/*
2027 		 * Must instantiate data for recursion
2028 		 */
2029 		hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2030 		hammer2_chain_unlock(parent);
2031 		break;
2032 	case HAMMER2_BREF_TYPE_DATA:
2033 	case HAMMER2_BREF_TYPE_FREEMAP:
2034 	case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2035 	case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2036 		/* not applicable to recovery scan */
2037 		return 0;
2038 		break;
2039 	default:
2040 		return EDOM;
2041 	}
2042 
2043 	/*
2044 	 * Defer operation if depth limit reached or if we are crossing a
2045 	 * PFS boundary.
2046 	 */
2047 	if (info->depth >= HAMMER2_RECOVERY_MAXDEPTH || pfs_boundary) {
2048 		struct hammer2_recovery_elm *elm;
2049 
2050 		elm = kmalloc(sizeof(*elm), M_HAMMER2, M_ZERO | M_WAITOK);
2051 		elm->chain = parent;
2052 		elm->sync_tid = sync_tid;
2053 		hammer2_chain_ref(parent);
2054 		TAILQ_INSERT_TAIL(&info->list, elm, entry);
2055 		/* unlocked by caller */
2056 
2057 		return(0);
2058 	}
2059 
2060 
2061 	/*
2062 	 * Recursive scan of the last flushed transaction only.  We are
2063 	 * doing this without pmp assignments so don't leave the chains
2064 	 * hanging around after we are done with them.
2065 	 */
2066 	cache_index = 0;
2067 	chain = hammer2_chain_scan(parent, NULL, &cache_index,
2068 				   HAMMER2_LOOKUP_NODATA);
2069 	while (chain) {
2070 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
2071 		if (chain->bref.mirror_tid >= sync_tid) {
2072 			++info->depth;
2073 			error = hammer2_recovery_scan(trans, hmp, chain,
2074 						      info, sync_tid);
2075 			--info->depth;
2076 			if (error)
2077 				cumulative_error = error;
2078 		}
2079 		chain = hammer2_chain_scan(parent, chain, &cache_index,
2080 					   HAMMER2_LOOKUP_NODATA);
2081 	}
2082 
2083 	return cumulative_error;
2084 }
2085 
2086 /*
2087  * Sync the entire filesystem; this is called from the filesystem syncer
2088  * process periodically and whenever a user calls sync(1) on the hammer
2089  * mountpoint.
2090  *
2091  * Currently is actually called from the syncer! \o/
2092  *
2093  * This task will have to snapshot the state of the dirty inode chain.
2094  * From that, it will have to make sure all of the inodes on the dirty
2095  * chain have IO initiated. We make sure that io is initiated for the root
2096  * block.
2097  *
2098  * If waitfor is set, we wait for media to acknowledge the new rootblock.
2099  *
2100  * THINKS: side A vs side B, to have sync not stall all I/O?
2101  */
2102 int
2103 hammer2_vfs_sync(struct mount *mp, int waitfor)
2104 {
2105 	struct hammer2_sync_info info;
2106 	hammer2_inode_t *iroot;
2107 	hammer2_chain_t *chain;
2108 	hammer2_chain_t *parent;
2109 	hammer2_pfsmount_t *pmp;
2110 	hammer2_mount_t *hmp;
2111 	int flags;
2112 	int error;
2113 	int total_error;
2114 	int force_fchain;
2115 	int i;
2116 	int j;
2117 
2118 	pmp = MPTOPMP(mp);
2119 	iroot = pmp->iroot;
2120 	KKASSERT(iroot);
2121 	KKASSERT(iroot->pmp == pmp);
2122 
2123 	/*
2124 	 * We can't acquire locks on existing vnodes while in a transaction
2125 	 * without risking a deadlock.  This assumes that vfsync() can be
2126 	 * called without the vnode locked (which it can in DragonFly).
2127 	 * Otherwise we'd have to implement a multi-pass or flag the lock
2128 	 * failures and retry.
2129 	 *
2130 	 * The reclamation code interlocks with the sync list's token
2131 	 * (by removing the vnode from the scan list) before unlocking
2132 	 * the inode, giving us time to ref the inode.
2133 	 */
2134 	/*flags = VMSC_GETVP;*/
2135 	flags = 0;
2136 	if (waitfor & MNT_LAZY)
2137 		flags |= VMSC_ONEPASS;
2138 
2139 	/*
2140 	 * Start our flush transaction.  This does not return until all
2141 	 * concurrent transactions have completed and will prevent any
2142 	 * new transactions from running concurrently, except for the
2143 	 * buffer cache transactions.
2144 	 *
2145 	 * For efficiency do an async pass before making sure with a
2146 	 * synchronous pass on all related buffer cache buffers.  It
2147 	 * should theoretically not be possible for any new file buffers
2148 	 * to be instantiated during this sequence.
2149 	 */
2150 	hammer2_trans_init(&info.trans, pmp, HAMMER2_TRANS_ISFLUSH |
2151 					     HAMMER2_TRANS_PREFLUSH);
2152 	hammer2_run_unlinkq(&info.trans, pmp);
2153 
2154 	info.error = 0;
2155 	info.waitfor = MNT_NOWAIT;
2156 	vsyncscan(mp, flags | VMSC_NOWAIT, hammer2_sync_scan2, &info);
2157 	info.waitfor = MNT_WAIT;
2158 	vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2159 
2160 	/*
2161 	 * Clear PREFLUSH.  This prevents (or asserts on) any new logical
2162 	 * buffer cache flushes which occur during the flush.  Device buffers
2163 	 * are not affected.
2164 	 */
2165 
2166 #if 0
2167 	if (info.error == 0 && (waitfor & MNT_WAIT)) {
2168 		info.waitfor = waitfor;
2169 		    vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2170 
2171 	}
2172 #endif
2173 	hammer2_bioq_sync(info.trans.pmp);
2174 	atomic_clear_int(&info.trans.flags, HAMMER2_TRANS_PREFLUSH);
2175 
2176 	total_error = 0;
2177 
2178 	/*
2179 	 * Flush all storage elements making up the cluster
2180 	 *
2181 	 * We must also flush any deleted siblings because the super-root
2182 	 * flush won't do it for us.  They all must be staged or the
2183 	 * super-root flush will not be able to update its block table
2184 	 * properly.
2185 	 *
2186 	 * XXX currently done serially instead of concurrently
2187 	 */
2188 	for (i = 0; iroot && i < iroot->cluster.nchains; ++i) {
2189 		chain = iroot->cluster.array[i];
2190 		if (chain) {
2191 			hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
2192 			hammer2_flush(&info.trans, &chain);
2193 			hammer2_chain_unlock(chain);
2194 		}
2195 		if (chain) {
2196 			hammer2_chain_t *nchain;
2197 			chain = TAILQ_FIRST(&chain->core->ownerq);
2198 			hammer2_chain_ref(chain);
2199 			while (chain) {
2200 				hammer2_chain_lock(chain,
2201 						   HAMMER2_RESOLVE_ALWAYS);
2202 				hammer2_flush(&info.trans, &chain);
2203 				hammer2_chain_unlock(chain);
2204 				nchain = TAILQ_NEXT(chain, core_entry);
2205 				if (nchain)
2206 					hammer2_chain_ref(nchain);
2207 				hammer2_chain_drop(chain);
2208 				chain = nchain;
2209 			}
2210 		}
2211 	}
2212 #if 0
2213 	hammer2_trans_done(&info.trans);
2214 #endif
2215 
2216 	/*
2217 	 * Flush all volume roots to synchronize PFS flushes with the
2218 	 * storage media.  Use a super-root transaction for each one.
2219 	 *
2220 	 * The flush code will detect super-root -> pfs-root chain
2221 	 * transitions using the last pfs-root flush.
2222 	 */
2223 	for (i = 0; iroot && i < iroot->cluster.nchains; ++i) {
2224 		chain = iroot->cluster.array[i];
2225 		if (chain == NULL)
2226 			continue;
2227 
2228 		hmp = chain->hmp;
2229 
2230 		/*
2231 		 * We only have to flush each hmp once
2232 		 */
2233 		for (j = i - 1; j >= 0; --j) {
2234 			if (iroot->cluster.array[j] &&
2235 			    iroot->cluster.array[j]->hmp == hmp)
2236 				break;
2237 		}
2238 		if (j >= 0)
2239 			continue;
2240 		hammer2_trans_spmp(&info.trans, hmp->spmp);
2241 
2242 		/*
2243 		 * Force an update of the XID from the PFS root to the
2244 		 * topology root.  We couldn't do this from the PFS
2245 		 * transaction because a SPMP transaction is needed.
2246 		 * This does not modify blocks, instead what it does is
2247 		 * allow the flush code to find the transition point and
2248 		 * then update on the way back up.
2249 		 */
2250 		parent = TAILQ_LAST(&chain->above->ownerq, h2_core_list);
2251 		KKASSERT(chain->pmp != parent->pmp);
2252 		hammer2_chain_setsubmod(&info.trans, parent);
2253 
2254 		/*
2255 		 * Media mounts have two 'roots', vchain for the topology
2256 		 * and fchain for the free block table.  Flush both.
2257 		 *
2258 		 * Note that the topology and free block table are handled
2259 		 * independently, so the free block table can wind up being
2260 		 * ahead of the topology.  We depend on the bulk free scan
2261 		 * code to deal with any loose ends.
2262 		 */
2263 		hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
2264 		hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
2265 		if ((hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) ||
2266 		    hmp->fchain.update_xhi > hmp->fchain.update_xlo) {
2267 			/*
2268 			 * This will also modify vchain as a side effect,
2269 			 * mark vchain as modified now.
2270 			 */
2271 			hammer2_voldata_modify(hmp);
2272 			chain = &hmp->fchain;
2273 			hammer2_flush(&info.trans, &chain);
2274 			KKASSERT(chain == &hmp->fchain);
2275 		}
2276 		hammer2_chain_unlock(&hmp->fchain);
2277 		hammer2_chain_unlock(&hmp->vchain);
2278 
2279 		hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
2280 		if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) ||
2281 		    hmp->vchain.update_xhi > hmp->vchain.update_xlo) {
2282 			chain = &hmp->vchain;
2283 			hammer2_flush(&info.trans, &chain);
2284 			KKASSERT(chain == &hmp->vchain);
2285 			force_fchain = 1;
2286 		} else {
2287 			force_fchain = 0;
2288 		}
2289 		hammer2_chain_unlock(&hmp->vchain);
2290 
2291 #if 0
2292 		hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
2293 		if ((hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) ||
2294 		    hmp->fchain.update_xhi > hmp->fchain.update_xlo ||
2295 		    force_fchain) {
2296 			/* this will also modify vchain as a side effect */
2297 			chain = &hmp->fchain;
2298 			hammer2_flush(&info.trans, &chain);
2299 			KKASSERT(chain == &hmp->fchain);
2300 		}
2301 		hammer2_chain_unlock(&hmp->fchain);
2302 #endif
2303 
2304 		error = 0;
2305 
2306 		/*
2307 		 * We can't safely flush the volume header until we have
2308 		 * flushed any device buffers which have built up.
2309 		 *
2310 		 * XXX this isn't being incremental
2311 		 */
2312 		vn_lock(hmp->devvp, LK_EXCLUSIVE | LK_RETRY);
2313 		error = VOP_FSYNC(hmp->devvp, MNT_WAIT, 0);
2314 		vn_unlock(hmp->devvp);
2315 
2316 		/*
2317 		 * The flush code sets CHAIN_VOLUMESYNC to indicate that the
2318 		 * volume header needs synchronization via hmp->volsync.
2319 		 *
2320 		 * XXX synchronize the flag & data with only this flush XXX
2321 		 */
2322 		if (error == 0 &&
2323 		    (hmp->vchain.flags & HAMMER2_CHAIN_VOLUMESYNC)) {
2324 			struct buf *bp;
2325 
2326 			/*
2327 			 * Synchronize the disk before flushing the volume
2328 			 * header.
2329 			 */
2330 			bp = getpbuf(NULL);
2331 			bp->b_bio1.bio_offset = 0;
2332 			bp->b_bufsize = 0;
2333 			bp->b_bcount = 0;
2334 			bp->b_cmd = BUF_CMD_FLUSH;
2335 			bp->b_bio1.bio_done = biodone_sync;
2336 			bp->b_bio1.bio_flags |= BIO_SYNC;
2337 			vn_strategy(hmp->devvp, &bp->b_bio1);
2338 			biowait(&bp->b_bio1, "h2vol");
2339 			relpbuf(bp, NULL);
2340 
2341 			/*
2342 			 * Then we can safely flush the version of the
2343 			 * volume header synchronized by the flush code.
2344 			 */
2345 			i = hmp->volhdrno + 1;
2346 			if (i >= HAMMER2_NUM_VOLHDRS)
2347 				i = 0;
2348 			if (i * HAMMER2_ZONE_BYTES64 + HAMMER2_SEGSIZE >
2349 			    hmp->volsync.volu_size) {
2350 				i = 0;
2351 			}
2352 			kprintf("sync volhdr %d %jd\n",
2353 				i, (intmax_t)hmp->volsync.volu_size);
2354 			bp = getblk(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2355 				    HAMMER2_PBUFSIZE, 0, 0);
2356 			atomic_clear_int(&hmp->vchain.flags,
2357 					 HAMMER2_CHAIN_VOLUMESYNC);
2358 			bcopy(&hmp->volsync, bp->b_data, HAMMER2_PBUFSIZE);
2359 			bawrite(bp);
2360 			hmp->volhdrno = i;
2361 		}
2362 		if (error)
2363 			total_error = error;
2364 
2365 #if 0
2366 		hammer2_trans_done(&info.trans);
2367 #endif
2368 	}
2369 	hammer2_trans_done(&info.trans);
2370 
2371 	return (total_error);
2372 }
2373 
2374 /*
2375  * Sync passes.
2376  */
2377 static int
2378 hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data)
2379 {
2380 	struct hammer2_sync_info *info = data;
2381 	hammer2_inode_t *ip;
2382 	int error;
2383 
2384 	/*
2385 	 *
2386 	 */
2387 	ip = VTOI(vp);
2388 	if (ip == NULL)
2389 		return(0);
2390 	if (vp->v_type == VNON || vp->v_type == VBAD) {
2391 		vclrisdirty(vp);
2392 		return(0);
2393 	}
2394 	if ((ip->flags & HAMMER2_INODE_MODIFIED) == 0 &&
2395 	    RB_EMPTY(&vp->v_rbdirty_tree)) {
2396 		vclrisdirty(vp);
2397 		return(0);
2398 	}
2399 
2400 	/*
2401 	 * VOP_FSYNC will start a new transaction so replicate some code
2402 	 * here to do it inline (see hammer2_vop_fsync()).
2403 	 *
2404 	 * WARNING: The vfsync interacts with the buffer cache and might
2405 	 *          block, we can't hold the inode lock at that time.
2406 	 *	    However, we MUST ref ip before blocking to ensure that
2407 	 *	    it isn't ripped out from under us (since we do not
2408 	 *	    hold a lock on the vnode).
2409 	 */
2410 	hammer2_inode_ref(ip);
2411 	atomic_clear_int(&ip->flags, HAMMER2_INODE_MODIFIED);
2412 	if (vp)
2413 		vfsync(vp, MNT_NOWAIT, 1, NULL, NULL);
2414 
2415 	hammer2_inode_drop(ip);
2416 #if 1
2417 	error = 0;
2418 	if (error)
2419 		info->error = error;
2420 #endif
2421 	return(0);
2422 }
2423 
2424 static
2425 int
2426 hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp)
2427 {
2428 	return (0);
2429 }
2430 
2431 static
2432 int
2433 hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
2434 	       struct fid *fhp, struct vnode **vpp)
2435 {
2436 	return (0);
2437 }
2438 
2439 static
2440 int
2441 hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
2442 		 int *exflagsp, struct ucred **credanonp)
2443 {
2444 	return (0);
2445 }
2446 
2447 /*
2448  * Support code for hammer2_mount().  Read, verify, and install the volume
2449  * header into the HMP
2450  *
2451  * XXX read four volhdrs and use the one with the highest TID whos CRC
2452  *     matches.
2453  *
2454  * XXX check iCRCs.
2455  *
2456  * XXX For filesystems w/ less than 4 volhdrs, make sure to not write to
2457  *     nonexistant locations.
2458  *
2459  * XXX Record selected volhdr and ring updates to each of 4 volhdrs
2460  */
2461 static
2462 int
2463 hammer2_install_volume_header(hammer2_mount_t *hmp)
2464 {
2465 	hammer2_volume_data_t *vd;
2466 	struct buf *bp;
2467 	hammer2_crc32_t crc0, crc, bcrc0, bcrc;
2468 	int error_reported;
2469 	int error;
2470 	int valid;
2471 	int i;
2472 
2473 	error_reported = 0;
2474 	error = 0;
2475 	valid = 0;
2476 	bp = NULL;
2477 
2478 	/*
2479 	 * There are up to 4 copies of the volume header (syncs iterate
2480 	 * between them so there is no single master).  We don't trust the
2481 	 * volu_size field so we don't know precisely how large the filesystem
2482 	 * is, so depend on the OS to return an error if we go beyond the
2483 	 * block device's EOF.
2484 	 */
2485 	for (i = 0; i < HAMMER2_NUM_VOLHDRS; i++) {
2486 		error = bread(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2487 			      HAMMER2_VOLUME_BYTES, &bp);
2488 		if (error) {
2489 			brelse(bp);
2490 			bp = NULL;
2491 			continue;
2492 		}
2493 
2494 		vd = (struct hammer2_volume_data *) bp->b_data;
2495 		if ((vd->magic != HAMMER2_VOLUME_ID_HBO) &&
2496 		    (vd->magic != HAMMER2_VOLUME_ID_ABO)) {
2497 			brelse(bp);
2498 			bp = NULL;
2499 			continue;
2500 		}
2501 
2502 		if (vd->magic == HAMMER2_VOLUME_ID_ABO) {
2503 			/* XXX: Reversed-endianness filesystem */
2504 			kprintf("hammer2: reverse-endian filesystem detected");
2505 			brelse(bp);
2506 			bp = NULL;
2507 			continue;
2508 		}
2509 
2510 		crc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT0];
2511 		crc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC0_OFF,
2512 				      HAMMER2_VOLUME_ICRC0_SIZE);
2513 		bcrc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT1];
2514 		bcrc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC1_OFF,
2515 				       HAMMER2_VOLUME_ICRC1_SIZE);
2516 		if ((crc0 != crc) || (bcrc0 != bcrc)) {
2517 			kprintf("hammer2 volume header crc "
2518 				"mismatch copy #%d %08x/%08x\n",
2519 				i, crc0, crc);
2520 			error_reported = 1;
2521 			brelse(bp);
2522 			bp = NULL;
2523 			continue;
2524 		}
2525 		if (valid == 0 || hmp->voldata.mirror_tid < vd->mirror_tid) {
2526 			valid = 1;
2527 			hmp->voldata = *vd;
2528 			hmp->volhdrno = i;
2529 		}
2530 		brelse(bp);
2531 		bp = NULL;
2532 	}
2533 	if (valid) {
2534 		hmp->volsync = hmp->voldata;
2535 		error = 0;
2536 		if (error_reported || bootverbose || 1) { /* 1/DEBUG */
2537 			kprintf("hammer2: using volume header #%d\n",
2538 				hmp->volhdrno);
2539 		}
2540 	} else {
2541 		error = EINVAL;
2542 		kprintf("hammer2: no valid volume headers found!\n");
2543 	}
2544 	return (error);
2545 }
2546 
2547 /*
2548  * Reconnect using the passed file pointer.  The caller must ref the
2549  * fp for us.
2550  */
2551 void
2552 hammer2_cluster_reconnect(hammer2_mount_t *hmp, struct file *fp)
2553 {
2554 	size_t name_len;
2555 	const char *name = "disk-volume";
2556 
2557 	/*
2558 	 * Closes old comm descriptor, kills threads, cleans up
2559 	 * states, then installs the new descriptor and creates
2560 	 * new threads.
2561 	 */
2562 	kdmsg_iocom_reconnect(&hmp->iocom, fp, "hammer2");
2563 
2564 	/*
2565 	 * Setup LNK_CONN fields for autoinitiated state machine.  We
2566 	 * will use SPANs to advertise multiple PFSs so only pass the
2567 	 * fsid and HAMMER2_PFSTYPE_SUPROOT for the AUTOCONN.
2568 	 *
2569 	 * We are not initiating a LNK_SPAN so we do not have to set-up
2570 	 * iocom.auto_lnk_span.
2571 	 */
2572 	bzero(&hmp->iocom.auto_lnk_conn.pfs_clid,
2573 	      sizeof(hmp->iocom.auto_lnk_conn.pfs_clid));
2574 	hmp->iocom.auto_lnk_conn.pfs_fsid = hmp->voldata.fsid;
2575 	hmp->iocom.auto_lnk_conn.pfs_type = HAMMER2_PFSTYPE_SUPROOT;
2576 	hmp->iocom.auto_lnk_conn.proto_version = DMSG_SPAN_PROTO_1;
2577 #if 0
2578 	hmp->iocom.auto_lnk_conn.peer_type = hmp->voldata.peer_type;
2579 #endif
2580 	hmp->iocom.auto_lnk_conn.peer_type = DMSG_PEER_HAMMER2;
2581 
2582 	/*
2583 	 * Filter adjustment.  Clients do not need visibility into other
2584 	 * clients (otherwise millions of clients would present a serious
2585 	 * problem).  The fs_label also serves to restrict the namespace.
2586 	 */
2587 	hmp->iocom.auto_lnk_conn.peer_mask = 1LLU << DMSG_PEER_HAMMER2;
2588 	hmp->iocom.auto_lnk_conn.pfs_mask = (uint64_t)-1;
2589 
2590 #if 0
2591 	switch (ipdata->pfs_type) {
2592 	case DMSG_PFSTYPE_CLIENT:
2593 		hmp->iocom.auto_lnk_conn.peer_mask &=
2594 				~(1LLU << DMSG_PFSTYPE_CLIENT);
2595 		break;
2596 	default:
2597 		break;
2598 	}
2599 #endif
2600 
2601 	name_len = strlen(name);
2602 	if (name_len >= sizeof(hmp->iocom.auto_lnk_conn.fs_label))
2603 		name_len = sizeof(hmp->iocom.auto_lnk_conn.fs_label) - 1;
2604 	bcopy(name, hmp->iocom.auto_lnk_conn.fs_label, name_len);
2605 	hmp->iocom.auto_lnk_conn.fs_label[name_len] = 0;
2606 
2607 	kdmsg_iocom_autoinitiate(&hmp->iocom, hammer2_autodmsg);
2608 }
2609 
2610 static int
2611 hammer2_rcvdmsg(kdmsg_msg_t *msg)
2612 {
2613 	kprintf("RCVMSG %08x\n", msg->tcmd);
2614 
2615 	switch(msg->tcmd) {
2616 	case DMSG_DBG_SHELL:
2617 		/*
2618 		 * (non-transaction)
2619 		 * Execute shell command (not supported atm)
2620 		 */
2621 		kdmsg_msg_result(msg, DMSG_ERR_NOSUPP);
2622 		break;
2623 	case DMSG_DBG_SHELL | DMSGF_REPLY:
2624 		/*
2625 		 * (non-transaction)
2626 		 */
2627 		if (msg->aux_data) {
2628 			msg->aux_data[msg->aux_size - 1] = 0;
2629 			kprintf("HAMMER2 DBG: %s\n", msg->aux_data);
2630 		}
2631 		break;
2632 	default:
2633 		/*
2634 		 * Unsupported message received.  We only need to
2635 		 * reply if it's a transaction in order to close our end.
2636 		 * Ignore any one-way messages or any further messages
2637 		 * associated with the transaction.
2638 		 *
2639 		 * NOTE: This case also includes DMSG_LNK_ERROR messages
2640 		 *	 which might be one-way, replying to those would
2641 		 *	 cause an infinite ping-pong.
2642 		 */
2643 		if (msg->any.head.cmd & DMSGF_CREATE)
2644 			kdmsg_msg_reply(msg, DMSG_ERR_NOSUPP);
2645 		break;
2646 	}
2647 	return(0);
2648 }
2649 
2650 /*
2651  * This function is called after KDMSG has automatically handled processing
2652  * of a LNK layer message (typically CONN, SPAN, or CIRC).
2653  *
2654  * We tag off the LNK_CONN to trigger our LNK_VOLCONF messages which
2655  * advertises all available hammer2 super-root volumes.
2656  */
2657 static void
2658 hammer2_autodmsg(kdmsg_msg_t *msg)
2659 {
2660 	hammer2_mount_t *hmp = msg->iocom->handle;
2661 	int copyid;
2662 
2663 	kprintf("RCAMSG %08x\n", msg->tcmd);
2664 
2665 	switch(msg->tcmd) {
2666 	case DMSG_LNK_CONN | DMSGF_CREATE | DMSGF_REPLY:
2667 	case DMSG_LNK_CONN | DMSGF_CREATE | DMSGF_DELETE | DMSGF_REPLY:
2668 		if (msg->any.head.cmd & DMSGF_CREATE) {
2669 			kprintf("HAMMER2: VOLDATA DUMP\n");
2670 
2671 			/*
2672 			 * Dump the configuration stored in the volume header.
2673 			 * This will typically be import/export access rights,
2674 			 * master encryption keys (encrypted), etc.
2675 			 */
2676 			hammer2_voldata_lock(hmp);
2677 			copyid = 0;
2678 			while (copyid < HAMMER2_COPYID_COUNT) {
2679 				if (hmp->voldata.copyinfo[copyid].copyid)
2680 					hammer2_volconf_update(hmp, copyid);
2681 				++copyid;
2682 			}
2683 			hammer2_voldata_unlock(hmp);
2684 
2685 			kprintf("HAMMER2: INITIATE SPANs\n");
2686 			hammer2_update_spans(hmp);
2687 		}
2688 		if ((msg->any.head.cmd & DMSGF_DELETE) &&
2689 		    msg->state && (msg->state->txcmd & DMSGF_DELETE) == 0) {
2690 			kprintf("HAMMER2: CONN WAS TERMINATED\n");
2691 		}
2692 		break;
2693 	default:
2694 		break;
2695 	}
2696 }
2697 
2698 /*
2699  * Update LNK_SPAN state
2700  */
2701 void
2702 hammer2_update_spans(hammer2_mount_t *hmp)
2703 {
2704 	const hammer2_inode_data_t *ipdata;
2705 	hammer2_cluster_t *cparent;
2706 	hammer2_cluster_t *cluster;
2707 	hammer2_pfsmount_t *spmp;
2708 	hammer2_key_t key_next;
2709 	kdmsg_msg_t *rmsg;
2710 	size_t name_len;
2711 	int ddflag;
2712 
2713 	/*
2714 	 * Lookup mount point under the media-localized super-root.
2715 	 *
2716 	 * cluster->pmp will incorrectly point to spmp and must be fixed
2717 	 * up later on.
2718 	 */
2719 	spmp = hmp->spmp;
2720 	cparent = hammer2_inode_lock_ex(spmp->iroot);
2721 	cluster = hammer2_cluster_lookup(cparent, &key_next,
2722 					 HAMMER2_KEY_MIN,
2723 					 HAMMER2_KEY_MAX,
2724 					 0, &ddflag);
2725 	while (cluster) {
2726 		if (hammer2_cluster_type(cluster) != HAMMER2_BREF_TYPE_INODE)
2727 			continue;
2728 		ipdata = &hammer2_cluster_data(cluster)->ipdata;
2729 		kprintf("UPDATE SPANS: %s\n", ipdata->filename);
2730 
2731 		rmsg = kdmsg_msg_alloc(&hmp->iocom, NULL,
2732 				       DMSG_LNK_SPAN | DMSGF_CREATE,
2733 				       hammer2_lnk_span_reply, NULL);
2734 		rmsg->any.lnk_span.pfs_clid = ipdata->pfs_clid;
2735 		rmsg->any.lnk_span.pfs_fsid = ipdata->pfs_fsid;
2736 		rmsg->any.lnk_span.pfs_type = ipdata->pfs_type;
2737 		rmsg->any.lnk_span.peer_type = DMSG_PEER_HAMMER2;
2738 		rmsg->any.lnk_span.proto_version = DMSG_SPAN_PROTO_1;
2739 		name_len = ipdata->name_len;
2740 		if (name_len >= sizeof(rmsg->any.lnk_span.fs_label))
2741 			name_len = sizeof(rmsg->any.lnk_span.fs_label) - 1;
2742 		bcopy(ipdata->filename, rmsg->any.lnk_span.fs_label, name_len);
2743 
2744 		kdmsg_msg_write(rmsg);
2745 
2746 		cluster = hammer2_cluster_next(cparent, cluster,
2747 					       &key_next,
2748 					       key_next,
2749 					       HAMMER2_KEY_MAX,
2750 					       0);
2751 	}
2752 	hammer2_inode_unlock_ex(spmp->iroot, cparent);
2753 }
2754 
2755 static
2756 int
2757 hammer2_lnk_span_reply(kdmsg_state_t *state, kdmsg_msg_t *msg)
2758 {
2759 	if ((state->txcmd & DMSGF_DELETE) == 0 &&
2760 	    (msg->any.head.cmd & DMSGF_DELETE)) {
2761 		kdmsg_msg_reply(msg, 0);
2762 	}
2763 	return 0;
2764 }
2765 
2766 /*
2767  * Volume configuration updates are passed onto the userland service
2768  * daemon via the open LNK_CONN transaction.
2769  */
2770 void
2771 hammer2_volconf_update(hammer2_mount_t *hmp, int index)
2772 {
2773 	kdmsg_msg_t *msg;
2774 
2775 	/* XXX interlock against connection state termination */
2776 	kprintf("volconf update %p\n", hmp->iocom.conn_state);
2777 	if (hmp->iocom.conn_state) {
2778 		kprintf("TRANSMIT VOLCONF VIA OPEN CONN TRANSACTION\n");
2779 		msg = kdmsg_msg_alloc_state(hmp->iocom.conn_state,
2780 					    DMSG_LNK_HAMMER2_VOLCONF,
2781 					    NULL, NULL);
2782 		H2_LNK_VOLCONF(msg)->copy = hmp->voldata.copyinfo[index];
2783 		H2_LNK_VOLCONF(msg)->mediaid = hmp->voldata.fsid;
2784 		H2_LNK_VOLCONF(msg)->index = index;
2785 		kdmsg_msg_write(msg);
2786 	}
2787 }
2788 
2789 /*
2790  * This handles hysteresis on regular file flushes.  Because the BIOs are
2791  * routed to a thread it is possible for an excessive number to build up
2792  * and cause long front-end stalls long before the runningbuffspace limit
2793  * is hit, so we implement hammer2_flush_pipe to control the
2794  * hysteresis.
2795  *
2796  * This is a particular problem when compression is used.
2797  */
2798 void
2799 hammer2_lwinprog_ref(hammer2_pfsmount_t *pmp)
2800 {
2801 	atomic_add_int(&pmp->count_lwinprog, 1);
2802 }
2803 
2804 void
2805 hammer2_lwinprog_drop(hammer2_pfsmount_t *pmp)
2806 {
2807 	int lwinprog;
2808 
2809 	lwinprog = atomic_fetchadd_int(&pmp->count_lwinprog, -1);
2810 	if ((lwinprog & HAMMER2_LWINPROG_WAITING) &&
2811 	    (lwinprog & HAMMER2_LWINPROG_MASK) <= hammer2_flush_pipe * 2 / 3) {
2812 		atomic_clear_int(&pmp->count_lwinprog,
2813 				 HAMMER2_LWINPROG_WAITING);
2814 		wakeup(&pmp->count_lwinprog);
2815 	}
2816 }
2817 
2818 void
2819 hammer2_lwinprog_wait(hammer2_pfsmount_t *pmp)
2820 {
2821 	int lwinprog;
2822 
2823 	for (;;) {
2824 		lwinprog = pmp->count_lwinprog;
2825 		cpu_ccfence();
2826 		if ((lwinprog & HAMMER2_LWINPROG_MASK) < hammer2_flush_pipe)
2827 			break;
2828 		tsleep_interlock(&pmp->count_lwinprog, 0);
2829 		atomic_set_int(&pmp->count_lwinprog, HAMMER2_LWINPROG_WAITING);
2830 		lwinprog = pmp->count_lwinprog;
2831 		if ((lwinprog & HAMMER2_LWINPROG_MASK) < hammer2_flush_pipe)
2832 			break;
2833 		tsleep(&pmp->count_lwinprog, PINTERLOCKED, "h2wpipe", hz);
2834 	}
2835 }
2836 
2837 /*
2838  * Manage excessive memory resource use for chain and related
2839  * structures.
2840  */
2841 void
2842 hammer2_pfs_memory_wait(hammer2_pfsmount_t *pmp)
2843 {
2844 	long waiting;
2845 	long count;
2846 	long limit;
2847 #if 0
2848 	static int zzticks;
2849 #endif
2850 
2851 	/*
2852 	 * Atomic check condition and wait.  Also do an early speedup of
2853 	 * the syncer to try to avoid hitting the wait.
2854 	 */
2855 	for (;;) {
2856 		waiting = pmp->inmem_dirty_chains;
2857 		cpu_ccfence();
2858 		count = waiting & HAMMER2_DIRTYCHAIN_MASK;
2859 
2860 		limit = pmp->mp->mnt_nvnodelistsize / 10;
2861 		if (limit < hammer2_limit_dirty_chains)
2862 			limit = hammer2_limit_dirty_chains;
2863 		if (limit < 1000)
2864 			limit = 1000;
2865 
2866 #if 0
2867 		if ((int)(ticks - zzticks) > hz) {
2868 			zzticks = ticks;
2869 			kprintf("count %ld %ld\n", count, limit);
2870 		}
2871 #endif
2872 
2873 		/*
2874 		 * Block if there are too many dirty chains present, wait
2875 		 * for the flush to clean some out.
2876 		 */
2877 		if (count > limit) {
2878 			tsleep_interlock(&pmp->inmem_dirty_chains, 0);
2879 			if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
2880 					       waiting,
2881 				       waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
2882 				speedup_syncer(pmp->mp);
2883 				tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
2884 				       "chnmem", hz);
2885 			}
2886 			continue;	/* loop on success or fail */
2887 		}
2888 
2889 		/*
2890 		 * Try to start an early flush before we are forced to block.
2891 		 */
2892 		if (count > limit * 7 / 10)
2893 			speedup_syncer(pmp->mp);
2894 		break;
2895 	}
2896 }
2897 
2898 void
2899 hammer2_pfs_memory_inc(hammer2_pfsmount_t *pmp)
2900 {
2901 	if (pmp)
2902 		atomic_add_long(&pmp->inmem_dirty_chains, 1);
2903 }
2904 
2905 void
2906 hammer2_pfs_memory_wakeup(hammer2_pfsmount_t *pmp)
2907 {
2908 	long waiting;
2909 
2910 	if (pmp == NULL)
2911 		return;
2912 
2913 	for (;;) {
2914 		waiting = pmp->inmem_dirty_chains;
2915 		cpu_ccfence();
2916 		if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
2917 				       waiting,
2918 				       (waiting - 1) &
2919 					~HAMMER2_DIRTYCHAIN_WAITING)) {
2920 			break;
2921 		}
2922 	}
2923 
2924 	if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
2925 		wakeup(&pmp->inmem_dirty_chains);
2926 }
2927 
2928 /*
2929  * Debugging
2930  */
2931 void
2932 hammer2_dump_chain(hammer2_chain_t *chain, int tab, int *countp, char pfx)
2933 {
2934 	hammer2_chain_t *scan;
2935 	hammer2_chain_t *first_parent;
2936 
2937 	--*countp;
2938 	if (*countp == 0) {
2939 		kprintf("%*.*s...\n", tab, tab, "");
2940 		return;
2941 	}
2942 	if (*countp < 0)
2943 		return;
2944 	first_parent = chain->core ? TAILQ_FIRST(&chain->core->ownerq) : NULL;
2945 	kprintf("%*.*s%c-chain %p.%d %016jx/%d mir=%016jx\n",
2946 		tab, tab, "", pfx,
2947 		chain, chain->bref.type,
2948 		chain->bref.key, chain->bref.keybits,
2949 		chain->bref.mirror_tid);
2950 
2951 	kprintf("%*.*s      [%08x] (%s) mod=%08x del=%08x "
2952 		"lo=%08x hi=%08x refs=%d\n",
2953 		tab, tab, "",
2954 		chain->flags,
2955 		((chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2956 		chain->data) ?  (char *)chain->data->ipdata.filename : "?"),
2957 		chain->modify_xid,
2958 		chain->delete_xid,
2959 		chain->update_xlo,
2960 		chain->update_xhi,
2961 		chain->refs);
2962 
2963 	kprintf("%*.*s      core %p [%08x]",
2964 		tab, tab, "",
2965 		chain->core, (chain->core ? chain->core->flags : 0));
2966 
2967 	if (first_parent)
2968 		kprintf("\n%*.*s      fp=%p np=%p [fpflags %08x fprefs %d",
2969 			tab, tab, "",
2970 			first_parent,
2971 			(first_parent ? TAILQ_NEXT(first_parent, core_entry) :
2972 					NULL),
2973 			first_parent->flags,
2974 			first_parent->refs);
2975 	if (chain->core == NULL || RB_EMPTY(&chain->core->rbtree))
2976 		kprintf("\n");
2977 	else
2978 		kprintf(" {\n");
2979 	if (chain->core) {
2980 		RB_FOREACH(scan, hammer2_chain_tree, &chain->core->rbtree)
2981 			hammer2_dump_chain(scan, tab + 4, countp, 'a');
2982 		RB_FOREACH(scan, hammer2_chain_tree, &chain->core->dbtree)
2983 			hammer2_dump_chain(scan, tab + 4, countp, 'r');
2984 		TAILQ_FOREACH(scan, &chain->core->dbq, db_entry)
2985 			hammer2_dump_chain(scan, tab + 4, countp, 'd');
2986 	}
2987 	if (chain->core && !RB_EMPTY(&chain->core->rbtree)) {
2988 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE && chain->data)
2989 			kprintf("%*.*s}(%s)\n", tab, tab, "",
2990 				chain->data->ipdata.filename);
2991 		else
2992 			kprintf("%*.*s}\n", tab, tab, "");
2993 	}
2994 }
2995