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