5b8349f8245e6c321ef2a0a1d7b0ee8633620fb5
[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         int error;
71         int waitfor;
72 };
73
74 TAILQ_HEAD(hammer2_mntlist, hammer2_dev);
75 TAILQ_HEAD(hammer2_pfslist, hammer2_pfs);
76 static struct hammer2_mntlist hammer2_mntlist;
77 static struct hammer2_pfslist hammer2_pfslist;
78 static struct lock hammer2_mntlk;
79
80 int hammer2_debug;
81 int hammer2_cluster_enable = 1;
82 int hammer2_hardlink_enable = 1;
83 int hammer2_flush_pipe = 100;
84 int hammer2_synchronous_flush = 1;
85 int hammer2_dio_count;
86 long hammer2_limit_dirty_chains;
87 long hammer2_iod_file_read;
88 long hammer2_iod_meta_read;
89 long hammer2_iod_indr_read;
90 long hammer2_iod_fmap_read;
91 long hammer2_iod_volu_read;
92 long hammer2_iod_file_write;
93 long hammer2_iod_meta_write;
94 long hammer2_iod_indr_write;
95 long hammer2_iod_fmap_write;
96 long hammer2_iod_volu_write;
97 long hammer2_ioa_file_read;
98 long hammer2_ioa_meta_read;
99 long hammer2_ioa_indr_read;
100 long hammer2_ioa_fmap_read;
101 long hammer2_ioa_volu_read;
102 long hammer2_ioa_fmap_write;
103 long hammer2_ioa_file_write;
104 long hammer2_ioa_meta_write;
105 long hammer2_ioa_indr_write;
106 long hammer2_ioa_volu_write;
107
108 MALLOC_DECLARE(M_HAMMER2_CBUFFER);
109 MALLOC_DEFINE(M_HAMMER2_CBUFFER, "HAMMER2-compbuffer",
110                 "Buffer used for compression.");
111
112 MALLOC_DECLARE(M_HAMMER2_DEBUFFER);
113 MALLOC_DEFINE(M_HAMMER2_DEBUFFER, "HAMMER2-decompbuffer",
114                 "Buffer used for decompression.");
115
116 SYSCTL_NODE(_vfs, OID_AUTO, hammer2, CTLFLAG_RW, 0, "HAMMER2 filesystem");
117
118 SYSCTL_INT(_vfs_hammer2, OID_AUTO, debug, CTLFLAG_RW,
119            &hammer2_debug, 0, "");
120 SYSCTL_INT(_vfs_hammer2, OID_AUTO, cluster_enable, CTLFLAG_RW,
121            &hammer2_cluster_enable, 0, "");
122 SYSCTL_INT(_vfs_hammer2, OID_AUTO, hardlink_enable, CTLFLAG_RW,
123            &hammer2_hardlink_enable, 0, "");
124 SYSCTL_INT(_vfs_hammer2, OID_AUTO, flush_pipe, CTLFLAG_RW,
125            &hammer2_flush_pipe, 0, "");
126 SYSCTL_INT(_vfs_hammer2, OID_AUTO, synchronous_flush, CTLFLAG_RW,
127            &hammer2_synchronous_flush, 0, "");
128 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, limit_dirty_chains, CTLFLAG_RW,
129            &hammer2_limit_dirty_chains, 0, "");
130 SYSCTL_INT(_vfs_hammer2, OID_AUTO, dio_count, CTLFLAG_RD,
131            &hammer2_dio_count, 0, "");
132
133 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_read, CTLFLAG_RW,
134            &hammer2_iod_file_read, 0, "");
135 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_read, CTLFLAG_RW,
136            &hammer2_iod_meta_read, 0, "");
137 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_read, CTLFLAG_RW,
138            &hammer2_iod_indr_read, 0, "");
139 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_read, CTLFLAG_RW,
140            &hammer2_iod_fmap_read, 0, "");
141 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_read, CTLFLAG_RW,
142            &hammer2_iod_volu_read, 0, "");
143
144 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_file_write, CTLFLAG_RW,
145            &hammer2_iod_file_write, 0, "");
146 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_meta_write, CTLFLAG_RW,
147            &hammer2_iod_meta_write, 0, "");
148 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_indr_write, CTLFLAG_RW,
149            &hammer2_iod_indr_write, 0, "");
150 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_fmap_write, CTLFLAG_RW,
151            &hammer2_iod_fmap_write, 0, "");
152 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, iod_volu_write, CTLFLAG_RW,
153            &hammer2_iod_volu_write, 0, "");
154
155 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_file_read, CTLFLAG_RW,
156            &hammer2_ioa_file_read, 0, "");
157 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_meta_read, CTLFLAG_RW,
158            &hammer2_ioa_meta_read, 0, "");
159 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_indr_read, CTLFLAG_RW,
160            &hammer2_ioa_indr_read, 0, "");
161 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_fmap_read, CTLFLAG_RW,
162            &hammer2_ioa_fmap_read, 0, "");
163 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_volu_read, CTLFLAG_RW,
164            &hammer2_ioa_volu_read, 0, "");
165
166 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_file_write, CTLFLAG_RW,
167            &hammer2_ioa_file_write, 0, "");
168 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_meta_write, CTLFLAG_RW,
169            &hammer2_ioa_meta_write, 0, "");
170 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_indr_write, CTLFLAG_RW,
171            &hammer2_ioa_indr_write, 0, "");
172 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_fmap_write, CTLFLAG_RW,
173            &hammer2_ioa_fmap_write, 0, "");
174 SYSCTL_LONG(_vfs_hammer2, OID_AUTO, ioa_volu_write, CTLFLAG_RW,
175            &hammer2_ioa_volu_write, 0, "");
176
177 static int hammer2_vfs_init(struct vfsconf *conf);
178 static int hammer2_vfs_uninit(struct vfsconf *vfsp);
179 static int hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
180                                 struct ucred *cred);
181 static int hammer2_remount(hammer2_dev_t *, struct mount *, char *,
182                                 struct vnode *, struct ucred *);
183 static int hammer2_recovery(hammer2_dev_t *hmp);
184 static int hammer2_vfs_unmount(struct mount *mp, int mntflags);
185 static int hammer2_vfs_root(struct mount *mp, struct vnode **vpp);
186 static int hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp,
187                                 struct ucred *cred);
188 static int hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp,
189                                 struct ucred *cred);
190 static int hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
191                                 ino_t ino, struct vnode **vpp);
192 static int hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
193                                 struct fid *fhp, struct vnode **vpp);
194 static int hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp);
195 static int hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
196                                 int *exflagsp, struct ucred **credanonp);
197
198 static int hammer2_install_volume_header(hammer2_dev_t *hmp);
199 static int hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data);
200
201 static void hammer2_update_pmps(hammer2_dev_t *hmp);
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  * HAMMER2 vfs operations.
209  */
210 static struct vfsops hammer2_vfsops = {
211         .vfs_init       = hammer2_vfs_init,
212         .vfs_uninit     = hammer2_vfs_uninit,
213         .vfs_sync       = hammer2_vfs_sync,
214         .vfs_mount      = hammer2_vfs_mount,
215         .vfs_unmount    = hammer2_vfs_unmount,
216         .vfs_root       = hammer2_vfs_root,
217         .vfs_statfs     = hammer2_vfs_statfs,
218         .vfs_statvfs    = hammer2_vfs_statvfs,
219         .vfs_vget       = hammer2_vfs_vget,
220         .vfs_vptofh     = hammer2_vfs_vptofh,
221         .vfs_fhtovp     = hammer2_vfs_fhtovp,
222         .vfs_checkexp   = hammer2_vfs_checkexp
223 };
224
225 MALLOC_DEFINE(M_HAMMER2, "HAMMER2-mount", "");
226
227 VFS_SET(hammer2_vfsops, hammer2, 0);
228 MODULE_VERSION(hammer2, 1);
229
230 static
231 int
232 hammer2_vfs_init(struct vfsconf *conf)
233 {
234         static struct objcache_malloc_args margs_read;
235         static struct objcache_malloc_args margs_write;
236         static struct objcache_malloc_args margs_vop;
237
238         int error;
239
240         error = 0;
241
242         if (HAMMER2_BLOCKREF_BYTES != sizeof(struct hammer2_blockref))
243                 error = EINVAL;
244         if (HAMMER2_INODE_BYTES != sizeof(struct hammer2_inode_data))
245                 error = EINVAL;
246         if (HAMMER2_VOLUME_BYTES != sizeof(struct hammer2_volume_data))
247                 error = EINVAL;
248
249         if (error)
250                 kprintf("HAMMER2 structure size mismatch; cannot continue.\n");
251         
252         margs_read.objsize = 65536;
253         margs_read.mtype = M_HAMMER2_DEBUFFER;
254         
255         margs_write.objsize = 32768;
256         margs_write.mtype = M_HAMMER2_CBUFFER;
257
258         margs_vop.objsize = sizeof(hammer2_xop_t);
259         margs_vop.mtype = M_HAMMER2;
260         
261         /*
262          * Note thaht for the XOPS cache we want backing store allocations
263          * to use M_ZERO.  This is not allowed in objcache_get() (to avoid
264          * confusion), so use the backing store function that does it.  This
265          * means that initial XOPS objects are zerod but REUSED objects are
266          * not.  So we are responsible for cleaning the object up sufficiently
267          * for our needs before objcache_put()ing it back (typically just the
268          * FIFO indices).
269          */
270         cache_buffer_read = objcache_create(margs_read.mtype->ks_shortdesc,
271                                 0, 1, NULL, NULL, NULL,
272                                 objcache_malloc_alloc,
273                                 objcache_malloc_free,
274                                 &margs_read);
275         cache_buffer_write = objcache_create(margs_write.mtype->ks_shortdesc,
276                                 0, 1, NULL, NULL, NULL,
277                                 objcache_malloc_alloc,
278                                 objcache_malloc_free,
279                                 &margs_write);
280         cache_xops = objcache_create(margs_vop.mtype->ks_shortdesc,
281                                 0, 1, NULL, NULL, NULL,
282                                 objcache_malloc_alloc_zero,
283                                 objcache_malloc_free,
284                                 &margs_vop);
285
286
287         lockinit(&hammer2_mntlk, "mntlk", 0, 0);
288         TAILQ_INIT(&hammer2_mntlist);
289         TAILQ_INIT(&hammer2_pfslist);
290
291         hammer2_limit_dirty_chains = desiredvnodes / 10;
292
293         return (error);
294 }
295
296 static
297 int
298 hammer2_vfs_uninit(struct vfsconf *vfsp __unused)
299 {
300         objcache_destroy(cache_buffer_read);
301         objcache_destroy(cache_buffer_write);
302         objcache_destroy(cache_xops);
303         return 0;
304 }
305
306 /*
307  * Core PFS allocator.  Used to allocate the pmp structure for PFS cluster
308  * mounts and the spmp structure for media (hmp) structures.
309  *
310  * pmp->modify_tid tracks new modify_tid transaction ids for front-end
311  * transactions.  Note that synchronization does not use this field.
312  * (typically frontend operations and synchronization cannot run on the
313  * same PFS node at the same time).
314  *
315  * XXX check locking
316  */
317 hammer2_pfs_t *
318 hammer2_pfsalloc(hammer2_chain_t *chain, const hammer2_inode_data_t *ripdata,
319                  hammer2_tid_t modify_tid)
320 {
321         hammer2_inode_t *iroot;
322         hammer2_pfs_t *pmp;
323         int count;
324         int i;
325         int j;
326
327         /*
328          * Locate or create the PFS based on the cluster id.  If ripdata
329          * is NULL this is a spmp which is unique and is always allocated.
330          */
331         if (ripdata) {
332                 TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
333                         if (bcmp(&pmp->pfs_clid, &ripdata->meta.pfs_clid,
334                                  sizeof(pmp->pfs_clid)) == 0) {
335                                         break;
336                         }
337                 }
338         } else {
339                 pmp = NULL;
340         }
341
342         if (pmp == NULL) {
343                 pmp = kmalloc(sizeof(*pmp), M_HAMMER2, M_WAITOK | M_ZERO);
344                 hammer2_trans_manage_init(pmp);
345                 kmalloc_create(&pmp->minode, "HAMMER2-inodes");
346                 kmalloc_create(&pmp->mmsg, "HAMMER2-pfsmsg");
347                 lockinit(&pmp->lock, "pfslk", 0, 0);
348                 spin_init(&pmp->inum_spin, "hm2pfsalloc_inum");
349                 RB_INIT(&pmp->inum_tree);
350                 TAILQ_INIT(&pmp->unlinkq);
351                 spin_init(&pmp->list_spin, "hm2pfsalloc_list");
352
353                 for (j = 0; j < HAMMER2_XOPGROUPS; ++j)
354                         hammer2_xop_group_init(pmp, &pmp->xop_groups[j]);
355
356                 /*
357                  * Save the last media transaction id for the flusher.  Set
358                  * initial 
359                  */
360                 if (ripdata)
361                         pmp->pfs_clid = ripdata->meta.pfs_clid;
362                 TAILQ_INSERT_TAIL(&hammer2_pfslist, pmp, mntentry);
363
364                 /*
365                  * The synchronization thread may start too early, make
366                  * sure it stays frozen until we are ready to let it go.
367                  * XXX
368                  */
369                 /*
370                 pmp->primary_thr.flags = HAMMER2_THREAD_FROZEN |
371                                          HAMMER2_THREAD_REMASTER;
372                 */
373         }
374
375         /*
376          * Create the PFS's root inode.
377          */
378         if ((iroot = pmp->iroot) == NULL) {
379                 iroot = hammer2_inode_get(pmp, NULL, NULL, -1);
380                 pmp->iroot = iroot;
381                 hammer2_inode_ref(iroot);
382                 hammer2_inode_unlock(iroot);
383         }
384
385         /*
386          * Stop here if no chain is passed in.
387          */
388         if (chain == NULL)
389                 goto done;
390
391         /*
392          * When a chain is passed in we must add it to the PFS's root
393          * inode, update pmp->pfs_types[], and update the syncronization
394          * threads.
395          *
396          * At the moment empty spots can develop due to removals or failures.
397          * Ultimately we want to re-fill these spots but doing so might
398          * confused running code. XXX
399          */
400         hammer2_inode_ref(iroot);
401         hammer2_mtx_ex(&iroot->lock);
402         j = iroot->cluster.nchains;
403
404         kprintf("add PFS to pmp %p[%d]\n", pmp, j);
405
406         if (j == HAMMER2_MAXCLUSTER) {
407                 kprintf("hammer2_mount: cluster full!\n");
408                 /* XXX fatal error? */
409         } else {
410                 KKASSERT(chain->pmp == NULL);
411                 chain->pmp = pmp;
412                 hammer2_chain_ref(chain);
413                 iroot->cluster.array[j].chain = chain;
414                 pmp->pfs_types[j] = ripdata->meta.pfs_type;
415                 pmp->pfs_names[j] = kstrdup(ripdata->filename, M_HAMMER2);
416                 pmp->pfs_hmps[j] = chain->hmp;
417
418                 /*
419                  * If the PFS is already mounted we must account
420                  * for the mount_count here.
421                  */
422                 if (pmp->mp)
423                         ++chain->hmp->mount_count;
424
425                 /*
426                  * May have to fixup dirty chain tracking.  Previous
427                  * pmp was NULL so nothing to undo.
428                  */
429                 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
430                         hammer2_pfs_memory_inc(pmp);
431                 ++j;
432         }
433         iroot->cluster.nchains = j;
434
435         /*
436          * Update nmasters from any PFS inode which is part of the cluster.
437          * It is possible that this will result in a value which is too
438          * high.  MASTER PFSs are authoritative for pfs_nmasters and will
439          * override this value later on.
440          *
441          * (This informs us of masters that might not currently be
442          *  discoverable by this mount).
443          */
444         if (ripdata && pmp->pfs_nmasters < ripdata->meta.pfs_nmasters) {
445                 pmp->pfs_nmasters = ripdata->meta.pfs_nmasters;
446         }
447
448         /*
449          * Count visible masters.  Masters are usually added with
450          * ripdata->meta.pfs_nmasters set to 1.  This detects when there
451          * are more (XXX and must update the master inodes).
452          */
453         count = 0;
454         for (i = 0; i < iroot->cluster.nchains; ++i) {
455                 if (pmp->pfs_types[i] == HAMMER2_PFSTYPE_MASTER)
456                         ++count;
457         }
458         if (pmp->pfs_nmasters < count)
459                 pmp->pfs_nmasters = count;
460
461         /*
462          * Create missing synchronization and support threads.
463          *
464          * Single-node masters (including snapshots) have nothing to
465          * synchronize and do not require this thread.
466          *
467          * Multi-node masters or any number of soft masters, slaves, copy,
468          * or other PFS types need the thread.
469          *
470          * Each thread is responsible for its particular cluster index.
471          * We use independent threads so stalls or mismatches related to
472          * any given target do not affect other targets.
473          */
474         for (i = 0; i < iroot->cluster.nchains; ++i) {
475                 /*
476                  * Single-node masters (including snapshots) have nothing
477                  * to synchronize and will make direct xops support calls,
478                  * thus they do not require this thread.
479                  *
480                  * Note that there can be thousands of snapshots.  We do not
481                  * want to create thousands of threads.
482                  */
483                 if (pmp->pfs_nmasters <= 1 &&
484                     pmp->pfs_types[i] == HAMMER2_PFSTYPE_MASTER) {
485                         continue;
486                 }
487
488                 /*
489                  * Sync support thread
490                  */
491                 if (pmp->sync_thrs[i].td == NULL) {
492                         hammer2_thr_create(&pmp->sync_thrs[i], pmp,
493                                            "h2nod", i, -1,
494                                            hammer2_primary_sync_thread);
495                 }
496         }
497
498         /*
499          * Create missing Xop threads
500          */
501         if (pmp->mp)
502                 hammer2_xop_helper_create(pmp);
503
504         hammer2_mtx_unlock(&iroot->lock);
505         hammer2_inode_drop(iroot);
506 done:
507         return pmp;
508 }
509
510 /*
511  * Destroy a PFS, typically only occurs after the last mount on a device
512  * has gone away.
513  */
514 static void
515 hammer2_pfsfree(hammer2_pfs_t *pmp)
516 {
517         hammer2_inode_t *iroot;
518         int i;
519         int j;
520
521         /*
522          * Cleanup our reference on iroot.  iroot is (should) not be needed
523          * by the flush code.
524          */
525         TAILQ_REMOVE(&hammer2_pfslist, pmp, mntentry);
526
527         iroot = pmp->iroot;
528         if (iroot) {
529                 for (i = 0; i < iroot->cluster.nchains; ++i) {
530                         hammer2_thr_delete(&pmp->sync_thrs[i]);
531                         for (j = 0; j < HAMMER2_XOPGROUPS; ++j)
532                                 hammer2_thr_delete(&pmp->xop_groups[j].thrs[i]);
533                 }
534 #if REPORT_REFS_ERRORS
535                 if (pmp->iroot->refs != 1)
536                         kprintf("PMP->IROOT %p REFS WRONG %d\n",
537                                 pmp->iroot, pmp->iroot->refs);
538 #else
539                 KKASSERT(pmp->iroot->refs == 1);
540 #endif
541                 /* ref for pmp->iroot */
542                 hammer2_inode_drop(pmp->iroot);
543                 pmp->iroot = NULL;
544         }
545
546         kmalloc_destroy(&pmp->mmsg);
547         kmalloc_destroy(&pmp->minode);
548
549         kfree(pmp, M_HAMMER2);
550 }
551
552 /*
553  * Remove all references to hmp from the pfs list.  Any PFS which becomes
554  * empty is terminated and freed.
555  *
556  * XXX inefficient.
557  */
558 static void
559 hammer2_pfsfree_scan(hammer2_dev_t *hmp)
560 {
561         hammer2_pfs_t *pmp;
562         hammer2_inode_t *iroot;
563         hammer2_chain_t *rchain;
564         int didfreeze;
565         int i;
566         int j;
567
568 again:
569         TAILQ_FOREACH(pmp, &hammer2_pfslist, mntentry) {
570                 if ((iroot = pmp->iroot) == NULL)
571                         continue;
572                 if (hmp->spmp == pmp) {
573                         kprintf("unmount hmp %p remove spmp %p\n",
574                                 hmp, pmp);
575                         hmp->spmp = NULL;
576                 }
577
578                 /*
579                  * Determine if this PFS is affected.  If it is we must
580                  * freeze all management threads and lock its iroot.
581                  *
582                  * Freezing a management thread forces it idle, operations
583                  * in-progress will be aborted and it will have to start
584                  * over again when unfrozen, or exit if told to exit.
585                  */
586                 for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
587                         if (pmp->pfs_hmps[i] == hmp)
588                                 break;
589                 }
590                 if (i != HAMMER2_MAXCLUSTER) {
591                         /*
592                          * Make sure all synchronization threads are locked
593                          * down.
594                          */
595                         for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
596                                 if (pmp->pfs_hmps[i] == NULL)
597                                         continue;
598                                 hammer2_thr_freeze_async(&pmp->sync_thrs[i]);
599                                 for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
600                                         hammer2_thr_freeze_async(
601                                                 &pmp->xop_groups[j].thrs[i]);
602                                 }
603                         }
604                         for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
605                                 if (pmp->pfs_hmps[i] == NULL)
606                                         continue;
607                                 hammer2_thr_freeze(&pmp->sync_thrs[i]);
608                                 for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
609                                         hammer2_thr_freeze(
610                                                 &pmp->xop_groups[j].thrs[i]);
611                                 }
612                         }
613
614                         /*
615                          * Lock the inode and clean out matching chains.
616                          * Note that we cannot use hammer2_inode_lock_*()
617                          * here because that would attempt to validate the
618                          * cluster that we are in the middle of ripping
619                          * apart.
620                          *
621                          * WARNING! We are working directly on the inodes
622                          *          embedded cluster.
623                          */
624                         hammer2_mtx_ex(&iroot->lock);
625
626                         /*
627                          * Remove the chain from matching elements of the PFS.
628                          */
629                         for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
630                                 if (pmp->pfs_hmps[i] != hmp)
631                                         continue;
632                                 hammer2_thr_delete(&pmp->sync_thrs[i]);
633                                 for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
634                                         hammer2_thr_delete(
635                                                 &pmp->xop_groups[j].thrs[i]);
636                                 }
637                                 rchain = iroot->cluster.array[i].chain;
638                                 iroot->cluster.array[i].chain = NULL;
639                                 pmp->pfs_types[i] = 0;
640                                 if (pmp->pfs_names[i]) {
641                                         kfree(pmp->pfs_names[i], M_HAMMER2);
642                                         pmp->pfs_names[i] = NULL;
643                                 }
644                                 if (rchain) {
645                                         hammer2_chain_drop(rchain);
646                                         /* focus hint */
647                                         if (iroot->cluster.focus == rchain)
648                                                 iroot->cluster.focus = NULL;
649                                 }
650                                 pmp->pfs_hmps[i] = NULL;
651                         }
652                         hammer2_mtx_unlock(&iroot->lock);
653                         didfreeze = 1;  /* remaster, unfreeze down below */
654                 } else {
655                         didfreeze = 0;
656                 }
657
658                 /*
659                  * Cleanup trailing chains.  Gaps may remain.
660                  */
661                 for (i = HAMMER2_MAXCLUSTER - 1; i >= 0; --i) {
662                         if (pmp->pfs_hmps[i])
663                                 break;
664                 }
665                 iroot->cluster.nchains = i + 1;
666
667                 /*
668                  * If the PMP has no elements remaining we can destroy it.
669                  * (this will transition management threads from frozen->exit).
670                  */
671                 if (iroot->cluster.nchains == 0) {
672                         kprintf("unmount hmp %p last ref to PMP=%p\n",
673                                 hmp, pmp);
674                         hammer2_pfsfree(pmp);
675                         goto again;
676                 }
677
678                 /*
679                  * If elements still remain we need to set the REMASTER
680                  * flag and unfreeze it.
681                  */
682                 if (didfreeze) {
683                         for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
684                                 if (pmp->pfs_hmps[i] == NULL)
685                                         continue;
686                                 hammer2_thr_remaster(&pmp->sync_thrs[i]);
687                                 hammer2_thr_unfreeze(&pmp->sync_thrs[i]);
688                                 for (j = 0; j < HAMMER2_XOPGROUPS; ++j) {
689                                         hammer2_thr_remaster(
690                                                 &pmp->xop_groups[j].thrs[i]);
691                                         hammer2_thr_unfreeze(
692                                                 &pmp->xop_groups[j].thrs[i]);
693                                 }
694                         }
695                 }
696         }
697 }
698
699 /*
700  * Mount or remount HAMMER2 fileystem from physical media
701  *
702  *      mountroot
703  *              mp              mount point structure
704  *              path            NULL
705  *              data            <unused>
706  *              cred            <unused>
707  *
708  *      mount
709  *              mp              mount point structure
710  *              path            path to mount point
711  *              data            pointer to argument structure in user space
712  *                      volume  volume path (device@LABEL form)
713  *                      hflags  user mount flags
714  *              cred            user credentials
715  *
716  * RETURNS:     0       Success
717  *              !0      error number
718  */
719 static
720 int
721 hammer2_vfs_mount(struct mount *mp, char *path, caddr_t data,
722                   struct ucred *cred)
723 {
724         struct hammer2_mount_info info;
725         hammer2_pfs_t *pmp;
726         hammer2_pfs_t *spmp;
727         hammer2_dev_t *hmp;
728         hammer2_key_t key_next;
729         hammer2_key_t key_dummy;
730         hammer2_key_t lhc;
731         struct vnode *devvp;
732         struct nlookupdata nd;
733         hammer2_chain_t *parent;
734         hammer2_chain_t *chain;
735         hammer2_cluster_t *cluster;
736         const hammer2_inode_data_t *ripdata;
737         hammer2_blockref_t bref;
738         struct file *fp;
739         char devstr[MNAMELEN];
740         size_t size;
741         size_t done;
742         char *dev;
743         char *label;
744         int ronly = 1;
745         int error;
746         int cache_index;
747         int i;
748
749         hmp = NULL;
750         pmp = NULL;
751         dev = NULL;
752         label = NULL;
753         devvp = NULL;
754         cache_index = -1;
755
756         kprintf("hammer2_mount\n");
757
758         if (path == NULL) {
759                 /*
760                  * Root mount
761                  */
762                 bzero(&info, sizeof(info));
763                 info.cluster_fd = -1;
764                 ksnprintf(devstr, sizeof(devstr), "%s",
765                           mp->mnt_stat.f_mntfromname);
766                 kprintf("hammer2_mount: root '%s'\n", devstr);
767         } else {
768                 /*
769                  * Non-root mount or updating a mount
770                  */
771                 error = copyin(data, &info, sizeof(info));
772                 if (error)
773                         return (error);
774
775                 error = copyinstr(info.volume, devstr, MNAMELEN - 1, &done);
776                 if (error)
777                         return (error);
778         }
779
780         /* Extract device and label */
781         dev = devstr;
782         label = strchr(devstr, '@');
783         if (label == NULL ||
784             ((label + 1) - dev) > done) {
785                 return (EINVAL);
786         }
787         *label = '\0';
788         label++;
789         if (*label == '\0')
790                 return (EINVAL);
791
792         if (mp->mnt_flag & MNT_UPDATE) {
793                 /*
794                  * Update mount.  Note that pmp->iroot->cluster is
795                  * an inode-embedded cluster and thus cannot be
796                  * directly locked.
797                  *
798                  * XXX HAMMER2 needs to implement NFS export via
799                  *     mountctl.
800                  */
801                 pmp = MPTOPMP(mp);
802                 cluster = &pmp->iroot->cluster;
803                 for (i = 0; i < cluster->nchains; ++i) {
804                         if (cluster->array[i].chain == NULL)
805                                 continue;
806                         hmp = cluster->array[i].chain->hmp;
807                         devvp = hmp->devvp;
808                         error = hammer2_remount(hmp, mp, path,
809                                                 devvp, cred);
810                         if (error)
811                                 break;
812                 }
813
814                 return error;
815         }
816
817         /*
818          * HMP device mount
819          *
820          * Lookup name and verify it refers to a block device.
821          */
822         if (path) {
823                 error = nlookup_init(&nd, dev, UIO_SYSSPACE, NLC_FOLLOW);
824                 if (error == 0)
825                         error = nlookup(&nd);
826                 if (error == 0)
827                         error = cache_vref(&nd.nl_nch, nd.nl_cred, &devvp);
828                 nlookup_done(&nd);
829         } else {
830                 /* root mount */
831                 cdev_t cdev = kgetdiskbyname(dev);
832                 error = bdevvp(cdev, &devvp);
833                 if (error)
834                         kprintf("hammer2: cannot find '%s'\n", dev);
835         }
836
837         if (error == 0) {
838                 if (vn_isdisk(devvp, &error))
839                         error = vfs_mountedon(devvp);
840         }
841
842         /*
843          * Determine if the device has already been mounted.  After this
844          * check hmp will be non-NULL if we are doing the second or more
845          * hammer2 mounts from the same device.
846          */
847         lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
848         TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
849                 if (hmp->devvp == devvp)
850                         break;
851         }
852
853         /*
854          * Open the device if this isn't a secondary mount and construct
855          * the H2 device mount (hmp).
856          */
857         if (hmp == NULL) {
858                 hammer2_chain_t *schain;
859                 hammer2_xid_t xid;
860
861                 if (error == 0 && vcount(devvp) > 0)
862                         error = EBUSY;
863
864                 /*
865                  * Now open the device
866                  */
867                 if (error == 0) {
868                         ronly = ((mp->mnt_flag & MNT_RDONLY) != 0);
869                         vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
870                         error = vinvalbuf(devvp, V_SAVE, 0, 0);
871                         if (error == 0) {
872                                 error = VOP_OPEN(devvp,
873                                                  ronly ? FREAD : FREAD | FWRITE,
874                                                  FSCRED, NULL);
875                         }
876                         vn_unlock(devvp);
877                 }
878                 if (error && devvp) {
879                         vrele(devvp);
880                         devvp = NULL;
881                 }
882                 if (error) {
883                         lockmgr(&hammer2_mntlk, LK_RELEASE);
884                         return error;
885                 }
886                 hmp = kmalloc(sizeof(*hmp), M_HAMMER2, M_WAITOK | M_ZERO);
887                 ksnprintf(hmp->devrepname, sizeof(hmp->devrepname), "%s", dev);
888                 hmp->ronly = ronly;
889                 hmp->devvp = devvp;
890                 kmalloc_create(&hmp->mchain, "HAMMER2-chains");
891                 TAILQ_INSERT_TAIL(&hammer2_mntlist, hmp, mntentry);
892                 RB_INIT(&hmp->iotree);
893                 spin_init(&hmp->io_spin, "hm2mount_io");
894                 spin_init(&hmp->list_spin, "hm2mount_list");
895                 TAILQ_INIT(&hmp->flushq);
896
897                 lockinit(&hmp->vollk, "h2vol", 0, 0);
898
899                 /*
900                  * vchain setup. vchain.data is embedded.
901                  * vchain.refs is initialized and will never drop to 0.
902                  *
903                  * NOTE! voldata is not yet loaded.
904                  */
905                 hmp->vchain.hmp = hmp;
906                 hmp->vchain.refs = 1;
907                 hmp->vchain.data = (void *)&hmp->voldata;
908                 hmp->vchain.bref.type = HAMMER2_BREF_TYPE_VOLUME;
909                 hmp->vchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
910                 hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
911
912                 hammer2_chain_core_init(&hmp->vchain);
913                 /* hmp->vchain.u.xxx is left NULL */
914
915                 /*
916                  * fchain setup.  fchain.data is embedded.
917                  * fchain.refs is initialized and will never drop to 0.
918                  *
919                  * The data is not used but needs to be initialized to
920                  * pass assertion muster.  We use this chain primarily
921                  * as a placeholder for the freemap's top-level RBTREE
922                  * so it does not interfere with the volume's topology
923                  * RBTREE.
924                  */
925                 hmp->fchain.hmp = hmp;
926                 hmp->fchain.refs = 1;
927                 hmp->fchain.data = (void *)&hmp->voldata.freemap_blockset;
928                 hmp->fchain.bref.type = HAMMER2_BREF_TYPE_FREEMAP;
929                 hmp->fchain.bref.data_off = 0 | HAMMER2_PBUFRADIX;
930                 hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
931                 hmp->fchain.bref.methods =
932                         HAMMER2_ENC_CHECK(HAMMER2_CHECK_FREEMAP) |
933                         HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
934
935                 hammer2_chain_core_init(&hmp->fchain);
936                 /* hmp->fchain.u.xxx is left NULL */
937
938                 /*
939                  * Install the volume header and initialize fields from
940                  * voldata.
941                  */
942                 error = hammer2_install_volume_header(hmp);
943                 if (error) {
944                         hammer2_unmount_helper(mp, NULL, hmp);
945                         lockmgr(&hammer2_mntlk, LK_RELEASE);
946                         hammer2_vfs_unmount(mp, MNT_FORCE);
947                         return error;
948                 }
949
950                 /*
951                  * Really important to get these right or flush will get
952                  * confused.
953                  */
954                 hmp->spmp = hammer2_pfsalloc(NULL, NULL, 0);
955                 kprintf("alloc spmp %p tid %016jx\n",
956                         hmp->spmp, hmp->voldata.mirror_tid);
957                 spmp = hmp->spmp;
958
959                 /*
960                  * Dummy-up vchain and fchain's modify_tid.  mirror_tid
961                  * is inherited from the volume header.
962                  */
963                 xid = 0;
964                 hmp->vchain.bref.mirror_tid = hmp->voldata.mirror_tid;
965                 hmp->vchain.bref.modify_tid = hmp->vchain.bref.mirror_tid;
966                 hmp->vchain.pmp = spmp;
967                 hmp->fchain.bref.mirror_tid = hmp->voldata.freemap_tid;
968                 hmp->fchain.bref.modify_tid = hmp->fchain.bref.mirror_tid;
969                 hmp->fchain.pmp = spmp;
970
971                 /*
972                  * First locate the super-root inode, which is key 0
973                  * relative to the volume header's blockset.
974                  *
975                  * Then locate the root inode by scanning the directory keyspace
976                  * represented by the label.
977                  */
978                 parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
979                 schain = hammer2_chain_lookup(&parent, &key_dummy,
980                                       HAMMER2_SROOT_KEY, HAMMER2_SROOT_KEY,
981                                       &cache_index, 0);
982                 hammer2_chain_lookup_done(parent);
983                 if (schain == NULL) {
984                         kprintf("hammer2_mount: invalid super-root\n");
985                         hammer2_unmount_helper(mp, NULL, hmp);
986                         lockmgr(&hammer2_mntlk, LK_RELEASE);
987                         hammer2_vfs_unmount(mp, MNT_FORCE);
988                         return EINVAL;
989                 }
990                 if (schain->error) {
991                         kprintf("hammer2_mount: error %s reading super-root\n",
992                                 hammer2_error_str(schain->error));
993                         hammer2_chain_unlock(schain);
994                         hammer2_chain_drop(schain);
995                         schain = NULL;
996                         hammer2_unmount_helper(mp, NULL, hmp);
997                         lockmgr(&hammer2_mntlk, LK_RELEASE);
998                         hammer2_vfs_unmount(mp, MNT_FORCE);
999                         return EINVAL;
1000                 }
1001
1002                 /*
1003                  * The super-root always uses an inode_tid of 1 when
1004                  * creating PFSs.
1005                  */
1006                 spmp->inode_tid = 1;
1007                 spmp->modify_tid = schain->bref.modify_tid + 1;
1008
1009                 /*
1010                  * Sanity-check schain's pmp and finish initialization.
1011                  * Any chain belonging to the super-root topology should
1012                  * have a NULL pmp (not even set to spmp).
1013                  */
1014                 ripdata = &hammer2_chain_rdata(schain)->ipdata;
1015                 KKASSERT(schain->pmp == NULL);
1016                 spmp->pfs_clid = ripdata->meta.pfs_clid;
1017
1018                 /*
1019                  * Replace the dummy spmp->iroot with a real one.  It's
1020                  * easier to just do a wholesale replacement than to try
1021                  * to update the chain and fixup the iroot fields.
1022                  *
1023                  * The returned inode is locked with the supplied cluster.
1024                  */
1025                 cluster = hammer2_cluster_from_chain(schain);
1026                 hammer2_inode_drop(spmp->iroot);
1027                 spmp->iroot = NULL;
1028                 spmp->iroot = hammer2_inode_get(spmp, NULL, cluster, -1);
1029                 spmp->spmp_hmp = hmp;
1030                 spmp->pfs_types[0] = ripdata->meta.pfs_type;
1031                 spmp->pfs_hmps[0] = hmp;
1032                 hammer2_inode_ref(spmp->iroot);
1033                 hammer2_inode_unlock(spmp->iroot);
1034                 hammer2_cluster_unlock(cluster);
1035                 hammer2_cluster_drop(cluster);
1036                 schain = NULL;
1037                 /* leave spmp->iroot with one ref */
1038
1039                 if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1040                         error = hammer2_recovery(hmp);
1041                         /* XXX do something with error */
1042                 }
1043                 hammer2_update_pmps(hmp);
1044                 hammer2_iocom_init(hmp);
1045
1046                 /*
1047                  * Ref the cluster management messaging descriptor.  The mount
1048                  * program deals with the other end of the communications pipe.
1049                  *
1050                  * Root mounts typically do not supply one.
1051                  */
1052                 if (info.cluster_fd >= 0) {
1053                         fp = holdfp(curproc->p_fd, info.cluster_fd, -1);
1054                         if (fp) {
1055                                 hammer2_cluster_reconnect(hmp, fp);
1056                         } else {
1057                                 kprintf("hammer2_mount: bad cluster_fd!\n");
1058                         }
1059                 }
1060         } else {
1061                 spmp = hmp->spmp;
1062         }
1063
1064         /*
1065          * Lookup the mount point under the media-localized super-root.
1066          * Scanning hammer2_pfslist doesn't help us because it represents
1067          * PFS cluster ids which can aggregate several named PFSs together.
1068          *
1069          * cluster->pmp will incorrectly point to spmp and must be fixed
1070          * up later on.
1071          */
1072         hammer2_inode_lock(spmp->iroot, 0);
1073         parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
1074         lhc = hammer2_dirhash(label, strlen(label));
1075         chain = hammer2_chain_lookup(&parent, &key_next,
1076                                      lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1077                                      &cache_index, 0);
1078         while (chain) {
1079                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1080                     strcmp(label, chain->data->ipdata.filename) == 0) {
1081                         break;
1082                 }
1083                 chain = hammer2_chain_next(&parent, chain, &key_next,
1084                                             key_next,
1085                                             lhc + HAMMER2_DIRHASH_LOMASK,
1086                                             &cache_index, 0);
1087         }
1088         if (parent) {
1089                 hammer2_chain_unlock(parent);
1090                 hammer2_chain_drop(parent);
1091         }
1092         hammer2_inode_unlock(spmp->iroot);
1093
1094         /*
1095          * PFS could not be found?
1096          */
1097         if (chain == NULL) {
1098                 kprintf("hammer2_mount: PFS label not found\n");
1099                 hammer2_unmount_helper(mp, NULL, hmp);
1100                 lockmgr(&hammer2_mntlk, LK_RELEASE);
1101                 hammer2_vfs_unmount(mp, MNT_FORCE);
1102
1103                 return EINVAL;
1104         }
1105
1106         /*
1107          * Acquire the pmp structure (it should have already been allocated
1108          * via hammer2_update_pmps() so do not pass cluster in to add to
1109          * available chains).
1110          *
1111          * Check if the cluster has already been mounted.  A cluster can
1112          * only be mounted once, use null mounts to mount additional copies.
1113          */
1114         ripdata = &chain->data->ipdata;
1115         bref = chain->bref;
1116         pmp = hammer2_pfsalloc(NULL, ripdata, bref.modify_tid);
1117         hammer2_chain_unlock(chain);
1118         hammer2_chain_drop(chain);
1119
1120         if (pmp->mp) {
1121                 kprintf("hammer2_mount: PFS already mounted!\n");
1122                 hammer2_unmount_helper(mp, NULL, hmp);
1123                 lockmgr(&hammer2_mntlk, LK_RELEASE);
1124                 hammer2_vfs_unmount(mp, MNT_FORCE);
1125
1126                 return EBUSY;
1127         }
1128
1129         /*
1130          * Finish the mount
1131          */
1132         kprintf("hammer2_mount hmp=%p pmp=%p\n", hmp, pmp);
1133
1134         mp->mnt_flag = MNT_LOCAL;
1135         mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;   /* all entry pts are SMP */
1136         mp->mnt_kern_flag |= MNTK_THR_SYNC;     /* new vsyncscan semantics */
1137  
1138         /*
1139          * required mount structure initializations
1140          */
1141         mp->mnt_stat.f_iosize = HAMMER2_PBUFSIZE;
1142         mp->mnt_stat.f_bsize = HAMMER2_PBUFSIZE;
1143  
1144         mp->mnt_vstat.f_frsize = HAMMER2_PBUFSIZE;
1145         mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1146  
1147         /*
1148          * Optional fields
1149          */
1150         mp->mnt_iosize_max = MAXPHYS;
1151
1152         /*
1153          * Connect up mount pointers.
1154          */
1155         hammer2_mount_helper(mp, pmp);
1156
1157         lockmgr(&hammer2_mntlk, LK_RELEASE);
1158
1159         /*
1160          * Finish setup
1161          */
1162         vfs_getnewfsid(mp);
1163         vfs_add_vnodeops(mp, &hammer2_vnode_vops, &mp->mnt_vn_norm_ops);
1164         vfs_add_vnodeops(mp, &hammer2_spec_vops, &mp->mnt_vn_spec_ops);
1165         vfs_add_vnodeops(mp, &hammer2_fifo_vops, &mp->mnt_vn_fifo_ops);
1166
1167         if (path) {
1168                 copyinstr(info.volume, mp->mnt_stat.f_mntfromname,
1169                           MNAMELEN - 1, &size);
1170                 bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
1171         } /* else root mount, already in there */
1172
1173         bzero(mp->mnt_stat.f_mntonname, sizeof(mp->mnt_stat.f_mntonname));
1174         if (path) {
1175                 copyinstr(path, mp->mnt_stat.f_mntonname,
1176                           sizeof(mp->mnt_stat.f_mntonname) - 1,
1177                           &size);
1178         } else {
1179                 /* root mount */
1180                 mp->mnt_stat.f_mntonname[0] = '/';
1181         }
1182
1183         /*
1184          * Initial statfs to prime mnt_stat.
1185          */
1186         hammer2_vfs_statfs(mp, &mp->mnt_stat, cred);
1187         
1188         return 0;
1189 }
1190
1191 /*
1192  * Scan PFSs under the super-root and create hammer2_pfs structures.
1193  */
1194 static
1195 void
1196 hammer2_update_pmps(hammer2_dev_t *hmp)
1197 {
1198         const hammer2_inode_data_t *ripdata;
1199         hammer2_chain_t *parent;
1200         hammer2_chain_t *chain;
1201         hammer2_blockref_t bref;
1202         hammer2_pfs_t *spmp;
1203         hammer2_pfs_t *pmp;
1204         hammer2_key_t key_next;
1205         int cache_index = -1;
1206
1207         /*
1208          * Lookup mount point under the media-localized super-root.
1209          *
1210          * cluster->pmp will incorrectly point to spmp and must be fixed
1211          * up later on.
1212          */
1213         spmp = hmp->spmp;
1214         hammer2_inode_lock(spmp->iroot, 0);
1215         parent = hammer2_inode_chain(spmp->iroot, 0, HAMMER2_RESOLVE_ALWAYS);
1216         chain = hammer2_chain_lookup(&parent, &key_next,
1217                                          HAMMER2_KEY_MIN, HAMMER2_KEY_MAX,
1218                                          &cache_index, 0);
1219         while (chain) {
1220                 if (chain->bref.type != HAMMER2_BREF_TYPE_INODE)
1221                         continue;
1222                 ripdata = &chain->data->ipdata;
1223                 bref = chain->bref;
1224                 kprintf("ADD LOCAL PFS: %s\n", ripdata->filename);
1225
1226                 pmp = hammer2_pfsalloc(chain, ripdata, bref.modify_tid);
1227                 chain = hammer2_chain_next(&parent, chain, &key_next,
1228                                            key_next, HAMMER2_KEY_MAX,
1229                                            &cache_index, 0);
1230         }
1231         if (parent) {
1232                 hammer2_chain_unlock(parent);
1233                 hammer2_chain_drop(parent);
1234         }
1235         hammer2_inode_unlock(spmp->iroot);
1236 }
1237
1238 static
1239 int
1240 hammer2_remount(hammer2_dev_t *hmp, struct mount *mp, char *path __unused,
1241                 struct vnode *devvp, struct ucred *cred)
1242 {
1243         int error;
1244
1245         if (hmp->ronly && (mp->mnt_kern_flag & MNTK_WANTRDWR)) {
1246                 error = hammer2_recovery(hmp);
1247         } else {
1248                 error = 0;
1249         }
1250         return error;
1251 }
1252
1253 static
1254 int
1255 hammer2_vfs_unmount(struct mount *mp, int mntflags)
1256 {
1257         hammer2_pfs_t *pmp;
1258         int flags;
1259         int error = 0;
1260
1261         pmp = MPTOPMP(mp);
1262
1263         if (pmp == NULL)
1264                 return(0);
1265
1266         lockmgr(&hammer2_mntlk, LK_EXCLUSIVE);
1267
1268         /*
1269          * If mount initialization proceeded far enough we must flush
1270          * its vnodes and sync the underlying mount points.  Three syncs
1271          * are required to fully flush the filesystem (freemap updates lag
1272          * by one flush, and one extra for safety).
1273          */
1274         if (mntflags & MNT_FORCE)
1275                 flags = FORCECLOSE;
1276         else
1277                 flags = 0;
1278         if (pmp->iroot) {
1279                 error = vflush(mp, 0, flags);
1280                 if (error)
1281                         goto failed;
1282                 hammer2_vfs_sync(mp, MNT_WAIT);
1283                 hammer2_vfs_sync(mp, MNT_WAIT);
1284                 hammer2_vfs_sync(mp, MNT_WAIT);
1285         }
1286
1287         /*
1288          * Cleanup the frontend support XOPS threads
1289          */
1290         hammer2_xop_helper_cleanup(pmp);
1291
1292         /*
1293          * Cleanup our reference on ihidden.
1294          */
1295         if (pmp->ihidden) {
1296                 hammer2_inode_drop(pmp->ihidden);
1297                 pmp->ihidden = NULL;
1298         }
1299         if (pmp->mp)
1300                 hammer2_unmount_helper(mp, pmp, NULL);
1301
1302         error = 0;
1303 failed:
1304         lockmgr(&hammer2_mntlk, LK_RELEASE);
1305
1306         return (error);
1307 }
1308
1309 /*
1310  * Mount helper, hook the system mount into our PFS.
1311  * The mount lock is held.
1312  *
1313  * We must bump the mount_count on related devices for any
1314  * mounted PFSs.
1315  */
1316 static
1317 void
1318 hammer2_mount_helper(struct mount *mp, hammer2_pfs_t *pmp)
1319 {
1320         hammer2_cluster_t *cluster;
1321         hammer2_chain_t *rchain;
1322         int i;
1323
1324         mp->mnt_data = (qaddr_t)pmp;
1325         pmp->mp = mp;
1326
1327         /*
1328          * After pmp->mp is set we have to adjust hmp->mount_count.
1329          */
1330         cluster = &pmp->iroot->cluster;
1331         for (i = 0; i < cluster->nchains; ++i) {
1332                 rchain = cluster->array[i].chain;
1333                 if (rchain == NULL)
1334                         continue;
1335                 ++rchain->hmp->mount_count;
1336                 kprintf("hammer2_mount hmp=%p ++mount_count=%d\n",
1337                         rchain->hmp, rchain->hmp->mount_count);
1338         }
1339
1340         /*
1341          * Create missing Xop threads
1342          */
1343         hammer2_xop_helper_create(pmp);
1344 }
1345
1346 /*
1347  * Mount helper, unhook the system mount from our PFS.
1348  * The mount lock is held.
1349  *
1350  * If hmp is supplied a mount responsible for being the first to open
1351  * the block device failed and the block device and all PFSs using the
1352  * block device must be cleaned up.
1353  *
1354  * If pmp is supplied multiple devices might be backing the PFS and each
1355  * must be disconnect.  This might not be the last PFS using some of the
1356  * underlying devices.  Also, we have to adjust our hmp->mount_count
1357  * accounting for the devices backing the pmp which is now undergoing an
1358  * unmount.
1359  */
1360 static
1361 void
1362 hammer2_unmount_helper(struct mount *mp, hammer2_pfs_t *pmp, hammer2_dev_t *hmp)
1363 {
1364         hammer2_cluster_t *cluster;
1365         hammer2_chain_t *rchain;
1366         struct vnode *devvp;
1367         int dumpcnt;
1368         int ronly = 0;
1369         int i;
1370
1371         /*
1372          * If no device supplied this is a high-level unmount and we have to
1373          * to disconnect the mount, adjust mount_count, and locate devices
1374          * that might now have no mounts.
1375          */
1376         if (pmp) {
1377                 KKASSERT(hmp == NULL);
1378                 KKASSERT((void *)(intptr_t)mp->mnt_data == pmp);
1379                 pmp->mp = NULL;
1380                 mp->mnt_data = NULL;
1381
1382                 /*
1383                  * After pmp->mp is cleared we have to account for
1384                  * mount_count.
1385                  */
1386                 cluster = &pmp->iroot->cluster;
1387                 for (i = 0; i < cluster->nchains; ++i) {
1388                         rchain = cluster->array[i].chain;
1389                         if (rchain == NULL)
1390                                 continue;
1391                         --rchain->hmp->mount_count;
1392                         kprintf("hammer2_unmount hmp=%p --mount_count=%d\n",
1393                                 rchain->hmp, rchain->hmp->mount_count);
1394                         /* scrapping hmp now may invalidate the pmp */
1395                 }
1396 again:
1397                 TAILQ_FOREACH(hmp, &hammer2_mntlist, mntentry) {
1398                         if (hmp->mount_count == 0) {
1399                                 hammer2_unmount_helper(NULL, NULL, hmp);
1400                                 goto again;
1401                         }
1402                 }
1403                 return;
1404         }
1405
1406         /*
1407          * Try to terminate the block device.  We can't terminate it if
1408          * there are still PFSs referencing it.
1409          */
1410         kprintf("hammer2_unmount hmp=%p mount_count=%d\n",
1411                 hmp, hmp->mount_count);
1412         if (hmp->mount_count)
1413                 return;
1414
1415         hammer2_pfsfree_scan(hmp);
1416         hammer2_dev_exlock(hmp);        /* XXX order */
1417
1418         /*
1419          * Cycle the volume data lock as a safety (probably not needed any
1420          * more).  To ensure everything is out we need to flush at least
1421          * three times.  (1) The running of the unlinkq can dirty the
1422          * filesystem, (2) A normal flush can dirty the freemap, and
1423          * (3) ensure that the freemap is fully synchronized.
1424          *
1425          * The next mount's recovery scan can clean everything up but we want
1426          * to leave the filesystem in a 100% clean state on a normal unmount.
1427          */
1428 #if 0
1429         hammer2_voldata_lock(hmp);
1430         hammer2_voldata_unlock(hmp);
1431 #endif
1432         hammer2_iocom_uninit(hmp);
1433
1434         if ((hmp->vchain.flags | hmp->fchain.flags) &
1435             HAMMER2_CHAIN_FLUSH_MASK) {
1436                 kprintf("hammer2_unmount: chains left over "
1437                         "after final sync\n");
1438                 kprintf("    vchain %08x\n", hmp->vchain.flags);
1439                 kprintf("    fchain %08x\n", hmp->fchain.flags);
1440
1441                 if (hammer2_debug & 0x0010)
1442                         Debugger("entered debugger");
1443         }
1444
1445         KKASSERT(hmp->spmp == NULL);
1446
1447         /*
1448          * Finish up with the device vnode
1449          */
1450         if ((devvp = hmp->devvp) != NULL) {
1451                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1452                 vinvalbuf(devvp, (ronly ? 0 : V_SAVE), 0, 0);
1453                 hmp->devvp = NULL;
1454                 VOP_CLOSE(devvp, (ronly ? FREAD : FREAD|FWRITE), NULL);
1455                 vn_unlock(devvp);
1456                 vrele(devvp);
1457                 devvp = NULL;
1458         }
1459
1460         /*
1461          * Clear vchain/fchain flags that might prevent final cleanup
1462          * of these chains.
1463          */
1464         if (hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) {
1465                 atomic_clear_int(&hmp->vchain.flags,
1466                                  HAMMER2_CHAIN_MODIFIED);
1467                 hammer2_pfs_memory_wakeup(hmp->vchain.pmp);
1468                 hammer2_chain_drop(&hmp->vchain);
1469         }
1470         if (hmp->vchain.flags & HAMMER2_CHAIN_UPDATE) {
1471                 atomic_clear_int(&hmp->vchain.flags,
1472                                  HAMMER2_CHAIN_UPDATE);
1473                 hammer2_chain_drop(&hmp->vchain);
1474         }
1475
1476         if (hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) {
1477                 atomic_clear_int(&hmp->fchain.flags,
1478                                  HAMMER2_CHAIN_MODIFIED);
1479                 hammer2_pfs_memory_wakeup(hmp->fchain.pmp);
1480                 hammer2_chain_drop(&hmp->fchain);
1481         }
1482         if (hmp->fchain.flags & HAMMER2_CHAIN_UPDATE) {
1483                 atomic_clear_int(&hmp->fchain.flags,
1484                                  HAMMER2_CHAIN_UPDATE);
1485                 hammer2_chain_drop(&hmp->fchain);
1486         }
1487
1488         /*
1489          * Final drop of embedded freemap root chain to
1490          * clean up fchain.core (fchain structure is not
1491          * flagged ALLOCATED so it is cleaned out and then
1492          * left to rot).
1493          */
1494         hammer2_chain_drop(&hmp->fchain);
1495
1496         /*
1497          * Final drop of embedded volume root chain to clean
1498          * up vchain.core (vchain structure is not flagged
1499          * ALLOCATED so it is cleaned out and then left to
1500          * rot).
1501          */
1502         dumpcnt = 50;
1503         hammer2_dump_chain(&hmp->vchain, 0, &dumpcnt, 'v');
1504         dumpcnt = 50;
1505         hammer2_dump_chain(&hmp->fchain, 0, &dumpcnt, 'f');
1506         hammer2_dev_unlock(hmp);
1507         hammer2_chain_drop(&hmp->vchain);
1508
1509         hammer2_io_cleanup(hmp, &hmp->iotree);
1510         if (hmp->iofree_count) {
1511                 kprintf("io_cleanup: %d I/O's left hanging\n",
1512                         hmp->iofree_count);
1513         }
1514
1515         TAILQ_REMOVE(&hammer2_mntlist, hmp, mntentry);
1516         kmalloc_destroy(&hmp->mchain);
1517         kfree(hmp, M_HAMMER2);
1518 }
1519
1520 static
1521 int
1522 hammer2_vfs_vget(struct mount *mp, struct vnode *dvp,
1523              ino_t ino, struct vnode **vpp)
1524 {
1525         kprintf("hammer2_vget\n");
1526         return (EOPNOTSUPP);
1527 }
1528
1529 static
1530 int
1531 hammer2_vfs_root(struct mount *mp, struct vnode **vpp)
1532 {
1533         hammer2_pfs_t *pmp;
1534         int error;
1535         struct vnode *vp;
1536
1537         pmp = MPTOPMP(mp);
1538         if (pmp->iroot == NULL) {
1539                 *vpp = NULL;
1540                 return EINVAL;
1541         }
1542
1543         error = 0;
1544         hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
1545
1546         while (pmp->inode_tid == 0) {
1547                 hammer2_xop_ipcluster_t *xop;
1548                 hammer2_inode_meta_t *meta;
1549
1550                 xop = hammer2_xop_alloc(pmp->iroot, HAMMER2_XOP_MODIFYING);
1551                 hammer2_xop_start(&xop->head, hammer2_xop_ipcluster);
1552                 error = hammer2_xop_collect(&xop->head, 0);
1553
1554                 if (error == 0) {
1555                         meta = &xop->head.cluster.focus->data->ipdata.meta;
1556                         pmp->iroot->meta = *meta;
1557                         pmp->inode_tid = meta->pfs_inum + 1;
1558                         if (pmp->inode_tid < HAMMER2_INODE_START)
1559                                 pmp->inode_tid = HAMMER2_INODE_START;
1560                         pmp->modify_tid =
1561                                 xop->head.cluster.focus->bref.modify_tid + 1;
1562                         kprintf("PFS: Starting inode %jd\n",
1563                                 (intmax_t)pmp->inode_tid);
1564                         kprintf("PMP focus good set nextino=%ld mod=%016jx\n",
1565                                 pmp->inode_tid, pmp->modify_tid);
1566                         wakeup(&pmp->iroot);
1567
1568                         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1569
1570                         /*
1571                          * Prime the mount info.
1572                          */
1573                         hammer2_vfs_statfs(mp, &mp->mnt_stat, NULL);
1574
1575                         /*
1576                          * With the cluster operational, check for and
1577                          * install ihidden if needed.  The install_hidden
1578                          * code needs to get a transaction so we must unlock
1579                          * iroot around it.
1580                          *
1581                          * This is only applicable PFS mounts, there is no
1582                          * hidden directory in the spmp.
1583                          */
1584                         hammer2_inode_unlock(pmp->iroot);
1585                         hammer2_inode_install_hidden(pmp);
1586                         hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
1587
1588                         break;
1589                 }
1590
1591                 /*
1592                  * Loop, try again
1593                  */
1594                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1595                 hammer2_inode_unlock(pmp->iroot);
1596                 error = tsleep(&pmp->iroot, PCATCH, "h2root", hz);
1597                 hammer2_inode_lock(pmp->iroot, HAMMER2_RESOLVE_SHARED);
1598                 if (error == EINTR)
1599                         break;
1600         }
1601
1602         if (error) {
1603                 hammer2_inode_unlock(pmp->iroot);
1604                 *vpp = NULL;
1605         } else {
1606                 vp = hammer2_igetv(pmp->iroot, &error);
1607                 hammer2_inode_unlock(pmp->iroot);
1608                 *vpp = vp;
1609         }
1610
1611         return (error);
1612 }
1613
1614 /*
1615  * Filesystem status
1616  *
1617  * XXX incorporate ipdata->meta.inode_quota and data_quota
1618  */
1619 static
1620 int
1621 hammer2_vfs_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred)
1622 {
1623         hammer2_pfs_t *pmp;
1624         hammer2_dev_t *hmp;
1625         hammer2_blockref_t bref;
1626         int i;
1627
1628         /*
1629          * NOTE: iroot might not have validated the cluster yet.
1630          */
1631         pmp = MPTOPMP(mp);
1632
1633         mp->mnt_stat.f_files = 0;
1634         mp->mnt_stat.f_ffree = 0;
1635         mp->mnt_stat.f_blocks = 0;
1636         mp->mnt_stat.f_bfree = 0;
1637         mp->mnt_stat.f_bavail = 0;
1638
1639         for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
1640                 hmp = pmp->pfs_hmps[i];
1641                 if (hmp == NULL)
1642                         continue;
1643                 if (pmp->iroot->cluster.array[i].chain)
1644                         bref = pmp->iroot->cluster.array[i].chain->bref;
1645                 else
1646                         bzero(&bref, sizeof(bref));
1647
1648                 mp->mnt_stat.f_files = bref.inode_count;
1649                 mp->mnt_stat.f_ffree = 0;
1650                 mp->mnt_stat.f_blocks = (bref.data_count +
1651                                          hmp->voldata.allocator_free) /
1652                                         mp->mnt_vstat.f_bsize;
1653                 mp->mnt_stat.f_bfree =  hmp->voldata.allocator_free /
1654                                         mp->mnt_vstat.f_bsize;
1655                 mp->mnt_stat.f_bavail = mp->mnt_stat.f_bfree;
1656
1657                 *sbp = mp->mnt_stat;
1658         }
1659         return (0);
1660 }
1661
1662 static
1663 int
1664 hammer2_vfs_statvfs(struct mount *mp, struct statvfs *sbp, struct ucred *cred)
1665 {
1666         hammer2_pfs_t *pmp;
1667         hammer2_dev_t *hmp;
1668         hammer2_blockref_t bref;
1669         int i;
1670
1671         /*
1672          * NOTE: iroot might not have validated the cluster yet.
1673          */
1674         pmp = MPTOPMP(mp);
1675
1676         mp->mnt_vstat.f_bsize = 0;
1677         mp->mnt_vstat.f_files = 0;
1678         mp->mnt_vstat.f_ffree = 0;
1679         mp->mnt_vstat.f_blocks = 0;
1680         mp->mnt_vstat.f_bfree = 0;
1681         mp->mnt_vstat.f_bavail = 0;
1682
1683         for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
1684                 hmp = pmp->pfs_hmps[i];
1685                 if (hmp == NULL)
1686                         continue;
1687                 if (pmp->iroot->cluster.array[i].chain)
1688                         bref = pmp->iroot->cluster.array[i].chain->bref;
1689                 else
1690                         bzero(&bref, sizeof(bref));
1691
1692                 mp->mnt_vstat.f_bsize = HAMMER2_PBUFSIZE;
1693                 mp->mnt_vstat.f_files = bref.inode_count;
1694                 mp->mnt_vstat.f_ffree = 0;
1695                 mp->mnt_vstat.f_blocks = (bref.data_count +
1696                                          hmp->voldata.allocator_free) /
1697                                         mp->mnt_vstat.f_bsize;
1698                 mp->mnt_vstat.f_bfree = hmp->voldata.allocator_free /
1699                                         mp->mnt_vstat.f_bsize;
1700                 mp->mnt_vstat.f_bavail = mp->mnt_vstat.f_bfree;
1701
1702                 *sbp = mp->mnt_vstat;
1703         }
1704         return (0);
1705 }
1706
1707 /*
1708  * Mount-time recovery (RW mounts)
1709  *
1710  * Updates to the free block table are allowed to lag flushes by one
1711  * transaction.  In case of a crash, then on a fresh mount we must do an
1712  * incremental scan of the last committed transaction id and make sure that
1713  * all related blocks have been marked allocated.
1714  *
1715  * The super-root topology and each PFS has its own transaction id domain,
1716  * so we must track PFS boundary transitions.
1717  */
1718 struct hammer2_recovery_elm {
1719         TAILQ_ENTRY(hammer2_recovery_elm) entry;
1720         hammer2_chain_t *chain;
1721         hammer2_tid_t sync_tid;
1722 };
1723
1724 TAILQ_HEAD(hammer2_recovery_list, hammer2_recovery_elm);
1725
1726 struct hammer2_recovery_info {
1727         struct hammer2_recovery_list list;
1728         hammer2_tid_t   mtid;
1729         int     depth;
1730 };
1731
1732 static int hammer2_recovery_scan(hammer2_dev_t *hmp,
1733                         hammer2_chain_t *parent,
1734                         struct hammer2_recovery_info *info,
1735                         hammer2_tid_t sync_tid);
1736
1737 #define HAMMER2_RECOVERY_MAXDEPTH       10
1738
1739 static
1740 int
1741 hammer2_recovery(hammer2_dev_t *hmp)
1742 {
1743         struct hammer2_recovery_info info;
1744         struct hammer2_recovery_elm *elm;
1745         hammer2_chain_t *parent;
1746         hammer2_tid_t sync_tid;
1747         hammer2_tid_t mirror_tid;
1748         int error;
1749         int cumulative_error = 0;
1750
1751         hammer2_trans_init(hmp->spmp, 0);
1752
1753         sync_tid = hmp->voldata.freemap_tid;
1754         mirror_tid = hmp->voldata.mirror_tid;
1755
1756         kprintf("hammer2 mount \"%s\": ", hmp->devrepname);
1757         if (sync_tid >= mirror_tid) {
1758                 kprintf(" no recovery needed\n");
1759         } else {
1760                 kprintf(" freemap recovery %016jx-%016jx\n",
1761                         sync_tid + 1, mirror_tid);
1762         }
1763
1764         TAILQ_INIT(&info.list);
1765         info.depth = 0;
1766         parent = hammer2_chain_lookup_init(&hmp->vchain, 0);
1767         cumulative_error = hammer2_recovery_scan(hmp, parent,
1768                                                  &info, sync_tid);
1769         hammer2_chain_lookup_done(parent);
1770
1771         while ((elm = TAILQ_FIRST(&info.list)) != NULL) {
1772                 TAILQ_REMOVE(&info.list, elm, entry);
1773                 parent = elm->chain;
1774                 sync_tid = elm->sync_tid;
1775                 kfree(elm, M_HAMMER2);
1776
1777                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1778                 error = hammer2_recovery_scan(hmp, parent,
1779                                               &info, hmp->voldata.freemap_tid);
1780                 hammer2_chain_unlock(parent);
1781                 hammer2_chain_drop(parent);     /* drop elm->chain ref */
1782                 if (error)
1783                         cumulative_error = error;
1784         }
1785         hammer2_trans_done(hmp->spmp);
1786
1787         return cumulative_error;
1788 }
1789
1790 static
1791 int
1792 hammer2_recovery_scan(hammer2_dev_t *hmp, hammer2_chain_t *parent,
1793                       struct hammer2_recovery_info *info,
1794                       hammer2_tid_t sync_tid)
1795 {
1796         const hammer2_inode_data_t *ripdata;
1797         hammer2_chain_t *chain;
1798         int cache_index;
1799         int cumulative_error = 0;
1800         int error;
1801
1802         /*
1803          * Adjust freemap to ensure that the block(s) are marked allocated.
1804          */
1805         if (parent->bref.type != HAMMER2_BREF_TYPE_VOLUME) {
1806                 hammer2_freemap_adjust(hmp, &parent->bref,
1807                                        HAMMER2_FREEMAP_DORECOVER);
1808         }
1809
1810         /*
1811          * Check type for recursive scan
1812          */
1813         switch(parent->bref.type) {
1814         case HAMMER2_BREF_TYPE_VOLUME:
1815                 /* data already instantiated */
1816                 break;
1817         case HAMMER2_BREF_TYPE_INODE:
1818                 /*
1819                  * Must instantiate data for DIRECTDATA test and also
1820                  * for recursion.
1821                  */
1822                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1823                 ripdata = &hammer2_chain_rdata(parent)->ipdata;
1824                 if (ripdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1825                         /* not applicable to recovery scan */
1826                         hammer2_chain_unlock(parent);
1827                         return 0;
1828                 }
1829                 hammer2_chain_unlock(parent);
1830                 break;
1831         case HAMMER2_BREF_TYPE_INDIRECT:
1832                 /*
1833                  * Must instantiate data for recursion
1834                  */
1835                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1836                 hammer2_chain_unlock(parent);
1837                 break;
1838         case HAMMER2_BREF_TYPE_DATA:
1839         case HAMMER2_BREF_TYPE_FREEMAP:
1840         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1841         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1842                 /* not applicable to recovery scan */
1843                 return 0;
1844                 break;
1845         default:
1846                 return EDOM;
1847         }
1848
1849         /*
1850          * Defer operation if depth limit reached or if we are crossing a
1851          * PFS boundary.
1852          */
1853         if (info->depth >= HAMMER2_RECOVERY_MAXDEPTH) {
1854                 struct hammer2_recovery_elm *elm;
1855
1856                 elm = kmalloc(sizeof(*elm), M_HAMMER2, M_ZERO | M_WAITOK);
1857                 elm->chain = parent;
1858                 elm->sync_tid = sync_tid;
1859                 hammer2_chain_ref(parent);
1860                 TAILQ_INSERT_TAIL(&info->list, elm, entry);
1861                 /* unlocked by caller */
1862
1863                 return(0);
1864         }
1865
1866
1867         /*
1868          * Recursive scan of the last flushed transaction only.  We are
1869          * doing this without pmp assignments so don't leave the chains
1870          * hanging around after we are done with them.
1871          */
1872         cache_index = 0;
1873         chain = hammer2_chain_scan(parent, NULL, &cache_index,
1874                                    HAMMER2_LOOKUP_NODATA);
1875         while (chain) {
1876                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
1877                 if (chain->bref.mirror_tid > sync_tid) {
1878                         ++info->depth;
1879                         error = hammer2_recovery_scan(hmp, chain,
1880                                                       info, sync_tid);
1881                         --info->depth;
1882                         if (error)
1883                                 cumulative_error = error;
1884                 }
1885
1886                 /*
1887                  * Flush the recovery at the PFS boundary to stage it for
1888                  * the final flush of the super-root topology.
1889                  */
1890                 if ((chain->bref.flags & HAMMER2_BREF_FLAG_PFSROOT) &&
1891                     (chain->flags & HAMMER2_CHAIN_ONFLUSH)) {
1892                         hammer2_flush(chain, info->mtid, 1);
1893                 }
1894                 chain = hammer2_chain_scan(parent, chain, &cache_index,
1895                                            HAMMER2_LOOKUP_NODATA);
1896         }
1897
1898         return cumulative_error;
1899 }
1900
1901 /*
1902  * Sync a mount point; this is called on a per-mount basis from the
1903  * filesystem syncer process periodically and whenever a user issues
1904  * a sync.
1905  */
1906 int
1907 hammer2_vfs_sync(struct mount *mp, int waitfor)
1908 {
1909         hammer2_xop_flush_t *xop;
1910         struct hammer2_sync_info info;
1911         hammer2_inode_t *iroot;
1912         hammer2_pfs_t *pmp;
1913         int flags;
1914         int error;
1915
1916         pmp = MPTOPMP(mp);
1917         iroot = pmp->iroot;
1918         KKASSERT(iroot);
1919         KKASSERT(iroot->pmp == pmp);
1920
1921         /*
1922          * We can't acquire locks on existing vnodes while in a transaction
1923          * without risking a deadlock.  This assumes that vfsync() can be
1924          * called without the vnode locked (which it can in DragonFly).
1925          * Otherwise we'd have to implement a multi-pass or flag the lock
1926          * failures and retry.
1927          *
1928          * The reclamation code interlocks with the sync list's token
1929          * (by removing the vnode from the scan list) before unlocking
1930          * the inode, giving us time to ref the inode.
1931          */
1932         /*flags = VMSC_GETVP;*/
1933         flags = 0;
1934         if (waitfor & MNT_LAZY)
1935                 flags |= VMSC_ONEPASS;
1936
1937 #if 0
1938         /*
1939          * Preflush the vnodes using a normal transaction before interlocking
1940          * with a flush transaction.
1941          */
1942         hammer2_trans_init(pmp, 0);
1943         info.error = 0;
1944         info.waitfor = MNT_NOWAIT;
1945         vsyncscan(mp, flags | VMSC_NOWAIT, hammer2_sync_scan2, &info);
1946         hammer2_trans_done(pmp);
1947 #endif
1948
1949         /*
1950          * Start our flush transaction.  This does not return until all
1951          * concurrent transactions have completed and will prevent any
1952          * new transactions from running concurrently, except for the
1953          * buffer cache transactions.
1954          *
1955          * For efficiency do an async pass before making sure with a
1956          * synchronous pass on all related buffer cache buffers.  It
1957          * should theoretically not be possible for any new file buffers
1958          * to be instantiated during this sequence.
1959          */
1960         hammer2_trans_init(pmp, HAMMER2_TRANS_ISFLUSH |
1961                                 HAMMER2_TRANS_PREFLUSH);
1962         hammer2_inode_run_unlinkq(pmp);
1963
1964         info.error = 0;
1965         info.waitfor = MNT_NOWAIT;
1966         vsyncscan(mp, flags | VMSC_NOWAIT, hammer2_sync_scan2, &info);
1967         info.waitfor = MNT_WAIT;
1968         vsyncscan(mp, flags, hammer2_sync_scan2, &info);
1969
1970         /*
1971          * Clear PREFLUSH.  This prevents (or asserts on) any new logical
1972          * buffer cache flushes which occur during the flush.  Device buffers
1973          * are not affected.
1974          */
1975         hammer2_bioq_sync(pmp);
1976         hammer2_trans_clear_preflush(pmp);
1977
1978         /*
1979          * Use the XOP interface to concurrently flush all nodes to
1980          * synchronize the PFSROOT subtopology to the media.  A standard
1981          * end-of-scan ENOENT error indicates cluster sufficiency.
1982          *
1983          * Note that this flush will not be visible on crash recovery until
1984          * we flush the super-root topology in the next loop.
1985          *
1986          * XXX For now wait for all flushes to complete.
1987          */
1988         if (iroot) {
1989                 xop = hammer2_xop_alloc(iroot, HAMMER2_XOP_MODIFYING);
1990                 hammer2_xop_start(&xop->head, hammer2_inode_xop_flush);
1991                 error = hammer2_xop_collect(&xop->head,
1992                                             HAMMER2_XOP_COLLECT_WAITALL);
1993                 if (error == ENOENT)
1994                         error = 0;
1995         } else {
1996                 error = 0;
1997         }
1998         hammer2_trans_done(pmp);
1999
2000         return (error);
2001 }
2002
2003 /*
2004  * Sync passes.
2005  *
2006  * Note that we ignore the tranasction mtid we got above.  Instead,
2007  * each vfsync below will ultimately get its own via TRANS_BUFCACHE
2008  * transactions.
2009  */
2010 static int
2011 hammer2_sync_scan2(struct mount *mp, struct vnode *vp, void *data)
2012 {
2013         struct hammer2_sync_info *info = data;
2014         hammer2_inode_t *ip;
2015         int error;
2016
2017         /*
2018          * Degenerate cases.  Note that ip == NULL typically means the
2019          * syncer vnode itself and we don't want to vclrisdirty() in that
2020          * situation.
2021          */
2022         ip = VTOI(vp);
2023         if (ip == NULL) {
2024                 return(0);
2025         }
2026         if (vp->v_type == VNON || vp->v_type == VBAD) {
2027                 vclrisdirty(vp);
2028                 return(0);
2029         }
2030
2031         /*
2032          * VOP_FSYNC will start a new transaction so replicate some code
2033          * here to do it inline (see hammer2_vop_fsync()).
2034          *
2035          * WARNING: The vfsync interacts with the buffer cache and might
2036          *          block, we can't hold the inode lock at that time.
2037          *          However, we MUST ref ip before blocking to ensure that
2038          *          it isn't ripped out from under us (since we do not
2039          *          hold a lock on the vnode).
2040          */
2041         hammer2_inode_ref(ip);
2042         if ((ip->flags & HAMMER2_INODE_MODIFIED) ||
2043             !RB_EMPTY(&vp->v_rbdirty_tree)) {
2044                 vfsync(vp, info->waitfor, 1, NULL, NULL);
2045                 hammer2_inode_fsync(ip);
2046         }
2047         if ((ip->flags & HAMMER2_INODE_MODIFIED) == 0 &&
2048             RB_EMPTY(&vp->v_rbdirty_tree)) {
2049                 vclrisdirty(vp);
2050         }
2051
2052         hammer2_inode_drop(ip);
2053 #if 1
2054         error = 0;
2055         if (error)
2056                 info->error = error;
2057 #endif
2058         return(0);
2059 }
2060
2061 static
2062 int
2063 hammer2_vfs_vptofh(struct vnode *vp, struct fid *fhp)
2064 {
2065         return (0);
2066 }
2067
2068 static
2069 int
2070 hammer2_vfs_fhtovp(struct mount *mp, struct vnode *rootvp,
2071                struct fid *fhp, struct vnode **vpp)
2072 {
2073         return (0);
2074 }
2075
2076 static
2077 int
2078 hammer2_vfs_checkexp(struct mount *mp, struct sockaddr *nam,
2079                  int *exflagsp, struct ucred **credanonp)
2080 {
2081         return (0);
2082 }
2083
2084 /*
2085  * Support code for hammer2_vfs_mount().  Read, verify, and install the volume
2086  * header into the HMP
2087  *
2088  * XXX read four volhdrs and use the one with the highest TID whos CRC
2089  *     matches.
2090  *
2091  * XXX check iCRCs.
2092  *
2093  * XXX For filesystems w/ less than 4 volhdrs, make sure to not write to
2094  *     nonexistant locations.
2095  *
2096  * XXX Record selected volhdr and ring updates to each of 4 volhdrs
2097  */
2098 static
2099 int
2100 hammer2_install_volume_header(hammer2_dev_t *hmp)
2101 {
2102         hammer2_volume_data_t *vd;
2103         struct buf *bp;
2104         hammer2_crc32_t crc0, crc, bcrc0, bcrc;
2105         int error_reported;
2106         int error;
2107         int valid;
2108         int i;
2109
2110         error_reported = 0;
2111         error = 0;
2112         valid = 0;
2113         bp = NULL;
2114
2115         /*
2116          * There are up to 4 copies of the volume header (syncs iterate
2117          * between them so there is no single master).  We don't trust the
2118          * volu_size field so we don't know precisely how large the filesystem
2119          * is, so depend on the OS to return an error if we go beyond the
2120          * block device's EOF.
2121          */
2122         for (i = 0; i < HAMMER2_NUM_VOLHDRS; i++) {
2123                 error = bread(hmp->devvp, i * HAMMER2_ZONE_BYTES64,
2124                               HAMMER2_VOLUME_BYTES, &bp);
2125                 if (error) {
2126                         brelse(bp);
2127                         bp = NULL;
2128                         continue;
2129                 }
2130
2131                 vd = (struct hammer2_volume_data *) bp->b_data;
2132                 if ((vd->magic != HAMMER2_VOLUME_ID_HBO) &&
2133                     (vd->magic != HAMMER2_VOLUME_ID_ABO)) {
2134                         brelse(bp);
2135                         bp = NULL;
2136                         continue;
2137                 }
2138
2139                 if (vd->magic == HAMMER2_VOLUME_ID_ABO) {
2140                         /* XXX: Reversed-endianness filesystem */
2141                         kprintf("hammer2: reverse-endian filesystem detected");
2142                         brelse(bp);
2143                         bp = NULL;
2144                         continue;
2145                 }
2146
2147                 crc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT0];
2148                 crc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC0_OFF,
2149                                       HAMMER2_VOLUME_ICRC0_SIZE);
2150                 bcrc = vd->icrc_sects[HAMMER2_VOL_ICRC_SECT1];
2151                 bcrc0 = hammer2_icrc32(bp->b_data + HAMMER2_VOLUME_ICRC1_OFF,
2152                                        HAMMER2_VOLUME_ICRC1_SIZE);
2153                 if ((crc0 != crc) || (bcrc0 != bcrc)) {
2154                         kprintf("hammer2 volume header crc "
2155                                 "mismatch copy #%d %08x/%08x\n",
2156                                 i, crc0, crc);
2157                         error_reported = 1;
2158                         brelse(bp);
2159                         bp = NULL;
2160                         continue;
2161                 }
2162                 if (valid == 0 || hmp->voldata.mirror_tid < vd->mirror_tid) {
2163                         valid = 1;
2164                         hmp->voldata = *vd;
2165                         hmp->volhdrno = i;
2166                 }
2167                 brelse(bp);
2168                 bp = NULL;
2169         }
2170         if (valid) {
2171                 hmp->volsync = hmp->voldata;
2172                 error = 0;
2173                 if (error_reported || bootverbose || 1) { /* 1/DEBUG */
2174                         kprintf("hammer2: using volume header #%d\n",
2175                                 hmp->volhdrno);
2176                 }
2177         } else {
2178                 error = EINVAL;
2179                 kprintf("hammer2: no valid volume headers found!\n");
2180         }
2181         return (error);
2182 }
2183
2184 /*
2185  * This handles hysteresis on regular file flushes.  Because the BIOs are
2186  * routed to a thread it is possible for an excessive number to build up
2187  * and cause long front-end stalls long before the runningbuffspace limit
2188  * is hit, so we implement hammer2_flush_pipe to control the
2189  * hysteresis.
2190  *
2191  * This is a particular problem when compression is used.
2192  */
2193 void
2194 hammer2_lwinprog_ref(hammer2_pfs_t *pmp)
2195 {
2196         atomic_add_int(&pmp->count_lwinprog, 1);
2197 }
2198
2199 void
2200 hammer2_lwinprog_drop(hammer2_pfs_t *pmp)
2201 {
2202         int lwinprog;
2203
2204         lwinprog = atomic_fetchadd_int(&pmp->count_lwinprog, -1);
2205         if ((lwinprog & HAMMER2_LWINPROG_WAITING) &&
2206             (lwinprog & HAMMER2_LWINPROG_MASK) <= hammer2_flush_pipe * 2 / 3) {
2207                 atomic_clear_int(&pmp->count_lwinprog,
2208                                  HAMMER2_LWINPROG_WAITING);
2209                 wakeup(&pmp->count_lwinprog);
2210         }
2211         if ((lwinprog & HAMMER2_LWINPROG_WAITING0) &&
2212             (lwinprog & HAMMER2_LWINPROG_MASK) <= 0) {
2213                 atomic_clear_int(&pmp->count_lwinprog,
2214                                  HAMMER2_LWINPROG_WAITING0);
2215                 wakeup(&pmp->count_lwinprog);
2216         }
2217 }
2218
2219 void
2220 hammer2_lwinprog_wait(hammer2_pfs_t *pmp, int flush_pipe)
2221 {
2222         int lwinprog;
2223         int lwflag = (flush_pipe) ? HAMMER2_LWINPROG_WAITING :
2224                                     HAMMER2_LWINPROG_WAITING0;
2225
2226         for (;;) {
2227                 lwinprog = pmp->count_lwinprog;
2228                 cpu_ccfence();
2229                 if ((lwinprog & HAMMER2_LWINPROG_MASK) <= flush_pipe)
2230                         break;
2231                 tsleep_interlock(&pmp->count_lwinprog, 0);
2232                 atomic_set_int(&pmp->count_lwinprog, lwflag);
2233                 lwinprog = pmp->count_lwinprog;
2234                 if ((lwinprog & HAMMER2_LWINPROG_MASK) <= flush_pipe)
2235                         break;
2236                 tsleep(&pmp->count_lwinprog, PINTERLOCKED, "h2wpipe", hz);
2237         }
2238 }
2239
2240 /*
2241  * Manage excessive memory resource use for chain and related
2242  * structures.
2243  */
2244 void
2245 hammer2_pfs_memory_wait(hammer2_pfs_t *pmp)
2246 {
2247         uint32_t waiting;
2248         uint32_t count;
2249         uint32_t limit;
2250 #if 0
2251         static int zzticks;
2252 #endif
2253
2254         /*
2255          * Atomic check condition and wait.  Also do an early speedup of
2256          * the syncer to try to avoid hitting the wait.
2257          */
2258         for (;;) {
2259                 waiting = pmp->inmem_dirty_chains;
2260                 cpu_ccfence();
2261                 count = waiting & HAMMER2_DIRTYCHAIN_MASK;
2262
2263                 limit = pmp->mp->mnt_nvnodelistsize / 10;
2264                 if (limit < hammer2_limit_dirty_chains)
2265                         limit = hammer2_limit_dirty_chains;
2266                 if (limit < 1000)
2267                         limit = 1000;
2268
2269 #if 0
2270                 if ((int)(ticks - zzticks) > hz) {
2271                         zzticks = ticks;
2272                         kprintf("count %ld %ld\n", count, limit);
2273                 }
2274 #endif
2275
2276                 /*
2277                  * Block if there are too many dirty chains present, wait
2278                  * for the flush to clean some out.
2279                  */
2280                 if (count > limit) {
2281                         tsleep_interlock(&pmp->inmem_dirty_chains, 0);
2282                         if (atomic_cmpset_int(&pmp->inmem_dirty_chains,
2283                                                waiting,
2284                                        waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
2285                                 speedup_syncer(pmp->mp);
2286                                 tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
2287                                        "chnmem", hz);
2288                         }
2289                         continue;       /* loop on success or fail */
2290                 }
2291
2292                 /*
2293                  * Try to start an early flush before we are forced to block.
2294                  */
2295                 if (count > limit * 7 / 10)
2296                         speedup_syncer(pmp->mp);
2297                 break;
2298         }
2299 }
2300
2301 void
2302 hammer2_pfs_memory_inc(hammer2_pfs_t *pmp)
2303 {
2304         if (pmp) {
2305                 atomic_add_int(&pmp->inmem_dirty_chains, 1);
2306         }
2307 }
2308
2309 void
2310 hammer2_pfs_memory_wakeup(hammer2_pfs_t *pmp)
2311 {
2312         uint32_t waiting;
2313
2314         if (pmp == NULL)
2315                 return;
2316
2317         for (;;) {
2318                 waiting = pmp->inmem_dirty_chains;
2319                 cpu_ccfence();
2320                 if (atomic_cmpset_int(&pmp->inmem_dirty_chains,
2321                                        waiting,
2322                                        (waiting - 1) &
2323                                         ~HAMMER2_DIRTYCHAIN_WAITING)) {
2324                         break;
2325                 }
2326         }
2327
2328         if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
2329                 wakeup(&pmp->inmem_dirty_chains);
2330 }
2331
2332 /*
2333  * Debugging
2334  */
2335 void
2336 hammer2_dump_chain(hammer2_chain_t *chain, int tab, int *countp, char pfx)
2337 {
2338         hammer2_chain_t *scan;
2339         hammer2_chain_t *parent;
2340
2341         --*countp;
2342         if (*countp == 0) {
2343                 kprintf("%*.*s...\n", tab, tab, "");
2344                 return;
2345         }
2346         if (*countp < 0)
2347                 return;
2348         kprintf("%*.*s%c-chain %p.%d %016jx/%d mir=%016jx\n",
2349                 tab, tab, "", pfx,
2350                 chain, chain->bref.type,
2351                 chain->bref.key, chain->bref.keybits,
2352                 chain->bref.mirror_tid);
2353
2354         kprintf("%*.*s      [%08x] (%s) refs=%d",
2355                 tab, tab, "",
2356                 chain->flags,
2357                 ((chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2358                 chain->data) ?  (char *)chain->data->ipdata.filename : "?"),
2359                 chain->refs);
2360
2361         parent = chain->parent;
2362         if (parent)
2363                 kprintf("\n%*.*s      p=%p [pflags %08x prefs %d",
2364                         tab, tab, "",
2365                         parent, parent->flags, parent->refs);
2366         if (RB_EMPTY(&chain->core.rbtree)) {
2367                 kprintf("\n");
2368         } else {
2369                 kprintf(" {\n");
2370                 RB_FOREACH(scan, hammer2_chain_tree, &chain->core.rbtree)
2371                         hammer2_dump_chain(scan, tab + 4, countp, 'a');
2372                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE && chain->data)
2373                         kprintf("%*.*s}(%s)\n", tab, tab, "",
2374                                 chain->data->ipdata.filename);
2375                 else
2376                         kprintf("%*.*s}\n", tab, tab, "");
2377         }
2378 }