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