]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_mount.c
hv_kbd: Fix build with EVDEV_SUPPORT kernel option disabled.
[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                         (void)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, fsid_up_len;
1158         uint64_t flag;
1159         gid_t *grps;
1160         fsid_t *fsid_up;
1161         bool vfs_suser_failed;
1162
1163         ASSERT_VOP_ELOCKED(vp, __func__);
1164         KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1165         mp = vp->v_mount;
1166
1167         if ((vp->v_vflag & VV_ROOT) == 0) {
1168                 if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1169                     == 0)
1170                         error = EXDEV;
1171                 else
1172                         error = EINVAL;
1173                 vput(vp);
1174                 return (error);
1175         }
1176
1177         /*
1178          * We only allow the filesystem to be reloaded if it
1179          * is currently mounted read-only.
1180          */
1181         flag = mp->mnt_flag;
1182         if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1183                 vput(vp);
1184                 return (EOPNOTSUPP);    /* Needs translation */
1185         }
1186         /*
1187          * Only privileged root, or (if MNT_USER is set) the user that
1188          * did the original mount is permitted to update it.
1189          */
1190         /*
1191          * For the case of mountd(8) doing exports in a jail, the vfs_suser()
1192          * call does not cause failure.  vfs_domount() has already checked
1193          * that "root" is doing this and vfs_suser() will fail when
1194          * the file system has been mounted outside the jail.
1195          * jail_export set true indicates that "export" is not mixed
1196          * with other options that change mount behaviour.
1197          */
1198         vfs_suser_failed = false;
1199         error = vfs_suser(mp, td);
1200         if (jail_export && error != 0) {
1201                 error = 0;
1202                 vfs_suser_failed = true;
1203         }
1204         if (error != 0) {
1205                 vput(vp);
1206                 return (error);
1207         }
1208         if (vfs_busy(mp, MBF_NOWAIT)) {
1209                 vput(vp);
1210                 return (EBUSY);
1211         }
1212         VI_LOCK(vp);
1213         if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1214                 VI_UNLOCK(vp);
1215                 vfs_unbusy(mp);
1216                 vput(vp);
1217                 return (EBUSY);
1218         }
1219         vp->v_iflag |= VI_MOUNT;
1220         VI_UNLOCK(vp);
1221         VOP_UNLOCK(vp);
1222
1223         rootvp = NULL;
1224         vfs_op_enter(mp);
1225         vn_seqc_write_begin(vp);
1226
1227         if (vfs_getopt(*optlist, "fsid", (void **)&fsid_up,
1228             &fsid_up_len) == 0) {
1229                 if (fsid_up_len != sizeof(*fsid_up)) {
1230                         error = EINVAL;
1231                         goto end;
1232                 }
1233                 if (fsidcmp(fsid_up, &mp->mnt_stat.f_fsid) != 0) {
1234                         error = ENOENT;
1235                         goto end;
1236                 }
1237                 vfs_deleteopt(*optlist, "fsid");
1238         }
1239
1240         MNT_ILOCK(mp);
1241         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1242                 MNT_IUNLOCK(mp);
1243                 error = EBUSY;
1244                 goto end;
1245         }
1246         if (vfs_suser_failed) {
1247                 KASSERT((fsflags & (MNT_EXPORTED | MNT_UPDATE)) ==
1248                     (MNT_EXPORTED | MNT_UPDATE),
1249                     ("%s: jailed export did not set expected fsflags",
1250                      __func__));
1251                 /*
1252                  * For this case, only MNT_UPDATE and
1253                  * MNT_EXPORTED have been set in fsflags
1254                  * by the options.  Only set MNT_UPDATE,
1255                  * since that is the one that would be set
1256                  * when set in fsflags, below.
1257                  */
1258                 mp->mnt_flag |= MNT_UPDATE;
1259         } else {
1260                 mp->mnt_flag &= ~MNT_UPDATEMASK;
1261                 mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1262                     MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1263                 if ((mp->mnt_flag & MNT_ASYNC) == 0)
1264                         mp->mnt_kern_flag &= ~MNTK_ASYNC;
1265         }
1266         rootvp = vfs_cache_root_clear(mp);
1267         MNT_IUNLOCK(mp);
1268         mp->mnt_optnew = *optlist;
1269         vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1270
1271         /*
1272          * Mount the filesystem.
1273          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1274          * get.  No freeing of cn_pnbuf.
1275          */
1276         /*
1277          * For the case of mountd(8) doing exports from within a vnet jail,
1278          * "from" is typically not set correctly such that VFS_MOUNT() will
1279          * return ENOENT. It is not obvious that VFS_MOUNT() ever needs to be
1280          * called when mountd is doing exports, but this check only applies to
1281          * the specific case where it is running inside a vnet jail, to
1282          * avoid any POLA violation.
1283          */
1284         error = 0;
1285         if (!jail_export)
1286                 error = VFS_MOUNT(mp);
1287
1288         export_error = 0;
1289         /* Process the export option. */
1290         if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1291             &len) == 0) {
1292                 /* Assume that there is only 1 ABI for each length. */
1293                 switch (len) {
1294                 case (sizeof(struct oexport_args)):
1295                         bzero(&o2export, sizeof(o2export));
1296                         /* FALLTHROUGH */
1297                 case (sizeof(o2export)):
1298                         bcopy(bufp, &o2export, len);
1299                         export.ex_flags = (uint64_t)o2export.ex_flags;
1300                         export.ex_root = o2export.ex_root;
1301                         export.ex_uid = o2export.ex_anon.cr_uid;
1302                         export.ex_groups = NULL;
1303                         export.ex_ngroups = o2export.ex_anon.cr_ngroups;
1304                         if (export.ex_ngroups > 0) {
1305                                 if (export.ex_ngroups <= XU_NGROUPS) {
1306                                         export.ex_groups = malloc(
1307                                             export.ex_ngroups * sizeof(gid_t),
1308                                             M_TEMP, M_WAITOK);
1309                                         for (i = 0; i < export.ex_ngroups; i++)
1310                                                 export.ex_groups[i] =
1311                                                   o2export.ex_anon.cr_groups[i];
1312                                 } else
1313                                         export_error = EINVAL;
1314                         } else if (export.ex_ngroups < 0)
1315                                 export_error = EINVAL;
1316                         export.ex_addr = o2export.ex_addr;
1317                         export.ex_addrlen = o2export.ex_addrlen;
1318                         export.ex_mask = o2export.ex_mask;
1319                         export.ex_masklen = o2export.ex_masklen;
1320                         export.ex_indexfile = o2export.ex_indexfile;
1321                         export.ex_numsecflavors = o2export.ex_numsecflavors;
1322                         if (export.ex_numsecflavors < MAXSECFLAVORS) {
1323                                 for (i = 0; i < export.ex_numsecflavors; i++)
1324                                         export.ex_secflavors[i] =
1325                                             o2export.ex_secflavors[i];
1326                         } else
1327                                 export_error = EINVAL;
1328                         if (export_error == 0)
1329                                 export_error = vfs_export(mp, &export, 1);
1330                         free(export.ex_groups, M_TEMP);
1331                         break;
1332                 case (sizeof(export)):
1333                         bcopy(bufp, &export, len);
1334                         grps = NULL;
1335                         if (export.ex_ngroups > 0) {
1336                                 if (export.ex_ngroups <= NGROUPS_MAX) {
1337                                         grps = malloc(export.ex_ngroups *
1338                                             sizeof(gid_t), M_TEMP, M_WAITOK);
1339                                         export_error = copyin(export.ex_groups,
1340                                             grps, export.ex_ngroups *
1341                                             sizeof(gid_t));
1342                                         if (export_error == 0)
1343                                                 export.ex_groups = grps;
1344                                 } else
1345                                         export_error = EINVAL;
1346                         } else if (export.ex_ngroups == 0)
1347                                 export.ex_groups = NULL;
1348                         else
1349                                 export_error = EINVAL;
1350                         if (export_error == 0)
1351                                 export_error = vfs_export(mp, &export, 1);
1352                         free(grps, M_TEMP);
1353                         break;
1354                 default:
1355                         export_error = EINVAL;
1356                         break;
1357                 }
1358         }
1359
1360         MNT_ILOCK(mp);
1361         if (error == 0) {
1362                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1363                     MNT_SNAPSHOT);
1364         } else {
1365                 /*
1366                  * If we fail, restore old mount flags. MNT_QUOTA is special,
1367                  * because it is not part of MNT_UPDATEMASK, but it could have
1368                  * changed in the meantime if quotactl(2) was called.
1369                  * All in all we want current value of MNT_QUOTA, not the old
1370                  * one.
1371                  */
1372                 mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1373         }
1374         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1375             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1376                 mp->mnt_kern_flag |= MNTK_ASYNC;
1377         else
1378                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1379         MNT_IUNLOCK(mp);
1380
1381         if (error != 0)
1382                 goto end;
1383
1384         mount_devctl_event("REMOUNT", mp, true);
1385         if (mp->mnt_opt != NULL)
1386                 vfs_freeopts(mp->mnt_opt);
1387         mp->mnt_opt = mp->mnt_optnew;
1388         *optlist = NULL;
1389         (void)VFS_STATFS(mp, &mp->mnt_stat);
1390         /*
1391          * Prevent external consumers of mount options from reading
1392          * mnt_optnew.
1393          */
1394         mp->mnt_optnew = NULL;
1395
1396         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1397                 vfs_allocate_syncvnode(mp);
1398         else
1399                 vfs_deallocate_syncvnode(mp);
1400 end:
1401         vfs_op_exit(mp);
1402         if (rootvp != NULL) {
1403                 vn_seqc_write_end(rootvp);
1404                 vrele(rootvp);
1405         }
1406         vn_seqc_write_end(vp);
1407         vfs_unbusy(mp);
1408         VI_LOCK(vp);
1409         vp->v_iflag &= ~VI_MOUNT;
1410         VI_UNLOCK(vp);
1411         vrele(vp);
1412         return (error != 0 ? error : export_error);
1413 }
1414
1415 /*
1416  * vfs_domount(): actually attempt a filesystem mount.
1417  */
1418 static int
1419 vfs_domount(
1420         struct thread *td,              /* Calling thread. */
1421         const char *fstype,             /* Filesystem type. */
1422         char *fspath,                   /* Mount path. */
1423         uint64_t fsflags,               /* Flags common to all filesystems. */
1424         bool jail_export,               /* Got export option in vnet prison. */
1425         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1426         )
1427 {
1428         struct vfsconf *vfsp;
1429         struct nameidata nd;
1430         struct vnode *vp;
1431         char *pathbuf;
1432         int error;
1433
1434         /*
1435          * Be ultra-paranoid about making sure the type and fspath
1436          * variables will fit in our mp buffers, including the
1437          * terminating NUL.
1438          */
1439         if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1440                 return (ENAMETOOLONG);
1441
1442         if (jail_export) {
1443                 error = priv_check(td, PRIV_NFS_DAEMON);
1444                 if (error)
1445                         return (error);
1446         } else if (jailed(td->td_ucred) || usermount == 0) {
1447                 if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1448                         return (error);
1449         }
1450
1451         /*
1452          * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1453          */
1454         if (fsflags & MNT_EXPORTED) {
1455                 error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1456                 if (error)
1457                         return (error);
1458         }
1459         if (fsflags & MNT_SUIDDIR) {
1460                 error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1461                 if (error)
1462                         return (error);
1463         }
1464         /*
1465          * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1466          */
1467         if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1468                 if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1469                         fsflags |= MNT_NOSUID | MNT_USER;
1470         }
1471
1472         /* Load KLDs before we lock the covered vnode to avoid reversals. */
1473         vfsp = NULL;
1474         if ((fsflags & MNT_UPDATE) == 0) {
1475                 /* Don't try to load KLDs if we're mounting the root. */
1476                 if (fsflags & MNT_ROOTFS) {
1477                         if ((vfsp = vfs_byname(fstype)) == NULL)
1478                                 return (ENODEV);
1479                 } else {
1480                         if ((vfsp = vfs_byname_kld(fstype, td, &error)) == NULL)
1481                                 return (error);
1482                 }
1483         }
1484
1485         /*
1486          * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1487          */
1488         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1 | WANTPARENT,
1489             UIO_SYSSPACE, fspath, td);
1490         error = namei(&nd);
1491         if (error != 0)
1492                 return (error);
1493         vp = nd.ni_vp;
1494         /*
1495          * Don't allow stacking file mounts to work around problems with the way
1496          * that namei sets nd.ni_dvp to vp_crossmp for these.
1497          */
1498         if (vp->v_type == VREG)
1499                 fsflags |= MNT_NOCOVER;
1500         if ((fsflags & MNT_UPDATE) == 0) {
1501                 if ((vp->v_vflag & VV_ROOT) != 0 &&
1502                     (fsflags & MNT_NOCOVER) != 0) {
1503                         vput(vp);
1504                         error = EBUSY;
1505                         goto out;
1506                 }
1507                 pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1508                 strcpy(pathbuf, fspath);
1509                 /*
1510                  * Note: we allow any vnode type here. If the path sanity check
1511                  * succeeds, the type will be validated in vfs_domount_first
1512                  * above.
1513                  */
1514                 if (vp->v_type == VDIR)
1515                         error = vn_path_to_global_path(td, vp, pathbuf,
1516                             MNAMELEN);
1517                 else
1518                         error = vn_path_to_global_path_hardlink(td, vp,
1519                             nd.ni_dvp, pathbuf, MNAMELEN,
1520                             nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen);
1521                 if (error == 0) {
1522                         error = vfs_domount_first(td, vfsp, pathbuf, vp,
1523                             fsflags, optlist);
1524                 }
1525                 free(pathbuf, M_TEMP);
1526         } else
1527                 error = vfs_domount_update(td, vp, fsflags, jail_export,
1528                     optlist);
1529
1530 out:
1531         NDFREE(&nd, NDF_ONLY_PNBUF);
1532         vrele(nd.ni_dvp);
1533
1534         return (error);
1535 }
1536
1537 /*
1538  * Unmount a filesystem.
1539  *
1540  * Note: unmount takes a path to the vnode mounted on as argument, not
1541  * special file (as before).
1542  */
1543 #ifndef _SYS_SYSPROTO_H_
1544 struct unmount_args {
1545         char    *path;
1546         int     flags;
1547 };
1548 #endif
1549 /* ARGSUSED */
1550 int
1551 sys_unmount(struct thread *td, struct unmount_args *uap)
1552 {
1553
1554         return (kern_unmount(td, uap->path, uap->flags));
1555 }
1556
1557 int
1558 kern_unmount(struct thread *td, const char *path, int flags)
1559 {
1560         struct nameidata nd;
1561         struct mount *mp;
1562         char *pathbuf;
1563         int error, id0, id1;
1564
1565         AUDIT_ARG_VALUE(flags);
1566         if (jailed(td->td_ucred) || usermount == 0) {
1567                 error = priv_check(td, PRIV_VFS_UNMOUNT);
1568                 if (error)
1569                         return (error);
1570         }
1571
1572         pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1573         error = copyinstr(path, pathbuf, MNAMELEN, NULL);
1574         if (error) {
1575                 free(pathbuf, M_TEMP);
1576                 return (error);
1577         }
1578         if (flags & MNT_BYFSID) {
1579                 AUDIT_ARG_TEXT(pathbuf);
1580                 /* Decode the filesystem ID. */
1581                 if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
1582                         free(pathbuf, M_TEMP);
1583                         return (EINVAL);
1584                 }
1585
1586                 mtx_lock(&mountlist_mtx);
1587                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1588                         if (mp->mnt_stat.f_fsid.val[0] == id0 &&
1589                             mp->mnt_stat.f_fsid.val[1] == id1) {
1590                                 vfs_ref(mp);
1591                                 break;
1592                         }
1593                 }
1594                 mtx_unlock(&mountlist_mtx);
1595         } else {
1596                 /*
1597                  * Try to find global path for path argument.
1598                  */
1599                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1600                     UIO_SYSSPACE, pathbuf, td);
1601                 if (namei(&nd) == 0) {
1602                         NDFREE(&nd, NDF_ONLY_PNBUF);
1603                         error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1604                             MNAMELEN);
1605                         if (error == 0)
1606                                 vput(nd.ni_vp);
1607                 }
1608                 mtx_lock(&mountlist_mtx);
1609                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1610                         if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1611                                 vfs_ref(mp);
1612                                 break;
1613                         }
1614                 }
1615                 mtx_unlock(&mountlist_mtx);
1616         }
1617         free(pathbuf, M_TEMP);
1618         if (mp == NULL) {
1619                 /*
1620                  * Previously we returned ENOENT for a nonexistent path and
1621                  * EINVAL for a non-mountpoint.  We cannot tell these apart
1622                  * now, so in the !MNT_BYFSID case return the more likely
1623                  * EINVAL for compatibility.
1624                  */
1625                 return ((flags & MNT_BYFSID) ? ENOENT : EINVAL);
1626         }
1627
1628         /*
1629          * Don't allow unmounting the root filesystem.
1630          */
1631         if (mp->mnt_flag & MNT_ROOTFS) {
1632                 vfs_rel(mp);
1633                 return (EINVAL);
1634         }
1635         error = dounmount(mp, flags, td);
1636         return (error);
1637 }
1638
1639 /*
1640  * Return error if any of the vnodes, ignoring the root vnode
1641  * and the syncer vnode, have non-zero usecount.
1642  *
1643  * This function is purely advisory - it can return false positives
1644  * and negatives.
1645  */
1646 static int
1647 vfs_check_usecounts(struct mount *mp)
1648 {
1649         struct vnode *vp, *mvp;
1650
1651         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1652                 if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1653                     vp->v_usecount != 0) {
1654                         VI_UNLOCK(vp);
1655                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1656                         return (EBUSY);
1657                 }
1658                 VI_UNLOCK(vp);
1659         }
1660
1661         return (0);
1662 }
1663
1664 static void
1665 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1666 {
1667
1668         mtx_assert(MNT_MTX(mp), MA_OWNED);
1669         mp->mnt_kern_flag &= ~mntkflags;
1670         if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1671                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
1672                 wakeup(mp);
1673         }
1674         vfs_op_exit_locked(mp);
1675         MNT_IUNLOCK(mp);
1676         if (coveredvp != NULL) {
1677                 VOP_UNLOCK(coveredvp);
1678                 vdrop(coveredvp);
1679         }
1680         vn_finished_write(mp);
1681 }
1682
1683 /*
1684  * There are various reference counters associated with the mount point.
1685  * Normally it is permitted to modify them without taking the mnt ilock,
1686  * but this behavior can be temporarily disabled if stable value is needed
1687  * or callers are expected to block (e.g. to not allow new users during
1688  * forced unmount).
1689  */
1690 void
1691 vfs_op_enter(struct mount *mp)
1692 {
1693         struct mount_pcpu *mpcpu;
1694         int cpu;
1695
1696         MNT_ILOCK(mp);
1697         mp->mnt_vfs_ops++;
1698         if (mp->mnt_vfs_ops > 1) {
1699                 MNT_IUNLOCK(mp);
1700                 return;
1701         }
1702         vfs_op_barrier_wait(mp);
1703         CPU_FOREACH(cpu) {
1704                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1705
1706                 mp->mnt_ref += mpcpu->mntp_ref;
1707                 mpcpu->mntp_ref = 0;
1708
1709                 mp->mnt_lockref += mpcpu->mntp_lockref;
1710                 mpcpu->mntp_lockref = 0;
1711
1712                 mp->mnt_writeopcount += mpcpu->mntp_writeopcount;
1713                 mpcpu->mntp_writeopcount = 0;
1714         }
1715         MPASSERT(mp->mnt_ref > 0 && mp->mnt_lockref >= 0 &&
1716             mp->mnt_writeopcount >= 0, mp,
1717             ("invalid count(s): ref %d lockref %d writeopcount %d",
1718             mp->mnt_ref, mp->mnt_lockref, mp->mnt_writeopcount));
1719         MNT_IUNLOCK(mp);
1720         vfs_assert_mount_counters(mp);
1721 }
1722
1723 void
1724 vfs_op_exit_locked(struct mount *mp)
1725 {
1726
1727         mtx_assert(MNT_MTX(mp), MA_OWNED);
1728
1729         MPASSERT(mp->mnt_vfs_ops > 0, mp,
1730             ("invalid vfs_ops count %d", mp->mnt_vfs_ops));
1731         MPASSERT(mp->mnt_vfs_ops > 1 ||
1732             (mp->mnt_kern_flag & (MNTK_UNMOUNT | MNTK_SUSPEND)) == 0, mp,
1733             ("vfs_ops too low %d in unmount or suspend", mp->mnt_vfs_ops));
1734         mp->mnt_vfs_ops--;
1735 }
1736
1737 void
1738 vfs_op_exit(struct mount *mp)
1739 {
1740
1741         MNT_ILOCK(mp);
1742         vfs_op_exit_locked(mp);
1743         MNT_IUNLOCK(mp);
1744 }
1745
1746 struct vfs_op_barrier_ipi {
1747         struct mount *mp;
1748         struct smp_rendezvous_cpus_retry_arg srcra;
1749 };
1750
1751 static void
1752 vfs_op_action_func(void *arg)
1753 {
1754         struct vfs_op_barrier_ipi *vfsopipi;
1755         struct mount *mp;
1756
1757         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1758         mp = vfsopipi->mp;
1759
1760         if (!vfs_op_thread_entered(mp))
1761                 smp_rendezvous_cpus_done(arg);
1762 }
1763
1764 static void
1765 vfs_op_wait_func(void *arg, int cpu)
1766 {
1767         struct vfs_op_barrier_ipi *vfsopipi;
1768         struct mount *mp;
1769         struct mount_pcpu *mpcpu;
1770
1771         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1772         mp = vfsopipi->mp;
1773
1774         mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1775         while (atomic_load_int(&mpcpu->mntp_thread_in_ops))
1776                 cpu_spinwait();
1777 }
1778
1779 void
1780 vfs_op_barrier_wait(struct mount *mp)
1781 {
1782         struct vfs_op_barrier_ipi vfsopipi;
1783
1784         vfsopipi.mp = mp;
1785
1786         smp_rendezvous_cpus_retry(all_cpus,
1787             smp_no_rendezvous_barrier,
1788             vfs_op_action_func,
1789             smp_no_rendezvous_barrier,
1790             vfs_op_wait_func,
1791             &vfsopipi.srcra);
1792 }
1793
1794 #ifdef DIAGNOSTIC
1795 void
1796 vfs_assert_mount_counters(struct mount *mp)
1797 {
1798         struct mount_pcpu *mpcpu;
1799         int cpu;
1800
1801         if (mp->mnt_vfs_ops == 0)
1802                 return;
1803
1804         CPU_FOREACH(cpu) {
1805                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1806                 if (mpcpu->mntp_ref != 0 ||
1807                     mpcpu->mntp_lockref != 0 ||
1808                     mpcpu->mntp_writeopcount != 0)
1809                         vfs_dump_mount_counters(mp);
1810         }
1811 }
1812
1813 void
1814 vfs_dump_mount_counters(struct mount *mp)
1815 {
1816         struct mount_pcpu *mpcpu;
1817         int ref, lockref, writeopcount;
1818         int cpu;
1819
1820         printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1821
1822         printf("        ref : ");
1823         ref = mp->mnt_ref;
1824         CPU_FOREACH(cpu) {
1825                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1826                 printf("%d ", mpcpu->mntp_ref);
1827                 ref += mpcpu->mntp_ref;
1828         }
1829         printf("\n");
1830         printf("    lockref : ");
1831         lockref = mp->mnt_lockref;
1832         CPU_FOREACH(cpu) {
1833                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1834                 printf("%d ", mpcpu->mntp_lockref);
1835                 lockref += mpcpu->mntp_lockref;
1836         }
1837         printf("\n");
1838         printf("writeopcount: ");
1839         writeopcount = mp->mnt_writeopcount;
1840         CPU_FOREACH(cpu) {
1841                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1842                 printf("%d ", mpcpu->mntp_writeopcount);
1843                 writeopcount += mpcpu->mntp_writeopcount;
1844         }
1845         printf("\n");
1846
1847         printf("counter       struct total\n");
1848         printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1849         printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1850         printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1851
1852         panic("invalid counts on struct mount");
1853 }
1854 #endif
1855
1856 int
1857 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1858 {
1859         struct mount_pcpu *mpcpu;
1860         int cpu, sum;
1861
1862         switch (which) {
1863         case MNT_COUNT_REF:
1864                 sum = mp->mnt_ref;
1865                 break;
1866         case MNT_COUNT_LOCKREF:
1867                 sum = mp->mnt_lockref;
1868                 break;
1869         case MNT_COUNT_WRITEOPCOUNT:
1870                 sum = mp->mnt_writeopcount;
1871                 break;
1872         }
1873
1874         CPU_FOREACH(cpu) {
1875                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1876                 switch (which) {
1877                 case MNT_COUNT_REF:
1878                         sum += mpcpu->mntp_ref;
1879                         break;
1880                 case MNT_COUNT_LOCKREF:
1881                         sum += mpcpu->mntp_lockref;
1882                         break;
1883                 case MNT_COUNT_WRITEOPCOUNT:
1884                         sum += mpcpu->mntp_writeopcount;
1885                         break;
1886                 }
1887         }
1888         return (sum);
1889 }
1890
1891 /*
1892  * Do the actual filesystem unmount.
1893  */
1894 int
1895 dounmount(struct mount *mp, int flags, struct thread *td)
1896 {
1897         struct vnode *coveredvp, *rootvp;
1898         int error;
1899         uint64_t async_flag;
1900         int mnt_gen_r;
1901
1902         if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
1903                 mnt_gen_r = mp->mnt_gen;
1904                 VI_LOCK(coveredvp);
1905                 vholdl(coveredvp);
1906                 vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
1907                 /*
1908                  * Check for mp being unmounted while waiting for the
1909                  * covered vnode lock.
1910                  */
1911                 if (coveredvp->v_mountedhere != mp ||
1912                     coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
1913                         VOP_UNLOCK(coveredvp);
1914                         vdrop(coveredvp);
1915                         vfs_rel(mp);
1916                         return (EBUSY);
1917                 }
1918         }
1919
1920         /*
1921          * Only privileged root, or (if MNT_USER is set) the user that did the
1922          * original mount is permitted to unmount this filesystem.
1923          */
1924         error = vfs_suser(mp, td);
1925         if (error != 0) {
1926                 if (coveredvp != NULL) {
1927                         VOP_UNLOCK(coveredvp);
1928                         vdrop(coveredvp);
1929                 }
1930                 vfs_rel(mp);
1931                 return (error);
1932         }
1933
1934         vfs_op_enter(mp);
1935
1936         vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
1937         MNT_ILOCK(mp);
1938         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
1939             (mp->mnt_flag & MNT_UPDATE) != 0 ||
1940             !TAILQ_EMPTY(&mp->mnt_uppers)) {
1941                 dounmount_cleanup(mp, coveredvp, 0);
1942                 return (EBUSY);
1943         }
1944         mp->mnt_kern_flag |= MNTK_UNMOUNT;
1945         rootvp = vfs_cache_root_clear(mp);
1946         if (coveredvp != NULL)
1947                 vn_seqc_write_begin(coveredvp);
1948         if (flags & MNT_NONBUSY) {
1949                 MNT_IUNLOCK(mp);
1950                 error = vfs_check_usecounts(mp);
1951                 MNT_ILOCK(mp);
1952                 if (error != 0) {
1953                         vn_seqc_write_end(coveredvp);
1954                         dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
1955                         if (rootvp != NULL) {
1956                                 vn_seqc_write_end(rootvp);
1957                                 vrele(rootvp);
1958                         }
1959                         return (error);
1960                 }
1961         }
1962         /* Allow filesystems to detect that a forced unmount is in progress. */
1963         if (flags & MNT_FORCE) {
1964                 mp->mnt_kern_flag |= MNTK_UNMOUNTF;
1965                 MNT_IUNLOCK(mp);
1966                 /*
1967                  * Must be done after setting MNTK_UNMOUNTF and before
1968                  * waiting for mnt_lockref to become 0.
1969                  */
1970                 VFS_PURGE(mp);
1971                 MNT_ILOCK(mp);
1972         }
1973         error = 0;
1974         if (mp->mnt_lockref) {
1975                 mp->mnt_kern_flag |= MNTK_DRAINING;
1976                 error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
1977                     "mount drain", 0);
1978         }
1979         MNT_IUNLOCK(mp);
1980         KASSERT(mp->mnt_lockref == 0,
1981             ("%s: invalid lock refcount in the drain path @ %s:%d",
1982             __func__, __FILE__, __LINE__));
1983         KASSERT(error == 0,
1984             ("%s: invalid return value for msleep in the drain path @ %s:%d",
1985             __func__, __FILE__, __LINE__));
1986
1987         /*
1988          * We want to keep the vnode around so that we can vn_seqc_write_end
1989          * after we are done with unmount. Downgrade our reference to a mere
1990          * hold count so that we don't interefere with anything.
1991          */
1992         if (rootvp != NULL) {
1993                 vhold(rootvp);
1994                 vrele(rootvp);
1995         }
1996
1997         if (mp->mnt_flag & MNT_EXPUBLIC)
1998                 vfs_setpublicfs(NULL, NULL, NULL);
1999
2000         vfs_periodic(mp, MNT_WAIT);
2001         MNT_ILOCK(mp);
2002         async_flag = mp->mnt_flag & MNT_ASYNC;
2003         mp->mnt_flag &= ~MNT_ASYNC;
2004         mp->mnt_kern_flag &= ~MNTK_ASYNC;
2005         MNT_IUNLOCK(mp);
2006         vfs_deallocate_syncvnode(mp);
2007         error = VFS_UNMOUNT(mp, flags);
2008         vn_finished_write(mp);
2009         /*
2010          * If we failed to flush the dirty blocks for this mount point,
2011          * undo all the cdir/rdir and rootvnode changes we made above.
2012          * Unless we failed to do so because the device is reporting that
2013          * it doesn't exist anymore.
2014          */
2015         if (error && error != ENXIO) {
2016                 MNT_ILOCK(mp);
2017                 if ((mp->mnt_flag & MNT_RDONLY) == 0) {
2018                         MNT_IUNLOCK(mp);
2019                         vfs_allocate_syncvnode(mp);
2020                         MNT_ILOCK(mp);
2021                 }
2022                 mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
2023                 mp->mnt_flag |= async_flag;
2024                 if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
2025                     (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
2026                         mp->mnt_kern_flag |= MNTK_ASYNC;
2027                 if (mp->mnt_kern_flag & MNTK_MWAIT) {
2028                         mp->mnt_kern_flag &= ~MNTK_MWAIT;
2029                         wakeup(mp);
2030                 }
2031                 vfs_op_exit_locked(mp);
2032                 MNT_IUNLOCK(mp);
2033                 if (coveredvp) {
2034                         vn_seqc_write_end(coveredvp);
2035                         VOP_UNLOCK(coveredvp);
2036                         vdrop(coveredvp);
2037                 }
2038                 if (rootvp != NULL) {
2039                         vn_seqc_write_end(rootvp);
2040                         vdrop(rootvp);
2041                 }
2042                 return (error);
2043         }
2044         mtx_lock(&mountlist_mtx);
2045         TAILQ_REMOVE(&mountlist, mp, mnt_list);
2046         mtx_unlock(&mountlist_mtx);
2047         EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
2048         if (coveredvp != NULL) {
2049                 VI_LOCK(coveredvp);
2050                 vn_irflag_unset_locked(coveredvp, VIRF_MOUNTPOINT);
2051                 coveredvp->v_mountedhere = NULL;
2052                 vn_seqc_write_end_locked(coveredvp);
2053                 VI_UNLOCK(coveredvp);
2054                 VOP_UNLOCK(coveredvp);
2055                 vdrop(coveredvp);
2056         }
2057         mount_devctl_event("UNMOUNT", mp, false);
2058         if (rootvp != NULL) {
2059                 vn_seqc_write_end(rootvp);
2060                 vdrop(rootvp);
2061         }
2062         vfs_event_signal(NULL, VQ_UNMOUNT, 0);
2063         if (rootvnode != NULL && mp == rootvnode->v_mount) {
2064                 vrele(rootvnode);
2065                 rootvnode = NULL;
2066         }
2067         if (mp == rootdevmp)
2068                 rootdevmp = NULL;
2069         vfs_mount_destroy(mp);
2070         return (0);
2071 }
2072
2073 /*
2074  * Report errors during filesystem mounting.
2075  */
2076 void
2077 vfs_mount_error(struct mount *mp, const char *fmt, ...)
2078 {
2079         struct vfsoptlist *moptlist = mp->mnt_optnew;
2080         va_list ap;
2081         int error, len;
2082         char *errmsg;
2083
2084         error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
2085         if (error || errmsg == NULL || len <= 0)
2086                 return;
2087
2088         va_start(ap, fmt);
2089         vsnprintf(errmsg, (size_t)len, fmt, ap);
2090         va_end(ap);
2091 }
2092
2093 void
2094 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
2095 {
2096         va_list ap;
2097         int error, len;
2098         char *errmsg;
2099
2100         error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
2101         if (error || errmsg == NULL || len <= 0)
2102                 return;
2103
2104         va_start(ap, fmt);
2105         vsnprintf(errmsg, (size_t)len, fmt, ap);
2106         va_end(ap);
2107 }
2108
2109 /*
2110  * ---------------------------------------------------------------------
2111  * Functions for querying mount options/arguments from filesystems.
2112  */
2113
2114 /*
2115  * Check that no unknown options are given
2116  */
2117 int
2118 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
2119 {
2120         struct vfsopt *opt;
2121         char errmsg[255];
2122         const char **t, *p, *q;
2123         int ret = 0;
2124
2125         TAILQ_FOREACH(opt, opts, link) {
2126                 p = opt->name;
2127                 q = NULL;
2128                 if (p[0] == 'n' && p[1] == 'o')
2129                         q = p + 2;
2130                 for(t = global_opts; *t != NULL; t++) {
2131                         if (strcmp(*t, p) == 0)
2132                                 break;
2133                         if (q != NULL) {
2134                                 if (strcmp(*t, q) == 0)
2135                                         break;
2136                         }
2137                 }
2138                 if (*t != NULL)
2139                         continue;
2140                 for(t = legal; *t != NULL; t++) {
2141                         if (strcmp(*t, p) == 0)
2142                                 break;
2143                         if (q != NULL) {
2144                                 if (strcmp(*t, q) == 0)
2145                                         break;
2146                         }
2147                 }
2148                 if (*t != NULL)
2149                         continue;
2150                 snprintf(errmsg, sizeof(errmsg),
2151                     "mount option <%s> is unknown", p);
2152                 ret = EINVAL;
2153         }
2154         if (ret != 0) {
2155                 TAILQ_FOREACH(opt, opts, link) {
2156                         if (strcmp(opt->name, "errmsg") == 0) {
2157                                 strncpy((char *)opt->value, errmsg, opt->len);
2158                                 break;
2159                         }
2160                 }
2161                 if (opt == NULL)
2162                         printf("%s\n", errmsg);
2163         }
2164         return (ret);
2165 }
2166
2167 /*
2168  * Get a mount option by its name.
2169  *
2170  * Return 0 if the option was found, ENOENT otherwise.
2171  * If len is non-NULL it will be filled with the length
2172  * of the option. If buf is non-NULL, it will be filled
2173  * with the address of the option.
2174  */
2175 int
2176 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
2177 {
2178         struct vfsopt *opt;
2179
2180         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2181
2182         TAILQ_FOREACH(opt, opts, link) {
2183                 if (strcmp(name, opt->name) == 0) {
2184                         opt->seen = 1;
2185                         if (len != NULL)
2186                                 *len = opt->len;
2187                         if (buf != NULL)
2188                                 *buf = opt->value;
2189                         return (0);
2190                 }
2191         }
2192         return (ENOENT);
2193 }
2194
2195 int
2196 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
2197 {
2198         struct vfsopt *opt;
2199
2200         if (opts == NULL)
2201                 return (-1);
2202
2203         TAILQ_FOREACH(opt, opts, link) {
2204                 if (strcmp(name, opt->name) == 0) {
2205                         opt->seen = 1;
2206                         return (opt->pos);
2207                 }
2208         }
2209         return (-1);
2210 }
2211
2212 int
2213 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
2214 {
2215         char *opt_value, *vtp;
2216         quad_t iv;
2217         int error, opt_len;
2218
2219         error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
2220         if (error != 0)
2221                 return (error);
2222         if (opt_len == 0 || opt_value == NULL)
2223                 return (EINVAL);
2224         if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
2225                 return (EINVAL);
2226         iv = strtoq(opt_value, &vtp, 0);
2227         if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
2228                 return (EINVAL);
2229         if (iv < 0)
2230                 return (EINVAL);
2231         switch (vtp[0]) {
2232         case 't': case 'T':
2233                 iv *= 1024;
2234                 /* FALLTHROUGH */
2235         case 'g': case 'G':
2236                 iv *= 1024;
2237                 /* FALLTHROUGH */
2238         case 'm': case 'M':
2239                 iv *= 1024;
2240                 /* FALLTHROUGH */
2241         case 'k': case 'K':
2242                 iv *= 1024;
2243         case '\0':
2244                 break;
2245         default:
2246                 return (EINVAL);
2247         }
2248         *value = iv;
2249
2250         return (0);
2251 }
2252
2253 char *
2254 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
2255 {
2256         struct vfsopt *opt;
2257
2258         *error = 0;
2259         TAILQ_FOREACH(opt, opts, link) {
2260                 if (strcmp(name, opt->name) != 0)
2261                         continue;
2262                 opt->seen = 1;
2263                 if (opt->len == 0 ||
2264                     ((char *)opt->value)[opt->len - 1] != '\0') {
2265                         *error = EINVAL;
2266                         return (NULL);
2267                 }
2268                 return (opt->value);
2269         }
2270         *error = ENOENT;
2271         return (NULL);
2272 }
2273
2274 int
2275 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
2276         uint64_t val)
2277 {
2278         struct vfsopt *opt;
2279
2280         TAILQ_FOREACH(opt, opts, link) {
2281                 if (strcmp(name, opt->name) == 0) {
2282                         opt->seen = 1;
2283                         if (w != NULL)
2284                                 *w |= val;
2285                         return (1);
2286                 }
2287         }
2288         if (w != NULL)
2289                 *w &= ~val;
2290         return (0);
2291 }
2292
2293 int
2294 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
2295 {
2296         va_list ap;
2297         struct vfsopt *opt;
2298         int ret;
2299
2300         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2301
2302         TAILQ_FOREACH(opt, opts, link) {
2303                 if (strcmp(name, opt->name) != 0)
2304                         continue;
2305                 opt->seen = 1;
2306                 if (opt->len == 0 || opt->value == NULL)
2307                         return (0);
2308                 if (((char *)opt->value)[opt->len - 1] != '\0')
2309                         return (0);
2310                 va_start(ap, fmt);
2311                 ret = vsscanf(opt->value, fmt, ap);
2312                 va_end(ap);
2313                 return (ret);
2314         }
2315         return (0);
2316 }
2317
2318 int
2319 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
2320 {
2321         struct vfsopt *opt;
2322
2323         TAILQ_FOREACH(opt, opts, link) {
2324                 if (strcmp(name, opt->name) != 0)
2325                         continue;
2326                 opt->seen = 1;
2327                 if (opt->value == NULL)
2328                         opt->len = len;
2329                 else {
2330                         if (opt->len != len)
2331                                 return (EINVAL);
2332                         bcopy(value, opt->value, len);
2333                 }
2334                 return (0);
2335         }
2336         return (ENOENT);
2337 }
2338
2339 int
2340 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2341 {
2342         struct vfsopt *opt;
2343
2344         TAILQ_FOREACH(opt, opts, link) {
2345                 if (strcmp(name, opt->name) != 0)
2346                         continue;
2347                 opt->seen = 1;
2348                 if (opt->value == NULL)
2349                         opt->len = len;
2350                 else {
2351                         if (opt->len < len)
2352                                 return (EINVAL);
2353                         opt->len = len;
2354                         bcopy(value, opt->value, len);
2355                 }
2356                 return (0);
2357         }
2358         return (ENOENT);
2359 }
2360
2361 int
2362 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2363 {
2364         struct vfsopt *opt;
2365
2366         TAILQ_FOREACH(opt, opts, link) {
2367                 if (strcmp(name, opt->name) != 0)
2368                         continue;
2369                 opt->seen = 1;
2370                 if (opt->value == NULL)
2371                         opt->len = strlen(value) + 1;
2372                 else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2373                         return (EINVAL);
2374                 return (0);
2375         }
2376         return (ENOENT);
2377 }
2378
2379 /*
2380  * Find and copy a mount option.
2381  *
2382  * The size of the buffer has to be specified
2383  * in len, if it is not the same length as the
2384  * mount option, EINVAL is returned.
2385  * Returns ENOENT if the option is not found.
2386  */
2387 int
2388 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2389 {
2390         struct vfsopt *opt;
2391
2392         KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2393
2394         TAILQ_FOREACH(opt, opts, link) {
2395                 if (strcmp(name, opt->name) == 0) {
2396                         opt->seen = 1;
2397                         if (len != opt->len)
2398                                 return (EINVAL);
2399                         bcopy(opt->value, dest, opt->len);
2400                         return (0);
2401                 }
2402         }
2403         return (ENOENT);
2404 }
2405
2406 int
2407 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2408 {
2409
2410         /*
2411          * Filesystems only fill in part of the structure for updates, we
2412          * have to read the entirety first to get all content.
2413          */
2414         if (sbp != &mp->mnt_stat)
2415                 memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2416
2417         /*
2418          * Set these in case the underlying filesystem fails to do so.
2419          */
2420         sbp->f_version = STATFS_VERSION;
2421         sbp->f_namemax = NAME_MAX;
2422         sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2423
2424         return (mp->mnt_op->vfs_statfs(mp, sbp));
2425 }
2426
2427 void
2428 vfs_mountedfrom(struct mount *mp, const char *from)
2429 {
2430
2431         bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2432         strlcpy(mp->mnt_stat.f_mntfromname, from,
2433             sizeof mp->mnt_stat.f_mntfromname);
2434 }
2435
2436 /*
2437  * ---------------------------------------------------------------------
2438  * This is the api for building mount args and mounting filesystems from
2439  * inside the kernel.
2440  *
2441  * The API works by accumulation of individual args.  First error is
2442  * latched.
2443  *
2444  * XXX: should be documented in new manpage kernel_mount(9)
2445  */
2446
2447 /* A memory allocation which must be freed when we are done */
2448 struct mntaarg {
2449         SLIST_ENTRY(mntaarg)    next;
2450 };
2451
2452 /* The header for the mount arguments */
2453 struct mntarg {
2454         struct iovec *v;
2455         int len;
2456         int error;
2457         SLIST_HEAD(, mntaarg)   list;
2458 };
2459
2460 /*
2461  * Add a boolean argument.
2462  *
2463  * flag is the boolean value.
2464  * name must start with "no".
2465  */
2466 struct mntarg *
2467 mount_argb(struct mntarg *ma, int flag, const char *name)
2468 {
2469
2470         KASSERT(name[0] == 'n' && name[1] == 'o',
2471             ("mount_argb(...,%s): name must start with 'no'", name));
2472
2473         return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2474 }
2475
2476 /*
2477  * Add an argument printf style
2478  */
2479 struct mntarg *
2480 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2481 {
2482         va_list ap;
2483         struct mntaarg *maa;
2484         struct sbuf *sb;
2485         int len;
2486
2487         if (ma == NULL) {
2488                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2489                 SLIST_INIT(&ma->list);
2490         }
2491         if (ma->error)
2492                 return (ma);
2493
2494         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2495             M_MOUNT, M_WAITOK);
2496         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2497         ma->v[ma->len].iov_len = strlen(name) + 1;
2498         ma->len++;
2499
2500         sb = sbuf_new_auto();
2501         va_start(ap, fmt);
2502         sbuf_vprintf(sb, fmt, ap);
2503         va_end(ap);
2504         sbuf_finish(sb);
2505         len = sbuf_len(sb) + 1;
2506         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2507         SLIST_INSERT_HEAD(&ma->list, maa, next);
2508         bcopy(sbuf_data(sb), maa + 1, len);
2509         sbuf_delete(sb);
2510
2511         ma->v[ma->len].iov_base = maa + 1;
2512         ma->v[ma->len].iov_len = len;
2513         ma->len++;
2514
2515         return (ma);
2516 }
2517
2518 /*
2519  * Add an argument which is a userland string.
2520  */
2521 struct mntarg *
2522 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2523 {
2524         struct mntaarg *maa;
2525         char *tbuf;
2526
2527         if (val == NULL)
2528                 return (ma);
2529         if (ma == NULL) {
2530                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2531                 SLIST_INIT(&ma->list);
2532         }
2533         if (ma->error)
2534                 return (ma);
2535         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2536         SLIST_INSERT_HEAD(&ma->list, maa, next);
2537         tbuf = (void *)(maa + 1);
2538         ma->error = copyinstr(val, tbuf, len, NULL);
2539         return (mount_arg(ma, name, tbuf, -1));
2540 }
2541
2542 /*
2543  * Plain argument.
2544  *
2545  * If length is -1, treat value as a C string.
2546  */
2547 struct mntarg *
2548 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2549 {
2550
2551         if (ma == NULL) {
2552                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2553                 SLIST_INIT(&ma->list);
2554         }
2555         if (ma->error)
2556                 return (ma);
2557
2558         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2559             M_MOUNT, M_WAITOK);
2560         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2561         ma->v[ma->len].iov_len = strlen(name) + 1;
2562         ma->len++;
2563
2564         ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2565         if (len < 0)
2566                 ma->v[ma->len].iov_len = strlen(val) + 1;
2567         else
2568                 ma->v[ma->len].iov_len = len;
2569         ma->len++;
2570         return (ma);
2571 }
2572
2573 /*
2574  * Free a mntarg structure
2575  */
2576 static void
2577 free_mntarg(struct mntarg *ma)
2578 {
2579         struct mntaarg *maa;
2580
2581         while (!SLIST_EMPTY(&ma->list)) {
2582                 maa = SLIST_FIRST(&ma->list);
2583                 SLIST_REMOVE_HEAD(&ma->list, next);
2584                 free(maa, M_MOUNT);
2585         }
2586         free(ma->v, M_MOUNT);
2587         free(ma, M_MOUNT);
2588 }
2589
2590 /*
2591  * Mount a filesystem
2592  */
2593 int
2594 kernel_mount(struct mntarg *ma, uint64_t flags)
2595 {
2596         struct uio auio;
2597         int error;
2598
2599         KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2600         KASSERT(ma->error != 0 || ma->v != NULL, ("kernel_mount NULL ma->v"));
2601         KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2602
2603         error = ma->error;
2604         if (error == 0) {
2605                 auio.uio_iov = ma->v;
2606                 auio.uio_iovcnt = ma->len;
2607                 auio.uio_segflg = UIO_SYSSPACE;
2608                 error = vfs_donmount(curthread, flags, &auio);
2609         }
2610         free_mntarg(ma);
2611         return (error);
2612 }
2613
2614 /*
2615  * A printflike function to mount a filesystem.
2616  */
2617 int
2618 kernel_vmount(int flags, ...)
2619 {
2620         struct mntarg *ma = NULL;
2621         va_list ap;
2622         const char *cp;
2623         const void *vp;
2624         int error;
2625
2626         va_start(ap, flags);
2627         for (;;) {
2628                 cp = va_arg(ap, const char *);
2629                 if (cp == NULL)
2630                         break;
2631                 vp = va_arg(ap, const void *);
2632                 ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2633         }
2634         va_end(ap);
2635
2636         error = kernel_mount(ma, flags);
2637         return (error);
2638 }
2639
2640 /* Map from mount options to printable formats. */
2641 static struct mntoptnames optnames[] = {
2642         MNTOPT_NAMES
2643 };
2644
2645 #define DEVCTL_LEN 1024
2646 static void
2647 mount_devctl_event(const char *type, struct mount *mp, bool donew)
2648 {
2649         const uint8_t *cp;
2650         struct mntoptnames *fp;
2651         struct sbuf sb;
2652         struct statfs *sfp = &mp->mnt_stat;
2653         char *buf;
2654
2655         buf = malloc(DEVCTL_LEN, M_MOUNT, M_NOWAIT);
2656         if (buf == NULL)
2657                 return;
2658         sbuf_new(&sb, buf, DEVCTL_LEN, SBUF_FIXEDLEN);
2659         sbuf_cpy(&sb, "mount-point=\"");
2660         devctl_safe_quote_sb(&sb, sfp->f_mntonname);
2661         sbuf_cat(&sb, "\" mount-dev=\"");
2662         devctl_safe_quote_sb(&sb, sfp->f_mntfromname);
2663         sbuf_cat(&sb, "\" mount-type=\"");
2664         devctl_safe_quote_sb(&sb, sfp->f_fstypename);
2665         sbuf_cat(&sb, "\" fsid=0x");
2666         cp = (const uint8_t *)&sfp->f_fsid.val[0];
2667         for (int i = 0; i < sizeof(sfp->f_fsid); i++)
2668                 sbuf_printf(&sb, "%02x", cp[i]);
2669         sbuf_printf(&sb, " owner=%u flags=\"", sfp->f_owner);
2670         for (fp = optnames; fp->o_opt != 0; fp++) {
2671                 if ((mp->mnt_flag & fp->o_opt) != 0) {
2672                         sbuf_cat(&sb, fp->o_name);
2673                         sbuf_putc(&sb, ';');
2674                 }
2675         }
2676         sbuf_putc(&sb, '"');
2677         sbuf_finish(&sb);
2678
2679         /*
2680          * Options are not published because the form of the options depends on
2681          * the file system and may include binary data. In addition, they don't
2682          * necessarily provide enough useful information to be actionable when
2683          * devd processes them.
2684          */
2685
2686         if (sbuf_error(&sb) == 0)
2687                 devctl_notify("VFS", "FS", type, sbuf_data(&sb));
2688         sbuf_delete(&sb);
2689         free(buf, M_MOUNT);
2690 }
2691
2692 /*
2693  * Force remount specified mount point to read-only.  The argument
2694  * must be busied to avoid parallel unmount attempts.
2695  *
2696  * Intended use is to prevent further writes if some metadata
2697  * inconsistency is detected.  Note that the function still flushes
2698  * all cached metadata and data for the mount point, which might be
2699  * not always suitable.
2700  */
2701 int
2702 vfs_remount_ro(struct mount *mp)
2703 {
2704         struct vfsoptlist *opts;
2705         struct vfsopt *opt;
2706         struct vnode *vp_covered, *rootvp;
2707         int error;
2708
2709         vfs_op_enter(mp);
2710         KASSERT(mp->mnt_lockref > 0,
2711             ("vfs_remount_ro: mp %p is not busied", mp));
2712         KASSERT((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0,
2713             ("vfs_remount_ro: mp %p is being unmounted (and busy?)", mp));
2714
2715         rootvp = NULL;
2716         vp_covered = mp->mnt_vnodecovered;
2717         error = vget(vp_covered, LK_EXCLUSIVE | LK_NOWAIT);
2718         if (error != 0) {
2719                 vfs_op_exit(mp);
2720                 return (error);
2721         }
2722         VI_LOCK(vp_covered);
2723         if ((vp_covered->v_iflag & VI_MOUNT) != 0) {
2724                 VI_UNLOCK(vp_covered);
2725                 vput(vp_covered);
2726                 vfs_op_exit(mp);
2727                 return (EBUSY);
2728         }
2729         vp_covered->v_iflag |= VI_MOUNT;
2730         VI_UNLOCK(vp_covered);
2731         vn_seqc_write_begin(vp_covered);
2732
2733         MNT_ILOCK(mp);
2734         if ((mp->mnt_flag & MNT_RDONLY) != 0) {
2735                 MNT_IUNLOCK(mp);
2736                 error = EBUSY;
2737                 goto out;
2738         }
2739         mp->mnt_flag |= MNT_UPDATE | MNT_FORCE | MNT_RDONLY;
2740         rootvp = vfs_cache_root_clear(mp);
2741         MNT_IUNLOCK(mp);
2742
2743         opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK | M_ZERO);
2744         TAILQ_INIT(opts);
2745         opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK | M_ZERO);
2746         opt->name = strdup("ro", M_MOUNT);
2747         opt->value = NULL;
2748         TAILQ_INSERT_TAIL(opts, opt, link);
2749         vfs_mergeopts(opts, mp->mnt_opt);
2750         mp->mnt_optnew = opts;
2751
2752         error = VFS_MOUNT(mp);
2753
2754         if (error == 0) {
2755                 MNT_ILOCK(mp);
2756                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_FORCE);
2757                 MNT_IUNLOCK(mp);
2758                 vfs_deallocate_syncvnode(mp);
2759                 if (mp->mnt_opt != NULL)
2760                         vfs_freeopts(mp->mnt_opt);
2761                 mp->mnt_opt = mp->mnt_optnew;
2762         } else {
2763                 MNT_ILOCK(mp);
2764                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_FORCE | MNT_RDONLY);
2765                 MNT_IUNLOCK(mp);
2766                 vfs_freeopts(mp->mnt_optnew);
2767         }
2768         mp->mnt_optnew = NULL;
2769
2770 out:
2771         vfs_op_exit(mp);
2772         VI_LOCK(vp_covered);
2773         vp_covered->v_iflag &= ~VI_MOUNT;
2774         VI_UNLOCK(vp_covered);
2775         vput(vp_covered);
2776         vn_seqc_write_end(vp_covered);
2777         if (rootvp != NULL) {
2778                 vn_seqc_write_end(rootvp);
2779                 vrele(rootvp);
2780         }
2781         return (error);
2782 }
2783
2784 /*
2785  * Suspend write operations on all local writeable filesystems.  Does
2786  * full sync of them in the process.
2787  *
2788  * Iterate over the mount points in reverse order, suspending most
2789  * recently mounted filesystems first.  It handles a case where a
2790  * filesystem mounted from a md(4) vnode-backed device should be
2791  * suspended before the filesystem that owns the vnode.
2792  */
2793 void
2794 suspend_all_fs(void)
2795 {
2796         struct mount *mp;
2797         int error;
2798
2799         mtx_lock(&mountlist_mtx);
2800         TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
2801                 error = vfs_busy(mp, MBF_MNTLSTLOCK | MBF_NOWAIT);
2802                 if (error != 0)
2803                         continue;
2804                 if ((mp->mnt_flag & (MNT_RDONLY | MNT_LOCAL)) != MNT_LOCAL ||
2805                     (mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2806                         mtx_lock(&mountlist_mtx);
2807                         vfs_unbusy(mp);
2808                         continue;
2809                 }
2810                 error = vfs_write_suspend(mp, 0);
2811                 if (error == 0) {
2812                         MNT_ILOCK(mp);
2813                         MPASS((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0);
2814                         mp->mnt_kern_flag |= MNTK_SUSPEND_ALL;
2815                         MNT_IUNLOCK(mp);
2816                         mtx_lock(&mountlist_mtx);
2817                 } else {
2818                         printf("suspend of %s failed, error %d\n",
2819                             mp->mnt_stat.f_mntonname, error);
2820                         mtx_lock(&mountlist_mtx);
2821                         vfs_unbusy(mp);
2822                 }
2823         }
2824         mtx_unlock(&mountlist_mtx);
2825 }
2826
2827 /*
2828  * Clone the mnt_exjail field to a new mount point.
2829  */
2830 void
2831 vfs_exjail_clone(struct mount *inmp, struct mount *outmp)
2832 {
2833         struct ucred *cr;
2834         struct prison *pr;
2835
2836         MNT_ILOCK(inmp);
2837         cr = inmp->mnt_exjail;
2838         if (cr != NULL) {
2839                 crhold(cr);
2840                 MNT_IUNLOCK(inmp);
2841                 pr = cr->cr_prison;
2842                 sx_slock(&allprison_lock);
2843                 if (!prison_isalive(pr)) {
2844                         sx_sunlock(&allprison_lock);
2845                         crfree(cr);
2846                         return;
2847                 }
2848                 MNT_ILOCK(outmp);
2849                 if (outmp->mnt_exjail == NULL) {
2850                         outmp->mnt_exjail = cr;
2851                         atomic_add_int(&pr->pr_exportcnt, 1);
2852                         cr = NULL;
2853                 }
2854                 MNT_IUNLOCK(outmp);
2855                 sx_sunlock(&allprison_lock);
2856                 if (cr != NULL)
2857                         crfree(cr);
2858         } else
2859                 MNT_IUNLOCK(inmp);
2860 }
2861
2862 void
2863 resume_all_fs(void)
2864 {
2865         struct mount *mp;
2866
2867         mtx_lock(&mountlist_mtx);
2868         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2869                 if ((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0)
2870                         continue;
2871                 mtx_unlock(&mountlist_mtx);
2872                 MNT_ILOCK(mp);
2873                 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) != 0);
2874                 mp->mnt_kern_flag &= ~MNTK_SUSPEND_ALL;
2875                 MNT_IUNLOCK(mp);
2876                 vfs_write_resume(mp, 0);
2877                 mtx_lock(&mountlist_mtx);
2878                 vfs_unbusy(mp);
2879         }
2880         mtx_unlock(&mountlist_mtx);
2881 }