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