Merge branch 'vendor/GCC50'
[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         mtx_init(&pmp->wthread_mtx);
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                 hammer2_inode_ref(pmp->iroot);
740                 ccms_thread_lock(&pmp->iroot->topo_cst, CCMS_STATE_EXCLUSIVE);
741
742                 if (pmp->iroot->cluster.nchains + cluster->nchains >
743                     HAMMER2_MAXCLUSTER) {
744                         kprintf("hammer2_mount: cluster full!\n");
745
746                         ccms_thread_unlock(&pmp->iroot->topo_cst);
747                         hammer2_inode_drop(pmp->iroot);
748
749                         hammer2_cluster_unlock(cluster);
750                         hammer2_vfs_unmount_hmp1(mp, hmp);
751                         hammer2_vfs_unmount_hmp2(mp, hmp);
752                         lockmgr(&hammer2_mntlk, LK_RELEASE);
753                         hammer2_vfs_unmount(mp, MNT_FORCE);
754                         return EBUSY;
755                 }
756                 kprintf("hammer2_vfs_mount: Adding pfs to existing cluster\n");
757                 j = pmp->iroot->cluster.nchains;
758                 for (i = 0; i < cluster->nchains; ++i) {
759                         rchain = cluster->array[i];
760                         KKASSERT(rchain->pmp == NULL);
761                         rchain->pmp = pmp;
762                         hammer2_chain_ref(cluster->array[i]);
763                         pmp->iroot->cluster.array[j] = cluster->array[i];
764                         ++j;
765                 }
766                 pmp->iroot->cluster.nchains = j;
767                 ccms_thread_unlock(&pmp->iroot->topo_cst);
768                 hammer2_inode_drop(pmp->iroot);
769                 hammer2_cluster_unlock(cluster);
770                 lockmgr(&hammer2_mntlk, LK_RELEASE);
771
772                 kprintf("ok\n");
773                 hammer2_inode_install_hidden(pmp);
774
775                 return ERANGE;
776         }
777
778         /*
779          * Block device opened successfully, finish initializing the
780          * mount structure.
781          *
782          * From this point on we have to call hammer2_unmount() on failure.
783          */
784         pmp = hammer2_pfsalloc(ripdata, bref.mirror_tid);
785         kprintf("PMP mirror_tid is %016jx\n", bref.mirror_tid);
786         for (i = 0; i < cluster->nchains; ++i) {
787                 rchain = cluster->array[i];
788                 KKASSERT(rchain->pmp == NULL);
789                 rchain->pmp = pmp;
790                 atomic_set_int(&rchain->flags, HAMMER2_CHAIN_MOUNTED);
791         }
792         cluster->pmp = pmp;
793
794         ccms_domain_init(&pmp->ccms_dom);
795         TAILQ_INSERT_TAIL(&hammer2_pfslist, pmp, mntentry);
796         lockmgr(&hammer2_mntlk, LK_RELEASE);
797
798         kprintf("hammer2_mount hmp=%p pmp=%p pmpcnt=%d\n",
799                 hmp, pmp, hmp->pmp_count);
800
801         mp->mnt_flag = MNT_LOCAL;
802         mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;   /* all entry pts are SMP */
803         mp->mnt_kern_flag |= MNTK_THR_SYNC;     /* new vsyncscan semantics */
804
805         /*
806          * required mount structure initializations
807          */
808         mp->mnt_stat.f_iosize = HAMMER2_PBUFSIZE;
809         mp->mnt_stat.f_bsize = HAMMER2_PBUFSIZE;
810
811         mp->mnt_vstat.f_frsize = HAMMER2_PBUFSIZE;
812         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
813
814         /*
815          * Optional fields
816          */
817         mp->mnt_iosize_max = MAXPHYS;
818         mp->mnt_data = (qaddr_t)pmp;
819         pmp->mp = mp;
820
821         /*
822          * After this point hammer2_vfs_unmount() has visibility on hmp
823          * and manual hmp1/hmp2 calls are not needed on fatal errors.
824          */
825         pmp->iroot = hammer2_inode_get(pmp, NULL, cluster);
826         hammer2_inode_ref(pmp->iroot);          /* ref for pmp->iroot */
827         hammer2_inode_unlock_ex(pmp->iroot, cluster);
828
829         /*
830          * The logical file buffer bio write thread handles things
831          * like physical block assignment and compression.
832          *
833          * (only applicable to pfs mounts, not applicable to spmp)
834          */
835         pmp->wthread_destroy = 0;
836         lwkt_create(hammer2_write_thread, pmp,
837                     &pmp->wthread_td, NULL, 0, -1, "hwrite-%s", label);
838
839         /*
840          * With the cluster operational install ihidden.
841          * (only applicable to pfs mounts, not applicable to spmp)
842          */
843         hammer2_inode_install_hidden(pmp);
844
845         /*
846          * Finish setup
847          */
848         vfs_getnewfsid(mp);
849         vfs_add_vnodeops(mp, &hammer2_vnode_vops, &mp->mnt_vn_norm_ops);
850         vfs_add_vnodeops(mp, &hammer2_spec_vops, &mp->mnt_vn_spec_ops);
851         vfs_add_vnodeops(mp, &hammer2_fifo_vops, &mp->mnt_vn_fifo_ops);
852
853         copyinstr(info.volume, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, &size);
854         bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
855         bzero(mp->mnt_stat.f_mntonname, sizeof(mp->mnt_stat.f_mntonname));
856         copyinstr(path, mp->mnt_stat.f_mntonname,
857                   sizeof(mp->mnt_stat.f_mntonname) - 1,
858                   &size);
859
860         /*
861          * Initial statfs to prime mnt_stat.
862          */
863         hammer2_vfs_statfs(mp, &mp->mnt_stat, cred);
864         
865         return 0;
866 }
867
868 /*
869  * Handle bioq for strategy write
870  */
871 static
872 void
873 hammer2_write_thread(void *arg)
874 {
875         hammer2_pfsmount_t *pmp;
876         struct bio *bio;
877         struct buf *bp;
878         hammer2_trans_t trans;
879         struct vnode *vp;
880         hammer2_inode_t *ip;
881         hammer2_cluster_t *cparent;
882         hammer2_inode_data_t *wipdata;
883         hammer2_key_t lbase;
884         int lblksize;
885         int pblksize;
886         int error;
887         
888         pmp = arg;
889         
890         mtx_lock(&pmp->wthread_mtx);
891         while (pmp->wthread_destroy == 0) {
892                 if (bioq_first(&pmp->wthread_bioq) == NULL) {
893                         mtxsleep(&pmp->wthread_bioq, &pmp->wthread_mtx,
894                                  0, "h2bioqw", 0);
895                 }
896                 cparent = NULL;
897
898                 hammer2_trans_init(&trans, pmp, HAMMER2_TRANS_BUFCACHE);
899
900                 while ((bio = bioq_takefirst(&pmp->wthread_bioq)) != NULL) {
901                         /*
902                          * dummy bio for synchronization.  The transaction
903                          * must be reinitialized.
904                          */
905                         if (bio->bio_buf == NULL) {
906                                 bio->bio_flags |= BIO_DONE;
907                                 wakeup(bio);
908                                 hammer2_trans_done(&trans);
909                                 hammer2_trans_init(&trans, pmp,
910                                                    HAMMER2_TRANS_BUFCACHE);
911                                 continue;
912                         }
913
914                         /*
915                          * else normal bio processing
916                          */
917                         mtx_unlock(&pmp->wthread_mtx);
918
919                         hammer2_lwinprog_drop(pmp);
920                         
921                         error = 0;
922                         bp = bio->bio_buf;
923                         vp = bp->b_vp;
924                         ip = VTOI(vp);
925
926                         /*
927                          * Inode is modified, flush size and mtime changes
928                          * to ensure that the file size remains consistent
929                          * with the buffers being flushed.
930                          *
931                          * NOTE: The inode_fsync() call only flushes the
932                          *       inode's meta-data state, it doesn't try
933                          *       to flush underlying buffers or chains.
934                          */
935                         cparent = hammer2_inode_lock_ex(ip);
936                         if (ip->flags & (HAMMER2_INODE_RESIZED |
937                                          HAMMER2_INODE_MTIME)) {
938                                 hammer2_inode_fsync(&trans, ip, cparent);
939                         }
940                         wipdata = hammer2_cluster_modify_ip(&trans, ip,
941                                                          cparent, 0);
942                         lblksize = hammer2_calc_logical(ip, bio->bio_offset,
943                                                         &lbase, NULL);
944                         pblksize = hammer2_calc_physical(ip, wipdata, lbase);
945                         hammer2_write_file_core(bp, &trans, ip, wipdata,
946                                                 cparent,
947                                                 lbase, IO_ASYNC,
948                                                 pblksize, &error);
949                         hammer2_cluster_modsync(cparent);
950                         hammer2_inode_unlock_ex(ip, cparent);
951                         if (error) {
952                                 kprintf("hammer2: error in buffer write\n");
953                                 bp->b_flags |= B_ERROR;
954                                 bp->b_error = EIO;
955                         }
956                         biodone(bio);
957                         mtx_lock(&pmp->wthread_mtx);
958                 }
959                 hammer2_trans_done(&trans);
960         }
961         pmp->wthread_destroy = -1;
962         wakeup(&pmp->wthread_destroy);
963         
964         mtx_unlock(&pmp->wthread_mtx);
965 }
966
967 void
968 hammer2_bioq_sync(hammer2_pfsmount_t *pmp)
969 {
970         struct bio sync_bio;
971
972         bzero(&sync_bio, sizeof(sync_bio));     /* dummy with no bio_buf */
973         mtx_lock(&pmp->wthread_mtx);
974         if (pmp->wthread_destroy == 0 &&
975             TAILQ_FIRST(&pmp->wthread_bioq.queue)) {
976                 bioq_insert_tail(&pmp->wthread_bioq, &sync_bio);
977                 while ((sync_bio.bio_flags & BIO_DONE) == 0)
978                         mtxsleep(&sync_bio, &pmp->wthread_mtx, 0, "h2bioq", 0);
979         }
980         mtx_unlock(&pmp->wthread_mtx);
981 }
982
983 /* 
984  * Return a chain suitable for I/O, creating the chain if necessary
985  * and assigning its physical block.
986  */
987 static
988 hammer2_cluster_t *
989 hammer2_assign_physical(hammer2_trans_t *trans,
990                         hammer2_inode_t *ip, hammer2_cluster_t *cparent,
991                         hammer2_key_t lbase, int pblksize, int *errorp)
992 {
993         hammer2_cluster_t *cluster;
994         hammer2_cluster_t *dparent;
995         hammer2_key_t key_dummy;
996         int pradix = hammer2_getradix(pblksize);
997         int ddflag;
998
999         /*
1000          * Locate the chain associated with lbase, return a locked chain.
1001          * However, do not instantiate any data reference (which utilizes a
1002          * device buffer) because we will be using direct IO via the
1003          * logical buffer cache buffer.
1004          */
1005         *errorp = 0;
1006         KKASSERT(pblksize >= HAMMER2_ALLOC_MIN);
1007 retry:
1008         dparent = hammer2_cluster_lookup_init(cparent, 0);
1009         cluster = hammer2_cluster_lookup(dparent, &key_dummy,
1010                                      lbase, lbase,
1011                                      HAMMER2_LOOKUP_NODATA, &ddflag);
1012
1013         if (cluster == NULL) {
1014                 /*
1015                  * We found a hole, create a new chain entry.
1016                  *
1017                  * NOTE: DATA chains are created without device backing
1018                  *       store (nor do we want any).
1019                  */
1020                 *errorp = hammer2_cluster_create(trans, dparent, &cluster,
1021                                                lbase, HAMMER2_PBUFRADIX,
1022                                                HAMMER2_BREF_TYPE_DATA,
1023                                                pblksize, 0);
1024                 if (cluster == NULL) {
1025                         hammer2_cluster_lookup_done(dparent);
1026                         panic("hammer2_cluster_create: par=%p error=%d\n",
1027                                 dparent->focus, *errorp);
1028                         goto retry;
1029                 }
1030                 /*ip->delta_dcount += pblksize;*/
1031         } else {
1032                 switch (hammer2_cluster_type(cluster)) {
1033                 case HAMMER2_BREF_TYPE_INODE:
1034                         /*
1035                          * The data is embedded in the inode.  The
1036                          * caller is responsible for marking the inode
1037                          * modified and copying the data to the embedded
1038                          * area.
1039                          */
1040                         break;
1041                 case HAMMER2_BREF_TYPE_DATA:
1042                         if (hammer2_cluster_need_resize(cluster, pblksize)) {
1043                                 hammer2_cluster_resize(trans, ip,
1044                                                      dparent, cluster,
1045                                                      pradix,
1046                                                      HAMMER2_MODIFY_OPTDATA);
1047                         }
1048
1049                         /*
1050                          * DATA buffers must be marked modified whether the
1051                          * data is in a logical buffer or not.  We also have
1052                          * to make this call to fixup the chain data pointers
1053                          * after resizing in case this is an encrypted or
1054                          * compressed buffer.
1055                          */
1056                         hammer2_cluster_modify(trans, cluster,
1057                                                HAMMER2_MODIFY_OPTDATA);
1058                         break;
1059                 default:
1060                         panic("hammer2_assign_physical: bad type");
1061                         /* NOT REACHED */
1062                         break;
1063                 }
1064         }
1065
1066         /*
1067          * Cleanup.  If cluster wound up being the inode itself, i.e.
1068          * the DIRECTDATA case for offset 0, then we need to update cparent.
1069          * The caller expects cparent to not become stale.
1070          */
1071         hammer2_cluster_lookup_done(dparent);
1072         /* dparent = NULL; safety */
1073         if (cluster && ddflag)
1074                 hammer2_cluster_replace_locked(cparent, cluster);
1075         return (cluster);
1076 }
1077
1078 /* 
1079  * bio queued from hammer2_vnops.c.
1080  *
1081  * The core write function which determines which path to take
1082  * depending on compression settings.  We also have to locate the
1083  * related clusters so we can calculate and set the check data for
1084  * the blockref.
1085  */
1086 static
1087 void
1088 hammer2_write_file_core(struct buf *bp, hammer2_trans_t *trans,
1089                         hammer2_inode_t *ip,
1090                         const hammer2_inode_data_t *ripdata,
1091                         hammer2_cluster_t *cparent,
1092                         hammer2_key_t lbase, int ioflag, int pblksize,
1093                         int *errorp)
1094 {
1095         hammer2_cluster_t *cluster;
1096
1097         switch(HAMMER2_DEC_ALGO(ripdata->comp_algo)) {
1098         case HAMMER2_COMP_NONE:
1099                 /*
1100                  * We have to assign physical storage to the buffer
1101                  * we intend to dirty or write now to avoid deadlocks
1102                  * in the strategy code later.
1103                  *
1104                  * This can return NOOFFSET for inode-embedded data.
1105                  * The strategy code will take care of it in that case.
1106                  */
1107                 cluster = hammer2_assign_physical(trans, ip, cparent,
1108                                                 lbase, pblksize,
1109                                                 errorp);
1110                 hammer2_write_bp(cluster, bp, ioflag, pblksize, errorp,
1111                                  ripdata->check_algo);
1112                 if (cluster)
1113                         hammer2_cluster_unlock(cluster);
1114                 break;
1115         case HAMMER2_COMP_AUTOZERO:
1116                 /*
1117                  * Check for zero-fill only
1118                  */
1119                 hammer2_zero_check_and_write(bp, trans, ip,
1120                                     ripdata, cparent, lbase,
1121                                     ioflag, pblksize, errorp,
1122                                     ripdata->check_algo);
1123                 break;
1124         case HAMMER2_COMP_LZ4:
1125         case HAMMER2_COMP_ZLIB:
1126         default:
1127                 /*
1128                  * Check for zero-fill and attempt compression.
1129                  */
1130                 hammer2_compress_and_write(bp, trans, ip,
1131                                            ripdata, cparent,
1132                                            lbase, ioflag,
1133                                            pblksize, errorp,
1134                                            ripdata->comp_algo,
1135                                            ripdata->check_algo);
1136                 break;
1137         }
1138 }
1139
1140 /*
1141  * Generic function that will perform the compression in compression
1142  * write path. The compression algorithm is determined by the settings
1143  * obtained from inode.
1144  */
1145 static
1146 void
1147 hammer2_compress_and_write(struct buf *bp, hammer2_trans_t *trans,
1148         hammer2_inode_t *ip, const hammer2_inode_data_t *ripdata,
1149         hammer2_cluster_t *cparent,
1150         hammer2_key_t lbase, int ioflag, int pblksize,
1151         int *errorp, int comp_algo, int check_algo)
1152 {
1153         hammer2_cluster_t *cluster;
1154         hammer2_chain_t *chain;
1155         int comp_size;
1156         int comp_block_size;
1157         int i;
1158         char *comp_buffer;
1159
1160         if (test_block_zeros(bp->b_data, pblksize)) {
1161                 zero_write(bp, trans, ip, ripdata, cparent, lbase, errorp);
1162                 return;
1163         }
1164
1165         comp_size = 0;
1166         comp_buffer = NULL;
1167
1168         KKASSERT(pblksize / 2 <= 32768);
1169                 
1170         if (ip->comp_heuristic < 8 || (ip->comp_heuristic & 7) == 0) {
1171                 z_stream strm_compress;
1172                 int comp_level;
1173                 int ret;
1174
1175                 switch(HAMMER2_DEC_ALGO(comp_algo)) {
1176                 case HAMMER2_COMP_LZ4:
1177                         comp_buffer = objcache_get(cache_buffer_write,
1178                                                    M_INTWAIT);
1179                         comp_size = LZ4_compress_limitedOutput(
1180                                         bp->b_data,
1181                                         &comp_buffer[sizeof(int)],
1182                                         pblksize,
1183                                         pblksize / 2 - sizeof(int));
1184                         /*
1185                          * We need to prefix with the size, LZ4
1186                          * doesn't do it for us.  Add the related
1187                          * overhead.
1188                          */
1189                         *(int *)comp_buffer = comp_size;
1190                         if (comp_size)
1191                                 comp_size += sizeof(int);
1192                         break;
1193                 case HAMMER2_COMP_ZLIB:
1194                         comp_level = HAMMER2_DEC_LEVEL(comp_algo);
1195                         if (comp_level == 0)
1196                                 comp_level = 6; /* default zlib compression */
1197                         else if (comp_level < 6)
1198                                 comp_level = 6;
1199                         else if (comp_level > 9)
1200                                 comp_level = 9;
1201                         ret = deflateInit(&strm_compress, comp_level);
1202                         if (ret != Z_OK) {
1203                                 kprintf("HAMMER2 ZLIB: fatal error "
1204                                         "on deflateInit.\n");
1205                         }
1206
1207                         comp_buffer = objcache_get(cache_buffer_write,
1208                                                    M_INTWAIT);
1209                         strm_compress.next_in = bp->b_data;
1210                         strm_compress.avail_in = pblksize;
1211                         strm_compress.next_out = comp_buffer;
1212                         strm_compress.avail_out = pblksize / 2;
1213                         ret = deflate(&strm_compress, Z_FINISH);
1214                         if (ret == Z_STREAM_END) {
1215                                 comp_size = pblksize / 2 -
1216                                             strm_compress.avail_out;
1217                         } else {
1218                                 comp_size = 0;
1219                         }
1220                         ret = deflateEnd(&strm_compress);
1221                         break;
1222                 default:
1223                         kprintf("Error: Unknown compression method.\n");
1224                         kprintf("Comp_method = %d.\n", comp_algo);
1225                         break;
1226                 }
1227         }
1228
1229         if (comp_size == 0) {
1230                 /*
1231                  * compression failed or turned off
1232                  */
1233                 comp_block_size = pblksize;     /* safety */
1234                 if (++ip->comp_heuristic > 128)
1235                         ip->comp_heuristic = 8;
1236         } else {
1237                 /*
1238                  * compression succeeded
1239                  */
1240                 ip->comp_heuristic = 0;
1241                 if (comp_size <= 1024) {
1242                         comp_block_size = 1024;
1243                 } else if (comp_size <= 2048) {
1244                         comp_block_size = 2048;
1245                 } else if (comp_size <= 4096) {
1246                         comp_block_size = 4096;
1247                 } else if (comp_size <= 8192) {
1248                         comp_block_size = 8192;
1249                 } else if (comp_size <= 16384) {
1250                         comp_block_size = 16384;
1251                 } else if (comp_size <= 32768) {
1252                         comp_block_size = 32768;
1253                 } else {
1254                         panic("hammer2: WRITE PATH: "
1255                               "Weird comp_size value.");
1256                         /* NOT REACHED */
1257                         comp_block_size = pblksize;
1258                 }
1259         }
1260
1261         cluster = hammer2_assign_physical(trans, ip, cparent,
1262                                           lbase, comp_block_size,
1263                                           errorp);
1264         ripdata = NULL;
1265
1266         if (*errorp) {
1267                 kprintf("WRITE PATH: An error occurred while "
1268                         "assigning physical space.\n");
1269                 KKASSERT(cluster == NULL);
1270                 goto done;
1271         }
1272
1273         for (i = 0; i < cluster->nchains; ++i) {
1274                 hammer2_inode_data_t *wipdata;
1275                 hammer2_io_t *dio;
1276                 char *bdata;
1277
1278                 chain = cluster->array[i];      /* XXX */
1279                 KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1280
1281                 switch(chain->bref.type) {
1282                 case HAMMER2_BREF_TYPE_INODE:
1283                         wipdata = &hammer2_chain_wdata(chain)->ipdata;
1284                         KKASSERT(wipdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA);
1285                         KKASSERT(bp->b_loffset == 0);
1286                         bcopy(bp->b_data, wipdata->u.data,
1287                               HAMMER2_EMBEDDED_BYTES);
1288                         break;
1289                 case HAMMER2_BREF_TYPE_DATA:
1290                         /*
1291                          * Optimize out the read-before-write
1292                          * if possible.
1293                          */
1294                         *errorp = hammer2_io_newnz(chain->hmp,
1295                                                    chain->bref.data_off,
1296                                                    chain->bytes,
1297                                                    &dio);
1298                         if (*errorp) {
1299                                 hammer2_io_brelse(&dio);
1300                                 kprintf("hammer2: WRITE PATH: "
1301                                         "dbp bread error\n");
1302                                 break;
1303                         }
1304                         bdata = hammer2_io_data(dio, chain->bref.data_off);
1305
1306                         /*
1307                          * When loading the block make sure we don't
1308                          * leave garbage after the compressed data.
1309                          */
1310                         if (comp_size) {
1311                                 chain->bref.methods =
1312                                         HAMMER2_ENC_COMP(comp_algo) +
1313                                         HAMMER2_ENC_CHECK(check_algo);
1314                                 bcopy(comp_buffer, bdata, comp_size);
1315                                 if (comp_size != comp_block_size) {
1316                                         bzero(bdata + comp_size,
1317                                               comp_block_size - comp_size);
1318                                 }
1319                         } else {
1320                                 chain->bref.methods =
1321                                         HAMMER2_ENC_COMP(
1322                                                 HAMMER2_COMP_NONE) +
1323                                         HAMMER2_ENC_CHECK(check_algo);
1324                                 bcopy(bp->b_data, bdata, pblksize);
1325                         }
1326
1327                         /*
1328                          * The flush code doesn't calculate check codes for
1329                          * file data (doing so can result in excessive I/O),
1330                          * so we do it here.
1331                          */
1332                         hammer2_chain_setcheck(chain, bdata);
1333
1334                         /*
1335                          * Device buffer is now valid, chain is no longer in
1336                          * the initial state.
1337                          *
1338                          * (No blockref table worries with file data)
1339                          */
1340                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1341
1342                         /* Now write the related bdp. */
1343                         if (ioflag & IO_SYNC) {
1344                                 /*
1345                                  * Synchronous I/O requested.
1346                                  */
1347                                 hammer2_io_bwrite(&dio);
1348                         /*
1349                         } else if ((ioflag & IO_DIRECT) &&
1350                                    loff + n == pblksize) {
1351                                 hammer2_io_bdwrite(&dio);
1352                         */
1353                         } else if (ioflag & IO_ASYNC) {
1354                                 hammer2_io_bawrite(&dio);
1355                         } else {
1356                                 hammer2_io_bdwrite(&dio);
1357                         }
1358                         break;
1359                 default:
1360                         panic("hammer2_write_bp: bad chain type %d\n",
1361                                 chain->bref.type);
1362                         /* NOT REACHED */
1363                         break;
1364                 }
1365         }
1366 done:
1367         if (cluster)
1368                 hammer2_cluster_unlock(cluster);
1369         if (comp_buffer)
1370                 objcache_put(cache_buffer_write, comp_buffer);
1371 }
1372
1373 /*
1374  * Function that performs zero-checking and writing without compression,
1375  * it corresponds to default zero-checking path.
1376  */
1377 static
1378 void
1379 hammer2_zero_check_and_write(struct buf *bp, hammer2_trans_t *trans,
1380         hammer2_inode_t *ip, const hammer2_inode_data_t *ripdata,
1381         hammer2_cluster_t *cparent,
1382         hammer2_key_t lbase, int ioflag, int pblksize, int *errorp,
1383         int check_algo)
1384 {
1385         hammer2_cluster_t *cluster;
1386
1387         if (test_block_zeros(bp->b_data, pblksize)) {
1388                 zero_write(bp, trans, ip, ripdata, cparent, lbase, errorp);
1389         } else {
1390                 cluster = hammer2_assign_physical(trans, ip, cparent,
1391                                                   lbase, pblksize, errorp);
1392                 hammer2_write_bp(cluster, bp, ioflag, pblksize, errorp,
1393                                  check_algo);
1394                 if (cluster)
1395                         hammer2_cluster_unlock(cluster);
1396         }
1397 }
1398
1399 /*
1400  * A function to test whether a block of data contains only zeros,
1401  * returns TRUE (non-zero) if the block is all zeros.
1402  */
1403 static
1404 int
1405 test_block_zeros(const char *buf, size_t bytes)
1406 {
1407         size_t i;
1408
1409         for (i = 0; i < bytes; i += sizeof(long)) {
1410                 if (*(const long *)(buf + i) != 0)
1411                         return (0);
1412         }
1413         return (1);
1414 }
1415
1416 /*
1417  * Function to "write" a block that contains only zeros.
1418  */
1419 static
1420 void
1421 zero_write(struct buf *bp, hammer2_trans_t *trans,
1422            hammer2_inode_t *ip, const hammer2_inode_data_t *ripdata,
1423            hammer2_cluster_t *cparent,
1424            hammer2_key_t lbase, int *errorp __unused)
1425 {
1426         hammer2_cluster_t *cluster;
1427         hammer2_media_data_t *data;
1428         hammer2_key_t key_dummy;
1429         int ddflag;
1430
1431         cparent = hammer2_cluster_lookup_init(cparent, 0);
1432         cluster = hammer2_cluster_lookup(cparent, &key_dummy, lbase, lbase,
1433                                      HAMMER2_LOOKUP_NODATA, &ddflag);
1434         if (cluster) {
1435                 data = hammer2_cluster_wdata(cluster);
1436
1437                 if (ddflag) {
1438                         KKASSERT(cluster->focus->flags &
1439                                  HAMMER2_CHAIN_MODIFIED);
1440                         bzero(data->ipdata.u.data, HAMMER2_EMBEDDED_BYTES);
1441                         hammer2_cluster_modsync(cluster);
1442                 } else {
1443                         hammer2_cluster_delete(trans, cparent, cluster,
1444                                                HAMMER2_DELETE_PERMANENT);
1445                 }
1446                 hammer2_cluster_unlock(cluster);
1447         }
1448         hammer2_cluster_lookup_done(cparent);
1449 }
1450
1451 /*
1452  * Function to write the data as it is, without performing any sort of
1453  * compression. This function is used in path without compression and
1454  * default zero-checking path.
1455  */
1456 static
1457 void
1458 hammer2_write_bp(hammer2_cluster_t *cluster, struct buf *bp, int ioflag,
1459                                 int pblksize, int *errorp, int check_algo)
1460 {
1461         hammer2_chain_t *chain;
1462         hammer2_inode_data_t *wipdata;
1463         hammer2_io_t *dio;
1464         char *bdata;
1465         int error;
1466         int i;
1467
1468         error = 0;      /* XXX TODO below */
1469
1470         for (i = 0; i < cluster->nchains; ++i) {
1471                 chain = cluster->array[i];      /* XXX */
1472                 KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1473
1474                 switch(chain->bref.type) {
1475                 case HAMMER2_BREF_TYPE_INODE:
1476                         wipdata = &hammer2_chain_wdata(chain)->ipdata;
1477                         KKASSERT(wipdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA);
1478                         KKASSERT(bp->b_loffset == 0);
1479                         bcopy(bp->b_data, wipdata->u.data,
1480                               HAMMER2_EMBEDDED_BYTES);
1481                         error = 0;
1482                         break;
1483                 case HAMMER2_BREF_TYPE_DATA:
1484                         error = hammer2_io_newnz(chain->hmp,
1485                                                  chain->bref.data_off,
1486                                                  chain->bytes, &dio);
1487                         if (error) {
1488                                 hammer2_io_bqrelse(&dio);
1489                                 kprintf("hammer2: WRITE PATH: "
1490                                         "dbp bread error\n");
1491                                 break;
1492                         }
1493                         bdata = hammer2_io_data(dio, chain->bref.data_off);
1494
1495                         chain->bref.methods = HAMMER2_ENC_COMP(
1496                                                         HAMMER2_COMP_NONE) +
1497                                               HAMMER2_ENC_CHECK(check_algo);
1498                         bcopy(bp->b_data, bdata, chain->bytes);
1499
1500                         /*
1501                          * The flush code doesn't calculate check codes for
1502                          * file data (doing so can result in excessive I/O),
1503                          * so we do it here.
1504                          */
1505                         hammer2_chain_setcheck(chain, bdata);
1506
1507                         /*
1508                          * Device buffer is now valid, chain is no longer in
1509                          * the initial state.
1510                          *
1511                          * (No blockref table worries with file data)
1512                          */
1513                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1514
1515                         if (ioflag & IO_SYNC) {
1516                                 /*
1517                                  * Synchronous I/O requested.
1518                                  */
1519                                 hammer2_io_bwrite(&dio);
1520                         /*
1521                         } else if ((ioflag & IO_DIRECT) &&
1522                                    loff + n == pblksize) {
1523                                 hammer2_io_bdwrite(&dio);
1524                         */
1525                         } else if (ioflag & IO_ASYNC) {
1526                                 hammer2_io_bawrite(&dio);
1527                         } else {
1528                                 hammer2_io_bdwrite(&dio);
1529                         }
1530                         break;
1531                 default:
1532                         panic("hammer2_write_bp: bad chain type %d\n",
1533                               chain->bref.type);
1534                         /* NOT REACHED */
1535                         error = 0;
1536                         break;
1537                 }
1538                 KKASSERT(error == 0);   /* XXX TODO */
1539         }
1540         *errorp = error;
1541 }
1542
1543 static
1544 int
1545 hammer2_remount(hammer2_mount_t *hmp, struct mount *mp, char *path,
1546                 struct vnode *devvp, struct ucred *cred)
1547 {
1548         int error;
1549
1550         if (hmp->ronly && (mp->mnt_kern_flag & MNTK_WANTRDWR)) {
1551                 error = hammer2_recovery(hmp);
1552         } else {
1553                 error = 0;
1554         }
1555         return error;
1556 }
1557
1558 static
1559 int
1560 hammer2_vfs_unmount(struct mount *mp, int mntflags)
1561 {
1562         hammer2_pfsmount_t *pmp;
1563         hammer2_mount_t *hmp;
1564         hammer2_chain_t *rchain;
1565         hammer2_cluster_t *cluster;
1566         int flags;
1567         int error = 0;
1568         int i;
1569
1570         pmp = MPTOPMP(mp);
1571
1572         if (pmp == NULL)
1573                 return(0);
1574
1575         lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1576         TAILQ_REMOVE(&hammer2_pfslist, pmp, mntentry);
1577
1578         /*
1579          * If mount initialization proceeded far enough we must flush
1580          * its vnodes.
1581          */
1582         if (mntflags & MNT_FORCE)
1583                 flags = FORCECLOSE;
1584         else
1585                 flags = 0;
1586         if (pmp->iroot) {
1587                 error = vflush(mp, 0, flags);
1588                 if (error)
1589                         goto failed;
1590         }
1591
1592         ccms_domain_uninit(&pmp->ccms_dom);
1593
1594         if (pmp->wthread_td) {
1595                 mtx_lock(&pmp->wthread_mtx);
1596                 pmp->wthread_destroy = 1;
1597                 wakeup(&pmp->wthread_bioq);
1598                 while (pmp->wthread_destroy != -1) {
1599                         mtxsleep(&pmp->wthread_destroy,
1600                                 &pmp->wthread_mtx, 0,
1601                                 "umount-sleep", 0);
1602                 }
1603                 mtx_unlock(&pmp->wthread_mtx);
1604                 pmp->wthread_td = NULL;
1605         }
1606
1607         /*
1608          * Cleanup our reference on ihidden.
1609          */
1610         if (pmp->ihidden) {
1611                 hammer2_inode_drop(pmp->ihidden);
1612                 pmp->ihidden = NULL;
1613         }
1614
1615         /*
1616          * Cleanup our reference on iroot.  iroot is (should) not be needed
1617          * by the flush code.
1618          */
1619         if (pmp->iroot) {
1620                 cluster = &pmp->iroot->cluster;
1621                 for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
1622                         rchain = pmp->iroot->cluster.array[i];
1623                         if (rchain == NULL)
1624                                 continue;
1625                         hmp = rchain->hmp;
1626                         hammer2_vfs_unmount_hmp1(mp, hmp);
1627
1628                         atomic_clear_int(&rchain->flags, HAMMER2_CHAIN_MOUNTED);
1629 #if REPORT_REFS_ERRORS
1630                         if (rchain->refs != 1)
1631                                 kprintf("PMP->RCHAIN %p REFS WRONG %d\n",
1632                                         rchain, rchain->refs);
1633 #else
1634                         KKASSERT(rchain->refs == 1);
1635 #endif
1636                         hammer2_chain_drop(rchain);
1637                         cluster->array[i] = NULL;
1638                         hammer2_vfs_unmount_hmp2(mp, hmp);
1639                 }
1640                 cluster->focus = NULL;
1641
1642 #if REPORT_REFS_ERRORS
1643                 if (pmp->iroot->refs != 1)
1644                         kprintf("PMP->IROOT %p REFS WRONG %d\n",
1645                                 pmp->iroot, pmp->iroot->refs);
1646 #else
1647                 KKASSERT(pmp->iroot->refs == 1);
1648 #endif
1649                 /* ref for pmp->iroot */
1650                 hammer2_inode_drop(pmp->iroot);
1651                 pmp->iroot = NULL;
1652         }
1653
1654         pmp->mp = NULL;
1655         mp->mnt_data = NULL;
1656
1657         kmalloc_destroy(&pmp->mmsg);
1658         kmalloc_destroy(&pmp->minode);
1659
1660         kfree(pmp, M_HAMMER2);
1661         error = 0;
1662
1663 failed:
1664         lockmgr(&hammer2_mntlk, LK_RELEASE);
1665
1666         return (error);
1667 }
1668
1669 static
1670 void
1671 hammer2_vfs_unmount_hmp1(struct mount *mp, hammer2_mount_t *hmp)
1672 {
1673         hammer2_mount_exlock(hmp);
1674         --hmp->pmp_count;
1675
1676         kprintf("hammer2_unmount hmp=%p pmpcnt=%d\n", hmp, hmp->pmp_count);
1677
1678         /*
1679          * Cycle the volume data lock as a safety (probably not needed any
1680          * more).  To ensure everything is out we need to flush at least
1681          * three times.  (1) The running of the unlinkq can dirty the
1682          * filesystem, (2) A normal flush can dirty the freemap, and
1683          * (3) ensure that the freemap is fully synchronized.
1684          *
1685          * The next mount's recovery scan can clean everything up but we want
1686          * to leave the filesystem in a 100% clean state on a normal unmount.
1687          */
1688         hammer2_voldata_lock(hmp);
1689         hammer2_voldata_unlock(hmp);
1690         if (mp->mnt_data) {
1691                 hammer2_vfs_sync(mp, MNT_WAIT);
1692                 hammer2_vfs_sync(mp, MNT_WAIT);
1693                 hammer2_vfs_sync(mp, MNT_WAIT);
1694         }
1695
1696         /*
1697          * XXX chain depend deadlock?
1698          */
1699         hammer2_iocom_uninit(hmp);
1700
1701         if (hmp->pmp_count == 0) {
1702                 if ((hmp->vchain.flags | hmp->fchain.flags) &
1703                     HAMMER2_CHAIN_FLUSH_MASK) {
1704                         kprintf("hammer2_unmount: chains left over "
1705                                 "after final sync\n");
1706                         kprintf("    vchain %08x\n", hmp->vchain.flags);
1707                         kprintf("    fchain %08x\n", hmp->fchain.flags);
1708
1709                         if (hammer2_debug & 0x0010)
1710                                 Debugger("entered debugger");
1711                 }
1712         }
1713 }
1714
1715 static
1716 void
1717 hammer2_vfs_unmount_hmp2(struct mount *mp, hammer2_mount_t *hmp)
1718 {
1719         hammer2_pfsmount_t *spmp;
1720         struct vnode *devvp;
1721         int dumpcnt;
1722         int ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
1723
1724         /*
1725          * If no PFS's left drop the master hammer2_mount for the
1726          * device.
1727          */
1728         if (hmp->pmp_count == 0) {
1729                 /*
1730                  * Clean up SPMP and the super-root inode
1731                  */
1732                 spmp = hmp->spmp;
1733                 if (spmp) {
1734                         if (spmp->iroot) {
1735                                 hammer2_inode_drop(spmp->iroot);
1736                                 spmp->iroot = NULL;
1737                         }
1738                         hmp->spmp = NULL;
1739                         kmalloc_destroy(&spmp->mmsg);
1740                         kmalloc_destroy(&spmp->minode);
1741                         kfree(spmp, M_HAMMER2);
1742                 }
1743
1744                 /*
1745                  * Finish up with the device vnode
1746                  */
1747                 if ((devvp = hmp->devvp) != NULL) {
1748                         vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1749                         vinvalbuf(devvp, (ronly ? 0 : V_SAVE), 0, 0);
1750                         hmp->devvp = NULL;
1751                         VOP_CLOSE(devvp, (ronly ? FREAD : FREAD|FWRITE), NULL);
1752                         vn_unlock(devvp);
1753                         vrele(devvp);
1754                         devvp = NULL;
1755                 }
1756
1757                 /*
1758                  * Clear vchain/fchain flags that might prevent final cleanup
1759                  * of these chains.
1760                  */
1761                 if (hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) {
1762                         atomic_clear_int(&hmp->vchain.flags,
1763                                          HAMMER2_CHAIN_MODIFIED);
1764                         hammer2_pfs_memory_wakeup(hmp->vchain.pmp);
1765                         hammer2_chain_drop(&hmp->vchain);
1766                 }
1767                 if (hmp->vchain.flags & HAMMER2_CHAIN_UPDATE) {
1768                         atomic_clear_int(&hmp->vchain.flags,
1769                                          HAMMER2_CHAIN_UPDATE);
1770                         hammer2_chain_drop(&hmp->vchain);
1771                 }
1772
1773                 if (hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) {
1774                         atomic_clear_int(&hmp->fchain.flags,
1775                                          HAMMER2_CHAIN_MODIFIED);
1776                         hammer2_pfs_memory_wakeup(hmp->fchain.pmp);
1777                         hammer2_chain_drop(&hmp->fchain);
1778                 }
1779                 if (hmp->fchain.flags & HAMMER2_CHAIN_UPDATE) {
1780                         atomic_clear_int(&hmp->fchain.flags,
1781                                          HAMMER2_CHAIN_UPDATE);
1782                         hammer2_chain_drop(&hmp->fchain);
1783                 }
1784
1785                 /*
1786                  * Final drop of embedded freemap root chain to
1787                  * clean up fchain.core (fchain structure is not
1788                  * flagged ALLOCATED so it is cleaned out and then
1789                  * left to rot).
1790                  */
1791                 hammer2_chain_drop(&hmp->fchain);
1792
1793                 /*
1794                  * Final drop of embedded volume root chain to clean
1795                  * up vchain.core (vchain structure is not flagged
1796                  * ALLOCATED so it is cleaned out and then left to
1797                  * rot).
1798                  */
1799                 dumpcnt = 50;
1800                 hammer2_dump_chain(&hmp->vchain, 0, &dumpcnt, 'v');
1801                 dumpcnt = 50;
1802                 hammer2_dump_chain(&hmp->fchain, 0, &dumpcnt, 'f');
1803                 hammer2_mount_unlock(hmp);
1804                 hammer2_chain_drop(&hmp->vchain);
1805
1806                 hammer2_io_cleanup(hmp, &hmp->iotree);
1807                 if (hmp->iofree_count) {
1808                         kprintf("io_cleanup: %d I/O's left hanging\n",
1809                                 hmp->iofree_count);
1810                 }
1811
1812                 TAILQ_REMOVE(&hammer2_mntlist, hmp, mntentry);
1813                 kmalloc_destroy(&hmp->mchain);
1814                 kfree(hmp, M_HAMMER2);
1815         } else {
1816                 hammer2_mount_unlock(hmp);
1817         }
1818 }
1819
1820 static
1821 int
1822 hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
1823              ino_t ino, struct vnode **vpp)
1824 {
1825         kprintf("hammer2_vget\n");
1826         return (EOPNOTSUPP);
1827 }
1828
1829 static
1830 int
1831 hammer2_vfs_root(struct mount *mp, struct vnode **vpp)
1832 {
1833         hammer2_pfsmount_t *pmp;
1834         hammer2_cluster_t *cparent;
1835         int error;
1836         struct vnode *vp;
1837
1838         pmp = MPTOPMP(mp);
1839         if (pmp->iroot == NULL) {
1840                 *vpp = NULL;
1841                 error = EINVAL;
1842         } else {
1843                 cparent = hammer2_inode_lock_sh(pmp->iroot);
1844                 vp = hammer2_igetv(pmp->iroot, cparent, &error);
1845                 hammer2_inode_unlock_sh(pmp->iroot, cparent);
1846                 *vpp = vp;
1847                 if (vp == NULL)
1848                         kprintf("vnodefail\n");
1849         }
1850
1851         return (error);
1852 }
1853
1854 /*
1855  * Filesystem status
1856  *
1857  * XXX incorporate ipdata->inode_quota and data_quota
1858  */
1859 static
1860 int
1861 hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred)
1862 {
1863         hammer2_pfsmount_t *pmp;
1864         hammer2_mount_t *hmp;
1865
1866         pmp = MPTOPMP(mp);
1867         KKASSERT(pmp->iroot->cluster.nchains >= 1);
1868         hmp = pmp->iroot->cluster.focus->hmp;   /* XXX */
1869
1870         mp->mnt_stat.f_files = pmp->inode_count;
1871         mp->mnt_stat.f_ffree = 0;
1872         mp->mnt_stat.f_blocks = hmp->voldata.allocator_size / HAMMER2_PBUFSIZE;
1873         mp->mnt_stat.f_bfree =  hmp->voldata.allocator_free / HAMMER2_PBUFSIZE;
1874         mp->mnt_stat.f_bavail = mp->mnt_stat.f_bfree;
1875
1876         *sbp = mp->mnt_stat;
1877         return (0);
1878 }
1879
1880 static
1881 int
1882 hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp, struct ucred *cred)
1883 {
1884         hammer2_pfsmount_t *pmp;
1885         hammer2_mount_t *hmp;
1886
1887         pmp = MPTOPMP(mp);
1888         KKASSERT(pmp->iroot->cluster.nchains >= 1);
1889         hmp = pmp->iroot->cluster.focus->hmp;   /* XXX */
1890
1891         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1892         mp->mnt_vstat.f_files = pmp->inode_count;
1893         mp->mnt_vstat.f_ffree = 0;
1894         mp->mnt_vstat.f_blocks = hmp->voldata.allocator_size / HAMMER2_PBUFSIZE;
1895         mp->mnt_vstat.f_bfree =  hmp->voldata.allocator_free / HAMMER2_PBUFSIZE;
1896         mp->mnt_vstat.f_bavail = mp->mnt_vstat.f_bfree;
1897
1898         *sbp = mp->mnt_vstat;
1899         return (0);
1900 }
1901
1902 /*
1903  * Mount-time recovery (RW mounts)
1904  *
1905  * Updates to the free block table are allowed to lag flushes by one
1906  * transaction.  In case of a crash, then on a fresh mount we must do an
1907  * incremental scan of the last committed transaction id and make sure that
1908  * all related blocks have been marked allocated.
1909  *
1910  * The super-root topology and each PFS has its own transaction id domain,
1911  * so we must track PFS boundary transitions.
1912  */
1913 struct hammer2_recovery_elm {
1914         TAILQ_ENTRY(hammer2_recovery_elm) entry;
1915         hammer2_chain_t *chain;
1916         hammer2_tid_t sync_tid;
1917 };
1918
1919 TAILQ_HEAD(hammer2_recovery_list, hammer2_recovery_elm);
1920
1921 struct hammer2_recovery_info {
1922         struct hammer2_recovery_list list;
1923         int     depth;
1924 };
1925
1926 static int hammer2_recovery_scan(hammer2_trans_t *trans, hammer2_mount_t *hmp,
1927                         hammer2_chain_t *parent,
1928                         struct hammer2_recovery_info *info,
1929                         hammer2_tid_t sync_tid);
1930
1931 #define HAMMER2_RECOVERY_MAXDEPTH       10
1932
1933 static
1934 int
1935 hammer2_recovery(hammer2_mount_t *hmp)
1936 {
1937         hammer2_trans_t trans;
1938         struct hammer2_recovery_info info;
1939         struct hammer2_recovery_elm *elm;
1940         hammer2_chain_t *parent;
1941         hammer2_tid_t sync_tid;
1942         int error;
1943         int cumulative_error = 0;
1944
1945         hammer2_trans_init(&trans, hmp->spmp, 0);
1946
1947         sync_tid = 0;
1948         TAILQ_INIT(&info.list);
1949         info.depth = 0;
1950         parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
1951         cumulative_error = hammer2_recovery_scan(&trans, hmp, parent,
1952                                                  &info, sync_tid);
1953         hammer2_chain_lookup_done(parent);
1954
1955         while ((elm = TAILQ_FIRST(&info.list)) != NULL) {
1956                 TAILQ_REMOVE(&info.list, elm, entry);
1957                 parent = elm->chain;
1958                 sync_tid = elm->sync_tid;
1959                 kfree(elm, M_HAMMER2);
1960
1961                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1962                                            HAMMER2_RESOLVE_NOREF);
1963                 error = hammer2_recovery_scan(&trans, hmp, parent,
1964                                               &info, sync_tid);
1965                 hammer2_chain_unlock(parent);
1966                 if (error)
1967                         cumulative_error = error;
1968         }
1969         hammer2_trans_done(&trans);
1970
1971         return cumulative_error;
1972 }
1973
1974 static
1975 int
1976 hammer2_recovery_scan(hammer2_trans_t *trans, hammer2_mount_t *hmp,
1977                       hammer2_chain_t *parent,
1978                       struct hammer2_recovery_info *info,
1979                       hammer2_tid_t sync_tid)
1980 {
1981         const hammer2_inode_data_t *ripdata;
1982         hammer2_chain_t *chain;
1983         int cache_index;
1984         int cumulative_error = 0;
1985         int pfs_boundary = 0;
1986         int error;
1987
1988         /*
1989          * Adjust freemap to ensure that the block(s) are marked allocated.
1990          */
1991         if (parent->bref.type != HAMMER2_BREF_TYPE_VOLUME) {
1992                 hammer2_freemap_adjust(trans, hmp, &parent->bref,
1993                                        HAMMER2_FREEMAP_DORECOVER);
1994         }
1995
1996         /*
1997          * Check type for recursive scan
1998          */
1999         switch(parent->bref.type) {
2000         case HAMMER2_BREF_TYPE_VOLUME:
2001                 /* data already instantiated */
2002                 break;
2003         case HAMMER2_BREF_TYPE_INODE:
2004                 /*
2005                  * Must instantiate data for DIRECTDATA test and also
2006                  * for recursion.
2007                  */
2008                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2009                 ripdata = &hammer2_chain_rdata(parent)->ipdata;
2010                 if (ripdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2011                         /* not applicable to recovery scan */
2012                         hammer2_chain_unlock(parent);
2013                         return 0;
2014                 }
2015                 if ((ripdata->op_flags & HAMMER2_OPFLAG_PFSROOT) &&
2016                     info->depth != 0) {
2017                         pfs_boundary = 1;
2018                         sync_tid = parent->bref.mirror_tid - 1;
2019                 }
2020                 hammer2_chain_unlock(parent);
2021                 break;
2022         case HAMMER2_BREF_TYPE_INDIRECT:
2023                 /*
2024                  * Must instantiate data for recursion
2025                  */
2026                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2027                 hammer2_chain_unlock(parent);
2028                 break;
2029         case HAMMER2_BREF_TYPE_DATA:
2030         case HAMMER2_BREF_TYPE_FREEMAP:
2031         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2032         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2033                 /* not applicable to recovery scan */
2034                 return 0;
2035                 break;
2036         default:
2037                 return EDOM;
2038         }
2039
2040         /*
2041          * Defer operation if depth limit reached or if we are crossing a
2042          * PFS boundary.
2043          */
2044         if (info->depth >= HAMMER2_RECOVERY_MAXDEPTH || pfs_boundary) {
2045                 struct hammer2_recovery_elm *elm;
2046
2047                 elm = kmalloc(sizeof(*elm), M_HAMMER2, M_ZERO | M_WAITOK);
2048                 elm->chain = parent;
2049                 elm->sync_tid = sync_tid;
2050                 hammer2_chain_ref(parent);
2051                 TAILQ_INSERT_TAIL(&info->list, elm, entry);
2052                 /* unlocked by caller */
2053
2054                 return(0);
2055         }
2056
2057
2058         /*
2059          * Recursive scan of the last flushed transaction only.  We are
2060          * doing this without pmp assignments so don't leave the chains
2061          * hanging around after we are done with them.
2062          */
2063         cache_index = 0;
2064         chain = hammer2_chain_scan(parent, NULL, &cache_index,
2065                                    HAMMER2_LOOKUP_NODATA);
2066         while (chain) {
2067                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
2068                 if (chain->bref.mirror_tid >= sync_tid) {
2069                         ++info->depth;
2070                         error = hammer2_recovery_scan(trans, hmp, chain,
2071                                                       info, sync_tid);
2072                         --info->depth;
2073                         if (error)
2074                                 cumulative_error = error;
2075                 }
2076                 chain = hammer2_chain_scan(parent, chain, &cache_index,
2077                                            HAMMER2_LOOKUP_NODATA);
2078         }
2079
2080         return cumulative_error;
2081 }
2082
2083 /*
2084  * Sync the entire filesystem; this is called from the filesystem syncer
2085  * process periodically and whenever a user calls sync(1) on the hammer
2086  * mountpoint.
2087  *
2088  * Currently is actually called from the syncer! \o/
2089  *
2090  * This task will have to snapshot the state of the dirty inode chain.
2091  * From that, it will have to make sure all of the inodes on the dirty
2092  * chain have IO initiated. We make sure that io is initiated for the root
2093  * block.
2094  *
2095  * If waitfor is set, we wait for media to acknowledge the new rootblock.
2096  *
2097  * THINKS: side A vs side B, to have sync not stall all I/O?
2098  */
2099 int
2100 hammer2_vfs_sync(struct mount *mp, int waitfor)
2101 {
2102         struct hammer2_sync_info info;
2103         hammer2_inode_t *iroot;
2104         hammer2_chain_t *chain;
2105         hammer2_chain_t *parent;
2106         hammer2_pfsmount_t *pmp;
2107         hammer2_mount_t *hmp;
2108         int flags;
2109         int error;
2110         int total_error;
2111         int force_fchain;
2112         int i;
2113         int j;
2114
2115         pmp = MPTOPMP(mp);
2116         iroot = pmp->iroot;
2117         KKASSERT(iroot);
2118         KKASSERT(iroot->pmp == pmp);
2119
2120         /*
2121          * We can't acquire locks on existing vnodes while in a transaction
2122          * without risking a deadlock.  This assumes that vfsync() can be
2123          * called without the vnode locked (which it can in DragonFly).
2124          * Otherwise we'd have to implement a multi-pass or flag the lock
2125          * failures and retry.
2126          *
2127          * The reclamation code interlocks with the sync list's token
2128          * (by removing the vnode from the scan list) before unlocking
2129          * the inode, giving us time to ref the inode.
2130          */
2131         /*flags = VMSC_GETVP;*/
2132         flags = 0;
2133         if (waitfor & MNT_LAZY)
2134                 flags |= VMSC_ONEPASS;
2135
2136         /*
2137          * Start our flush transaction.  This does not return until all
2138          * concurrent transactions have completed and will prevent any
2139          * new transactions from running concurrently, except for the
2140          * buffer cache transactions.
2141          *
2142          * For efficiency do an async pass before making sure with a
2143          * synchronous pass on all related buffer cache buffers.  It
2144          * should theoretically not be possible for any new file buffers
2145          * to be instantiated during this sequence.
2146          */
2147         hammer2_trans_init(&info.trans, pmp, HAMMER2_TRANS_ISFLUSH |
2148                                              HAMMER2_TRANS_PREFLUSH);
2149         hammer2_run_unlinkq(&info.trans, pmp);
2150
2151         info.error = 0;
2152         info.waitfor = MNT_NOWAIT;
2153         vsyncscan(mp, flags | VMSC_NOWAIT, hammer2_sync_scan2, &info);
2154         info.waitfor = MNT_WAIT;
2155         vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2156
2157         /*
2158          * Clear PREFLUSH.  This prevents (or asserts on) any new logical
2159          * buffer cache flushes which occur during the flush.  Device buffers
2160          * are not affected.
2161          */
2162
2163 #if 0
2164         if (info.error == 0 && (waitfor & MNT_WAIT)) {
2165                 info.waitfor = waitfor;
2166                     vsyncscan(mp, flags, hammer2_sync_scan2, &info);
2167
2168         }
2169 #endif
2170         hammer2_bioq_sync(info.trans.pmp);
2171         atomic_clear_int(&info.trans.flags, HAMMER2_TRANS_PREFLUSH);
2172
2173         total_error = 0;
2174
2175         /*
2176          * Flush all storage elements making up the cluster
2177          *
2178          * We must also flush any deleted siblings because the super-root
2179          * flush won't do it for us.  They all must be staged or the
2180          * super-root flush will not be able to update its block table
2181          * properly.
2182          *
2183          * XXX currently done serially instead of concurrently
2184          */
2185         for (i = 0; iroot && i < iroot->cluster.nchains; ++i) {
2186                 chain = iroot->cluster.array[i];
2187                 if (chain) {
2188                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
2189                         hammer2_flush(&info.trans, chain);
2190                         hammer2_chain_unlock(chain);
2191                 }
2192         }
2193 #if 0
2194         hammer2_trans_done(&info.trans);
2195 #endif
2196
2197         /*
2198          * Flush all volume roots to synchronize PFS flushes with the
2199          * storage media.  Use a super-root transaction for each one.
2200          *
2201          * The flush code will detect super-root -> pfs-root chain
2202          * transitions using the last pfs-root flush.
2203          */
2204         for (i = 0; iroot && i < iroot->cluster.nchains; ++i) {
2205                 chain = iroot->cluster.array[i];
2206                 if (chain == NULL)
2207                         continue;
2208
2209                 hmp = chain->hmp;
2210
2211                 /*
2212                  * We only have to flush each hmp once
2213                  */
2214                 for (j = i - 1; j >= 0; --j) {
2215                         if (iroot->cluster.array[j] &&
2216                             iroot->cluster.array[j]->hmp == hmp)
2217                                 break;
2218                 }
2219                 if (j >= 0)
2220                         continue;
2221                 hammer2_trans_spmp(&info.trans, hmp->spmp);
2222
2223                 /*
2224                  * Force an update of the XID from the PFS root to the
2225                  * topology root.  We couldn't do this from the PFS
2226                  * transaction because a SPMP transaction is needed.
2227                  * This does not modify blocks, instead what it does is
2228                  * allow the flush code to find the transition point and
2229                  * then update on the way back up.
2230                  */
2231                 parent = chain->parent;
2232                 KKASSERT(chain->pmp != parent->pmp);
2233                 hammer2_chain_setflush(&info.trans, parent);
2234
2235                 /*
2236                  * Media mounts have two 'roots', vchain for the topology
2237                  * and fchain for the free block table.  Flush both.
2238                  *
2239                  * Note that the topology and free block table are handled
2240                  * independently, so the free block table can wind up being
2241                  * ahead of the topology.  We depend on the bulk free scan
2242                  * code to deal with any loose ends.
2243                  */
2244                 hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
2245                 hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
2246                 if (hmp->fchain.flags & HAMMER2_CHAIN_FLUSH_MASK) {
2247                         /*
2248                          * This will also modify vchain as a side effect,
2249                          * mark vchain as modified now.
2250                          */
2251                         hammer2_voldata_modify(hmp);
2252                         chain = &hmp->fchain;
2253                         hammer2_flush(&info.trans, chain);
2254                         KKASSERT(chain == &hmp->fchain);
2255                 }
2256                 hammer2_chain_unlock(&hmp->fchain);
2257                 hammer2_chain_unlock(&hmp->vchain);
2258
2259                 hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
2260                 if (hmp->vchain.flags & HAMMER2_CHAIN_FLUSH_MASK) {
2261                         chain = &hmp->vchain;
2262                         hammer2_flush(&info.trans, chain);
2263                         KKASSERT(chain == &hmp->vchain);
2264                         force_fchain = 1;
2265                 } else {
2266                         force_fchain = 0;
2267                 }
2268                 hammer2_chain_unlock(&hmp->vchain);
2269
2270 #if 0
2271                 hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
2272                 if ((hmp->fchain.flags & HAMMER2_CHAIN_FLUSH_MASK) ||
2273                     force_fchain) {
2274                         /* this will also modify vchain as a side effect */
2275                         chain = &hmp->fchain;
2276                         hammer2_flush(&info.trans, chain);
2277                         KKASSERT(chain == &hmp->fchain);
2278                 }
2279                 hammer2_chain_unlock(&hmp->fchain);
2280 #endif
2281
2282                 error = 0;
2283
2284                 /*
2285                  * We can't safely flush the volume header until we have
2286                  * flushed any device buffers which have built up.
2287                  *
2288                  * XXX this isn't being incremental
2289                  */
2290                 vn_lock(hmp->devvp, LK_EXCLUSIVE | LK_RETRY);
2291                 error = VOP_FSYNC(hmp->devvp, MNT_WAIT, 0);
2292                 vn_unlock(hmp->devvp);
2293
2294                 /*
2295                  * The flush code sets CHAIN_VOLUMESYNC to indicate that the
2296                  * volume header needs synchronization via hmp->volsync.
2297                  *
2298                  * XXX synchronize the flag & data with only this flush XXX
2299                  */
2300                 if (error == 0 &&
2301                     (hmp->vchain.flags & HAMMER2_CHAIN_VOLUMESYNC)) {
2302                         struct buf *bp;
2303
2304                         /*
2305                          * Synchronize the disk before flushing the volume
2306                          * header.
2307                          */
2308                         bp = getpbuf(NULL);
2309                         bp->b_bio1.bio_offset = 0;
2310                         bp->b_bufsize = 0;
2311                         bp->b_bcount = 0;
2312                         bp->b_cmd = BUF_CMD_FLUSH;
2313                         bp->b_bio1.bio_done = biodone_sync;
2314                         bp->b_bio1.bio_flags |= BIO_SYNC;
2315                         vn_strategy(hmp->devvp, &bp->b_bio1);
2316                         biowait(&bp->b_bio1, "h2vol");
2317                         relpbuf(bp, NULL);
2318
2319                         /*
2320                          * Then we can safely flush the version of the
2321                          * volume header synchronized by the flush code.
2322                          */
2323                         i = hmp->volhdrno + 1;
2324                         if (i >= HAMMER2_NUM_VOLHDRS)
2325                                 i = 0;
2326                         if (i * HAMMER2_ZONE_BYTES64 + HAMMER2_SEGSIZE >
2327                             hmp->volsync.volu_size) {
2328                                 i = 0;
2329                         }
2330                         kprintf("sync volhdr %d %jd\n",
2331                                 i, (intmax_t)hmp->volsync.volu_size);
2332                         bp = getblk(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2333                                     HAMMER2_PBUFSIZE, 0, 0);
2334                         atomic_clear_int(&hmp->vchain.flags,
2335                                          HAMMER2_CHAIN_VOLUMESYNC);
2336                         bcopy(&hmp->volsync, bp->b_data, HAMMER2_PBUFSIZE);
2337                         bawrite(bp);
2338                         hmp->volhdrno = i;
2339                 }
2340                 if (error)
2341                         total_error = error;
2342
2343 #if 0
2344                 hammer2_trans_done(&info.trans);
2345 #endif
2346         }
2347         hammer2_trans_done(&info.trans);
2348
2349         return (total_error);
2350 }
2351
2352 /*
2353  * Sync passes.
2354  */
2355 static int
2356 hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data)
2357 {
2358         struct hammer2_sync_info *info = data;
2359         hammer2_inode_t *ip;
2360         int error;
2361
2362         /*
2363          *
2364          */
2365         ip = VTOI(vp);
2366         if (ip == NULL)
2367                 return(0);
2368         if (vp->v_type == VNON || vp->v_type == VBAD) {
2369                 vclrisdirty(vp);
2370                 return(0);
2371         }
2372         if ((ip->flags & HAMMER2_INODE_MODIFIED) == 0 &&
2373             RB_EMPTY(&vp->v_rbdirty_tree)) {
2374                 vclrisdirty(vp);
2375                 return(0);
2376         }
2377
2378         /*
2379          * VOP_FSYNC will start a new transaction so replicate some code
2380          * here to do it inline (see hammer2_vop_fsync()).
2381          *
2382          * WARNING: The vfsync interacts with the buffer cache and might
2383          *          block, we can't hold the inode lock at that time.
2384          *          However, we MUST ref ip before blocking to ensure that
2385          *          it isn't ripped out from under us (since we do not
2386          *          hold a lock on the vnode).
2387          */
2388         hammer2_inode_ref(ip);
2389         atomic_clear_int(&ip->flags, HAMMER2_INODE_MODIFIED);
2390         if (vp)
2391                 vfsync(vp, MNT_NOWAIT, 1, NULL, NULL);
2392
2393         hammer2_inode_drop(ip);
2394 #if 1
2395         error = 0;
2396         if (error)
2397                 info->error = error;
2398 #endif
2399         return(0);
2400 }
2401
2402 static
2403 int
2404 hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp)
2405 {
2406         return (0);
2407 }
2408
2409 static
2410 int
2411 hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
2412                struct fid *fhp, struct vnode **vpp)
2413 {
2414         return (0);
2415 }
2416
2417 static
2418 int
2419 hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
2420                  int *exflagsp, struct ucred **credanonp)
2421 {
2422         return (0);
2423 }
2424
2425 /*
2426  * Support code for hammer2_vfs_mount().  Read, verify, and install the volume
2427  * header into the HMP
2428  *
2429  * XXX read four volhdrs and use the one with the highest TID whos CRC
2430  *     matches.
2431  *
2432  * XXX check iCRCs.
2433  *
2434  * XXX For filesystems w/ less than 4 volhdrs, make sure to not write to
2435  *     nonexistant locations.
2436  *
2437  * XXX Record selected volhdr and ring updates to each of 4 volhdrs
2438  */
2439 static
2440 int
2441 hammer2_install_volume_header(hammer2_mount_t *hmp)
2442 {
2443         hammer2_volume_data_t *vd;
2444         struct buf *bp;
2445         hammer2_crc32_t crc0, crc, bcrc0, bcrc;
2446         int error_reported;
2447         int error;
2448         int valid;
2449         int i;
2450
2451         error_reported = 0;
2452         error = 0;
2453         valid = 0;
2454         bp = NULL;
2455
2456         /*
2457          * There are up to 4 copies of the volume header (syncs iterate
2458          * between them so there is no single master).  We don't trust the
2459          * volu_size field so we don't know precisely how large the filesystem
2460          * is, so depend on the OS to return an error if we go beyond the
2461          * block device's EOF.
2462          */
2463         for (i = 0; i < HAMMER2_NUM_VOLHDRS; i++) {
2464                 error = bread(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2465                               HAMMER2_VOLUME_BYTES, &bp);
2466                 if (error) {
2467                         brelse(bp);
2468                         bp = NULL;
2469                         continue;
2470                 }
2471
2472                 vd = (struct hammer2_volume_data *) bp->b_data;
2473                 if ((vd->magic != HAMMER2_VOLUME_ID_HBO) &&
2474                     (vd->magic != HAMMER2_VOLUME_ID_ABO)) {
2475                         brelse(bp);
2476                         bp = NULL;
2477                         continue;
2478                 }
2479
2480                 if (vd->magic == HAMMER2_VOLUME_ID_ABO) {
2481                         /* XXX: Reversed-endianness filesystem */
2482                         kprintf("hammer2: reverse-endian filesystem detected");
2483                         brelse(bp);
2484                         bp = NULL;
2485                         continue;
2486                 }
2487
2488                 crc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT0];
2489                 crc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC0_OFF,
2490                                       HAMMER2_VOLUME_ICRC0_SIZE);
2491                 bcrc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT1];
2492                 bcrc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC1_OFF,
2493                                        HAMMER2_VOLUME_ICRC1_SIZE);
2494                 if ((crc0 != crc) || (bcrc0 != bcrc)) {
2495                         kprintf("hammer2 volume header crc "
2496                                 "mismatch copy #%d %08x/%08x\n",
2497                                 i, crc0, crc);
2498                         error_reported = 1;
2499                         brelse(bp);
2500                         bp = NULL;
2501                         continue;
2502                 }
2503                 if (valid == 0 || hmp->voldata.mirror_tid < vd->mirror_tid) {
2504                         valid = 1;
2505                         hmp->voldata = *vd;
2506                         hmp->volhdrno = i;
2507                 }
2508                 brelse(bp);
2509                 bp = NULL;
2510         }
2511         if (valid) {
2512                 hmp->volsync = hmp->voldata;
2513                 error = 0;
2514                 if (error_reported || bootverbose || 1) { /* 1/DEBUG */
2515                         kprintf("hammer2: using volume header #%d\n",
2516                                 hmp->volhdrno);
2517                 }
2518         } else {
2519                 error = EINVAL;
2520                 kprintf("hammer2: no valid volume headers found!\n");
2521         }
2522         return (error);
2523 }
2524
2525 /*
2526  * This handles hysteresis on regular file flushes.  Because the BIOs are
2527  * routed to a thread it is possible for an excessive number to build up
2528  * and cause long front-end stalls long before the runningbuffspace limit
2529  * is hit, so we implement hammer2_flush_pipe to control the
2530  * hysteresis.
2531  *
2532  * This is a particular problem when compression is used.
2533  */
2534 void
2535 hammer2_lwinprog_ref(hammer2_pfsmount_t *pmp)
2536 {
2537         atomic_add_int(&pmp->count_lwinprog, 1);
2538 }
2539
2540 void
2541 hammer2_lwinprog_drop(hammer2_pfsmount_t *pmp)
2542 {
2543         int lwinprog;
2544
2545         lwinprog = atomic_fetchadd_int(&pmp->count_lwinprog, -1);
2546         if ((lwinprog & HAMMER2_LWINPROG_WAITING) &&
2547             (lwinprog & HAMMER2_LWINPROG_MASK) <= hammer2_flush_pipe * 2 / 3) {
2548                 atomic_clear_int(&pmp->count_lwinprog,
2549                                  HAMMER2_LWINPROG_WAITING);
2550                 wakeup(&pmp->count_lwinprog);
2551         }
2552 }
2553
2554 void
2555 hammer2_lwinprog_wait(hammer2_pfsmount_t *pmp)
2556 {
2557         int lwinprog;
2558
2559         for (;;) {
2560                 lwinprog = pmp->count_lwinprog;
2561                 cpu_ccfence();
2562                 if ((lwinprog & HAMMER2_LWINPROG_MASK) < hammer2_flush_pipe)
2563                         break;
2564                 tsleep_interlock(&pmp->count_lwinprog, 0);
2565                 atomic_set_int(&pmp->count_lwinprog, HAMMER2_LWINPROG_WAITING);
2566                 lwinprog = pmp->count_lwinprog;
2567                 if ((lwinprog & HAMMER2_LWINPROG_MASK) < hammer2_flush_pipe)
2568                         break;
2569                 tsleep(&pmp->count_lwinprog, PINTERLOCKED, "h2wpipe", hz);
2570         }
2571 }
2572
2573 /*
2574  * Manage excessive memory resource use for chain and related
2575  * structures.
2576  */
2577 void
2578 hammer2_pfs_memory_wait(hammer2_pfsmount_t *pmp)
2579 {
2580         uint32_t waiting;
2581         uint32_t count;
2582         uint32_t limit;
2583 #if 0
2584         static int zzticks;
2585 #endif
2586
2587         /*
2588          * Atomic check condition and wait.  Also do an early speedup of
2589          * the syncer to try to avoid hitting the wait.
2590          */
2591         for (;;) {
2592                 waiting = pmp->inmem_dirty_chains;
2593                 cpu_ccfence();
2594                 count = waiting & HAMMER2_DIRTYCHAIN_MASK;
2595
2596                 limit = pmp->mp->mnt_nvnodelistsize / 10;
2597                 if (limit < hammer2_limit_dirty_chains)
2598                         limit = hammer2_limit_dirty_chains;
2599                 if (limit < 1000)
2600                         limit = 1000;
2601
2602 #if 0
2603                 if ((int)(ticks - zzticks) > hz) {
2604                         zzticks = ticks;
2605                         kprintf("count %ld %ld\n", count, limit);
2606                 }
2607 #endif
2608
2609                 /*
2610                  * Block if there are too many dirty chains present, wait
2611                  * for the flush to clean some out.
2612                  */
2613                 if (count > limit) {
2614                         tsleep_interlock(&pmp->inmem_dirty_chains, 0);
2615                         if (atomic_cmpset_int(&pmp->inmem_dirty_chains,
2616                                                waiting,
2617                                        waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
2618                                 speedup_syncer(pmp->mp);
2619                                 tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
2620                                        "chnmem", hz);
2621                         }
2622                         continue;       /* loop on success or fail */
2623                 }
2624
2625                 /*
2626                  * Try to start an early flush before we are forced to block.
2627                  */
2628                 if (count > limit * 7 / 10)
2629                         speedup_syncer(pmp->mp);
2630                 break;
2631         }
2632 }
2633
2634 void
2635 hammer2_pfs_memory_inc(hammer2_pfsmount_t *pmp)
2636 {
2637         if (pmp) {
2638                 atomic_add_int(&pmp->inmem_dirty_chains, 1);
2639         }
2640 }
2641
2642 void
2643 hammer2_pfs_memory_wakeup(hammer2_pfsmount_t *pmp)
2644 {
2645         uint32_t waiting;
2646
2647         if (pmp == NULL)
2648                 return;
2649
2650         for (;;) {
2651                 waiting = pmp->inmem_dirty_chains;
2652                 cpu_ccfence();
2653                 if (atomic_cmpset_int(&pmp->inmem_dirty_chains,
2654                                        waiting,
2655                                        (waiting - 1) &
2656                                         ~HAMMER2_DIRTYCHAIN_WAITING)) {
2657                         break;
2658                 }
2659         }
2660
2661         if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
2662                 wakeup(&pmp->inmem_dirty_chains);
2663 }
2664
2665 /*
2666  * Debugging
2667  */
2668 void
2669 hammer2_dump_chain(hammer2_chain_t *chain, int tab, int *countp, char pfx)
2670 {
2671         hammer2_chain_t *scan;
2672         hammer2_chain_t *parent;
2673
2674         --*countp;
2675         if (*countp == 0) {
2676                 kprintf("%*.*s...\n", tab, tab, "");
2677                 return;
2678         }
2679         if (*countp < 0)
2680                 return;
2681         kprintf("%*.*s%c-chain %p.%d %016jx/%d mir=%016jx\n",
2682                 tab, tab, "", pfx,
2683                 chain, chain->bref.type,
2684                 chain->bref.key, chain->bref.keybits,
2685                 chain->bref.mirror_tid);
2686
2687         kprintf("%*.*s      [%08x] (%s) refs=%d\n",
2688                 tab, tab, "",
2689                 chain->flags,
2690                 ((chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2691                 chain->data) ?  (char *)chain->data->ipdata.filename : "?"),
2692                 chain->refs);
2693
2694         kprintf("%*.*s      core [%08x]",
2695                 tab, tab, "",
2696                 chain->core.flags);
2697
2698         parent = chain->parent;
2699         if (parent)
2700                 kprintf("\n%*.*s      p=%p [pflags %08x prefs %d",
2701                         tab, tab, "",
2702                         parent, parent->flags, parent->refs);
2703         if (RB_EMPTY(&chain->core.rbtree)) {
2704                 kprintf("\n");
2705         } else {
2706                 kprintf(" {\n");
2707                 RB_FOREACH(scan, hammer2_chain_tree, &chain->core.rbtree)
2708                         hammer2_dump_chain(scan, tab + 4, countp, 'a');
2709                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE && chain->data)
2710                         kprintf("%*.*s}(%s)\n", tab, tab, "",
2711                                 chain->data->ipdata.filename);
2712                 else
2713                         kprintf("%*.*s}\n", tab, tab, "");
2714         }
2715 }