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