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