]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_mount.c
vfs: flip deferred_inact to atomic
[FreeBSD/FreeBSD.git] / sys / kern / vfs_mount.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1999-2004 Poul-Henning Kamp
5  * Copyright (c) 1999 Michael Smith
6  * Copyright (c) 1989, 1993
7  *      The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38
39 #include <sys/cdefs.h>
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/smp.h>
43 #include <sys/devctl.h>
44 #include <sys/eventhandler.h>
45 #include <sys/fcntl.h>
46 #include <sys/jail.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/libkern.h>
50 #include <sys/malloc.h>
51 #include <sys/mount.h>
52 #include <sys/mutex.h>
53 #include <sys/namei.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/filedesc.h>
57 #include <sys/reboot.h>
58 #include <sys/sbuf.h>
59 #include <sys/syscallsubr.h>
60 #include <sys/sysproto.h>
61 #include <sys/sx.h>
62 #include <sys/sysctl.h>
63 #include <sys/systm.h>
64 #include <sys/vnode.h>
65 #include <vm/uma.h>
66
67 #include <geom/geom.h>
68
69 #include <machine/stdarg.h>
70
71 #include <security/audit/audit.h>
72 #include <security/mac/mac_framework.h>
73
74 #define VFS_MOUNTARG_SIZE_MAX   (1024 * 64)
75
76 static int      vfs_domount(struct thread *td, const char *fstype, char *fspath,
77                     uint64_t fsflags, bool jail_export,
78                     struct vfsoptlist **optlist);
79 static void     free_mntarg(struct mntarg *ma);
80
81 static int      usermount = 0;
82 SYSCTL_INT(_vfs, OID_AUTO, usermount, CTLFLAG_RW, &usermount, 0,
83     "Unprivileged users may mount and unmount file systems");
84
85 static bool     default_autoro = false;
86 SYSCTL_BOOL(_vfs, OID_AUTO, default_autoro, CTLFLAG_RW, &default_autoro, 0,
87     "Retry failed r/w mount as r/o if no explicit ro/rw option is specified");
88
89 MALLOC_DEFINE(M_MOUNT, "mount", "vfs mount structure");
90 MALLOC_DEFINE(M_STATFS, "statfs", "statfs structure");
91 static uma_zone_t mount_zone;
92
93 /* List of mounted filesystems. */
94 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
95
96 /* For any iteration/modification of mountlist */
97 struct mtx_padalign __exclusive_cache_line mountlist_mtx;
98 MTX_SYSINIT(mountlist, &mountlist_mtx, "mountlist", MTX_DEF);
99
100 EVENTHANDLER_LIST_DEFINE(vfs_mounted);
101 EVENTHANDLER_LIST_DEFINE(vfs_unmounted);
102
103 static void mount_devctl_event(const char *type, struct mount *mp, bool donew);
104
105 /*
106  * Global opts, taken by all filesystems
107  */
108 static const char *global_opts[] = {
109         "errmsg",
110         "fstype",
111         "fspath",
112         "ro",
113         "rw",
114         "nosuid",
115         "noexec",
116         NULL
117 };
118
119 static int
120 mount_init(void *mem, int size, int flags)
121 {
122         struct mount *mp;
123
124         mp = (struct mount *)mem;
125         mtx_init(&mp->mnt_mtx, "struct mount mtx", NULL, MTX_DEF);
126         mtx_init(&mp->mnt_listmtx, "struct mount vlist mtx", NULL, MTX_DEF);
127         lockinit(&mp->mnt_explock, PVFS, "explock", 0, 0);
128         mp->mnt_pcpu = uma_zalloc_pcpu(pcpu_zone_16, M_WAITOK | M_ZERO);
129         mp->mnt_ref = 0;
130         mp->mnt_vfs_ops = 1;
131         mp->mnt_rootvnode = NULL;
132         return (0);
133 }
134
135 static void
136 mount_fini(void *mem, int size)
137 {
138         struct mount *mp;
139
140         mp = (struct mount *)mem;
141         uma_zfree_pcpu(pcpu_zone_16, mp->mnt_pcpu);
142         lockdestroy(&mp->mnt_explock);
143         mtx_destroy(&mp->mnt_listmtx);
144         mtx_destroy(&mp->mnt_mtx);
145 }
146
147 static void
148 vfs_mount_init(void *dummy __unused)
149 {
150
151         mount_zone = uma_zcreate("Mountpoints", sizeof(struct mount), NULL,
152             NULL, mount_init, mount_fini, UMA_ALIGN_CACHE, UMA_ZONE_NOFREE);
153 }
154 SYSINIT(vfs_mount, SI_SUB_VFS, SI_ORDER_ANY, vfs_mount_init, NULL);
155
156 /*
157  * ---------------------------------------------------------------------
158  * Functions for building and sanitizing the mount options
159  */
160
161 /* Remove one mount option. */
162 static void
163 vfs_freeopt(struct vfsoptlist *opts, struct vfsopt *opt)
164 {
165
166         TAILQ_REMOVE(opts, opt, link);
167         free(opt->name, M_MOUNT);
168         if (opt->value != NULL)
169                 free(opt->value, M_MOUNT);
170         free(opt, M_MOUNT);
171 }
172
173 /* Release all resources related to the mount options. */
174 void
175 vfs_freeopts(struct vfsoptlist *opts)
176 {
177         struct vfsopt *opt;
178
179         while (!TAILQ_EMPTY(opts)) {
180                 opt = TAILQ_FIRST(opts);
181                 vfs_freeopt(opts, opt);
182         }
183         free(opts, M_MOUNT);
184 }
185
186 void
187 vfs_deleteopt(struct vfsoptlist *opts, const char *name)
188 {
189         struct vfsopt *opt, *temp;
190
191         if (opts == NULL)
192                 return;
193         TAILQ_FOREACH_SAFE(opt, opts, link, temp)  {
194                 if (strcmp(opt->name, name) == 0)
195                         vfs_freeopt(opts, opt);
196         }
197 }
198
199 static int
200 vfs_isopt_ro(const char *opt)
201 {
202
203         if (strcmp(opt, "ro") == 0 || strcmp(opt, "rdonly") == 0 ||
204             strcmp(opt, "norw") == 0)
205                 return (1);
206         return (0);
207 }
208
209 static int
210 vfs_isopt_rw(const char *opt)
211 {
212
213         if (strcmp(opt, "rw") == 0 || strcmp(opt, "noro") == 0)
214                 return (1);
215         return (0);
216 }
217
218 /*
219  * Check if options are equal (with or without the "no" prefix).
220  */
221 static int
222 vfs_equalopts(const char *opt1, const char *opt2)
223 {
224         char *p;
225
226         /* "opt" vs. "opt" or "noopt" vs. "noopt" */
227         if (strcmp(opt1, opt2) == 0)
228                 return (1);
229         /* "noopt" vs. "opt" */
230         if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
231                 return (1);
232         /* "opt" vs. "noopt" */
233         if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
234                 return (1);
235         while ((p = strchr(opt1, '.')) != NULL &&
236             !strncmp(opt1, opt2, ++p - opt1)) {
237                 opt2 += p - opt1;
238                 opt1 = p;
239                 /* "foo.noopt" vs. "foo.opt" */
240                 if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
241                         return (1);
242                 /* "foo.opt" vs. "foo.noopt" */
243                 if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
244                         return (1);
245         }
246         /* "ro" / "rdonly" / "norw" / "rw" / "noro" */
247         if ((vfs_isopt_ro(opt1) || vfs_isopt_rw(opt1)) &&
248             (vfs_isopt_ro(opt2) || vfs_isopt_rw(opt2)))
249                 return (1);
250         return (0);
251 }
252
253 /*
254  * If a mount option is specified several times,
255  * (with or without the "no" prefix) only keep
256  * the last occurrence of it.
257  */
258 static void
259 vfs_sanitizeopts(struct vfsoptlist *opts)
260 {
261         struct vfsopt *opt, *opt2, *tmp;
262
263         TAILQ_FOREACH_REVERSE(opt, opts, vfsoptlist, link) {
264                 opt2 = TAILQ_PREV(opt, vfsoptlist, link);
265                 while (opt2 != NULL) {
266                         if (vfs_equalopts(opt->name, opt2->name)) {
267                                 tmp = TAILQ_PREV(opt2, vfsoptlist, link);
268                                 vfs_freeopt(opts, opt2);
269                                 opt2 = tmp;
270                         } else {
271                                 opt2 = TAILQ_PREV(opt2, vfsoptlist, link);
272                         }
273                 }
274         }
275 }
276
277 /*
278  * Build a linked list of mount options from a struct uio.
279  */
280 int
281 vfs_buildopts(struct uio *auio, struct vfsoptlist **options)
282 {
283         struct vfsoptlist *opts;
284         struct vfsopt *opt;
285         size_t memused, namelen, optlen;
286         unsigned int i, iovcnt;
287         int error;
288
289         opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
290         TAILQ_INIT(opts);
291         memused = 0;
292         iovcnt = auio->uio_iovcnt;
293         for (i = 0; i < iovcnt; i += 2) {
294                 namelen = auio->uio_iov[i].iov_len;
295                 optlen = auio->uio_iov[i + 1].iov_len;
296                 memused += sizeof(struct vfsopt) + optlen + namelen;
297                 /*
298                  * Avoid consuming too much memory, and attempts to overflow
299                  * memused.
300                  */
301                 if (memused > VFS_MOUNTARG_SIZE_MAX ||
302                     optlen > VFS_MOUNTARG_SIZE_MAX ||
303                     namelen > VFS_MOUNTARG_SIZE_MAX) {
304                         error = EINVAL;
305                         goto bad;
306                 }
307
308                 opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
309                 opt->name = malloc(namelen, M_MOUNT, M_WAITOK);
310                 opt->value = NULL;
311                 opt->len = 0;
312                 opt->pos = i / 2;
313                 opt->seen = 0;
314
315                 /*
316                  * Do this early, so jumps to "bad" will free the current
317                  * option.
318                  */
319                 TAILQ_INSERT_TAIL(opts, opt, link);
320
321                 if (auio->uio_segflg == UIO_SYSSPACE) {
322                         bcopy(auio->uio_iov[i].iov_base, opt->name, namelen);
323                 } else {
324                         error = copyin(auio->uio_iov[i].iov_base, opt->name,
325                             namelen);
326                         if (error)
327                                 goto bad;
328                 }
329                 /* Ensure names are null-terminated strings. */
330                 if (namelen == 0 || opt->name[namelen - 1] != '\0') {
331                         error = EINVAL;
332                         goto bad;
333                 }
334                 if (optlen != 0) {
335                         opt->len = optlen;
336                         opt->value = malloc(optlen, M_MOUNT, M_WAITOK);
337                         if (auio->uio_segflg == UIO_SYSSPACE) {
338                                 bcopy(auio->uio_iov[i + 1].iov_base, opt->value,
339                                     optlen);
340                         } else {
341                                 error = copyin(auio->uio_iov[i + 1].iov_base,
342                                     opt->value, optlen);
343                                 if (error)
344                                         goto bad;
345                         }
346                 }
347         }
348         vfs_sanitizeopts(opts);
349         *options = opts;
350         return (0);
351 bad:
352         vfs_freeopts(opts);
353         return (error);
354 }
355
356 /*
357  * Merge the old mount options with the new ones passed
358  * in the MNT_UPDATE case.
359  *
360  * XXX: This function will keep a "nofoo" option in the new
361  * options.  E.g, if the option's canonical name is "foo",
362  * "nofoo" ends up in the mount point's active options.
363  */
364 static void
365 vfs_mergeopts(struct vfsoptlist *toopts, struct vfsoptlist *oldopts)
366 {
367         struct vfsopt *opt, *new;
368
369         TAILQ_FOREACH(opt, oldopts, link) {
370                 new = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
371                 new->name = strdup(opt->name, M_MOUNT);
372                 if (opt->len != 0) {
373                         new->value = malloc(opt->len, M_MOUNT, M_WAITOK);
374                         bcopy(opt->value, new->value, opt->len);
375                 } else
376                         new->value = NULL;
377                 new->len = opt->len;
378                 new->seen = opt->seen;
379                 TAILQ_INSERT_HEAD(toopts, new, link);
380         }
381         vfs_sanitizeopts(toopts);
382 }
383
384 /*
385  * Mount a filesystem.
386  */
387 #ifndef _SYS_SYSPROTO_H_
388 struct nmount_args {
389         struct iovec *iovp;
390         unsigned int iovcnt;
391         int flags;
392 };
393 #endif
394 int
395 sys_nmount(struct thread *td, struct nmount_args *uap)
396 {
397         struct uio *auio;
398         int error;
399         u_int iovcnt;
400         uint64_t flags;
401
402         /*
403          * Mount flags are now 64-bits. On 32-bit archtectures only
404          * 32-bits are passed in, but from here on everything handles
405          * 64-bit flags correctly.
406          */
407         flags = uap->flags;
408
409         AUDIT_ARG_FFLAGS(flags);
410         CTR4(KTR_VFS, "%s: iovp %p with iovcnt %d and flags %d", __func__,
411             uap->iovp, uap->iovcnt, flags);
412
413         /*
414          * Filter out MNT_ROOTFS.  We do not want clients of nmount() in
415          * userspace to set this flag, but we must filter it out if we want
416          * MNT_UPDATE on the root file system to work.
417          * MNT_ROOTFS should only be set by the kernel when mounting its
418          * root file system.
419          */
420         flags &= ~MNT_ROOTFS;
421
422         iovcnt = uap->iovcnt;
423         /*
424          * Check that we have an even number of iovec's
425          * and that we have at least two options.
426          */
427         if ((iovcnt & 1) || (iovcnt < 4)) {
428                 CTR2(KTR_VFS, "%s: failed for invalid iovcnt %d", __func__,
429                     uap->iovcnt);
430                 return (EINVAL);
431         }
432
433         error = copyinuio(uap->iovp, iovcnt, &auio);
434         if (error) {
435                 CTR2(KTR_VFS, "%s: failed for invalid uio op with %d errno",
436                     __func__, error);
437                 return (error);
438         }
439         error = vfs_donmount(td, flags, auio);
440
441         free(auio, M_IOV);
442         return (error);
443 }
444
445 /*
446  * ---------------------------------------------------------------------
447  * Various utility functions
448  */
449
450 /*
451  * Get a reference on a mount point from a vnode.
452  *
453  * The vnode is allowed to be passed unlocked and race against dooming. Note in
454  * such case there are no guarantees the referenced mount point will still be
455  * associated with it after the function returns.
456  */
457 struct mount *
458 vfs_ref_from_vp(struct vnode *vp)
459 {
460         struct mount *mp;
461         struct mount_pcpu *mpcpu;
462
463         mp = atomic_load_ptr(&vp->v_mount);
464         if (__predict_false(mp == NULL)) {
465                 return (mp);
466         }
467         if (vfs_op_thread_enter(mp, mpcpu)) {
468                 if (__predict_true(mp == vp->v_mount)) {
469                         vfs_mp_count_add_pcpu(mpcpu, ref, 1);
470                         vfs_op_thread_exit(mp, mpcpu);
471                 } else {
472                         vfs_op_thread_exit(mp, mpcpu);
473                         mp = NULL;
474                 }
475         } else {
476                 MNT_ILOCK(mp);
477                 if (mp == vp->v_mount) {
478                         MNT_REF(mp);
479                         MNT_IUNLOCK(mp);
480                 } else {
481                         MNT_IUNLOCK(mp);
482                         mp = NULL;
483                 }
484         }
485         return (mp);
486 }
487
488 void
489 vfs_ref(struct mount *mp)
490 {
491         struct mount_pcpu *mpcpu;
492
493         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
494         if (vfs_op_thread_enter(mp, mpcpu)) {
495                 vfs_mp_count_add_pcpu(mpcpu, ref, 1);
496                 vfs_op_thread_exit(mp, mpcpu);
497                 return;
498         }
499
500         MNT_ILOCK(mp);
501         MNT_REF(mp);
502         MNT_IUNLOCK(mp);
503 }
504
505 void
506 vfs_rel(struct mount *mp)
507 {
508         struct mount_pcpu *mpcpu;
509
510         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
511         if (vfs_op_thread_enter(mp, mpcpu)) {
512                 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
513                 vfs_op_thread_exit(mp, mpcpu);
514                 return;
515         }
516
517         MNT_ILOCK(mp);
518         MNT_REL(mp);
519         MNT_IUNLOCK(mp);
520 }
521
522 /*
523  * Allocate and initialize the mount point struct.
524  */
525 struct mount *
526 vfs_mount_alloc(struct vnode *vp, struct vfsconf *vfsp, const char *fspath,
527     struct ucred *cred)
528 {
529         struct mount *mp;
530
531         mp = uma_zalloc(mount_zone, M_WAITOK);
532         bzero(&mp->mnt_startzero,
533             __rangeof(struct mount, mnt_startzero, mnt_endzero));
534         mp->mnt_kern_flag = 0;
535         mp->mnt_flag = 0;
536         mp->mnt_rootvnode = NULL;
537         mp->mnt_vnodecovered = NULL;
538         mp->mnt_op = NULL;
539         mp->mnt_vfc = NULL;
540         TAILQ_INIT(&mp->mnt_nvnodelist);
541         mp->mnt_nvnodelistsize = 0;
542         TAILQ_INIT(&mp->mnt_lazyvnodelist);
543         mp->mnt_lazyvnodelistsize = 0;
544         MPPASS(mp->mnt_ref == 0 && mp->mnt_lockref == 0 &&
545             mp->mnt_writeopcount == 0, mp);
546         MPASSERT(mp->mnt_vfs_ops == 1, mp,
547             ("vfs_ops should be 1 but %d found", mp->mnt_vfs_ops));
548         (void) vfs_busy(mp, MBF_NOWAIT);
549         atomic_add_acq_int(&vfsp->vfc_refcount, 1);
550         mp->mnt_op = vfsp->vfc_vfsops;
551         mp->mnt_vfc = vfsp;
552         mp->mnt_stat.f_type = vfsp->vfc_typenum;
553         mp->mnt_gen++;
554         strlcpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
555         mp->mnt_vnodecovered = vp;
556         mp->mnt_cred = crdup(cred);
557         mp->mnt_stat.f_owner = cred->cr_uid;
558         strlcpy(mp->mnt_stat.f_mntonname, fspath, MNAMELEN);
559         mp->mnt_iosize_max = DFLTPHYS;
560 #ifdef MAC
561         mac_mount_init(mp);
562         mac_mount_create(cred, mp);
563 #endif
564         arc4rand(&mp->mnt_hashseed, sizeof mp->mnt_hashseed, 0);
565         TAILQ_INIT(&mp->mnt_uppers);
566         return (mp);
567 }
568
569 /*
570  * Destroy the mount struct previously allocated by vfs_mount_alloc().
571  */
572 void
573 vfs_mount_destroy(struct mount *mp)
574 {
575
576         MPPASS(mp->mnt_vfs_ops != 0, mp);
577
578         vfs_assert_mount_counters(mp);
579
580         MNT_ILOCK(mp);
581         mp->mnt_kern_flag |= MNTK_REFEXPIRE;
582         if (mp->mnt_kern_flag & MNTK_MWAIT) {
583                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
584                 wakeup(mp);
585         }
586         while (mp->mnt_ref)
587                 msleep(mp, MNT_MTX(mp), PVFS, "mntref", 0);
588         KASSERT(mp->mnt_ref == 0,
589             ("%s: invalid refcount in the drain path @ %s:%d", __func__,
590             __FILE__, __LINE__));
591         MPPASS(mp->mnt_writeopcount == 0, mp);
592         MPPASS(mp->mnt_secondary_writes == 0, mp);
593         atomic_subtract_rel_int(&mp->mnt_vfc->vfc_refcount, 1);
594         if (!TAILQ_EMPTY(&mp->mnt_nvnodelist)) {
595                 struct vnode *vp;
596
597                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes)
598                         vn_printf(vp, "dangling vnode ");
599                 panic("unmount: dangling vnode");
600         }
601         KASSERT(TAILQ_EMPTY(&mp->mnt_uppers), ("mnt_uppers"));
602         MPPASS(mp->mnt_nvnodelistsize == 0, mp);
603         MPPASS(mp->mnt_lazyvnodelistsize == 0, mp);
604         MPPASS(mp->mnt_lockref == 0, mp);
605         MNT_IUNLOCK(mp);
606
607         MPASSERT(mp->mnt_vfs_ops == 1, mp,
608             ("vfs_ops should be 1 but %d found", mp->mnt_vfs_ops));
609
610         MPASSERT(mp->mnt_rootvnode == NULL, mp,
611             ("mount point still has a root vnode %p", mp->mnt_rootvnode));
612
613         if (mp->mnt_vnodecovered != NULL)
614                 vrele(mp->mnt_vnodecovered);
615 #ifdef MAC
616         mac_mount_destroy(mp);
617 #endif
618         if (mp->mnt_opt != NULL)
619                 vfs_freeopts(mp->mnt_opt);
620         if (mp->mnt_exjail != NULL) {
621                 atomic_subtract_int(&mp->mnt_exjail->cr_prison->pr_exportcnt,
622                     1);
623                 crfree(mp->mnt_exjail);
624         }
625         if (mp->mnt_export != NULL) {
626                 vfs_free_addrlist(mp->mnt_export);
627                 free(mp->mnt_export, M_MOUNT);
628         }
629         crfree(mp->mnt_cred);
630         uma_zfree(mount_zone, mp);
631 }
632
633 static bool
634 vfs_should_downgrade_to_ro_mount(uint64_t fsflags, int error)
635 {
636         /* This is an upgrade of an exisiting mount. */
637         if ((fsflags & MNT_UPDATE) != 0)
638                 return (false);
639         /* This is already an R/O mount. */
640         if ((fsflags & MNT_RDONLY) != 0)
641                 return (false);
642
643         switch (error) {
644         case ENODEV:    /* generic, geom, ... */
645         case EACCES:    /* cam/scsi, ... */
646         case EROFS:     /* md, mmcsd, ... */
647                 /*
648                  * These errors can be returned by the storage layer to signal
649                  * that the media is read-only.  No harm in the R/O mount
650                  * attempt if the error was returned for some other reason.
651                  */
652                 return (true);
653         default:
654                 return (false);
655         }
656 }
657
658 int
659 vfs_donmount(struct thread *td, uint64_t fsflags, struct uio *fsoptions)
660 {
661         struct vfsoptlist *optlist;
662         struct vfsopt *opt, *tmp_opt;
663         char *fstype, *fspath, *errmsg;
664         int error, fstypelen, fspathlen, errmsg_len, errmsg_pos;
665         bool autoro, has_nonexport, jail_export;
666
667         errmsg = fspath = NULL;
668         errmsg_len = fspathlen = 0;
669         errmsg_pos = -1;
670         autoro = default_autoro;
671
672         error = vfs_buildopts(fsoptions, &optlist);
673         if (error)
674                 return (error);
675
676         if (vfs_getopt(optlist, "errmsg", (void **)&errmsg, &errmsg_len) == 0)
677                 errmsg_pos = vfs_getopt_pos(optlist, "errmsg");
678
679         /*
680          * We need these two options before the others,
681          * and they are mandatory for any filesystem.
682          * Ensure they are NUL terminated as well.
683          */
684         fstypelen = 0;
685         error = vfs_getopt(optlist, "fstype", (void **)&fstype, &fstypelen);
686         if (error || fstypelen <= 0 || fstype[fstypelen - 1] != '\0') {
687                 error = EINVAL;
688                 if (errmsg != NULL)
689                         strncpy(errmsg, "Invalid fstype", errmsg_len);
690                 goto bail;
691         }
692         fspathlen = 0;
693         error = vfs_getopt(optlist, "fspath", (void **)&fspath, &fspathlen);
694         if (error || fspathlen <= 0 || fspath[fspathlen - 1] != '\0') {
695                 error = EINVAL;
696                 if (errmsg != NULL)
697                         strncpy(errmsg, "Invalid fspath", errmsg_len);
698                 goto bail;
699         }
700
701         /*
702          * Check to see that "export" is only used with the "update", "fstype",
703          * "fspath", "from" and "errmsg" options when in a vnet jail.
704          * These are the ones used to set/update exports by mountd(8).
705          * If only the above options are set in a jail that can run mountd(8),
706          * then the jail_export argument of vfs_domount() will be true.
707          * When jail_export is true, the vfs_suser() check does not cause
708          * failure, but limits the update to exports only.
709          * This allows mountd(8) running within the vnet jail
710          * to export file systems visible within the jail, but
711          * mounted outside of the jail.
712          */
713         /*
714          * We need to see if we have the "update" option
715          * before we call vfs_domount(), since vfs_domount() has special
716          * logic based on MNT_UPDATE.  This is very important
717          * when we want to update the root filesystem.
718          */
719         has_nonexport = false;
720         jail_export = false;
721         TAILQ_FOREACH_SAFE(opt, optlist, link, tmp_opt) {
722                 int do_freeopt = 0;
723
724                 if (jailed(td->td_ucred) &&
725                     strcmp(opt->name, "export") != 0 &&
726                     strcmp(opt->name, "update") != 0 &&
727                     strcmp(opt->name, "fstype") != 0 &&
728                     strcmp(opt->name, "fspath") != 0 &&
729                     strcmp(opt->name, "from") != 0 &&
730                     strcmp(opt->name, "errmsg") != 0)
731                         has_nonexport = true;
732                 if (strcmp(opt->name, "update") == 0) {
733                         fsflags |= MNT_UPDATE;
734                         do_freeopt = 1;
735                 }
736                 else if (strcmp(opt->name, "async") == 0)
737                         fsflags |= MNT_ASYNC;
738                 else if (strcmp(opt->name, "force") == 0) {
739                         fsflags |= MNT_FORCE;
740                         do_freeopt = 1;
741                 }
742                 else if (strcmp(opt->name, "reload") == 0) {
743                         fsflags |= MNT_RELOAD;
744                         do_freeopt = 1;
745                 }
746                 else if (strcmp(opt->name, "multilabel") == 0)
747                         fsflags |= MNT_MULTILABEL;
748                 else if (strcmp(opt->name, "noasync") == 0)
749                         fsflags &= ~MNT_ASYNC;
750                 else if (strcmp(opt->name, "noatime") == 0)
751                         fsflags |= MNT_NOATIME;
752                 else if (strcmp(opt->name, "atime") == 0) {
753                         free(opt->name, M_MOUNT);
754                         opt->name = strdup("nonoatime", M_MOUNT);
755                 }
756                 else if (strcmp(opt->name, "noclusterr") == 0)
757                         fsflags |= MNT_NOCLUSTERR;
758                 else if (strcmp(opt->name, "clusterr") == 0) {
759                         free(opt->name, M_MOUNT);
760                         opt->name = strdup("nonoclusterr", M_MOUNT);
761                 }
762                 else if (strcmp(opt->name, "noclusterw") == 0)
763                         fsflags |= MNT_NOCLUSTERW;
764                 else if (strcmp(opt->name, "clusterw") == 0) {
765                         free(opt->name, M_MOUNT);
766                         opt->name = strdup("nonoclusterw", M_MOUNT);
767                 }
768                 else if (strcmp(opt->name, "noexec") == 0)
769                         fsflags |= MNT_NOEXEC;
770                 else if (strcmp(opt->name, "exec") == 0) {
771                         free(opt->name, M_MOUNT);
772                         opt->name = strdup("nonoexec", M_MOUNT);
773                 }
774                 else if (strcmp(opt->name, "nosuid") == 0)
775                         fsflags |= MNT_NOSUID;
776                 else if (strcmp(opt->name, "suid") == 0) {
777                         free(opt->name, M_MOUNT);
778                         opt->name = strdup("nonosuid", M_MOUNT);
779                 }
780                 else if (strcmp(opt->name, "nosymfollow") == 0)
781                         fsflags |= MNT_NOSYMFOLLOW;
782                 else if (strcmp(opt->name, "symfollow") == 0) {
783                         free(opt->name, M_MOUNT);
784                         opt->name = strdup("nonosymfollow", M_MOUNT);
785                 }
786                 else if (strcmp(opt->name, "noro") == 0) {
787                         fsflags &= ~MNT_RDONLY;
788                         autoro = false;
789                 }
790                 else if (strcmp(opt->name, "rw") == 0) {
791                         fsflags &= ~MNT_RDONLY;
792                         autoro = false;
793                 }
794                 else if (strcmp(opt->name, "ro") == 0) {
795                         fsflags |= MNT_RDONLY;
796                         autoro = false;
797                 }
798                 else if (strcmp(opt->name, "rdonly") == 0) {
799                         free(opt->name, M_MOUNT);
800                         opt->name = strdup("ro", M_MOUNT);
801                         fsflags |= MNT_RDONLY;
802                         autoro = false;
803                 }
804                 else if (strcmp(opt->name, "autoro") == 0) {
805                         do_freeopt = 1;
806                         autoro = true;
807                 }
808                 else if (strcmp(opt->name, "suiddir") == 0)
809                         fsflags |= MNT_SUIDDIR;
810                 else if (strcmp(opt->name, "sync") == 0)
811                         fsflags |= MNT_SYNCHRONOUS;
812                 else if (strcmp(opt->name, "union") == 0)
813                         fsflags |= MNT_UNION;
814                 else if (strcmp(opt->name, "export") == 0) {
815                         fsflags |= MNT_EXPORTED;
816                         jail_export = true;
817                 } else if (strcmp(opt->name, "automounted") == 0) {
818                         fsflags |= MNT_AUTOMOUNTED;
819                         do_freeopt = 1;
820                 } else if (strcmp(opt->name, "nocover") == 0) {
821                         fsflags |= MNT_NOCOVER;
822                         do_freeopt = 1;
823                 } else if (strcmp(opt->name, "cover") == 0) {
824                         fsflags &= ~MNT_NOCOVER;
825                         do_freeopt = 1;
826                 } else if (strcmp(opt->name, "emptydir") == 0) {
827                         fsflags |= MNT_EMPTYDIR;
828                         do_freeopt = 1;
829                 } else if (strcmp(opt->name, "noemptydir") == 0) {
830                         fsflags &= ~MNT_EMPTYDIR;
831                         do_freeopt = 1;
832                 }
833                 if (do_freeopt)
834                         vfs_freeopt(optlist, opt);
835         }
836
837         /*
838          * Be ultra-paranoid about making sure the type and fspath
839          * variables will fit in our mp buffers, including the
840          * terminating NUL.
841          */
842         if (fstypelen > MFSNAMELEN || fspathlen > MNAMELEN) {
843                 error = ENAMETOOLONG;
844                 goto bail;
845         }
846
847         /*
848          * If has_nonexport is true or the caller is not running within a
849          * vnet prison that can run mountd(8), set jail_export false.
850          */
851         if (has_nonexport || !jailed(td->td_ucred) ||
852             !prison_check_nfsd(td->td_ucred))
853                 jail_export = false;
854
855         error = vfs_domount(td, fstype, fspath, fsflags, jail_export, &optlist);
856         if (error == ENOENT) {
857                 error = EINVAL;
858                 if (errmsg != NULL)
859                         strncpy(errmsg, "Invalid fstype", errmsg_len);
860                 goto bail;
861         }
862
863         /*
864          * See if we can mount in the read-only mode if the error code suggests
865          * that it could be possible and the mount options allow for that.
866          * Never try it if "[no]{ro|rw}" has been explicitly requested and not
867          * overridden by "autoro".
868          */
869         if (autoro && vfs_should_downgrade_to_ro_mount(fsflags, error)) {
870                 printf("%s: R/W mount failed, possibly R/O media,"
871                     " trying R/O mount\n", __func__);
872                 fsflags |= MNT_RDONLY;
873                 error = vfs_domount(td, fstype, fspath, fsflags, jail_export,
874                     &optlist);
875         }
876 bail:
877         /* copyout the errmsg */
878         if (errmsg_pos != -1 && ((2 * errmsg_pos + 1) < fsoptions->uio_iovcnt)
879             && errmsg_len > 0 && errmsg != NULL) {
880                 if (fsoptions->uio_segflg == UIO_SYSSPACE) {
881                         bcopy(errmsg,
882                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
883                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
884                 } else {
885                         copyout(errmsg,
886                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
887                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
888                 }
889         }
890
891         if (optlist != NULL)
892                 vfs_freeopts(optlist);
893         return (error);
894 }
895
896 /*
897  * Old mount API.
898  */
899 #ifndef _SYS_SYSPROTO_H_
900 struct mount_args {
901         char    *type;
902         char    *path;
903         int     flags;
904         caddr_t data;
905 };
906 #endif
907 /* ARGSUSED */
908 int
909 sys_mount(struct thread *td, struct mount_args *uap)
910 {
911         char *fstype;
912         struct vfsconf *vfsp = NULL;
913         struct mntarg *ma = NULL;
914         uint64_t flags;
915         int error;
916
917         /*
918          * Mount flags are now 64-bits. On 32-bit architectures only
919          * 32-bits are passed in, but from here on everything handles
920          * 64-bit flags correctly.
921          */
922         flags = uap->flags;
923
924         AUDIT_ARG_FFLAGS(flags);
925
926         /*
927          * Filter out MNT_ROOTFS.  We do not want clients of mount() in
928          * userspace to set this flag, but we must filter it out if we want
929          * MNT_UPDATE on the root file system to work.
930          * MNT_ROOTFS should only be set by the kernel when mounting its
931          * root file system.
932          */
933         flags &= ~MNT_ROOTFS;
934
935         fstype = malloc(MFSNAMELEN, M_TEMP, M_WAITOK);
936         error = copyinstr(uap->type, fstype, MFSNAMELEN, NULL);
937         if (error) {
938                 free(fstype, M_TEMP);
939                 return (error);
940         }
941
942         AUDIT_ARG_TEXT(fstype);
943         vfsp = vfs_byname_kld(fstype, td, &error);
944         free(fstype, M_TEMP);
945         if (vfsp == NULL)
946                 return (ENOENT);
947         if (((vfsp->vfc_flags & VFCF_SBDRY) != 0 &&
948             vfsp->vfc_vfsops_sd->vfs_cmount == NULL) ||
949             ((vfsp->vfc_flags & VFCF_SBDRY) == 0 &&
950             vfsp->vfc_vfsops->vfs_cmount == NULL))
951                 return (EOPNOTSUPP);
952
953         ma = mount_argsu(ma, "fstype", uap->type, MFSNAMELEN);
954         ma = mount_argsu(ma, "fspath", uap->path, MNAMELEN);
955         ma = mount_argb(ma, flags & MNT_RDONLY, "noro");
956         ma = mount_argb(ma, !(flags & MNT_NOSUID), "nosuid");
957         ma = mount_argb(ma, !(flags & MNT_NOEXEC), "noexec");
958
959         if ((vfsp->vfc_flags & VFCF_SBDRY) != 0)
960                 return (vfsp->vfc_vfsops_sd->vfs_cmount(ma, uap->data, flags));
961         return (vfsp->vfc_vfsops->vfs_cmount(ma, uap->data, flags));
962 }
963
964 /*
965  * vfs_domount_first(): first file system mount (not update)
966  */
967 static int
968 vfs_domount_first(
969         struct thread *td,              /* Calling thread. */
970         struct vfsconf *vfsp,           /* File system type. */
971         char *fspath,                   /* Mount path. */
972         struct vnode *vp,               /* Vnode to be covered. */
973         uint64_t fsflags,               /* Flags common to all filesystems. */
974         struct vfsoptlist **optlist     /* Options local to the filesystem. */
975         )
976 {
977         struct vattr va;
978         struct mount *mp;
979         struct vnode *newdp, *rootvp;
980         int error, error1;
981         bool unmounted;
982
983         ASSERT_VOP_ELOCKED(vp, __func__);
984         KASSERT((fsflags & MNT_UPDATE) == 0, ("MNT_UPDATE shouldn't be here"));
985
986         /*
987          * If the jail of the calling thread lacks permission for this type of
988          * file system, or is trying to cover its own root, deny immediately.
989          */
990         if (jailed(td->td_ucred) && (!prison_allow(td->td_ucred,
991             vfsp->vfc_prison_flag) || vp == td->td_ucred->cr_prison->pr_root)) {
992                 vput(vp);
993                 return (EPERM);
994         }
995
996         /*
997          * If the user is not root, ensure that they own the directory
998          * onto which we are attempting to mount.
999          */
1000         error = VOP_GETATTR(vp, &va, td->td_ucred);
1001         if (error == 0 && va.va_uid != td->td_ucred->cr_uid)
1002                 error = priv_check_cred(td->td_ucred, PRIV_VFS_ADMIN);
1003         if (error == 0)
1004                 error = vinvalbuf(vp, V_SAVE, 0, 0);
1005         if (vfsp->vfc_flags & VFCF_FILEMOUNT) {
1006                 if (error == 0 && vp->v_type != VDIR && vp->v_type != VREG)
1007                         error = EINVAL;
1008                 /*
1009                  * For file mounts, ensure that there is only one hardlink to the file.
1010                  */
1011                 if (error == 0 && vp->v_type == VREG && va.va_nlink != 1)
1012                         error = EINVAL;
1013         } else {
1014                 if (error == 0 && vp->v_type != VDIR)
1015                         error = ENOTDIR;
1016         }
1017         if (error == 0 && (fsflags & MNT_EMPTYDIR) != 0)
1018                 error = vn_dir_check_empty(vp);
1019         if (error == 0) {
1020                 VI_LOCK(vp);
1021                 if ((vp->v_iflag & VI_MOUNT) == 0 && vp->v_mountedhere == NULL)
1022                         vp->v_iflag |= VI_MOUNT;
1023                 else
1024                         error = EBUSY;
1025                 VI_UNLOCK(vp);
1026         }
1027         if (error != 0) {
1028                 vput(vp);
1029                 return (error);
1030         }
1031         vn_seqc_write_begin(vp);
1032         VOP_UNLOCK(vp);
1033
1034         /* Allocate and initialize the filesystem. */
1035         mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
1036         /* XXXMAC: pass to vfs_mount_alloc? */
1037         mp->mnt_optnew = *optlist;
1038         /* Set the mount level flags. */
1039         mp->mnt_flag = (fsflags & (MNT_UPDATEMASK | MNT_ROOTFS | MNT_RDONLY));
1040
1041         /*
1042          * Mount the filesystem.
1043          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1044          * get.  No freeing of cn_pnbuf.
1045          */
1046         error1 = 0;
1047         unmounted = true;
1048         if ((error = VFS_MOUNT(mp)) != 0 ||
1049             (error1 = VFS_STATFS(mp, &mp->mnt_stat)) != 0 ||
1050             (error1 = VFS_ROOT(mp, LK_EXCLUSIVE, &newdp)) != 0) {
1051                 rootvp = NULL;
1052                 if (error1 != 0) {
1053                         MPASS(error == 0);
1054                         rootvp = vfs_cache_root_clear(mp);
1055                         if (rootvp != NULL) {
1056                                 vhold(rootvp);
1057                                 vrele(rootvp);
1058                         }
1059                         (void)vn_start_write(NULL, &mp, V_WAIT);
1060                         MNT_ILOCK(mp);
1061                         mp->mnt_kern_flag |= MNTK_UNMOUNT | MNTK_UNMOUNTF;
1062                         MNT_IUNLOCK(mp);
1063                         VFS_PURGE(mp);
1064                         error = VFS_UNMOUNT(mp, 0);
1065                         vn_finished_write(mp);
1066                         if (error != 0) {
1067                                 printf(
1068                     "failed post-mount (%d): rollback unmount returned %d\n",
1069                                     error1, error);
1070                                 unmounted = false;
1071                         }
1072                         error = error1;
1073                 }
1074                 vfs_unbusy(mp);
1075                 mp->mnt_vnodecovered = NULL;
1076                 if (unmounted) {
1077                         /* XXXKIB wait for mnt_lockref drain? */
1078                         vfs_mount_destroy(mp);
1079                 }
1080                 VI_LOCK(vp);
1081                 vp->v_iflag &= ~VI_MOUNT;
1082                 VI_UNLOCK(vp);
1083                 if (rootvp != NULL) {
1084                         vn_seqc_write_end(rootvp);
1085                         vdrop(rootvp);
1086                 }
1087                 vn_seqc_write_end(vp);
1088                 vrele(vp);
1089                 return (error);
1090         }
1091         vn_seqc_write_begin(newdp);
1092         VOP_UNLOCK(newdp);
1093
1094         if (mp->mnt_opt != NULL)
1095                 vfs_freeopts(mp->mnt_opt);
1096         mp->mnt_opt = mp->mnt_optnew;
1097         *optlist = NULL;
1098
1099         /*
1100          * Prevent external consumers of mount options from reading mnt_optnew.
1101          */
1102         mp->mnt_optnew = NULL;
1103
1104         MNT_ILOCK(mp);
1105         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1106             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1107                 mp->mnt_kern_flag |= MNTK_ASYNC;
1108         else
1109                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1110         MNT_IUNLOCK(mp);
1111
1112         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1113         cache_purge(vp);
1114         VI_LOCK(vp);
1115         vp->v_iflag &= ~VI_MOUNT;
1116         vn_irflag_set_locked(vp, VIRF_MOUNTPOINT);
1117         vp->v_mountedhere = mp;
1118         VI_UNLOCK(vp);
1119         /* Place the new filesystem at the end of the mount list. */
1120         mtx_lock(&mountlist_mtx);
1121         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1122         mtx_unlock(&mountlist_mtx);
1123         vfs_event_signal(NULL, VQ_MOUNT, 0);
1124         vn_lock(newdp, LK_EXCLUSIVE | LK_RETRY);
1125         VOP_UNLOCK(vp);
1126         EVENTHANDLER_DIRECT_INVOKE(vfs_mounted, mp, newdp, td);
1127         VOP_UNLOCK(newdp);
1128         mount_devctl_event("MOUNT", mp, false);
1129         mountcheckdirs(vp, newdp);
1130         vn_seqc_write_end(vp);
1131         vn_seqc_write_end(newdp);
1132         vrele(newdp);
1133         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1134                 vfs_allocate_syncvnode(mp);
1135         vfs_op_exit(mp);
1136         vfs_unbusy(mp);
1137         return (0);
1138 }
1139
1140 /*
1141  * vfs_domount_update(): update of mounted file system
1142  */
1143 static int
1144 vfs_domount_update(
1145         struct thread *td,              /* Calling thread. */
1146         struct vnode *vp,               /* Mount point vnode. */
1147         uint64_t fsflags,               /* Flags common to all filesystems. */
1148         bool jail_export,               /* Got export option in vnet prison. */
1149         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1150         )
1151 {
1152         struct export_args export;
1153         struct o2export_args o2export;
1154         struct vnode *rootvp;
1155         void *bufp;
1156         struct mount *mp;
1157         int error, export_error, i, len;
1158         uint64_t flag;
1159         gid_t *grps;
1160         bool vfs_suser_failed;
1161
1162         ASSERT_VOP_ELOCKED(vp, __func__);
1163         KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1164         mp = vp->v_mount;
1165
1166         if ((vp->v_vflag & VV_ROOT) == 0) {
1167                 if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1168                     == 0)
1169                         error = EXDEV;
1170                 else
1171                         error = EINVAL;
1172                 vput(vp);
1173                 return (error);
1174         }
1175
1176         /*
1177          * We only allow the filesystem to be reloaded if it
1178          * is currently mounted read-only.
1179          */
1180         flag = mp->mnt_flag;
1181         if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1182                 vput(vp);
1183                 return (EOPNOTSUPP);    /* Needs translation */
1184         }
1185         /*
1186          * Only privileged root, or (if MNT_USER is set) the user that
1187          * did the original mount is permitted to update it.
1188          */
1189         /*
1190          * For the case of mountd(8) doing exports in a jail, the vfs_suser()
1191          * call does not cause failure.  vfs_domount() has already checked
1192          * that "root" is doing this and vfs_suser() will fail when
1193          * the file system has been mounted outside the jail.
1194          * jail_export set true indicates that "export" is not mixed
1195          * with other options that change mount behaviour.
1196          */
1197         vfs_suser_failed = false;
1198         error = vfs_suser(mp, td);
1199         if (jail_export && error != 0) {
1200                 error = 0;
1201                 vfs_suser_failed = true;
1202         }
1203         if (error != 0) {
1204                 vput(vp);
1205                 return (error);
1206         }
1207         if (vfs_busy(mp, MBF_NOWAIT)) {
1208                 vput(vp);
1209                 return (EBUSY);
1210         }
1211         VI_LOCK(vp);
1212         if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1213                 VI_UNLOCK(vp);
1214                 vfs_unbusy(mp);
1215                 vput(vp);
1216                 return (EBUSY);
1217         }
1218         vp->v_iflag |= VI_MOUNT;
1219         VI_UNLOCK(vp);
1220         VOP_UNLOCK(vp);
1221
1222         vfs_op_enter(mp);
1223         vn_seqc_write_begin(vp);
1224
1225         rootvp = NULL;
1226         MNT_ILOCK(mp);
1227         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1228                 MNT_IUNLOCK(mp);
1229                 error = EBUSY;
1230                 goto end;
1231         }
1232         if (vfs_suser_failed) {
1233                 KASSERT((fsflags & (MNT_EXPORTED | MNT_UPDATE)) ==
1234                     (MNT_EXPORTED | MNT_UPDATE),
1235                     ("%s: jailed export did not set expected fsflags",
1236                      __func__));
1237                 /*
1238                  * For this case, only MNT_UPDATE and
1239                  * MNT_EXPORTED have been set in fsflags
1240                  * by the options.  Only set MNT_UPDATE,
1241                  * since that is the one that would be set
1242                  * when set in fsflags, below.
1243                  */
1244                 mp->mnt_flag |= MNT_UPDATE;
1245         } else {
1246                 mp->mnt_flag &= ~MNT_UPDATEMASK;
1247                 mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1248                     MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1249                 if ((mp->mnt_flag & MNT_ASYNC) == 0)
1250                         mp->mnt_kern_flag &= ~MNTK_ASYNC;
1251         }
1252         rootvp = vfs_cache_root_clear(mp);
1253         MNT_IUNLOCK(mp);
1254         mp->mnt_optnew = *optlist;
1255         vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1256
1257         /*
1258          * Mount the filesystem.
1259          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1260          * get.  No freeing of cn_pnbuf.
1261          */
1262         /*
1263          * For the case of mountd(8) doing exports from within a vnet jail,
1264          * "from" is typically not set correctly such that VFS_MOUNT() will
1265          * return ENOENT. It is not obvious that VFS_MOUNT() ever needs to be
1266          * called when mountd is doing exports, but this check only applies to
1267          * the specific case where it is running inside a vnet jail, to
1268          * avoid any POLA violation.
1269          */
1270         error = 0;
1271         if (!jail_export)
1272                 error = VFS_MOUNT(mp);
1273
1274         export_error = 0;
1275         /* Process the export option. */
1276         if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1277             &len) == 0) {
1278                 /* Assume that there is only 1 ABI for each length. */
1279                 switch (len) {
1280                 case (sizeof(struct oexport_args)):
1281                         bzero(&o2export, sizeof(o2export));
1282                         /* FALLTHROUGH */
1283                 case (sizeof(o2export)):
1284                         bcopy(bufp, &o2export, len);
1285                         export.ex_flags = (uint64_t)o2export.ex_flags;
1286                         export.ex_root = o2export.ex_root;
1287                         export.ex_uid = o2export.ex_anon.cr_uid;
1288                         export.ex_groups = NULL;
1289                         export.ex_ngroups = o2export.ex_anon.cr_ngroups;
1290                         if (export.ex_ngroups > 0) {
1291                                 if (export.ex_ngroups <= XU_NGROUPS) {
1292                                         export.ex_groups = malloc(
1293                                             export.ex_ngroups * sizeof(gid_t),
1294                                             M_TEMP, M_WAITOK);
1295                                         for (i = 0; i < export.ex_ngroups; i++)
1296                                                 export.ex_groups[i] =
1297                                                   o2export.ex_anon.cr_groups[i];
1298                                 } else
1299                                         export_error = EINVAL;
1300                         } else if (export.ex_ngroups < 0)
1301                                 export_error = EINVAL;
1302                         export.ex_addr = o2export.ex_addr;
1303                         export.ex_addrlen = o2export.ex_addrlen;
1304                         export.ex_mask = o2export.ex_mask;
1305                         export.ex_masklen = o2export.ex_masklen;
1306                         export.ex_indexfile = o2export.ex_indexfile;
1307                         export.ex_numsecflavors = o2export.ex_numsecflavors;
1308                         if (export.ex_numsecflavors < MAXSECFLAVORS) {
1309                                 for (i = 0; i < export.ex_numsecflavors; i++)
1310                                         export.ex_secflavors[i] =
1311                                             o2export.ex_secflavors[i];
1312                         } else
1313                                 export_error = EINVAL;
1314                         if (export_error == 0)
1315                                 export_error = vfs_export(mp, &export, 1);
1316                         free(export.ex_groups, M_TEMP);
1317                         break;
1318                 case (sizeof(export)):
1319                         bcopy(bufp, &export, len);
1320                         grps = NULL;
1321                         if (export.ex_ngroups > 0) {
1322                                 if (export.ex_ngroups <= NGROUPS_MAX) {
1323                                         grps = malloc(export.ex_ngroups *
1324                                             sizeof(gid_t), M_TEMP, M_WAITOK);
1325                                         export_error = copyin(export.ex_groups,
1326                                             grps, export.ex_ngroups *
1327                                             sizeof(gid_t));
1328                                         if (export_error == 0)
1329                                                 export.ex_groups = grps;
1330                                 } else
1331                                         export_error = EINVAL;
1332                         } else if (export.ex_ngroups == 0)
1333                                 export.ex_groups = NULL;
1334                         else
1335                                 export_error = EINVAL;
1336                         if (export_error == 0)
1337                                 export_error = vfs_export(mp, &export, 1);
1338                         free(grps, M_TEMP);
1339                         break;
1340                 default:
1341                         export_error = EINVAL;
1342                         break;
1343                 }
1344         }
1345
1346         MNT_ILOCK(mp);
1347         if (error == 0) {
1348                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1349                     MNT_SNAPSHOT);
1350         } else {
1351                 /*
1352                  * If we fail, restore old mount flags. MNT_QUOTA is special,
1353                  * because it is not part of MNT_UPDATEMASK, but it could have
1354                  * changed in the meantime if quotactl(2) was called.
1355                  * All in all we want current value of MNT_QUOTA, not the old
1356                  * one.
1357                  */
1358                 mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1359         }
1360         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1361             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1362                 mp->mnt_kern_flag |= MNTK_ASYNC;
1363         else
1364                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1365         MNT_IUNLOCK(mp);
1366
1367         if (error != 0)
1368                 goto end;
1369
1370         mount_devctl_event("REMOUNT", mp, true);
1371         if (mp->mnt_opt != NULL)
1372                 vfs_freeopts(mp->mnt_opt);
1373         mp->mnt_opt = mp->mnt_optnew;
1374         *optlist = NULL;
1375         (void)VFS_STATFS(mp, &mp->mnt_stat);
1376         /*
1377          * Prevent external consumers of mount options from reading
1378          * mnt_optnew.
1379          */
1380         mp->mnt_optnew = NULL;
1381
1382         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1383                 vfs_allocate_syncvnode(mp);
1384         else
1385                 vfs_deallocate_syncvnode(mp);
1386 end:
1387         vfs_op_exit(mp);
1388         if (rootvp != NULL) {
1389                 vn_seqc_write_end(rootvp);
1390                 vrele(rootvp);
1391         }
1392         vn_seqc_write_end(vp);
1393         vfs_unbusy(mp);
1394         VI_LOCK(vp);
1395         vp->v_iflag &= ~VI_MOUNT;
1396         VI_UNLOCK(vp);
1397         vrele(vp);
1398         return (error != 0 ? error : export_error);
1399 }
1400
1401 /*
1402  * vfs_domount(): actually attempt a filesystem mount.
1403  */
1404 static int
1405 vfs_domount(
1406         struct thread *td,              /* Calling thread. */
1407         const char *fstype,             /* Filesystem type. */
1408         char *fspath,                   /* Mount path. */
1409         uint64_t fsflags,               /* Flags common to all filesystems. */
1410         bool jail_export,               /* Got export option in vnet prison. */
1411         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1412         )
1413 {
1414         struct vfsconf *vfsp;
1415         struct nameidata nd;
1416         struct vnode *vp;
1417         char *pathbuf;
1418         int error;
1419
1420         /*
1421          * Be ultra-paranoid about making sure the type and fspath
1422          * variables will fit in our mp buffers, including the
1423          * terminating NUL.
1424          */
1425         if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1426                 return (ENAMETOOLONG);
1427
1428         if (jail_export) {
1429                 error = priv_check(td, PRIV_NFS_DAEMON);
1430                 if (error)
1431                         return (error);
1432         } else if (jailed(td->td_ucred) || usermount == 0) {
1433                 if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1434                         return (error);
1435         }
1436
1437         /*
1438          * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1439          */
1440         if (fsflags & MNT_EXPORTED) {
1441                 error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1442                 if (error)
1443                         return (error);
1444         }
1445         if (fsflags & MNT_SUIDDIR) {
1446                 error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1447                 if (error)
1448                         return (error);
1449         }
1450         /*
1451          * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1452          */
1453         if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1454                 if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1455                         fsflags |= MNT_NOSUID | MNT_USER;
1456         }
1457
1458         /* Load KLDs before we lock the covered vnode to avoid reversals. */
1459         vfsp = NULL;
1460         if ((fsflags & MNT_UPDATE) == 0) {
1461                 /* Don't try to load KLDs if we're mounting the root. */
1462                 if (fsflags & MNT_ROOTFS) {
1463                         if ((vfsp = vfs_byname(fstype)) == NULL)
1464                                 return (ENODEV);
1465                 } else {
1466                         if ((vfsp = vfs_byname_kld(fstype, td, &error)) == NULL)
1467                                 return (error);
1468                 }
1469         }
1470
1471         /*
1472          * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1473          */
1474         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1 | WANTPARENT,
1475             UIO_SYSSPACE, fspath, td);
1476         error = namei(&nd);
1477         if (error != 0)
1478                 return (error);
1479         vp = nd.ni_vp;
1480         /*
1481          * Don't allow stacking file mounts to work around problems with the way
1482          * that namei sets nd.ni_dvp to vp_crossmp for these.
1483          */
1484         if (vp->v_type == VREG)
1485                 fsflags |= MNT_NOCOVER;
1486         if ((fsflags & MNT_UPDATE) == 0) {
1487                 if ((vp->v_vflag & VV_ROOT) != 0 &&
1488                     (fsflags & MNT_NOCOVER) != 0) {
1489                         vput(vp);
1490                         error = EBUSY;
1491                         goto out;
1492                 }
1493                 pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1494                 strcpy(pathbuf, fspath);
1495                 /*
1496                  * Note: we allow any vnode type here. If the path sanity check
1497                  * succeeds, the type will be validated in vfs_domount_first
1498                  * above.
1499                  */
1500                 if (vp->v_type == VDIR)
1501                         error = vn_path_to_global_path(td, vp, pathbuf,
1502                             MNAMELEN);
1503                 else
1504                         error = vn_path_to_global_path_hardlink(td, vp,
1505                             nd.ni_dvp, pathbuf, MNAMELEN,
1506                             nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen);
1507                 if (error == 0) {
1508                         error = vfs_domount_first(td, vfsp, pathbuf, vp,
1509                             fsflags, optlist);
1510                 }
1511                 free(pathbuf, M_TEMP);
1512         } else
1513                 error = vfs_domount_update(td, vp, fsflags, jail_export,
1514                     optlist);
1515
1516 out:
1517         NDFREE(&nd, NDF_ONLY_PNBUF);
1518         vrele(nd.ni_dvp);
1519
1520         return (error);
1521 }
1522
1523 /*
1524  * Unmount a filesystem.
1525  *
1526  * Note: unmount takes a path to the vnode mounted on as argument, not
1527  * special file (as before).
1528  */
1529 #ifndef _SYS_SYSPROTO_H_
1530 struct unmount_args {
1531         char    *path;
1532         int     flags;
1533 };
1534 #endif
1535 /* ARGSUSED */
1536 int
1537 sys_unmount(struct thread *td, struct unmount_args *uap)
1538 {
1539
1540         return (kern_unmount(td, uap->path, uap->flags));
1541 }
1542
1543 int
1544 kern_unmount(struct thread *td, const char *path, int flags)
1545 {
1546         struct nameidata nd;
1547         struct mount *mp;
1548         char *pathbuf;
1549         int error, id0, id1;
1550
1551         AUDIT_ARG_VALUE(flags);
1552         if (jailed(td->td_ucred) || usermount == 0) {
1553                 error = priv_check(td, PRIV_VFS_UNMOUNT);
1554                 if (error)
1555                         return (error);
1556         }
1557
1558         pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1559         error = copyinstr(path, pathbuf, MNAMELEN, NULL);
1560         if (error) {
1561                 free(pathbuf, M_TEMP);
1562                 return (error);
1563         }
1564         if (flags & MNT_BYFSID) {
1565                 AUDIT_ARG_TEXT(pathbuf);
1566                 /* Decode the filesystem ID. */
1567                 if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
1568                         free(pathbuf, M_TEMP);
1569                         return (EINVAL);
1570                 }
1571
1572                 mtx_lock(&mountlist_mtx);
1573                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1574                         if (mp->mnt_stat.f_fsid.val[0] == id0 &&
1575                             mp->mnt_stat.f_fsid.val[1] == id1) {
1576                                 vfs_ref(mp);
1577                                 break;
1578                         }
1579                 }
1580                 mtx_unlock(&mountlist_mtx);
1581         } else {
1582                 /*
1583                  * Try to find global path for path argument.
1584                  */
1585                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1586                     UIO_SYSSPACE, pathbuf, td);
1587                 if (namei(&nd) == 0) {
1588                         NDFREE(&nd, NDF_ONLY_PNBUF);
1589                         error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1590                             MNAMELEN);
1591                         if (error == 0)
1592                                 vput(nd.ni_vp);
1593                 }
1594                 mtx_lock(&mountlist_mtx);
1595                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1596                         if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1597                                 vfs_ref(mp);
1598                                 break;
1599                         }
1600                 }
1601                 mtx_unlock(&mountlist_mtx);
1602         }
1603         free(pathbuf, M_TEMP);
1604         if (mp == NULL) {
1605                 /*
1606                  * Previously we returned ENOENT for a nonexistent path and
1607                  * EINVAL for a non-mountpoint.  We cannot tell these apart
1608                  * now, so in the !MNT_BYFSID case return the more likely
1609                  * EINVAL for compatibility.
1610                  */
1611                 return ((flags & MNT_BYFSID) ? ENOENT : EINVAL);
1612         }
1613
1614         /*
1615          * Don't allow unmounting the root filesystem.
1616          */
1617         if (mp->mnt_flag & MNT_ROOTFS) {
1618                 vfs_rel(mp);
1619                 return (EINVAL);
1620         }
1621         error = dounmount(mp, flags, td);
1622         return (error);
1623 }
1624
1625 /*
1626  * Return error if any of the vnodes, ignoring the root vnode
1627  * and the syncer vnode, have non-zero usecount.
1628  *
1629  * This function is purely advisory - it can return false positives
1630  * and negatives.
1631  */
1632 static int
1633 vfs_check_usecounts(struct mount *mp)
1634 {
1635         struct vnode *vp, *mvp;
1636
1637         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1638                 if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1639                     vp->v_usecount != 0) {
1640                         VI_UNLOCK(vp);
1641                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1642                         return (EBUSY);
1643                 }
1644                 VI_UNLOCK(vp);
1645         }
1646
1647         return (0);
1648 }
1649
1650 static void
1651 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1652 {
1653
1654         mtx_assert(MNT_MTX(mp), MA_OWNED);
1655         mp->mnt_kern_flag &= ~mntkflags;
1656         if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1657                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
1658                 wakeup(mp);
1659         }
1660         vfs_op_exit_locked(mp);
1661         MNT_IUNLOCK(mp);
1662         if (coveredvp != NULL) {
1663                 VOP_UNLOCK(coveredvp);
1664                 vdrop(coveredvp);
1665         }
1666         vn_finished_write(mp);
1667 }
1668
1669 /*
1670  * There are various reference counters associated with the mount point.
1671  * Normally it is permitted to modify them without taking the mnt ilock,
1672  * but this behavior can be temporarily disabled if stable value is needed
1673  * or callers are expected to block (e.g. to not allow new users during
1674  * forced unmount).
1675  */
1676 void
1677 vfs_op_enter(struct mount *mp)
1678 {
1679         struct mount_pcpu *mpcpu;
1680         int cpu;
1681
1682         MNT_ILOCK(mp);
1683         mp->mnt_vfs_ops++;
1684         if (mp->mnt_vfs_ops > 1) {
1685                 MNT_IUNLOCK(mp);
1686                 return;
1687         }
1688         vfs_op_barrier_wait(mp);
1689         CPU_FOREACH(cpu) {
1690                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1691
1692                 mp->mnt_ref += mpcpu->mntp_ref;
1693                 mpcpu->mntp_ref = 0;
1694
1695                 mp->mnt_lockref += mpcpu->mntp_lockref;
1696                 mpcpu->mntp_lockref = 0;
1697
1698                 mp->mnt_writeopcount += mpcpu->mntp_writeopcount;
1699                 mpcpu->mntp_writeopcount = 0;
1700         }
1701         MPASSERT(mp->mnt_ref > 0 && mp->mnt_lockref >= 0 &&
1702             mp->mnt_writeopcount >= 0, mp,
1703             ("invalid count(s): ref %d lockref %d writeopcount %d",
1704             mp->mnt_ref, mp->mnt_lockref, mp->mnt_writeopcount));
1705         MNT_IUNLOCK(mp);
1706         vfs_assert_mount_counters(mp);
1707 }
1708
1709 void
1710 vfs_op_exit_locked(struct mount *mp)
1711 {
1712
1713         mtx_assert(MNT_MTX(mp), MA_OWNED);
1714
1715         MPASSERT(mp->mnt_vfs_ops > 0, mp,
1716             ("invalid vfs_ops count %d", mp->mnt_vfs_ops));
1717         MPASSERT(mp->mnt_vfs_ops > 1 ||
1718             (mp->mnt_kern_flag & (MNTK_UNMOUNT | MNTK_SUSPEND)) == 0, mp,
1719             ("vfs_ops too low %d in unmount or suspend", mp->mnt_vfs_ops));
1720         mp->mnt_vfs_ops--;
1721 }
1722
1723 void
1724 vfs_op_exit(struct mount *mp)
1725 {
1726
1727         MNT_ILOCK(mp);
1728         vfs_op_exit_locked(mp);
1729         MNT_IUNLOCK(mp);
1730 }
1731
1732 struct vfs_op_barrier_ipi {
1733         struct mount *mp;
1734         struct smp_rendezvous_cpus_retry_arg srcra;
1735 };
1736
1737 static void
1738 vfs_op_action_func(void *arg)
1739 {
1740         struct vfs_op_barrier_ipi *vfsopipi;
1741         struct mount *mp;
1742
1743         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1744         mp = vfsopipi->mp;
1745
1746         if (!vfs_op_thread_entered(mp))
1747                 smp_rendezvous_cpus_done(arg);
1748 }
1749
1750 static void
1751 vfs_op_wait_func(void *arg, int cpu)
1752 {
1753         struct vfs_op_barrier_ipi *vfsopipi;
1754         struct mount *mp;
1755         struct mount_pcpu *mpcpu;
1756
1757         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1758         mp = vfsopipi->mp;
1759
1760         mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1761         while (atomic_load_int(&mpcpu->mntp_thread_in_ops))
1762                 cpu_spinwait();
1763 }
1764
1765 void
1766 vfs_op_barrier_wait(struct mount *mp)
1767 {
1768         struct vfs_op_barrier_ipi vfsopipi;
1769
1770         vfsopipi.mp = mp;
1771
1772         smp_rendezvous_cpus_retry(all_cpus,
1773             smp_no_rendezvous_barrier,
1774             vfs_op_action_func,
1775             smp_no_rendezvous_barrier,
1776             vfs_op_wait_func,
1777             &vfsopipi.srcra);
1778 }
1779
1780 #ifdef DIAGNOSTIC
1781 void
1782 vfs_assert_mount_counters(struct mount *mp)
1783 {
1784         struct mount_pcpu *mpcpu;
1785         int cpu;
1786
1787         if (mp->mnt_vfs_ops == 0)
1788                 return;
1789
1790         CPU_FOREACH(cpu) {
1791                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1792                 if (mpcpu->mntp_ref != 0 ||
1793                     mpcpu->mntp_lockref != 0 ||
1794                     mpcpu->mntp_writeopcount != 0)
1795                         vfs_dump_mount_counters(mp);
1796         }
1797 }
1798
1799 void
1800 vfs_dump_mount_counters(struct mount *mp)
1801 {
1802         struct mount_pcpu *mpcpu;
1803         int ref, lockref, writeopcount;
1804         int cpu;
1805
1806         printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1807
1808         printf("        ref : ");
1809         ref = mp->mnt_ref;
1810         CPU_FOREACH(cpu) {
1811                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1812                 printf("%d ", mpcpu->mntp_ref);
1813                 ref += mpcpu->mntp_ref;
1814         }
1815         printf("\n");
1816         printf("    lockref : ");
1817         lockref = mp->mnt_lockref;
1818         CPU_FOREACH(cpu) {
1819                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1820                 printf("%d ", mpcpu->mntp_lockref);
1821                 lockref += mpcpu->mntp_lockref;
1822         }
1823         printf("\n");
1824         printf("writeopcount: ");
1825         writeopcount = mp->mnt_writeopcount;
1826         CPU_FOREACH(cpu) {
1827                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1828                 printf("%d ", mpcpu->mntp_writeopcount);
1829                 writeopcount += mpcpu->mntp_writeopcount;
1830         }
1831         printf("\n");
1832
1833         printf("counter       struct total\n");
1834         printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1835         printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1836         printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1837
1838         panic("invalid counts on struct mount");
1839 }
1840 #endif
1841
1842 int
1843 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1844 {
1845         struct mount_pcpu *mpcpu;
1846         int cpu, sum;
1847
1848         switch (which) {
1849         case MNT_COUNT_REF:
1850                 sum = mp->mnt_ref;
1851                 break;
1852         case MNT_COUNT_LOCKREF:
1853                 sum = mp->mnt_lockref;
1854                 break;
1855         case MNT_COUNT_WRITEOPCOUNT:
1856                 sum = mp->mnt_writeopcount;
1857                 break;
1858         }
1859
1860         CPU_FOREACH(cpu) {
1861                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1862                 switch (which) {
1863                 case MNT_COUNT_REF:
1864                         sum += mpcpu->mntp_ref;
1865                         break;
1866                 case MNT_COUNT_LOCKREF:
1867                         sum += mpcpu->mntp_lockref;
1868                         break;
1869                 case MNT_COUNT_WRITEOPCOUNT:
1870                         sum += mpcpu->mntp_writeopcount;
1871                         break;
1872                 }
1873         }
1874         return (sum);
1875 }
1876
1877 /*
1878  * Do the actual filesystem unmount.
1879  */
1880 int
1881 dounmount(struct mount *mp, int flags, struct thread *td)
1882 {
1883         struct vnode *coveredvp, *rootvp;
1884         int error;
1885         uint64_t async_flag;
1886         int mnt_gen_r;
1887
1888         if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
1889                 mnt_gen_r = mp->mnt_gen;
1890                 VI_LOCK(coveredvp);
1891                 vholdl(coveredvp);
1892                 vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
1893                 /*
1894                  * Check for mp being unmounted while waiting for the
1895                  * covered vnode lock.
1896                  */
1897                 if (coveredvp->v_mountedhere != mp ||
1898                     coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
1899                         VOP_UNLOCK(coveredvp);
1900                         vdrop(coveredvp);
1901                         vfs_rel(mp);
1902                         return (EBUSY);
1903                 }
1904         }
1905
1906         /*
1907          * Only privileged root, or (if MNT_USER is set) the user that did the
1908          * original mount is permitted to unmount this filesystem.
1909          */
1910         error = vfs_suser(mp, td);
1911         if (error != 0) {
1912                 if (coveredvp != NULL) {
1913                         VOP_UNLOCK(coveredvp);
1914                         vdrop(coveredvp);
1915                 }
1916                 vfs_rel(mp);
1917                 return (error);
1918         }
1919
1920         vfs_op_enter(mp);
1921
1922         vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
1923         MNT_ILOCK(mp);
1924         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
1925             (mp->mnt_flag & MNT_UPDATE) != 0 ||
1926             !TAILQ_EMPTY(&mp->mnt_uppers)) {
1927                 dounmount_cleanup(mp, coveredvp, 0);
1928                 return (EBUSY);
1929         }
1930         mp->mnt_kern_flag |= MNTK_UNMOUNT;
1931         rootvp = vfs_cache_root_clear(mp);
1932         if (coveredvp != NULL)
1933                 vn_seqc_write_begin(coveredvp);
1934         if (flags & MNT_NONBUSY) {
1935                 MNT_IUNLOCK(mp);
1936                 error = vfs_check_usecounts(mp);
1937                 MNT_ILOCK(mp);
1938                 if (error != 0) {
1939                         vn_seqc_write_end(coveredvp);
1940                         dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
1941                         if (rootvp != NULL) {
1942                                 vn_seqc_write_end(rootvp);
1943                                 vrele(rootvp);
1944                         }
1945                         return (error);
1946                 }
1947         }
1948         /* Allow filesystems to detect that a forced unmount is in progress. */
1949         if (flags & MNT_FORCE) {
1950                 mp->mnt_kern_flag |= MNTK_UNMOUNTF;
1951                 MNT_IUNLOCK(mp);
1952                 /*
1953                  * Must be done after setting MNTK_UNMOUNTF and before
1954                  * waiting for mnt_lockref to become 0.
1955                  */
1956                 VFS_PURGE(mp);
1957                 MNT_ILOCK(mp);
1958         }
1959         error = 0;
1960         if (mp->mnt_lockref) {
1961                 mp->mnt_kern_flag |= MNTK_DRAINING;
1962                 error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
1963                     "mount drain", 0);
1964         }
1965         MNT_IUNLOCK(mp);
1966         KASSERT(mp->mnt_lockref == 0,
1967             ("%s: invalid lock refcount in the drain path @ %s:%d",
1968             __func__, __FILE__, __LINE__));
1969         KASSERT(error == 0,
1970             ("%s: invalid return value for msleep in the drain path @ %s:%d",
1971             __func__, __FILE__, __LINE__));
1972
1973         /*
1974          * We want to keep the vnode around so that we can vn_seqc_write_end
1975          * after we are done with unmount. Downgrade our reference to a mere
1976          * hold count so that we don't interefere with anything.
1977          */
1978         if (rootvp != NULL) {
1979                 vhold(rootvp);
1980                 vrele(rootvp);
1981         }
1982
1983         if (mp->mnt_flag & MNT_EXPUBLIC)
1984                 vfs_setpublicfs(NULL, NULL, NULL);
1985
1986         vfs_periodic(mp, MNT_WAIT);
1987         MNT_ILOCK(mp);
1988         async_flag = mp->mnt_flag & MNT_ASYNC;
1989         mp->mnt_flag &= ~MNT_ASYNC;
1990         mp->mnt_kern_flag &= ~MNTK_ASYNC;
1991         MNT_IUNLOCK(mp);
1992         vfs_deallocate_syncvnode(mp);
1993         error = VFS_UNMOUNT(mp, flags);
1994         vn_finished_write(mp);
1995         /*
1996          * If we failed to flush the dirty blocks for this mount point,
1997          * undo all the cdir/rdir and rootvnode changes we made above.
1998          * Unless we failed to do so because the device is reporting that
1999          * it doesn't exist anymore.
2000          */
2001         if (error && error != ENXIO) {
2002                 MNT_ILOCK(mp);
2003                 if ((mp->mnt_flag & MNT_RDONLY) == 0) {
2004                         MNT_IUNLOCK(mp);
2005                         vfs_allocate_syncvnode(mp);
2006                         MNT_ILOCK(mp);
2007                 }
2008                 mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
2009                 mp->mnt_flag |= async_flag;
2010                 if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
2011                     (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
2012                         mp->mnt_kern_flag |= MNTK_ASYNC;
2013                 if (mp->mnt_kern_flag & MNTK_MWAIT) {
2014                         mp->mnt_kern_flag &= ~MNTK_MWAIT;
2015                         wakeup(mp);
2016                 }
2017                 vfs_op_exit_locked(mp);
2018                 MNT_IUNLOCK(mp);
2019                 if (coveredvp) {
2020                         vn_seqc_write_end(coveredvp);
2021                         VOP_UNLOCK(coveredvp);
2022                         vdrop(coveredvp);
2023                 }
2024                 if (rootvp != NULL) {
2025                         vn_seqc_write_end(rootvp);
2026                         vdrop(rootvp);
2027                 }
2028                 return (error);
2029         }
2030         mtx_lock(&mountlist_mtx);
2031         TAILQ_REMOVE(&mountlist, mp, mnt_list);
2032         mtx_unlock(&mountlist_mtx);
2033         EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
2034         if (coveredvp != NULL) {
2035                 VI_LOCK(coveredvp);
2036                 vn_irflag_unset_locked(coveredvp, VIRF_MOUNTPOINT);
2037                 coveredvp->v_mountedhere = NULL;
2038                 vn_seqc_write_end_locked(coveredvp);
2039                 VI_UNLOCK(coveredvp);
2040                 VOP_UNLOCK(coveredvp);
2041                 vdrop(coveredvp);
2042         }
2043         mount_devctl_event("UNMOUNT", mp, false);
2044         if (rootvp != NULL) {
2045                 vn_seqc_write_end(rootvp);
2046                 vdrop(rootvp);
2047         }
2048         vfs_event_signal(NULL, VQ_UNMOUNT, 0);
2049         if (rootvnode != NULL && mp == rootvnode->v_mount) {
2050                 vrele(rootvnode);
2051                 rootvnode = NULL;
2052         }
2053         if (mp == rootdevmp)
2054                 rootdevmp = NULL;
2055         vfs_mount_destroy(mp);
2056         return (0);
2057 }
2058
2059 /*
2060  * Report errors during filesystem mounting.
2061  */
2062 void
2063 vfs_mount_error(struct mount *mp, const char *fmt, ...)
2064 {
2065         struct vfsoptlist *moptlist = mp->mnt_optnew;
2066         va_list ap;
2067         int error, len;
2068         char *errmsg;
2069
2070         error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
2071         if (error || errmsg == NULL || len <= 0)
2072                 return;
2073
2074         va_start(ap, fmt);
2075         vsnprintf(errmsg, (size_t)len, fmt, ap);
2076         va_end(ap);
2077 }
2078
2079 void
2080 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
2081 {
2082         va_list ap;
2083         int error, len;
2084         char *errmsg;
2085
2086         error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
2087         if (error || errmsg == NULL || len <= 0)
2088                 return;
2089
2090         va_start(ap, fmt);
2091         vsnprintf(errmsg, (size_t)len, fmt, ap);
2092         va_end(ap);
2093 }
2094
2095 /*
2096  * ---------------------------------------------------------------------
2097  * Functions for querying mount options/arguments from filesystems.
2098  */
2099
2100 /*
2101  * Check that no unknown options are given
2102  */
2103 int
2104 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
2105 {
2106         struct vfsopt *opt;
2107         char errmsg[255];
2108         const char **t, *p, *q;
2109         int ret = 0;
2110
2111         TAILQ_FOREACH(opt, opts, link) {
2112                 p = opt->name;
2113                 q = NULL;
2114                 if (p[0] == 'n' && p[1] == 'o')
2115                         q = p + 2;
2116                 for(t = global_opts; *t != NULL; t++) {
2117                         if (strcmp(*t, p) == 0)
2118                                 break;
2119                         if (q != NULL) {
2120                                 if (strcmp(*t, q) == 0)
2121                                         break;
2122                         }
2123                 }
2124                 if (*t != NULL)
2125                         continue;
2126                 for(t = legal; *t != NULL; t++) {
2127                         if (strcmp(*t, p) == 0)
2128                                 break;
2129                         if (q != NULL) {
2130                                 if (strcmp(*t, q) == 0)
2131                                         break;
2132                         }
2133                 }
2134                 if (*t != NULL)
2135                         continue;
2136                 snprintf(errmsg, sizeof(errmsg),
2137                     "mount option <%s> is unknown", p);
2138                 ret = EINVAL;
2139         }
2140         if (ret != 0) {
2141                 TAILQ_FOREACH(opt, opts, link) {
2142                         if (strcmp(opt->name, "errmsg") == 0) {
2143                                 strncpy((char *)opt->value, errmsg, opt->len);
2144                                 break;
2145                         }
2146                 }
2147                 if (opt == NULL)
2148                         printf("%s\n", errmsg);
2149         }
2150         return (ret);
2151 }
2152
2153 /*
2154  * Get a mount option by its name.
2155  *
2156  * Return 0 if the option was found, ENOENT otherwise.
2157  * If len is non-NULL it will be filled with the length
2158  * of the option. If buf is non-NULL, it will be filled
2159  * with the address of the option.
2160  */
2161 int
2162 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
2163 {
2164         struct vfsopt *opt;
2165
2166         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2167
2168         TAILQ_FOREACH(opt, opts, link) {
2169                 if (strcmp(name, opt->name) == 0) {
2170                         opt->seen = 1;
2171                         if (len != NULL)
2172                                 *len = opt->len;
2173                         if (buf != NULL)
2174                                 *buf = opt->value;
2175                         return (0);
2176                 }
2177         }
2178         return (ENOENT);
2179 }
2180
2181 int
2182 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
2183 {
2184         struct vfsopt *opt;
2185
2186         if (opts == NULL)
2187                 return (-1);
2188
2189         TAILQ_FOREACH(opt, opts, link) {
2190                 if (strcmp(name, opt->name) == 0) {
2191                         opt->seen = 1;
2192                         return (opt->pos);
2193                 }
2194         }
2195         return (-1);
2196 }
2197
2198 int
2199 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
2200 {
2201         char *opt_value, *vtp;
2202         quad_t iv;
2203         int error, opt_len;
2204
2205         error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
2206         if (error != 0)
2207                 return (error);
2208         if (opt_len == 0 || opt_value == NULL)
2209                 return (EINVAL);
2210         if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
2211                 return (EINVAL);
2212         iv = strtoq(opt_value, &vtp, 0);
2213         if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
2214                 return (EINVAL);
2215         if (iv < 0)
2216                 return (EINVAL);
2217         switch (vtp[0]) {
2218         case 't': case 'T':
2219                 iv *= 1024;
2220                 /* FALLTHROUGH */
2221         case 'g': case 'G':
2222                 iv *= 1024;
2223                 /* FALLTHROUGH */
2224         case 'm': case 'M':
2225                 iv *= 1024;
2226                 /* FALLTHROUGH */
2227         case 'k': case 'K':
2228                 iv *= 1024;
2229         case '\0':
2230                 break;
2231         default:
2232                 return (EINVAL);
2233         }
2234         *value = iv;
2235
2236         return (0);
2237 }
2238
2239 char *
2240 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
2241 {
2242         struct vfsopt *opt;
2243
2244         *error = 0;
2245         TAILQ_FOREACH(opt, opts, link) {
2246                 if (strcmp(name, opt->name) != 0)
2247                         continue;
2248                 opt->seen = 1;
2249                 if (opt->len == 0 ||
2250                     ((char *)opt->value)[opt->len - 1] != '\0') {
2251                         *error = EINVAL;
2252                         return (NULL);
2253                 }
2254                 return (opt->value);
2255         }
2256         *error = ENOENT;
2257         return (NULL);
2258 }
2259
2260 int
2261 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
2262         uint64_t val)
2263 {
2264         struct vfsopt *opt;
2265
2266         TAILQ_FOREACH(opt, opts, link) {
2267                 if (strcmp(name, opt->name) == 0) {
2268                         opt->seen = 1;
2269                         if (w != NULL)
2270                                 *w |= val;
2271                         return (1);
2272                 }
2273         }
2274         if (w != NULL)
2275                 *w &= ~val;
2276         return (0);
2277 }
2278
2279 int
2280 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
2281 {
2282         va_list ap;
2283         struct vfsopt *opt;
2284         int ret;
2285
2286         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2287
2288         TAILQ_FOREACH(opt, opts, link) {
2289                 if (strcmp(name, opt->name) != 0)
2290                         continue;
2291                 opt->seen = 1;
2292                 if (opt->len == 0 || opt->value == NULL)
2293                         return (0);
2294                 if (((char *)opt->value)[opt->len - 1] != '\0')
2295                         return (0);
2296                 va_start(ap, fmt);
2297                 ret = vsscanf(opt->value, fmt, ap);
2298                 va_end(ap);
2299                 return (ret);
2300         }
2301         return (0);
2302 }
2303
2304 int
2305 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
2306 {
2307         struct vfsopt *opt;
2308
2309         TAILQ_FOREACH(opt, opts, link) {
2310                 if (strcmp(name, opt->name) != 0)
2311                         continue;
2312                 opt->seen = 1;
2313                 if (opt->value == NULL)
2314                         opt->len = len;
2315                 else {
2316                         if (opt->len != len)
2317                                 return (EINVAL);
2318                         bcopy(value, opt->value, len);
2319                 }
2320                 return (0);
2321         }
2322         return (ENOENT);
2323 }
2324
2325 int
2326 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2327 {
2328         struct vfsopt *opt;
2329
2330         TAILQ_FOREACH(opt, opts, link) {
2331                 if (strcmp(name, opt->name) != 0)
2332                         continue;
2333                 opt->seen = 1;
2334                 if (opt->value == NULL)
2335                         opt->len = len;
2336                 else {
2337                         if (opt->len < len)
2338                                 return (EINVAL);
2339                         opt->len = len;
2340                         bcopy(value, opt->value, len);
2341                 }
2342                 return (0);
2343         }
2344         return (ENOENT);
2345 }
2346
2347 int
2348 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2349 {
2350         struct vfsopt *opt;
2351
2352         TAILQ_FOREACH(opt, opts, link) {
2353                 if (strcmp(name, opt->name) != 0)
2354                         continue;
2355                 opt->seen = 1;
2356                 if (opt->value == NULL)
2357                         opt->len = strlen(value) + 1;
2358                 else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2359                         return (EINVAL);
2360                 return (0);
2361         }
2362         return (ENOENT);
2363 }
2364
2365 /*
2366  * Find and copy a mount option.
2367  *
2368  * The size of the buffer has to be specified
2369  * in len, if it is not the same length as the
2370  * mount option, EINVAL is returned.
2371  * Returns ENOENT if the option is not found.
2372  */
2373 int
2374 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2375 {
2376         struct vfsopt *opt;
2377
2378         KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2379
2380         TAILQ_FOREACH(opt, opts, link) {
2381                 if (strcmp(name, opt->name) == 0) {
2382                         opt->seen = 1;
2383                         if (len != opt->len)
2384                                 return (EINVAL);
2385                         bcopy(opt->value, dest, opt->len);
2386                         return (0);
2387                 }
2388         }
2389         return (ENOENT);
2390 }
2391
2392 int
2393 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2394 {
2395
2396         /*
2397          * Filesystems only fill in part of the structure for updates, we
2398          * have to read the entirety first to get all content.
2399          */
2400         if (sbp != &mp->mnt_stat)
2401                 memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2402
2403         /*
2404          * Set these in case the underlying filesystem fails to do so.
2405          */
2406         sbp->f_version = STATFS_VERSION;
2407         sbp->f_namemax = NAME_MAX;
2408         sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2409
2410         return (mp->mnt_op->vfs_statfs(mp, sbp));
2411 }
2412
2413 void
2414 vfs_mountedfrom(struct mount *mp, const char *from)
2415 {
2416
2417         bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2418         strlcpy(mp->mnt_stat.f_mntfromname, from,
2419             sizeof mp->mnt_stat.f_mntfromname);
2420 }
2421
2422 /*
2423  * ---------------------------------------------------------------------
2424  * This is the api for building mount args and mounting filesystems from
2425  * inside the kernel.
2426  *
2427  * The API works by accumulation of individual args.  First error is
2428  * latched.
2429  *
2430  * XXX: should be documented in new manpage kernel_mount(9)
2431  */
2432
2433 /* A memory allocation which must be freed when we are done */
2434 struct mntaarg {
2435         SLIST_ENTRY(mntaarg)    next;
2436 };
2437
2438 /* The header for the mount arguments */
2439 struct mntarg {
2440         struct iovec *v;
2441         int len;
2442         int error;
2443         SLIST_HEAD(, mntaarg)   list;
2444 };
2445
2446 /*
2447  * Add a boolean argument.
2448  *
2449  * flag is the boolean value.
2450  * name must start with "no".
2451  */
2452 struct mntarg *
2453 mount_argb(struct mntarg *ma, int flag, const char *name)
2454 {
2455
2456         KASSERT(name[0] == 'n' && name[1] == 'o',
2457             ("mount_argb(...,%s): name must start with 'no'", name));
2458
2459         return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2460 }
2461
2462 /*
2463  * Add an argument printf style
2464  */
2465 struct mntarg *
2466 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2467 {
2468         va_list ap;
2469         struct mntaarg *maa;
2470         struct sbuf *sb;
2471         int len;
2472
2473         if (ma == NULL) {
2474                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2475                 SLIST_INIT(&ma->list);
2476         }
2477         if (ma->error)
2478                 return (ma);
2479
2480         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2481             M_MOUNT, M_WAITOK);
2482         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2483         ma->v[ma->len].iov_len = strlen(name) + 1;
2484         ma->len++;
2485
2486         sb = sbuf_new_auto();
2487         va_start(ap, fmt);
2488         sbuf_vprintf(sb, fmt, ap);
2489         va_end(ap);
2490         sbuf_finish(sb);
2491         len = sbuf_len(sb) + 1;
2492         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2493         SLIST_INSERT_HEAD(&ma->list, maa, next);
2494         bcopy(sbuf_data(sb), maa + 1, len);
2495         sbuf_delete(sb);
2496
2497         ma->v[ma->len].iov_base = maa + 1;
2498         ma->v[ma->len].iov_len = len;
2499         ma->len++;
2500
2501         return (ma);
2502 }
2503
2504 /*
2505  * Add an argument which is a userland string.
2506  */
2507 struct mntarg *
2508 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2509 {
2510         struct mntaarg *maa;
2511         char *tbuf;
2512
2513         if (val == NULL)
2514                 return (ma);
2515         if (ma == NULL) {
2516                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2517                 SLIST_INIT(&ma->list);
2518         }
2519         if (ma->error)
2520                 return (ma);
2521         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2522         SLIST_INSERT_HEAD(&ma->list, maa, next);
2523         tbuf = (void *)(maa + 1);
2524         ma->error = copyinstr(val, tbuf, len, NULL);
2525         return (mount_arg(ma, name, tbuf, -1));
2526 }
2527
2528 /*
2529  * Plain argument.
2530  *
2531  * If length is -1, treat value as a C string.
2532  */
2533 struct mntarg *
2534 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2535 {
2536
2537         if (ma == NULL) {
2538                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2539                 SLIST_INIT(&ma->list);
2540         }
2541         if (ma->error)
2542                 return (ma);
2543
2544         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2545             M_MOUNT, M_WAITOK);
2546         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2547         ma->v[ma->len].iov_len = strlen(name) + 1;
2548         ma->len++;
2549
2550         ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2551         if (len < 0)
2552                 ma->v[ma->len].iov_len = strlen(val) + 1;
2553         else
2554                 ma->v[ma->len].iov_len = len;
2555         ma->len++;
2556         return (ma);
2557 }
2558
2559 /*
2560  * Free a mntarg structure
2561  */
2562 static void
2563 free_mntarg(struct mntarg *ma)
2564 {
2565         struct mntaarg *maa;
2566
2567         while (!SLIST_EMPTY(&ma->list)) {
2568                 maa = SLIST_FIRST(&ma->list);
2569                 SLIST_REMOVE_HEAD(&ma->list, next);
2570                 free(maa, M_MOUNT);
2571         }
2572         free(ma->v, M_MOUNT);
2573         free(ma, M_MOUNT);
2574 }
2575
2576 /*
2577  * Mount a filesystem
2578  */
2579 int
2580 kernel_mount(struct mntarg *ma, uint64_t flags)
2581 {
2582         struct uio auio;
2583         int error;
2584
2585         KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2586         KASSERT(ma->error != 0 || ma->v != NULL, ("kernel_mount NULL ma->v"));
2587         KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2588
2589         error = ma->error;
2590         if (error == 0) {
2591                 auio.uio_iov = ma->v;
2592                 auio.uio_iovcnt = ma->len;
2593                 auio.uio_segflg = UIO_SYSSPACE;
2594                 error = vfs_donmount(curthread, flags, &auio);
2595         }
2596         free_mntarg(ma);
2597         return (error);
2598 }
2599
2600 /*
2601  * A printflike function to mount a filesystem.
2602  */
2603 int
2604 kernel_vmount(int flags, ...)
2605 {
2606         struct mntarg *ma = NULL;
2607         va_list ap;
2608         const char *cp;
2609         const void *vp;
2610         int error;
2611
2612         va_start(ap, flags);
2613         for (;;) {
2614                 cp = va_arg(ap, const char *);
2615                 if (cp == NULL)
2616                         break;
2617                 vp = va_arg(ap, const void *);
2618                 ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2619         }
2620         va_end(ap);
2621
2622         error = kernel_mount(ma, flags);
2623         return (error);
2624 }
2625
2626 /* Map from mount options to printable formats. */
2627 static struct mntoptnames optnames[] = {
2628         MNTOPT_NAMES
2629 };
2630
2631 #define DEVCTL_LEN 1024
2632 static void
2633 mount_devctl_event(const char *type, struct mount *mp, bool donew)
2634 {
2635         const uint8_t *cp;
2636         struct mntoptnames *fp;
2637         struct sbuf sb;
2638         struct statfs *sfp = &mp->mnt_stat;
2639         char *buf;
2640
2641         buf = malloc(DEVCTL_LEN, M_MOUNT, M_NOWAIT);
2642         if (buf == NULL)
2643                 return;
2644         sbuf_new(&sb, buf, DEVCTL_LEN, SBUF_FIXEDLEN);
2645         sbuf_cpy(&sb, "mount-point=\"");
2646         devctl_safe_quote_sb(&sb, sfp->f_mntonname);
2647         sbuf_cat(&sb, "\" mount-dev=\"");
2648         devctl_safe_quote_sb(&sb, sfp->f_mntfromname);
2649         sbuf_cat(&sb, "\" mount-type=\"");
2650         devctl_safe_quote_sb(&sb, sfp->f_fstypename);
2651         sbuf_cat(&sb, "\" fsid=0x");
2652         cp = (const uint8_t *)&sfp->f_fsid.val[0];
2653         for (int i = 0; i < sizeof(sfp->f_fsid); i++)
2654                 sbuf_printf(&sb, "%02x", cp[i]);
2655         sbuf_printf(&sb, " owner=%u flags=\"", sfp->f_owner);
2656         for (fp = optnames; fp->o_opt != 0; fp++) {
2657                 if ((mp->mnt_flag & fp->o_opt) != 0) {
2658                         sbuf_cat(&sb, fp->o_name);
2659                         sbuf_putc(&sb, ';');
2660                 }
2661         }
2662         sbuf_putc(&sb, '"');
2663         sbuf_finish(&sb);
2664
2665         /*
2666          * Options are not published because the form of the options depends on
2667          * the file system and may include binary data. In addition, they don't
2668          * necessarily provide enough useful information to be actionable when
2669          * devd processes them.
2670          */
2671
2672         if (sbuf_error(&sb) == 0)
2673                 devctl_notify("VFS", "FS", type, sbuf_data(&sb));
2674         sbuf_delete(&sb);
2675         free(buf, M_MOUNT);
2676 }
2677
2678 /*
2679  * Force remount specified mount point to read-only.  The argument
2680  * must be busied to avoid parallel unmount attempts.
2681  *
2682  * Intended use is to prevent further writes if some metadata
2683  * inconsistency is detected.  Note that the function still flushes
2684  * all cached metadata and data for the mount point, which might be
2685  * not always suitable.
2686  */
2687 int
2688 vfs_remount_ro(struct mount *mp)
2689 {
2690         struct vfsoptlist *opts;
2691         struct vfsopt *opt;
2692         struct vnode *vp_covered, *rootvp;
2693         int error;
2694
2695         KASSERT(mp->mnt_lockref > 0,
2696             ("vfs_remount_ro: mp %p is not busied", mp));
2697         KASSERT((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0,
2698             ("vfs_remount_ro: mp %p is being unmounted (and busy?)", mp));
2699
2700         rootvp = NULL;
2701         vp_covered = mp->mnt_vnodecovered;
2702         error = vget(vp_covered, LK_EXCLUSIVE | LK_NOWAIT);
2703         if (error != 0)
2704                 return (error);
2705         VI_LOCK(vp_covered);
2706         if ((vp_covered->v_iflag & VI_MOUNT) != 0) {
2707                 VI_UNLOCK(vp_covered);
2708                 vput(vp_covered);
2709                 return (EBUSY);
2710         }
2711         vp_covered->v_iflag |= VI_MOUNT;
2712         VI_UNLOCK(vp_covered);
2713         vfs_op_enter(mp);
2714         vn_seqc_write_begin(vp_covered);
2715
2716         MNT_ILOCK(mp);
2717         if ((mp->mnt_flag & MNT_RDONLY) != 0) {
2718                 MNT_IUNLOCK(mp);
2719                 error = EBUSY;
2720                 goto out;
2721         }
2722         mp->mnt_flag |= MNT_UPDATE | MNT_FORCE | MNT_RDONLY;
2723         rootvp = vfs_cache_root_clear(mp);
2724         MNT_IUNLOCK(mp);
2725
2726         opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK | M_ZERO);
2727         TAILQ_INIT(opts);
2728         opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK | M_ZERO);
2729         opt->name = strdup("ro", M_MOUNT);
2730         opt->value = NULL;
2731         TAILQ_INSERT_TAIL(opts, opt, link);
2732         vfs_mergeopts(opts, mp->mnt_opt);
2733         mp->mnt_optnew = opts;
2734
2735         error = VFS_MOUNT(mp);
2736
2737         if (error == 0) {
2738                 MNT_ILOCK(mp);
2739                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_FORCE);
2740                 MNT_IUNLOCK(mp);
2741                 vfs_deallocate_syncvnode(mp);
2742                 if (mp->mnt_opt != NULL)
2743                         vfs_freeopts(mp->mnt_opt);
2744                 mp->mnt_opt = mp->mnt_optnew;
2745         } else {
2746                 MNT_ILOCK(mp);
2747                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_FORCE | MNT_RDONLY);
2748                 MNT_IUNLOCK(mp);
2749                 vfs_freeopts(mp->mnt_optnew);
2750         }
2751         mp->mnt_optnew = NULL;
2752
2753 out:
2754         vfs_op_exit(mp);
2755         VI_LOCK(vp_covered);
2756         vp_covered->v_iflag &= ~VI_MOUNT;
2757         VI_UNLOCK(vp_covered);
2758         vput(vp_covered);
2759         vn_seqc_write_end(vp_covered);
2760         if (rootvp != NULL) {
2761                 vn_seqc_write_end(rootvp);
2762                 vrele(rootvp);
2763         }
2764         return (error);
2765 }
2766
2767 /*
2768  * Suspend write operations on all local writeable filesystems.  Does
2769  * full sync of them in the process.
2770  *
2771  * Iterate over the mount points in reverse order, suspending most
2772  * recently mounted filesystems first.  It handles a case where a
2773  * filesystem mounted from a md(4) vnode-backed device should be
2774  * suspended before the filesystem that owns the vnode.
2775  */
2776 void
2777 suspend_all_fs(void)
2778 {
2779         struct mount *mp;
2780         int error;
2781
2782         mtx_lock(&mountlist_mtx);
2783         TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
2784                 error = vfs_busy(mp, MBF_MNTLSTLOCK | MBF_NOWAIT);
2785                 if (error != 0)
2786                         continue;
2787                 if ((mp->mnt_flag & (MNT_RDONLY | MNT_LOCAL)) != MNT_LOCAL ||
2788                     (mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2789                         mtx_lock(&mountlist_mtx);
2790                         vfs_unbusy(mp);
2791                         continue;
2792                 }
2793                 error = vfs_write_suspend(mp, 0);
2794                 if (error == 0) {
2795                         MNT_ILOCK(mp);
2796                         MPASS((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0);
2797                         mp->mnt_kern_flag |= MNTK_SUSPEND_ALL;
2798                         MNT_IUNLOCK(mp);
2799                         mtx_lock(&mountlist_mtx);
2800                 } else {
2801                         printf("suspend of %s failed, error %d\n",
2802                             mp->mnt_stat.f_mntonname, error);
2803                         mtx_lock(&mountlist_mtx);
2804                         vfs_unbusy(mp);
2805                 }
2806         }
2807         mtx_unlock(&mountlist_mtx);
2808 }
2809
2810 void
2811 resume_all_fs(void)
2812 {
2813         struct mount *mp;
2814
2815         mtx_lock(&mountlist_mtx);
2816         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2817                 if ((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0)
2818                         continue;
2819                 mtx_unlock(&mountlist_mtx);
2820                 MNT_ILOCK(mp);
2821                 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) != 0);
2822                 mp->mnt_kern_flag &= ~MNTK_SUSPEND_ALL;
2823                 MNT_IUNLOCK(mp);
2824                 vfs_write_resume(mp, 0);
2825                 mtx_lock(&mountlist_mtx);
2826                 vfs_unbusy(mp);
2827         }
2828         mtx_unlock(&mountlist_mtx);
2829 }