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