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