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