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