hammer2 - Merge Daniel Flores's HAMMER2 GSOC project into the main tree
[dragonfly.git] / sys / vfs / hammer2 / hammer2_vfsops.c
1 /*-
2  * Copyright (c) 2011-2013 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 static struct hammer2_mntlist hammer2_mntlist;
79 static struct lock hammer2_mntlk;
80
81 int hammer2_debug;
82 int hammer2_cluster_enable = 1;
83 int hammer2_hardlink_enable = 1;
84 long hammer2_iod_file_read;
85 long hammer2_iod_meta_read;
86 long hammer2_iod_indr_read;
87 long hammer2_iod_fmap_read;
88 long hammer2_iod_volu_read;
89 long hammer2_iod_file_write;
90 long hammer2_iod_meta_write;
91 long hammer2_iod_indr_write;
92 long hammer2_iod_fmap_write;
93 long hammer2_iod_volu_write;
94 long hammer2_ioa_file_read;
95 long hammer2_ioa_meta_read;
96 long hammer2_ioa_indr_read;
97 long hammer2_ioa_fmap_read;
98 long hammer2_ioa_volu_read;
99 long hammer2_ioa_fmap_write;
100 long hammer2_ioa_file_write;
101 long hammer2_ioa_meta_write;
102 long hammer2_ioa_indr_write;
103 long hammer2_ioa_volu_write;
104
105 MALLOC_DECLARE(C_BUFFER);
106 MALLOC_DEFINE(C_BUFFER, "compbuffer", "Buffer used for compression.");
107
108 MALLOC_DECLARE(D_BUFFER);
109 MALLOC_DEFINE(D_BUFFER, "decompbuffer", "Buffer used for decompression.");
110
111 MALLOC_DECLARE(W_BIOQUEUE);
112 MALLOC_DEFINE(W_BIOQUEUE, "wbioqueue", "Writing bio queue.");
113
114 MALLOC_DECLARE(W_MTX);
115 MALLOC_DEFINE(W_MTX, "wmutex", "Mutex for write thread.");
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
126 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_read, CTLFLAG_RW,
127            &hammer2_iod_file_read, 0, "");
128 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_read, CTLFLAG_RW,
129            &hammer2_iod_meta_read, 0, "");
130 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_read, CTLFLAG_RW,
131            &hammer2_iod_indr_read, 0, "");
132 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_read, CTLFLAG_RW,
133            &hammer2_iod_fmap_read, 0, "");
134 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_read, CTLFLAG_RW,
135            &hammer2_iod_volu_read, 0, "");
136
137 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_write, CTLFLAG_RW,
138            &hammer2_iod_file_write, 0, "");
139 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_write, CTLFLAG_RW,
140            &hammer2_iod_meta_write, 0, "");
141 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_write, CTLFLAG_RW,
142            &hammer2_iod_indr_write, 0, "");
143 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_write, CTLFLAG_RW,
144            &hammer2_iod_fmap_write, 0, "");
145 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_write, CTLFLAG_RW,
146            &hammer2_iod_volu_write, 0, "");
147
148 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_file_read, CTLFLAG_RW,
149            &hammer2_ioa_file_read, 0, "");
150 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_meta_read, CTLFLAG_RW,
151            &hammer2_ioa_meta_read, 0, "");
152 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_indr_read, CTLFLAG_RW,
153            &hammer2_ioa_indr_read, 0, "");
154 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_fmap_read, CTLFLAG_RW,
155            &hammer2_ioa_fmap_read, 0, "");
156 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_volu_read, CTLFLAG_RW,
157            &hammer2_ioa_volu_read, 0, "");
158
159 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_file_write, CTLFLAG_RW,
160            &hammer2_ioa_file_write, 0, "");
161 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_meta_write, CTLFLAG_RW,
162            &hammer2_ioa_meta_write, 0, "");
163 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_indr_write, CTLFLAG_RW,
164            &hammer2_ioa_indr_write, 0, "");
165 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_fmap_write, CTLFLAG_RW,
166            &hammer2_ioa_fmap_write, 0, "");
167 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_volu_write, CTLFLAG_RW,
168            &hammer2_ioa_volu_write, 0, "");
169
170 static int hammer2_vfs_init(struct vfsconf *conf);
171 static int hammer2_vfs_uninit(struct vfsconf *vfsp);
172 static int hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
173                                 struct ucred *cred);
174 static int hammer2_remount(struct mount *, char *, struct vnode *,
175                                 struct ucred *);
176 static int hammer2_vfs_unmount(struct mount *mp, int mntflags);
177 static int hammer2_vfs_root(struct mount *mp, struct vnode **vpp);
178 static int hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp,
179                                 struct ucred *cred);
180 static int hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp,
181                                 struct ucred *cred);
182 static int hammer2_vfs_sync(struct mount *mp, int waitfor);
183 static int hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
184                                 ino_t ino, struct vnode **vpp);
185 static int hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
186                                 struct fid *fhp, struct vnode **vpp);
187 static int hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp);
188 static int hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
189                                 int *exflagsp, struct ucred **credanonp);
190
191 static int hammer2_install_volume_header(hammer2_mount_t *hmp);
192 static int hammer2_sync_scan1(struct mount *mp, struct vnode *vp, void *data);
193 static int hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data);
194
195 static void hammer2_write_thread(void *arg);
196
197 /* 
198  * Functions for compression in threads,
199  * from hammer2_vnops.c
200  */
201 static void hammer2_write_file_core_t(struct buf *bp, hammer2_trans_t *trans,
202                                 hammer2_inode_t *ip,
203                                 hammer2_inode_data_t *ipdata,
204                                 hammer2_chain_t **parentp,
205                                 hammer2_key_t lbase, int ioflag, int pblksize,
206                                 int *errorp);
207 static void hammer2_compress_and_write_t(struct buf *bp, hammer2_trans_t *trans,
208                                 hammer2_inode_t *ip,
209                                 hammer2_inode_data_t *ipdata,
210                                 hammer2_chain_t **parentp,
211                                 hammer2_key_t lbase, int ioflag,
212                                 int pblksize, int *errorp, int comp_method);
213 static void hammer2_zero_check_and_write_t(struct buf *bp,
214                                 hammer2_trans_t *trans, hammer2_inode_t *ip,
215                                 hammer2_inode_data_t *ipdata,
216                                 hammer2_chain_t **parentp,
217                                 hammer2_key_t lbase,
218                                 int ioflag, int pblksize, int* error);
219 static int test_block_not_zeros_t(char *buf, size_t bytes);
220 static void zero_write_t(struct buf *bp, hammer2_trans_t *trans,
221                                 hammer2_inode_t *ip,
222                                 hammer2_inode_data_t *ipdata,
223                                 hammer2_chain_t **parentp, 
224                                 hammer2_key_t lbase);
225 static void hammer2_write_bp_t(hammer2_chain_t *chain, struct buf *bp,
226                                 int ioflag, int pblksize);
227
228 static int hammer2_rcvdmsg(kdmsg_msg_t *msg);
229 static void hammer2_autodmsg(kdmsg_msg_t *msg);
230
231
232 /*
233  * HAMMER2 vfs operations.
234  */
235 static struct vfsops hammer2_vfsops = {
236         .vfs_init       = hammer2_vfs_init,
237         .vfs_uninit = hammer2_vfs_uninit,
238         .vfs_sync       = hammer2_vfs_sync,
239         .vfs_mount      = hammer2_vfs_mount,
240         .vfs_unmount    = hammer2_vfs_unmount,
241         .vfs_root       = hammer2_vfs_root,
242         .vfs_statfs     = hammer2_vfs_statfs,
243         .vfs_statvfs    = hammer2_vfs_statvfs,
244         .vfs_vget       = hammer2_vfs_vget,
245         .vfs_vptofh     = hammer2_vfs_vptofh,
246         .vfs_fhtovp     = hammer2_vfs_fhtovp,
247         .vfs_checkexp   = hammer2_vfs_checkexp
248 };
249
250 MALLOC_DEFINE(M_HAMMER2, "HAMMER2-mount", "");
251
252 VFS_SET(hammer2_vfsops, hammer2, 0);
253 MODULE_VERSION(hammer2, 1);
254
255 static
256 int
257 hammer2_vfs_init(struct vfsconf *conf)
258 {
259         static struct objcache_malloc_args margs_read;
260         static struct objcache_malloc_args margs_write;
261
262         int error;
263
264         error = 0;
265
266         if (HAMMER2_BLOCKREF_BYTES != sizeof(struct hammer2_blockref))
267                 error = EINVAL;
268         if (HAMMER2_INODE_BYTES != sizeof(struct hammer2_inode_data))
269                 error = EINVAL;
270         if (HAMMER2_VOLUME_BYTES != sizeof(struct hammer2_volume_data))
271                 error = EINVAL;
272
273         if (error)
274                 kprintf("HAMMER2 structure size mismatch; cannot continue.\n");
275         
276         margs_read.objsize = 65536;
277         margs_read.mtype = D_BUFFER;
278         
279         margs_write.objsize = 32768;
280         margs_write.mtype = C_BUFFER;
281         
282         cache_buffer_read = objcache_create(margs_read.mtype->ks_shortdesc,
283                                 0, 1, NULL, NULL, NULL, objcache_malloc_alloc,
284                                 objcache_malloc_free, &margs_read);
285         cache_buffer_write = objcache_create(margs_write.mtype->ks_shortdesc,
286                                 0, 1, NULL, NULL, NULL, objcache_malloc_alloc,
287                                 objcache_malloc_free, &margs_write);
288
289         lockinit(&hammer2_mntlk, "mntlk", 0, 0);
290         TAILQ_INIT(&hammer2_mntlist);
291
292         return (error);
293 }
294
295 static
296 int
297 hammer2_vfs_uninit(struct vfsconf *vfsp __unused)
298 {
299         objcache_destroy(cache_buffer_read);
300         objcache_destroy(cache_buffer_write);
301         return 0;
302 }
303
304 /*
305  * Mount or remount HAMMER2 fileystem from physical media
306  *
307  *      mountroot
308  *              mp              mount point structure
309  *              path            NULL
310  *              data            <unused>
311  *              cred            <unused>
312  *
313  *      mount
314  *              mp              mount point structure
315  *              path            path to mount point
316  *              data            pointer to argument structure in user space
317  *                      volume  volume path (device@LABEL form)
318  *                      hflags  user mount flags
319  *              cred            user credentials
320  *
321  * RETURNS:     0       Success
322  *              !0      error number
323  */
324 static
325 int
326 hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
327                   struct ucred *cred)
328 {
329         struct hammer2_mount_info info;
330         hammer2_pfsmount_t *pmp;
331         hammer2_mount_t *hmp;
332         hammer2_key_t lhc;
333         struct vnode *devvp;
334         struct nlookupdata nd;
335         hammer2_chain_t *parent;
336         hammer2_chain_t *schain;
337         hammer2_chain_t *rchain;
338         struct file *fp;
339         char devstr[MNAMELEN];
340         size_t size;
341         size_t done;
342         char *dev;
343         char *label;
344         int ronly = 1;
345         int error;
346
347         hmp = NULL;
348         pmp = NULL;
349         dev = NULL;
350         label = NULL;
351         devvp = NULL;
352         
353
354         kprintf("hammer2_mount\n");
355
356         if (path == NULL) {
357                 /*
358                  * Root mount
359                  */
360                 bzero(&info, sizeof(info));
361                 info.cluster_fd = -1;
362                 return (EOPNOTSUPP);
363         } else {
364                 /*
365                  * Non-root mount or updating a mount
366                  */
367                 error = copyin(data, &info, sizeof(info));
368                 if (error)
369                         return (error);
370
371                 error = copyinstr(info.volume, devstr, MNAMELEN - 1, &done);
372                 if (error)
373                         return (error);
374
375                 /* Extract device and label */
376                 dev = devstr;
377                 label = strchr(devstr, '@');
378                 if (label == NULL ||
379                     ((label + 1) - dev) > done) {
380                         return (EINVAL);
381                 }
382                 *label = '\0';
383                 label++;
384                 if (*label == '\0')
385                         return (EINVAL);
386
387                 if (mp->mnt_flag & MNT_UPDATE) {
388                         /* Update mount */
389                         /* HAMMER2 implements NFS export via mountctl */
390                         hmp = MPTOHMP(mp);
391                         devvp = hmp->devvp;
392                         error = hammer2_remount(mp, path, devvp, cred);
393                         return error;
394                 }
395         }
396
397         /*
398          * PFS mount
399          *
400          * Lookup name and verify it refers to a block device.
401          */
402         error = nlookup_init(&nd, dev, UIO_SYSSPACE, NLC_FOLLOW);
403         if (error == 0)
404                 error = nlookup(&nd);
405         if (error == 0)
406                 error = cache_vref(&nd.nl_nch, nd.nl_cred, &devvp);
407         nlookup_done(&nd);
408
409         if (error == 0) {
410                 if (vn_isdisk(devvp, &error))
411                         error = vfs_mountedon(devvp);
412         }
413
414         /*
415          * Determine if the device has already been mounted.  After this
416          * check hmp will be non-NULL if we are doing the second or more
417          * hammer2 mounts from the same device.
418          */
419         lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
420         TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
421                 if (hmp->devvp == devvp)
422                         break;
423         }
424
425         /*
426          * Open the device if this isn't a secondary mount and construct
427          * the H2 device mount (hmp).
428          */
429         if (hmp == NULL) {
430                 if (error == 0 && vcount(devvp) > 0)
431                         error = EBUSY;
432
433                 /*
434                  * Now open the device
435                  */
436                 if (error == 0) {
437                         ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
438                         vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
439                         error = vinvalbuf(devvp, V_SAVE, 0, 0);
440                         if (error == 0) {
441                                 error = VOP_OPEN(devvp,
442                                                  ronly ? FREAD : FREAD | FWRITE,
443                                                  FSCRED, NULL);
444                         }
445                         vn_unlock(devvp);
446                 }
447                 if (error && devvp) {
448                         vrele(devvp);
449                         devvp = NULL;
450                 }
451                 if (error) {
452                         lockmgr(&hammer2_mntlk, LK_RELEASE);
453                         return error;
454                 }
455                 hmp = kmalloc(sizeof(*hmp), M_HAMMER2, M_WAITOK | M_ZERO);
456                 hmp->ronly = ronly;
457                 hmp->devvp = devvp;
458                 kmalloc_create(&hmp->mchain, "HAMMER2-chains");
459                 TAILQ_INSERT_TAIL(&hammer2_mntlist, hmp, mntentry);
460
461                 lockinit(&hmp->alloclk, "h2alloc", 0, 0);
462                 lockinit(&hmp->voldatalk, "voldata", 0, LK_CANRECURSE);
463                 TAILQ_INIT(&hmp->transq);
464
465                 /*
466                  * vchain setup. vchain.data is embedded.
467                  * vchain.refs is initialized and will never drop to 0.
468                  */
469                 hmp->vchain.hmp = hmp;
470                 hmp->vchain.refs = 1;
471                 hmp->vchain.data = (void *)&hmp->voldata;
472                 hmp->vchain.bref.type = HAMMER2_BREF_TYPE_VOLUME;
473                 hmp->vchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
474                 hmp->vchain.delete_tid = HAMMER2_MAX_TID;
475                 hammer2_chain_core_alloc(&hmp->vchain, NULL);
476                 /* hmp->vchain.u.xxx is left NULL */
477
478                 /*
479                  * fchain setup.  fchain.data is embedded.
480                  * fchain.refs is initialized and will never drop to 0.
481                  *
482                  * The data is not used but needs to be initialized to
483                  * pass assertion muster.  We use this chain primarily
484                  * as a placeholder for the freemap's top-level RBTREE
485                  * so it does not interfere with the volume's topology
486                  * RBTREE.
487                  */
488                 hmp->fchain.hmp = hmp;
489                 hmp->fchain.refs = 1;
490                 hmp->fchain.data = (void *)&hmp->voldata.freemap_blockset;
491                 hmp->fchain.bref.type = HAMMER2_BREF_TYPE_FREEMAP;
492                 hmp->fchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
493                 hmp->fchain.bref.methods =
494                         HAMMER2_ENC_CHECK(HAMMER2_CHECK_FREEMAP) |
495                         HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
496                 hmp->fchain.delete_tid = HAMMER2_MAX_TID;
497
498                 hammer2_chain_core_alloc(&hmp->fchain, NULL);
499                 /* hmp->fchain.u.xxx is left NULL */
500
501                 /*
502                  * Install the volume header
503                  */
504                 error = hammer2_install_volume_header(hmp);
505                 if (error) {
506                         hammer2_vfs_unmount(mp, MNT_FORCE);
507                         return error;
508                 }
509
510                 /*
511                  * First locate the super-root inode, which is key 0
512                  * relative to the volume header's blockset.
513                  *
514                  * Then locate the root inode by scanning the directory keyspace
515                  * represented by the label.
516                  */
517                 parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
518                 schain = hammer2_chain_lookup(&parent,
519                                       HAMMER2_SROOT_KEY, HAMMER2_SROOT_KEY, 0);
520                 hammer2_chain_lookup_done(parent);
521                 if (schain == NULL) {
522                         kprintf("hammer2_mount: invalid super-root\n");
523                         hammer2_vfs_unmount(mp, MNT_FORCE);
524                         return EINVAL;
525                 }
526                 hammer2_chain_ref(schain);      /* for hmp->schain */
527                 hmp->schain = schain;           /* left locked for inode_get */
528                 hmp->sroot = hammer2_inode_get(NULL, NULL, schain);
529                 hammer2_inode_ref(hmp->sroot);  /* for hmp->sroot */
530                 hammer2_inode_unlock_ex(hmp->sroot, schain);
531                 schain = NULL;
532                 
533                 mtx_init(&hmp->wthread_mtx);
534                 bioq_init(&hmp->wthread_bioq);
535                 hmp->wthread_destroy = 0;
536         
537                 /*
538                  * Launch threads.
539                  */
540                 lwkt_create(hammer2_write_thread, hmp,
541                                 NULL, NULL, 0, -1, "hammer2-write");
542         }
543
544         /*
545          * Block device opened successfully, finish initializing the
546          * mount structure.
547          *
548          * From this point on we have to call hammer2_unmount() on failure.
549          */
550         pmp = kmalloc(sizeof(*pmp), M_HAMMER2, M_WAITOK | M_ZERO);
551         pmp->mount_cluster = kmalloc(sizeof(hammer2_cluster_t), M_HAMMER2,
552                                      M_WAITOK | M_ZERO);
553         pmp->cluster = pmp->mount_cluster;
554
555         kmalloc_create(&pmp->minode, "HAMMER2-inodes");
556         kmalloc_create(&pmp->mmsg, "HAMMER2-pfsmsg");
557
558         pmp->mount_cluster->hmp = hmp;
559         spin_init(&pmp->inum_spin);
560         RB_INIT(&pmp->inum_tree);
561
562         kdmsg_iocom_init(&pmp->iocom, pmp,
563                          KDMSG_IOCOMF_AUTOCONN |
564                          KDMSG_IOCOMF_AUTOSPAN |
565                          KDMSG_IOCOMF_AUTOCIRC,
566                          pmp->mmsg, hammer2_rcvdmsg);
567
568         ccms_domain_init(&pmp->ccms_dom);
569         ++hmp->pmp_count;
570         lockmgr(&hammer2_mntlk, LK_RELEASE);
571         kprintf("hammer2_mount hmp=%p pmp=%p pmpcnt=%d\n", hmp, pmp, hmp->pmp_count);
572
573         mp->mnt_flag = MNT_LOCAL;
574         mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;   /* all entry pts are SMP */
575
576         /*
577          * required mount structure initializations
578          */
579         mp->mnt_stat.f_iosize = HAMMER2_PBUFSIZE;
580         mp->mnt_stat.f_bsize = HAMMER2_PBUFSIZE;
581
582         mp->mnt_vstat.f_frsize = HAMMER2_PBUFSIZE;
583         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
584
585         /*
586          * Optional fields
587          */
588         mp->mnt_iosize_max = MAXPHYS;
589         mp->mnt_data = (qaddr_t)pmp;
590         pmp->mp = mp;
591
592         /*
593          * schain only has 1 ref now for its hmp->schain assignment.
594          * Setup for lookup (which will lock it).
595          */
596         parent = hammer2_chain_lookup_init(hmp->schain, 0);
597         lhc = hammer2_dirhash(label, strlen(label));
598         rchain = hammer2_chain_lookup(&parent,
599                                       lhc, lhc + HAMMER2_DIRHASH_LOMASK,
600                                       0);
601         while (rchain) {
602                 if (rchain->bref.type == HAMMER2_BREF_TYPE_INODE &&
603                     strcmp(label, rchain->data->ipdata.filename) == 0) {
604                         break;
605                 }
606                 rchain = hammer2_chain_next(&parent, rchain,
607                                             lhc, lhc + HAMMER2_DIRHASH_LOMASK,
608                                             0);
609         }
610         hammer2_chain_lookup_done(parent);
611         if (rchain == NULL) {
612                 kprintf("hammer2_mount: PFS label not found\n");
613                 hammer2_vfs_unmount(mp, MNT_FORCE);
614                 return EINVAL;
615         }
616         if (rchain->flags & HAMMER2_CHAIN_MOUNTED) {
617                 hammer2_chain_unlock(rchain);
618                 kprintf("hammer2_mount: PFS label already mounted!\n");
619                 hammer2_vfs_unmount(mp, MNT_FORCE);
620                 return EBUSY;
621         }
622         if (rchain->flags & HAMMER2_CHAIN_RECYCLE) {
623                 kprintf("hammer2_mount: PFS label currently recycling\n");
624                 hammer2_vfs_unmount(mp, MNT_FORCE);
625                 return EBUSY;
626         }
627
628         atomic_set_int(&rchain->flags, HAMMER2_CHAIN_MOUNTED);
629
630         /*
631          * NOTE: *_get() integrates chain's lock into the inode lock.
632          */
633         hammer2_chain_ref(rchain);              /* for pmp->rchain */
634         pmp->mount_cluster->rchain = rchain;    /* left held & unlocked */
635         pmp->iroot = hammer2_inode_get(pmp, NULL, rchain);
636         hammer2_inode_ref(pmp->iroot);          /* ref for pmp->iroot */
637
638         KKASSERT(rchain->pmp == NULL);          /* bootstrap the tracking pmp for rchain */
639         rchain->pmp = pmp;
640         atomic_add_long(&pmp->inmem_chains, 1);
641
642         hammer2_inode_unlock_ex(pmp->iroot, rchain);
643
644         kprintf("iroot %p\n", pmp->iroot);
645
646         /*
647          * Ref the cluster management messaging descriptor.  The mount
648          * program deals with the other end of the communications pipe.
649          */
650         fp = holdfp(curproc->p_fd, info.cluster_fd, -1);
651         if (fp == NULL) {
652                 kprintf("hammer2_mount: bad cluster_fd!\n");
653                 hammer2_vfs_unmount(mp, MNT_FORCE);
654                 return EBADF;
655         }
656         hammer2_cluster_reconnect(pmp, fp);
657
658         /*
659          * Finish setup
660          */
661         vfs_getnewfsid(mp);
662         vfs_add_vnodeops(mp, &hammer2_vnode_vops, &mp->mnt_vn_norm_ops);
663         vfs_add_vnodeops(mp, &hammer2_spec_vops, &mp->mnt_vn_spec_ops);
664         vfs_add_vnodeops(mp, &hammer2_fifo_vops, &mp->mnt_vn_fifo_ops);
665
666         copyinstr(info.volume, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, &size);
667         bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
668         bzero(mp->mnt_stat.f_mntonname, sizeof(mp->mnt_stat.f_mntonname));
669         copyinstr(path, mp->mnt_stat.f_mntonname,
670                   sizeof(mp->mnt_stat.f_mntonname) - 1,
671                   &size);
672
673         /*
674          * Initial statfs to prime mnt_stat.
675          */
676         hammer2_vfs_statfs(mp, &mp->mnt_stat, cred);
677         
678         return 0;
679 }
680
681 /*
682  * Handle bioq for strategy write
683  */
684 static
685 void
686 hammer2_write_thread(void *arg)
687 {
688         hammer2_mount_t* hmp;
689         struct bio *bio;
690         struct buf *bp;
691         hammer2_trans_t trans;
692         struct vnode *vp;
693         hammer2_inode_t *last_ip;
694         hammer2_inode_t *ip;
695         hammer2_chain_t *parent;
696         hammer2_chain_t **parentp; //to comply with the current functions...
697         hammer2_inode_data_t *ipdata;
698         hammer2_key_t lbase;
699         int lblksize;
700         int pblksize;
701         int error;
702         
703         hmp = arg;
704         
705         mtx_lock(&hmp->wthread_mtx);
706         while (hmp->wthread_destroy == 0) {
707                 if (bioq_first(&hmp->wthread_bioq) == NULL) {
708                         mtxsleep(&hmp->wthread_bioq, &hmp->wthread_mtx,
709                                  0, "h2bioqw", 0);
710                 }
711                 last_ip = NULL;
712                 parent = NULL;
713                 parentp = &parent;
714
715                 while ((bio = bioq_takefirst(&hmp->wthread_bioq)) != NULL) {
716                         mtx_unlock(&hmp->wthread_mtx);
717                         
718                         error = 0;
719                         bp = bio->bio_buf;
720                         vp = bp->b_vp;
721                         ip = VTOI(vp);
722
723                         /*
724                          * Cache transaction for multi-buffer flush efficiency.
725                          * Lock the ip separately for each buffer to allow
726                          * interleaving with frontend writes.
727                          */
728                         if (last_ip != ip) {
729                                 if (last_ip)
730                                         hammer2_trans_done(&trans);
731                                 hammer2_trans_init(&trans, ip->pmp,
732                                                    HAMMER2_TRANS_BUFCACHE);
733                                 last_ip = ip;
734                         }
735                         parent = hammer2_inode_lock_ex(ip);
736
737                         /*
738                          * Inode is modified, flush size and mtime changes
739                          * to ensure that the file size remains consistent
740                          * with the buffers being flushed.
741                          */
742                         if (ip->flags & (HAMMER2_INODE_RESIZED |
743                                          HAMMER2_INODE_MTIME)) {
744                                 hammer2_inode_fsync(&trans, ip, parentp);
745                         }
746                         ipdata = hammer2_chain_modify_ip(&trans, ip,
747                                                          parentp, 0);
748                         lblksize = hammer2_calc_logical(ip, bio->bio_offset,
749                                                         &lbase, NULL);
750                         pblksize = hammer2_calc_physical(ip, lbase);
751                         hammer2_write_file_core_t(bp, &trans, ip, ipdata,
752                                                 parentp,
753                                                 lbase, IO_ASYNC,
754                                                 pblksize, &error);
755                         hammer2_inode_unlock_ex(ip, parent);
756                         if (error) {
757                                 kprintf("An error occured in writing thread.\n");
758                                 break;
759                         }
760                         biodone(bio);
761                         mtx_lock(&hmp->wthread_mtx);
762                 }
763
764                 /*
765                  * Clean out transaction cache
766                  */
767                 if (last_ip)
768                         hammer2_trans_done(&trans);
769         }
770         hmp->wthread_destroy = -1;
771         wakeup(&hmp->wthread_destroy);
772         
773         mtx_unlock(&hmp->wthread_mtx);
774 }
775
776 /* 
777  * From hammer2_vnops.c. 
778  * Physical block assignement function.
779  */
780 static
781 hammer2_chain_t *
782 hammer2_assign_physical(hammer2_trans_t *trans,
783                         hammer2_inode_t *ip, hammer2_chain_t **parentp,
784                         hammer2_key_t lbase, int pblksize, int *errorp)
785 {
786         hammer2_chain_t *parent;
787         hammer2_chain_t *chain;
788         hammer2_off_t pbase;
789         int pradix = hammer2_getradix(pblksize);
790
791         /*
792          * Locate the chain associated with lbase, return a locked chain.
793          * However, do not instantiate any data reference (which utilizes a
794          * device buffer) because we will be using direct IO via the
795          * logical buffer cache buffer.
796          */
797         *errorp = 0;
798 retry:
799         parent = *parentp;
800         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS); /* extra lock */
801         chain = hammer2_chain_lookup(&parent,
802                                      lbase, lbase,
803                                      HAMMER2_LOOKUP_NODATA);
804
805         if (chain == NULL) {
806                 /*
807                  * We found a hole, create a new chain entry.
808                  *
809                  * NOTE: DATA chains are created without device backing
810                  *       store (nor do we want any).
811                  */
812                 *errorp = hammer2_chain_create(trans, &parent, &chain,
813                                                lbase, HAMMER2_PBUFRADIX,
814                                                HAMMER2_BREF_TYPE_DATA,
815                                                pblksize);
816                 if (chain == NULL) {
817                         hammer2_chain_lookup_done(parent);
818                         panic("hammer2_chain_create: par=%p error=%d\n",
819                                 parent, *errorp);
820                         goto retry;
821                 }
822
823                 pbase = chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX;
824                 /*ip->delta_dcount += pblksize;*/
825         } else {
826                 switch (chain->bref.type) {
827                 case HAMMER2_BREF_TYPE_INODE:
828                         /*
829                          * The data is embedded in the inode.  The
830                          * caller is responsible for marking the inode
831                          * modified and copying the data to the embedded
832                          * area.
833                          */
834                         pbase = NOOFFSET;
835                         break;
836                 case HAMMER2_BREF_TYPE_DATA:
837                         if (chain->bytes != pblksize) {
838                                 hammer2_chain_resize(trans, ip,
839                                                      parent, &chain,
840                                                      pradix,
841                                                      HAMMER2_MODIFY_OPTDATA);
842                         }
843                         hammer2_chain_modify(trans, &chain,
844                                              HAMMER2_MODIFY_OPTDATA);
845                         pbase = chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX;
846                         break;
847                 default:
848                         panic("hammer2_assign_physical: bad type");
849                         /* NOT REACHED */
850                         pbase = NOOFFSET;
851                         break;
852                 }
853         }
854
855         /*
856          * Cleanup.  If chain wound up being the inode (i.e. DIRECTDATA),
857          * we might have to replace *parentp.
858          */
859         hammer2_chain_lookup_done(parent);
860         if (chain) {
861                 if (*parentp != chain &&
862                     (*parentp)->core == chain->core) {
863                         parent = *parentp;
864                         *parentp = chain;               /* eats lock */
865                         hammer2_chain_unlock(parent);
866                         hammer2_chain_lock(chain, 0);   /* need another */
867                 }
868                 /* else chain already locked for return */
869         }
870         return (chain);
871 }
872
873 /* 
874  * From hammer2_vnops.c.
875  * The core write function which determines which path to take
876  * depending on compression settings.
877  */
878 static
879 void
880 hammer2_write_file_core_t(struct buf *bp, hammer2_trans_t *trans,
881                         hammer2_inode_t *ip, hammer2_inode_data_t *ipdata,
882                         hammer2_chain_t **parentp,
883                         hammer2_key_t lbase, int ioflag, int pblksize,
884                         int *errorp)
885 {
886         hammer2_chain_t *chain;
887         if (ipdata->comp_algo > HAMMER2_COMP_AUTOZERO) {
888                 hammer2_compress_and_write_t(bp, trans, ip,
889                                            ipdata, parentp,
890                                            lbase, ioflag,
891                                            pblksize, errorp, ipdata->comp_algo);
892         } else if (ipdata->comp_algo == HAMMER2_COMP_AUTOZERO) {
893                 hammer2_zero_check_and_write_t(bp, trans, ip,
894                                     ipdata, parentp, lbase,
895                                     ioflag, pblksize, errorp);
896         } else {
897                 /*
898                  * We have to assign physical storage to the buffer
899                  * we intend to dirty or write now to avoid deadlocks
900                  * in the strategy code later.
901                  *
902                  * This can return NOOFFSET for inode-embedded data.
903                  * The strategy code will take care of it in that case.
904                  */
905                 chain = hammer2_assign_physical(trans, ip, parentp,
906                                                 lbase, pblksize,
907                                                 errorp);
908                 hammer2_write_bp_t(chain, bp, ioflag, pblksize);
909                 if (chain)
910                         hammer2_chain_unlock(chain);
911         }
912         ipdata = &ip->chain->data->ipdata;      /* reload */
913 }
914
915 /*
916  * From hammer2_vnops.c
917  * Generic function that will perform the compression in compression
918  * write path. The compression algorithm is determined by the settings
919  * obtained from inode.
920  */
921 static
922 void
923 hammer2_compress_and_write_t(struct buf *bp, hammer2_trans_t *trans,
924         hammer2_inode_t *ip, hammer2_inode_data_t *ipdata,
925         hammer2_chain_t **parentp,
926         hammer2_key_t lbase, int ioflag, int pblksize,
927         int *errorp, int comp_method)
928 {
929         hammer2_chain_t *chain;
930
931         if (test_block_not_zeros_t(bp->b_data, pblksize)) {
932                 int compressed_size = 0;
933                 int compressed_block_size;
934                 char *compressed_buffer = NULL; //to avoid a compiler warning
935
936                 KKASSERT(pblksize / 2 <= 32768);
937                 
938                 if (ipdata->reserved85 < 8 || (ipdata->reserved85 & 7) == 0) {
939                         if ((comp_method & 0x0F) == HAMMER2_COMP_LZ4) {
940                                 //kprintf("LZ4 compression activated.\n");
941                                 compressed_buffer = objcache_get(cache_buffer_write, M_INTWAIT);
942                                 compressed_size = LZ4_compress_limitedOutput(bp->b_data,
943                                     &compressed_buffer[sizeof(int)], pblksize,
944                                     pblksize / 2 - sizeof(int));
945                                 *(int *)compressed_buffer = compressed_size;
946                                 if (compressed_size)
947                                         compressed_size += sizeof(int); /* our added overhead */
948                                 //kprintf("Compressed size = %d.\n", compressed_size);
949                         } else if ((comp_method & 0x0F) == HAMMER2_COMP_ZLIB) {
950                                 int comp_level = (comp_method >> 4) & 0x0F;
951                                 z_stream strm_compress;
952                                 int ret;
953                             //kprintf("ZLIB compression activated, level %d.\n", comp_level);
954
955                                 ret = deflateInit(&strm_compress, comp_level);
956                                 if (ret != Z_OK)
957                                         kprintf("HAMMER2 ZLIB: fatal error on deflateInit.\n");
958                                 
959                                 compressed_buffer = objcache_get(cache_buffer_write, M_INTWAIT);
960                                 strm_compress.next_in = bp->b_data;
961                                 strm_compress.avail_in = pblksize;
962                                 strm_compress.next_out = compressed_buffer;
963                                 strm_compress.avail_out = pblksize / 2;
964                                 ret = deflate(&strm_compress, Z_FINISH);
965                                 if (ret == Z_STREAM_END) {
966                                         compressed_size = pblksize / 2 - strm_compress.avail_out;
967                                 } else {
968                                         compressed_size = 0;
969                                 }
970                                 ret = deflateEnd(&strm_compress);
971                                 //kprintf("Compressed size = %d.\n", compressed_size);
972                         }
973                         else {
974                                 kprintf("Error: Unknown compression method.\n");
975                                 kprintf("Comp_method = %d.\n", comp_method);
976                                 //And the block will be written uncompressed...
977                         }
978                 }
979                 if (compressed_size == 0) { //compression failed or turned off
980                         compressed_block_size = pblksize;       /* safety */
981                         ++(ipdata->reserved85);
982                         if (ipdata->reserved85 == 255) { //protection against overflows
983                                 ipdata->reserved85 = 8;
984                         }
985                 } else {
986                         ipdata->reserved85 = 0;
987                         if (compressed_size <= 1024) {
988                                 compressed_block_size = 1024;
989                         } else if (compressed_size <= 2048) {
990                                 compressed_block_size = 2048;
991                         } else if (compressed_size <= 4096) {
992                                 compressed_block_size = 4096;
993                         } else if (compressed_size <= 8192) {
994                                 compressed_block_size = 8192;
995                         } else if (compressed_size <= 16384) {
996                                 compressed_block_size = 16384;
997                         } else if (compressed_size <= 32768) {
998                                 compressed_block_size = 32768;
999                         } else {
1000                                 panic("WRITE PATH: Weird compressed_size value.\n");
1001                                 compressed_block_size = pblksize;       /* NOT REACHED */
1002                         }
1003                 }
1004
1005                 chain = hammer2_assign_physical(trans, ip, parentp,
1006                                                 lbase, compressed_block_size,
1007                                                 errorp);
1008                 ipdata = &ip->chain->data->ipdata;      /* RELOAD */
1009                         
1010                 if (*errorp) {
1011                         kprintf("WRITE PATH: An error occurred while "
1012                                 "assigning physical space.\n");
1013                         KKASSERT(chain == NULL);
1014                 } else {
1015                         /* Get device offset */
1016                         hammer2_off_t pbase;
1017                         hammer2_off_t pmask;
1018                         hammer2_off_t peof;
1019                         size_t boff;
1020                         size_t psize;
1021                         struct buf *dbp;
1022                         
1023                         KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1024                         
1025                         switch(chain->bref.type) {
1026                         case HAMMER2_BREF_TYPE_INODE:
1027                                 KKASSERT(chain->data->ipdata.op_flags &
1028                                         HAMMER2_OPFLAG_DIRECTDATA);
1029                                 KKASSERT(bp->b_loffset == 0);
1030                                 bcopy(bp->b_data, chain->data->ipdata.u.data,
1031                                         HAMMER2_EMBEDDED_BYTES);
1032                                 break;
1033                         case HAMMER2_BREF_TYPE_DATA:                            
1034                                 psize = hammer2_devblksize(chain->bytes);
1035                                 pmask = (hammer2_off_t)psize - 1;
1036                                 pbase = chain->bref.data_off & ~pmask;
1037                                 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1038                                 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1039                                 int temp_check = HAMMER2_DEC_CHECK(chain->bref.methods);
1040
1041                                 /*
1042                                  * Optimize out the read-before-write if possible.
1043                                  */
1044                                 if (compressed_block_size == psize) {
1045                                         dbp = getblk(chain->hmp->devvp, pbase, psize, 0, 0);
1046                                 } else {
1047                                         *errorp = bread(chain->hmp->devvp, pbase, psize, &dbp);
1048                                         if (*errorp) {
1049                                                 kprintf("WRITE PATH: An error ocurred while bread().\n");
1050                                                 break;
1051                                         }
1052                                 }
1053
1054                                 /*
1055                                  * When loading the block make sure we don't leave garbage
1056                                  * after the compressed data.
1057                                  */
1058                                 if (compressed_size) {
1059                                         chain->bref.methods = HAMMER2_ENC_COMP(comp_method) +
1060                                                               HAMMER2_ENC_CHECK(temp_check);
1061                                         bcopy(compressed_buffer, dbp->b_data + boff,
1062                                               compressed_size);
1063                                         if (compressed_size != compressed_block_size) {
1064                                                 bzero(dbp->b_data + boff + compressed_size,
1065                                                       compressed_block_size - compressed_size);
1066                                         }
1067                                 } else {
1068                                         chain->bref.methods = HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
1069                                                               HAMMER2_ENC_CHECK(temp_check);
1070                                         bcopy(bp->b_data, dbp->b_data + boff, pblksize);
1071                                 }
1072
1073                                 /*
1074                                  * Device buffer is now valid, chain is no
1075                                  * longer in the initial state.
1076                                  */
1077                                 atomic_clear_int(&chain->flags,
1078                                                  HAMMER2_CHAIN_INITIAL);
1079
1080                                 /* Now write the related bdp. */
1081                                 if (ioflag & IO_SYNC) {
1082                                         /*
1083                                          * Synchronous I/O requested.
1084                                          */
1085                                         bwrite(dbp);
1086                                 /*
1087                                 } else if ((ioflag & IO_DIRECT) && loff + n == pblksize) {
1088                                         bdwrite(dbp);
1089                                 */
1090                                 } else if (ioflag & IO_ASYNC) {
1091                                         bawrite(dbp);
1092                                 } else if (hammer2_cluster_enable) {
1093                                         cluster_write(dbp, peof, HAMMER2_PBUFSIZE, 4/*XXX*/);
1094                                 } else {
1095                                         bdwrite(dbp);
1096                                 }
1097                                 break;
1098                         default:
1099                                 panic("hammer2_write_bp_t: bad chain type %d\n",
1100                                         chain->bref.type);
1101                         /* NOT REACHED */
1102                                 break;
1103                         }
1104                         
1105                         hammer2_chain_unlock(chain);
1106                 }
1107                 if (compressed_buffer)
1108                         objcache_put(cache_buffer_write, compressed_buffer);
1109         } else {
1110                 zero_write_t(bp, trans, ip, ipdata, parentp, lbase);
1111         }
1112 }
1113
1114 /*
1115  * Function that performs zero-checking and writing without compression,
1116  * it corresponds to default zero-checking path.
1117  */
1118 static
1119 void
1120 hammer2_zero_check_and_write_t(struct buf *bp, hammer2_trans_t *trans,
1121         hammer2_inode_t *ip, hammer2_inode_data_t *ipdata,
1122         hammer2_chain_t **parentp,
1123         hammer2_key_t lbase, int ioflag, int pblksize, int *errorp)
1124 {
1125         hammer2_chain_t *chain;
1126
1127         if (test_block_not_zeros_t(bp->b_data, pblksize)) {
1128                 chain = hammer2_assign_physical(trans, ip, parentp,
1129                                                 lbase, pblksize, errorp);
1130                 hammer2_write_bp_t(chain, bp, ioflag, pblksize);
1131                 if (chain)
1132                         hammer2_chain_unlock(chain);
1133         } else {
1134                 zero_write_t(bp, trans, ip, ipdata, parentp, lbase);
1135         }
1136 }
1137
1138 /*
1139  * A function to test whether a block of data contains only zeros,
1140  * returns 0 in that case or returns 1 otherwise.
1141  */
1142 static
1143 int
1144 test_block_not_zeros_t(char *buf, size_t bytes)
1145 {
1146         size_t i;
1147
1148         for (i = 0; i < bytes; i += sizeof(long)) {
1149                 if (*(long *)(buf + i) != 0)
1150                         return (1);
1151         }
1152         return (0);
1153 }
1154
1155 /*
1156  * Function to "write" a block that contains only zeros.
1157  */
1158 static
1159 void
1160 zero_write_t(struct buf *bp, hammer2_trans_t *trans, hammer2_inode_t *ip,
1161         hammer2_inode_data_t *ipdata, hammer2_chain_t **parentp,
1162         hammer2_key_t lbase)
1163 {
1164         hammer2_chain_t *parent;
1165         hammer2_chain_t *chain;
1166
1167         parent = hammer2_chain_lookup_init(*parentp, 0);
1168
1169         chain = hammer2_chain_lookup(&parent, lbase, lbase,
1170                                      HAMMER2_LOOKUP_NODATA);
1171         if (chain) {
1172                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1173                         bzero(chain->data->ipdata.u.data,
1174                               HAMMER2_EMBEDDED_BYTES);
1175                 } else {
1176                         hammer2_chain_delete(trans, chain, 0);
1177                 }
1178                 hammer2_chain_unlock(chain);
1179         }
1180         hammer2_chain_lookup_done(parent);
1181 }
1182
1183 /*
1184  * Function to write the data as it is, without performing any sort of
1185  * compression. This function is used in path without compression and
1186  * default zero-checking path.
1187  */
1188 static
1189 void
1190 hammer2_write_bp_t(hammer2_chain_t *chain, struct buf *bp, int ioflag,
1191                                 int pblksize)
1192 {
1193         hammer2_off_t pbase;
1194         hammer2_off_t pmask;
1195         hammer2_off_t peof;
1196         struct buf *dbp;
1197         size_t boff;
1198         size_t psize;
1199         int error;
1200         int temp_check = HAMMER2_DEC_CHECK(chain->bref.methods);
1201
1202         KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1203
1204         switch(chain->bref.type) {
1205         case HAMMER2_BREF_TYPE_INODE:
1206                 KKASSERT(chain->data->ipdata.op_flags &
1207                          HAMMER2_OPFLAG_DIRECTDATA);
1208                 KKASSERT(bp->b_loffset == 0);
1209                 bcopy(bp->b_data, chain->data->ipdata.u.data,
1210                       HAMMER2_EMBEDDED_BYTES);
1211                 break;
1212         case HAMMER2_BREF_TYPE_DATA:
1213                 psize = hammer2_devblksize(chain->bytes);
1214                 pmask = (hammer2_off_t)psize - 1;
1215                 pbase = chain->bref.data_off & ~pmask;
1216                 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1217                 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1218
1219                 if (psize == pblksize) {
1220                         dbp = getblk(chain->hmp->devvp, pbase,
1221                                 psize, 0, 0);
1222                 } else {
1223                         error = bread(chain->hmp->devvp, pbase, psize, &dbp);
1224                         if (error) {
1225                                 kprintf("WRITE PATH: An error ocurred while bread().\n");
1226                                 break;
1227                         }
1228                 }
1229
1230                 chain->bref.methods = HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
1231                                       HAMMER2_ENC_CHECK(temp_check);
1232                 bcopy(bp->b_data, dbp->b_data + boff, chain->bytes);
1233                 
1234                 /*
1235                  * Device buffer is now valid, chain is no
1236                  * longer in the initial state.
1237              */
1238                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1239
1240                 if (ioflag & IO_SYNC) {
1241                         /*
1242                          * Synchronous I/O requested.
1243                          */
1244                         bwrite(dbp);
1245                 /*
1246                 } else if ((ioflag & IO_DIRECT) && loff + n == pblksize) {
1247                         bdwrite(dbp);
1248                 */
1249                 } else if (ioflag & IO_ASYNC) {
1250                         bawrite(dbp);
1251                 } else if (hammer2_cluster_enable) {
1252                         cluster_write(dbp, peof, HAMMER2_PBUFSIZE, 4/*XXX*/);
1253                 } else {
1254                         bdwrite(dbp);
1255                 }
1256                 break;
1257         default:
1258                 panic("hammer2_write_bp_t: bad chain type %d\n",
1259                       chain->bref.type);
1260                 /* NOT REACHED */
1261                 break;
1262         }
1263 }
1264
1265 static
1266 int
1267 hammer2_remount(struct mount *mp, char *path, struct vnode *devvp,
1268                 struct ucred *cred)
1269 {
1270         return (0);
1271 }
1272
1273 static
1274 int
1275 hammer2_vfs_unmount(struct mount *mp, int mntflags)
1276 {
1277         hammer2_pfsmount_t *pmp;
1278         hammer2_mount_t *hmp;
1279         hammer2_cluster_t *cluster;
1280         int flags;
1281         int error = 0;
1282         int ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
1283         int dumpcnt;
1284         struct vnode *devvp;
1285
1286         pmp = MPTOPMP(mp);
1287         cluster = pmp->mount_cluster;
1288         hmp = cluster->hmp;
1289         flags = 0;
1290
1291         if (mntflags & MNT_FORCE)
1292                 flags |= FORCECLOSE;
1293
1294         hammer2_mount_exlock(hmp);
1295
1296         /*
1297          * If mount initialization proceeded far enough we must flush
1298          * its vnodes.
1299          */
1300         if (pmp->iroot)
1301                 error = vflush(mp, 0, flags);
1302
1303         if (error) {
1304                 hammer2_mount_unlock(hmp);
1305                 return error;
1306         }
1307
1308         lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1309         --hmp->pmp_count;
1310         kprintf("hammer2_unmount hmp=%p pmpcnt=%d\n", hmp, hmp->pmp_count);
1311
1312         /*
1313          * Flush any left over chains.  The voldata lock is only used
1314          * to synchronize against HAMMER2_CHAIN_MODIFIED_AUX.
1315          */
1316         hammer2_voldata_lock(hmp);
1317         if ((hmp->vchain.flags | hmp->fchain.flags) &
1318             (HAMMER2_CHAIN_MODIFIED | HAMMER2_CHAIN_SUBMODIFIED)) {
1319                 hammer2_voldata_unlock(hmp, 0);
1320                 hammer2_vfs_sync(mp, MNT_WAIT);
1321                 hammer2_vfs_sync(mp, MNT_WAIT);
1322         } else {
1323                 hammer2_voldata_unlock(hmp, 0);
1324         }
1325         if (hmp->pmp_count == 0) {
1326                 if (hmp->vchain.flags & (HAMMER2_CHAIN_MODIFIED |
1327                                          HAMMER2_CHAIN_SUBMODIFIED)) {
1328                         kprintf("hammer2_unmount: chains left over after "
1329                                 "final sync\n");
1330                         if (hammer2_debug & 0x0010)
1331                                 Debugger("entered debugger");
1332                 }
1333         }
1334
1335         /*
1336          * Cleanup the root and super-root chain elements (which should be
1337          * clean).
1338          */
1339         if (pmp->iroot) {
1340 #if REPORT_REFS_ERRORS
1341                 if (pmp->iroot->refs != 1)
1342                         kprintf("PMP->IROOT %p REFS WRONG %d\n",
1343                                 pmp->iroot, pmp->iroot->refs);
1344 #else
1345                 KKASSERT(pmp->iroot->refs == 1);
1346 #endif
1347                 hammer2_inode_drop(pmp->iroot);     /* ref for pmp->iroot */
1348                 pmp->iroot = NULL;
1349         }
1350         if (cluster->rchain) {
1351                 atomic_clear_int(&cluster->rchain->flags,
1352                                  HAMMER2_CHAIN_MOUNTED);
1353 #if REPORT_REFS_ERRORS
1354                 if (cluster->rchain->refs != 1)
1355                         kprintf("PMP->RCHAIN %p REFS WRONG %d\n",
1356                                 cluster->rchain, cluster->rchain->refs);
1357 #else
1358                 KKASSERT(cluster->rchain->refs == 1);
1359 #endif
1360                 hammer2_chain_drop(cluster->rchain);
1361                 cluster->rchain = NULL;
1362         }
1363         ccms_domain_uninit(&pmp->ccms_dom);
1364
1365         /*
1366          * Kill cluster controller
1367          */
1368         kdmsg_iocom_uninit(&pmp->iocom);
1369
1370         /*
1371          * If no PFS's left drop the master hammer2_mount for the device.
1372          */
1373         if (hmp->pmp_count == 0) {
1374                 if (hmp->sroot) {
1375                         hammer2_inode_drop(hmp->sroot);
1376                         hmp->sroot = NULL;
1377                 }
1378                 if (hmp->schain) {
1379 #if REPORT_REFS_ERRORS
1380                         if (hmp->schain->refs != 1)
1381                                 kprintf("HMP->SCHAIN %p REFS WRONG %d\n",
1382                                         hmp->schain, hmp->schain->refs);
1383 #else
1384                         KKASSERT(hmp->schain->refs == 1);
1385 #endif
1386                         hammer2_chain_drop(hmp->schain);
1387                         hmp->schain = NULL;
1388                 }
1389
1390                 /*
1391                  * Finish up with the device vnode
1392                  */
1393                 if ((devvp = hmp->devvp) != NULL) {
1394                         vinvalbuf(devvp, (ronly ? 0 : V_SAVE), 0, 0);
1395                         hmp->devvp = NULL;
1396                         VOP_CLOSE(devvp, (ronly ? FREAD : FREAD|FWRITE));
1397                         vrele(devvp);
1398                         devvp = NULL;
1399                 }
1400
1401                 /*
1402                  * Final drop of embedded freemap root chain to clean up
1403                  * fchain.core (fchain structure is not flagged ALLOCATED
1404                  * so it is cleaned out and then left to rot).
1405                  */
1406                 hammer2_chain_drop(&hmp->fchain);
1407
1408                 /*
1409                  * Final drop of embedded volume root chain to clean up
1410                  * vchain.core (vchain structure is not flagged ALLOCATED
1411                  * so it is cleaned out and then left to rot).
1412                  */
1413                 dumpcnt = 50;
1414                 hammer2_dump_chain(&hmp->vchain, 0, &dumpcnt);
1415                 hammer2_mount_unlock(hmp);
1416                 hammer2_chain_drop(&hmp->vchain);
1417         } else {
1418                 hammer2_mount_unlock(hmp);
1419         }
1420
1421         pmp->mp = NULL;
1422         mp->mnt_data = NULL;
1423
1424         pmp->mount_cluster = NULL;
1425         pmp->cluster = NULL;            /* XXX */
1426
1427         kmalloc_destroy(&pmp->mmsg);
1428         kmalloc_destroy(&pmp->minode);
1429
1430         cluster->hmp = NULL;
1431
1432         kfree(cluster, M_HAMMER2);
1433         kfree(pmp, M_HAMMER2);
1434         if (hmp->pmp_count == 0) {
1435                 mtx_lock(&hmp->wthread_mtx);
1436                 hmp->wthread_destroy = 1;
1437                 wakeup(&hmp->wthread_bioq);
1438                 while (hmp->wthread_destroy != -1) {
1439                         mtxsleep(&hmp->wthread_destroy, &hmp->wthread_mtx, 0,
1440                                 "umount-sleep", 0);
1441                 }
1442                 mtx_unlock(&hmp->wthread_mtx);
1443                 
1444                 TAILQ_REMOVE(&hammer2_mntlist, hmp, mntentry);
1445                 kmalloc_destroy(&hmp->mchain);
1446                 kfree(hmp, M_HAMMER2);
1447         }
1448         lockmgr(&hammer2_mntlk, LK_RELEASE);
1449
1450         return (error);
1451 }
1452
1453 static
1454 int
1455 hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
1456              ino_t ino, struct vnode **vpp)
1457 {
1458         kprintf("hammer2_vget\n");
1459         return (EOPNOTSUPP);
1460 }
1461
1462 static
1463 int
1464 hammer2_vfs_root(struct mount *mp, struct vnode **vpp)
1465 {
1466         hammer2_pfsmount_t *pmp;
1467         hammer2_chain_t *parent;
1468         int error;
1469         struct vnode *vp;
1470
1471         pmp = MPTOPMP(mp);
1472         if (pmp->iroot == NULL) {
1473                 *vpp = NULL;
1474                 error = EINVAL;
1475         } else {
1476                 parent = hammer2_inode_lock_sh(pmp->iroot);
1477                 vp = hammer2_igetv(pmp->iroot, &error);
1478                 hammer2_inode_unlock_sh(pmp->iroot, parent);
1479                 *vpp = vp;
1480                 if (vp == NULL)
1481                         kprintf("vnodefail\n");
1482         }
1483
1484         return (error);
1485 }
1486
1487 /*
1488  * Filesystem status
1489  *
1490  * XXX incorporate ipdata->inode_quota and data_quota
1491  */
1492 static
1493 int
1494 hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred)
1495 {
1496         hammer2_pfsmount_t *pmp;
1497         hammer2_mount_t *hmp;
1498
1499         pmp = MPTOPMP(mp);
1500         hmp = MPTOHMP(mp);
1501
1502         mp->mnt_stat.f_files = pmp->inode_count;
1503         mp->mnt_stat.f_ffree = 0;
1504         mp->mnt_stat.f_blocks = hmp->voldata.allocator_size / HAMMER2_PBUFSIZE;
1505         mp->mnt_stat.f_bfree =  hmp->voldata.allocator_free / HAMMER2_PBUFSIZE;
1506         mp->mnt_stat.f_bavail = mp->mnt_stat.f_bfree;
1507
1508         *sbp = mp->mnt_stat;
1509         return (0);
1510 }
1511
1512 static
1513 int
1514 hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp, struct ucred *cred)
1515 {
1516         hammer2_pfsmount_t *pmp;
1517         hammer2_mount_t *hmp;
1518
1519         pmp = MPTOPMP(mp);
1520         hmp = MPTOHMP(mp);
1521
1522         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1523         mp->mnt_vstat.f_files = pmp->inode_count;
1524         mp->mnt_vstat.f_ffree = 0;
1525         mp->mnt_vstat.f_blocks = hmp->voldata.allocator_size / HAMMER2_PBUFSIZE;
1526         mp->mnt_vstat.f_bfree =  hmp->voldata.allocator_free / HAMMER2_PBUFSIZE;
1527         mp->mnt_vstat.f_bavail = mp->mnt_vstat.f_bfree;
1528
1529         *sbp = mp->mnt_vstat;
1530         return (0);
1531 }
1532
1533 /*
1534  * Sync the entire filesystem; this is called from the filesystem syncer
1535  * process periodically and whenever a user calls sync(1) on the hammer
1536  * mountpoint.
1537  *
1538  * Currently is actually called from the syncer! \o/
1539  *
1540  * This task will have to snapshot the state of the dirty inode chain.
1541  * From that, it will have to make sure all of the inodes on the dirty
1542  * chain have IO initiated. We make sure that io is initiated for the root
1543  * block.
1544  *
1545  * If waitfor is set, we wait for media to acknowledge the new rootblock.
1546  *
1547  * THINKS: side A vs side B, to have sync not stall all I/O?
1548  */
1549 static
1550 int
1551 hammer2_vfs_sync(struct mount *mp, int waitfor)
1552 {
1553         struct hammer2_sync_info info;
1554         hammer2_pfsmount_t *pmp;
1555         hammer2_cluster_t *cluster;
1556         hammer2_mount_t *hmp;
1557         int flags;
1558         int error;
1559         int i;
1560
1561         pmp = MPTOPMP(mp);
1562
1563         /*
1564          * We can't acquire locks on existing vnodes while in a transaction
1565          * without risking a deadlock.  This assumes that vfsync() can be
1566          * called without the vnode locked (which it can in DragonFly).
1567          * Otherwise we'd have to implement a multi-pass or flag the lock
1568          * failures and retry.
1569          */
1570         /*flags = VMSC_GETVP;*/
1571         flags = 0;
1572         if (waitfor & MNT_LAZY)
1573                 flags |= VMSC_ONEPASS;
1574
1575         hammer2_trans_init(&info.trans, pmp, HAMMER2_TRANS_ISFLUSH);
1576
1577         info.error = 0;
1578         info.waitfor = MNT_NOWAIT;
1579         vmntvnodescan(mp, flags | VMSC_NOWAIT,
1580                       hammer2_sync_scan1,
1581                       hammer2_sync_scan2, &info);
1582         if (info.error == 0 && (waitfor & MNT_WAIT)) {
1583                 info.waitfor = waitfor;
1584                     vmntvnodescan(mp, flags,
1585                                   hammer2_sync_scan1,
1586                                   hammer2_sync_scan2, &info);
1587
1588         }
1589 #if 0
1590         if (waitfor == MNT_WAIT) {
1591                 /* XXX */
1592         } else {
1593                 /* XXX */
1594         }
1595 #endif
1596
1597         cluster = pmp->cluster;
1598         hmp = cluster->hmp;
1599
1600         hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
1601         if (hmp->vchain.flags & (HAMMER2_CHAIN_MODIFIED |
1602                                   HAMMER2_CHAIN_SUBMODIFIED)) {
1603                 hammer2_chain_flush(&info.trans, &hmp->vchain);
1604         }
1605         hammer2_chain_unlock(&hmp->vchain);
1606
1607 #if 1
1608         /*
1609          * Rollup flush.  The fsyncs above basically just flushed
1610          * data blocks.  The flush below gets all the meta-data.
1611          */
1612         hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
1613         if (hmp->fchain.flags & (HAMMER2_CHAIN_MODIFIED |
1614                                  HAMMER2_CHAIN_SUBMODIFIED)) {
1615                 /* this will modify vchain as a side effect */
1616                 hammer2_chain_flush(&info.trans, &hmp->fchain);
1617         }
1618         hammer2_chain_unlock(&hmp->fchain);
1619 #endif
1620
1621
1622         error = 0;
1623
1624         /*
1625          * We can't safely flush the volume header until we have
1626          * flushed any device buffers which have built up.
1627          *
1628          * XXX this isn't being incremental
1629          */
1630         vn_lock(hmp->devvp, LK_EXCLUSIVE | LK_RETRY);
1631         error = VOP_FSYNC(hmp->devvp, MNT_WAIT, 0);
1632         vn_unlock(hmp->devvp);
1633
1634         /*
1635          * The flush code sets CHAIN_VOLUMESYNC to indicate that the
1636          * volume header needs synchronization via hmp->volsync.
1637          *
1638          * XXX synchronize the flag & data with only this flush XXX
1639          */
1640         if (error == 0 && (hmp->vchain.flags & HAMMER2_CHAIN_VOLUMESYNC)) {
1641                 struct buf *bp;
1642
1643                 /*
1644                  * Synchronize the disk before flushing the volume
1645                  * header.
1646                  */
1647                 bp = getpbuf(NULL);
1648                 bp->b_bio1.bio_offset = 0;
1649                 bp->b_bufsize = 0;
1650                 bp->b_bcount = 0;
1651                 bp->b_cmd = BUF_CMD_FLUSH;
1652                 bp->b_bio1.bio_done = biodone_sync;
1653                 bp->b_bio1.bio_flags |= BIO_SYNC;
1654                 vn_strategy(hmp->devvp, &bp->b_bio1);
1655                 biowait(&bp->b_bio1, "h2vol");
1656                 relpbuf(bp, NULL);
1657
1658                 /*
1659                  * Then we can safely flush the version of the volume header
1660                  * synchronized by the flush code.
1661                  */
1662                 i = hmp->volhdrno + 1;
1663                 if (i >= HAMMER2_NUM_VOLHDRS)
1664                         i = 0;
1665                 if (i * HAMMER2_ZONE_BYTES64 + HAMMER2_SEGSIZE >
1666                     hmp->volsync.volu_size) {
1667                         i = 0;
1668                 }
1669                 kprintf("sync volhdr %d %jd\n",
1670                         i, (intmax_t)hmp->volsync.volu_size);
1671                 bp = getblk(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
1672                             HAMMER2_PBUFSIZE, 0, 0);
1673                 atomic_clear_int(&hmp->vchain.flags, HAMMER2_CHAIN_VOLUMESYNC);
1674                 bcopy(&hmp->volsync, bp->b_data, HAMMER2_PBUFSIZE);
1675                 bawrite(bp);
1676                 hmp->volhdrno = i;
1677         }
1678         hammer2_trans_done(&info.trans);
1679         return (error);
1680 }
1681
1682 /*
1683  * Sync passes.
1684  *
1685  * NOTE: We don't test SUBMODIFIED or MOVED here because the fsync code
1686  *       won't flush on those flags.  The syncer code above will do a
1687  *       general meta-data flush globally that will catch these flags.
1688  */
1689 static int
1690 hammer2_sync_scan1(struct mount *mp, struct vnode *vp, void *data)
1691 {
1692         hammer2_inode_t *ip;
1693
1694         ip = VTOI(vp);
1695         if (vp->v_type == VNON || ip == NULL ||
1696             ((ip->flags & HAMMER2_INODE_MODIFIED) == 0 &&
1697              RB_EMPTY(&vp->v_rbdirty_tree))) {
1698                 return(-1);
1699         }
1700         return(0);
1701 }
1702
1703 static int
1704 hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data)
1705 {
1706         struct hammer2_sync_info *info = data;
1707         hammer2_inode_t *ip;
1708         hammer2_chain_t *parent;
1709         int error;
1710
1711         ip = VTOI(vp);
1712         if (vp->v_type == VNON || vp->v_type == VBAD ||
1713             ((ip->flags & HAMMER2_INODE_MODIFIED) == 0 &&
1714              RB_EMPTY(&vp->v_rbdirty_tree))) {
1715                 return(0);
1716         }
1717
1718         /*
1719          * VOP_FSYNC will start a new transaction so replicate some code
1720          * here to do it inline (see hammer2_vop_fsync()).
1721          *
1722          * WARNING: The vfsync interacts with the buffer cache and might
1723          *          block, we can't hold the inode lock at that time.
1724          */
1725         atomic_clear_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1726         if (ip->vp)
1727                 vfsync(ip->vp, MNT_NOWAIT, 1, NULL, NULL);
1728         parent = hammer2_inode_lock_ex(ip);
1729         hammer2_chain_flush(&info->trans, parent);
1730         hammer2_inode_unlock_ex(ip, parent);
1731         error = 0;
1732 #if 0
1733         error = VOP_FSYNC(vp, MNT_NOWAIT, 0);
1734 #endif
1735         if (error)
1736                 info->error = error;
1737         return(0);
1738 }
1739
1740 static
1741 int
1742 hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp)
1743 {
1744         return (0);
1745 }
1746
1747 static
1748 int
1749 hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
1750                struct fid *fhp, struct vnode **vpp)
1751 {
1752         return (0);
1753 }
1754
1755 static
1756 int
1757 hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
1758                  int *exflagsp, struct ucred **credanonp)
1759 {
1760         return (0);
1761 }
1762
1763 /*
1764  * Support code for hammer2_mount().  Read, verify, and install the volume
1765  * header into the HMP
1766  *
1767  * XXX read four volhdrs and use the one with the highest TID whos CRC
1768  *     matches.
1769  *
1770  * XXX check iCRCs.
1771  *
1772  * XXX For filesystems w/ less than 4 volhdrs, make sure to not write to
1773  *     nonexistant locations.
1774  *
1775  * XXX Record selected volhdr and ring updates to each of 4 volhdrs
1776  */
1777 static
1778 int
1779 hammer2_install_volume_header(hammer2_mount_t *hmp)
1780 {
1781         hammer2_volume_data_t *vd;
1782         struct buf *bp;
1783         hammer2_crc32_t crc0, crc, bcrc0, bcrc;
1784         int error_reported;
1785         int error;
1786         int valid;
1787         int i;
1788
1789         error_reported = 0;
1790         error = 0;
1791         valid = 0;
1792         bp = NULL;
1793
1794         /*
1795          * There are up to 4 copies of the volume header (syncs iterate
1796          * between them so there is no single master).  We don't trust the
1797          * volu_size field so we don't know precisely how large the filesystem
1798          * is, so depend on the OS to return an error if we go beyond the
1799          * block device's EOF.
1800          */
1801         for (i = 0; i < HAMMER2_NUM_VOLHDRS; i++) {
1802                 error = bread(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
1803                               HAMMER2_VOLUME_BYTES, &bp);
1804                 if (error) {
1805                         brelse(bp);
1806                         bp = NULL;
1807                         continue;
1808                 }
1809
1810                 vd = (struct hammer2_volume_data *) bp->b_data;
1811                 if ((vd->magic != HAMMER2_VOLUME_ID_HBO) &&
1812                     (vd->magic != HAMMER2_VOLUME_ID_ABO)) {
1813                         brelse(bp);
1814                         bp = NULL;
1815                         continue;
1816                 }
1817
1818                 if (vd->magic == HAMMER2_VOLUME_ID_ABO) {
1819                         /* XXX: Reversed-endianness filesystem */
1820                         kprintf("hammer2: reverse-endian filesystem detected");
1821                         brelse(bp);
1822                         bp = NULL;
1823                         continue;
1824                 }
1825
1826                 crc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT0];
1827                 crc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC0_OFF,
1828                                       HAMMER2_VOLUME_ICRC0_SIZE);
1829                 bcrc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT1];
1830                 bcrc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC1_OFF,
1831                                        HAMMER2_VOLUME_ICRC1_SIZE);
1832                 if ((crc0 != crc) || (bcrc0 != bcrc)) {
1833                         kprintf("hammer2 volume header crc "
1834                                 "mismatch copy #%d %08x/%08x\n",
1835                                 i, crc0, crc);
1836                         error_reported = 1;
1837                         brelse(bp);
1838                         bp = NULL;
1839                         continue;
1840                 }
1841                 if (valid == 0 || hmp->voldata.mirror_tid < vd->mirror_tid) {
1842                         valid = 1;
1843                         hmp->voldata = *vd;
1844                         hmp->volhdrno = i;
1845                 }
1846                 brelse(bp);
1847                 bp = NULL;
1848         }
1849         if (valid) {
1850                 hmp->volsync = hmp->voldata;
1851                 error = 0;
1852                 if (error_reported || bootverbose || 1) { /* 1/DEBUG */
1853                         kprintf("hammer2: using volume header #%d\n",
1854                                 hmp->volhdrno);
1855                 }
1856         } else {
1857                 error = EINVAL;
1858                 kprintf("hammer2: no valid volume headers found!\n");
1859         }
1860         return (error);
1861 }
1862
1863 /*
1864  * Reconnect using the passed file pointer.  The caller must ref the
1865  * fp for us.
1866  */
1867 void
1868 hammer2_cluster_reconnect(hammer2_pfsmount_t *pmp, struct file *fp)
1869 {
1870         hammer2_inode_data_t *ipdata;
1871         hammer2_chain_t *parent;
1872         hammer2_mount_t *hmp;
1873         size_t name_len;
1874
1875         hmp = pmp->mount_cluster->hmp;
1876
1877         /*
1878          * Closes old comm descriptor, kills threads, cleans up
1879          * states, then installs the new descriptor and creates
1880          * new threads.
1881          */
1882         kdmsg_iocom_reconnect(&pmp->iocom, fp, "hammer2");
1883
1884         /*
1885          * Setup LNK_CONN fields for autoinitiated state machine
1886          */
1887         parent = hammer2_inode_lock_ex(pmp->iroot);
1888         ipdata = &parent->data->ipdata;
1889         pmp->iocom.auto_lnk_conn.pfs_clid = ipdata->pfs_clid;
1890         pmp->iocom.auto_lnk_conn.pfs_fsid = ipdata->pfs_fsid;
1891         pmp->iocom.auto_lnk_conn.pfs_type = ipdata->pfs_type;
1892         pmp->iocom.auto_lnk_conn.proto_version = DMSG_SPAN_PROTO_1;
1893         pmp->iocom.auto_lnk_conn.peer_type = hmp->voldata.peer_type;
1894
1895         /*
1896          * Filter adjustment.  Clients do not need visibility into other
1897          * clients (otherwise millions of clients would present a serious
1898          * problem).  The fs_label also serves to restrict the namespace.
1899          */
1900         pmp->iocom.auto_lnk_conn.peer_mask = 1LLU << HAMMER2_PEER_HAMMER2;
1901         pmp->iocom.auto_lnk_conn.pfs_mask = (uint64_t)-1;
1902         switch (ipdata->pfs_type) {
1903         case DMSG_PFSTYPE_CLIENT:
1904                 pmp->iocom.auto_lnk_conn.peer_mask &=
1905                                 ~(1LLU << DMSG_PFSTYPE_CLIENT);
1906                 break;
1907         default:
1908                 break;
1909         }
1910
1911         name_len = ipdata->name_len;
1912         if (name_len >= sizeof(pmp->iocom.auto_lnk_conn.fs_label))
1913                 name_len = sizeof(pmp->iocom.auto_lnk_conn.fs_label) - 1;
1914         bcopy(ipdata->filename,
1915               pmp->iocom.auto_lnk_conn.fs_label,
1916               name_len);
1917         pmp->iocom.auto_lnk_conn.fs_label[name_len] = 0;
1918
1919         /*
1920          * Setup LNK_SPAN fields for autoinitiated state machine
1921          */
1922         pmp->iocom.auto_lnk_span.pfs_clid = ipdata->pfs_clid;
1923         pmp->iocom.auto_lnk_span.pfs_fsid = ipdata->pfs_fsid;
1924         pmp->iocom.auto_lnk_span.pfs_type = ipdata->pfs_type;
1925         pmp->iocom.auto_lnk_span.peer_type = hmp->voldata.peer_type;
1926         pmp->iocom.auto_lnk_span.proto_version = DMSG_SPAN_PROTO_1;
1927         name_len = ipdata->name_len;
1928         if (name_len >= sizeof(pmp->iocom.auto_lnk_span.fs_label))
1929                 name_len = sizeof(pmp->iocom.auto_lnk_span.fs_label) - 1;
1930         bcopy(ipdata->filename,
1931               pmp->iocom.auto_lnk_span.fs_label,
1932               name_len);
1933         pmp->iocom.auto_lnk_span.fs_label[name_len] = 0;
1934         hammer2_inode_unlock_ex(pmp->iroot, parent);
1935
1936         kdmsg_iocom_autoinitiate(&pmp->iocom, hammer2_autodmsg);
1937 }
1938
1939 static int
1940 hammer2_rcvdmsg(kdmsg_msg_t *msg)
1941 {
1942         switch(msg->any.head.cmd & DMSGF_TRANSMASK) {
1943         case DMSG_DBG_SHELL:
1944                 /*
1945                  * (non-transaction)
1946                  * Execute shell command (not supported atm)
1947                  */
1948                 kdmsg_msg_reply(msg, DMSG_ERR_NOSUPP);
1949                 break;
1950         case DMSG_DBG_SHELL | DMSGF_REPLY:
1951                 /*
1952                  * (non-transaction)
1953                  */
1954                 if (msg->aux_data) {
1955                         msg->aux_data[msg->aux_size - 1] = 0;
1956                         kprintf("HAMMER2 DBG: %s\n", msg->aux_data);
1957                 }
1958                 break;
1959         default:
1960                 /*
1961                  * Unsupported message received.  We only need to
1962                  * reply if it's a transaction in order to close our end.
1963                  * Ignore any one-way messages are any further messages
1964                  * associated with the transaction.
1965                  *
1966                  * NOTE: This case also includes DMSG_LNK_ERROR messages
1967                  *       which might be one-way, replying to those would
1968                  *       cause an infinite ping-pong.
1969                  */
1970                 if (msg->any.head.cmd & DMSGF_CREATE)
1971                         kdmsg_msg_reply(msg, DMSG_ERR_NOSUPP);
1972                 break;
1973         }
1974         return(0);
1975 }
1976
1977 /*
1978  * This function is called after KDMSG has automatically handled processing
1979  * of a LNK layer message (typically CONN, SPAN, or CIRC).
1980  *
1981  * We tag off the LNK_CONN to trigger our LNK_VOLCONF messages which
1982  * advertises all available hammer2 super-root volumes.
1983  */
1984 static void
1985 hammer2_autodmsg(kdmsg_msg_t *msg)
1986 {
1987         hammer2_pfsmount_t *pmp = msg->iocom->handle;
1988         hammer2_mount_t *hmp = pmp->mount_cluster->hmp;
1989         int copyid;
1990
1991         /*
1992          * We only care about replies to our LNK_CONN auto-request.  kdmsg
1993          * has already processed the reply, we use this calback as a shim
1994          * to know when we can advertise available super-root volumes.
1995          */
1996         if ((msg->any.head.cmd & DMSGF_TRANSMASK) !=
1997             (DMSG_LNK_CONN | DMSGF_CREATE | DMSGF_REPLY) ||
1998             msg->state == NULL) {
1999                 return;
2000         }
2001
2002         kprintf("LNK_CONN REPLY RECEIVED CMD %08x\n", msg->any.head.cmd);
2003
2004         if (msg->any.head.cmd & DMSGF_CREATE) {
2005                 kprintf("HAMMER2: VOLDATA DUMP\n");
2006
2007                 /*
2008                  * Dump the configuration stored in the volume header
2009                  */
2010                 hammer2_voldata_lock(hmp);
2011                 for (copyid = 0; copyid < HAMMER2_COPYID_COUNT; ++copyid) {
2012                         if (hmp->voldata.copyinfo[copyid].copyid == 0)
2013                                 continue;
2014                         hammer2_volconf_update(pmp, copyid);
2015                 }
2016                 hammer2_voldata_unlock(hmp, 0);
2017         }
2018         if ((msg->any.head.cmd & DMSGF_DELETE) &&
2019             msg->state && (msg->state->txcmd & DMSGF_DELETE) == 0) {
2020                 kprintf("HAMMER2: CONN WAS TERMINATED\n");
2021         }
2022 }
2023
2024 /*
2025  * Volume configuration updates are passed onto the userland service
2026  * daemon via the open LNK_CONN transaction.
2027  */
2028 void
2029 hammer2_volconf_update(hammer2_pfsmount_t *pmp, int index)
2030 {
2031         hammer2_mount_t *hmp = pmp->mount_cluster->hmp;
2032         kdmsg_msg_t *msg;
2033
2034         /* XXX interlock against connection state termination */
2035         kprintf("volconf update %p\n", pmp->iocom.conn_state);
2036         if (pmp->iocom.conn_state) {
2037                 kprintf("TRANSMIT VOLCONF VIA OPEN CONN TRANSACTION\n");
2038                 msg = kdmsg_msg_alloc_state(pmp->iocom.conn_state,
2039                                             DMSG_LNK_VOLCONF, NULL, NULL);
2040                 msg->any.lnk_volconf.copy = hmp->voldata.copyinfo[index];
2041                 msg->any.lnk_volconf.mediaid = hmp->voldata.fsid;
2042                 msg->any.lnk_volconf.index = index;
2043                 kdmsg_msg_write(msg);
2044         }
2045 }
2046
2047 void
2048 hammer2_dump_chain(hammer2_chain_t *chain, int tab, int *countp)
2049 {
2050         hammer2_chain_t *scan;
2051
2052         --*countp;
2053         if (*countp == 0) {
2054                 kprintf("%*.*s...\n", tab, tab, "");
2055                 return;
2056         }
2057         if (*countp < 0)
2058                 return;
2059         kprintf("%*.*schain[%d] %p.%d [%08x][core=%p] (%s) dl=%p dt=%s refs=%d",
2060                 tab, tab, "",
2061                 chain->index, chain, chain->bref.type, chain->flags,
2062                 chain->core,
2063                 ((chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2064                 chain->data) ?  (char *)chain->data->ipdata.filename : "?"),
2065                 chain->next_parent,
2066                 (chain->delete_tid == HAMMER2_MAX_TID ? "max" : "fls"),
2067                 chain->refs);
2068         if (chain->core == NULL || RB_EMPTY(&chain->core->rbtree))
2069                 kprintf("\n");
2070         else
2071                 kprintf(" {\n");
2072         RB_FOREACH(scan, hammer2_chain_tree, &chain->core->rbtree) {
2073                 hammer2_dump_chain(scan, tab + 4, countp);
2074         }
2075         if (chain->core && !RB_EMPTY(&chain->core->rbtree)) {
2076                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE && chain->data)
2077                         kprintf("%*.*s}(%s)\n", tab, tab, "",
2078                                 chain->data->ipdata.filename);
2079                 else
2080                         kprintf("%*.*s}\n", tab, tab, "");
2081         }
2082 }