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