]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_mount.c
Add two options to allow mount to avoid covering up existing mount points.
[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 __FBSDID("$FreeBSD$");
41
42 #include <sys/param.h>
43 #include <sys/conf.h>
44 #include <sys/smp.h>
45 #include <sys/eventhandler.h>
46 #include <sys/fcntl.h>
47 #include <sys/jail.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/libkern.h>
51 #include <sys/malloc.h>
52 #include <sys/mount.h>
53 #include <sys/mutex.h>
54 #include <sys/namei.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/filedesc.h>
58 #include <sys/reboot.h>
59 #include <sys/sbuf.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysproto.h>
62 #include <sys/sx.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/systm.h>
66 #include <sys/vnode.h>
67 #include <vm/uma.h>
68
69 #include <geom/geom.h>
70
71 #include <machine/stdarg.h>
72
73 #include <security/audit/audit.h>
74 #include <security/mac/mac_framework.h>
75
76 #define VFS_MOUNTARG_SIZE_MAX   (1024 * 64)
77
78 static int      vfs_domount(struct thread *td, const char *fstype, char *fspath,
79                     uint64_t fsflags, struct vfsoptlist **optlist);
80 static void     free_mntarg(struct mntarg *ma);
81
82 static int      usermount = 0;
83 SYSCTL_INT(_vfs, OID_AUTO, usermount, CTLFLAG_RW, &usermount, 0,
84     "Unprivileged users may mount and unmount file systems");
85
86 static bool     default_autoro = false;
87 SYSCTL_BOOL(_vfs, OID_AUTO, default_autoro, CTLFLAG_RW, &default_autoro, 0,
88     "Retry failed r/w mount as r/o if no explicit ro/rw option is specified");
89
90 MALLOC_DEFINE(M_MOUNT, "mount", "vfs mount structure");
91 MALLOC_DEFINE(M_STATFS, "statfs", "statfs structure");
92 static uma_zone_t mount_zone;
93
94 /* List of mounted filesystems. */
95 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
96
97 /* For any iteration/modification of mountlist */
98 struct mtx mountlist_mtx;
99 MTX_SYSINIT(mountlist, &mountlist_mtx, "mountlist", MTX_DEF);
100
101 EVENTHANDLER_LIST_DEFINE(vfs_mounted);
102 EVENTHANDLER_LIST_DEFINE(vfs_unmounted);
103
104 /*
105  * Global opts, taken by all filesystems
106  */
107 static const char *global_opts[] = {
108         "errmsg",
109         "fstype",
110         "fspath",
111         "ro",
112         "rw",
113         "nosuid",
114         "noexec",
115         NULL
116 };
117
118 static int
119 mount_init(void *mem, int size, int flags)
120 {
121         struct mount *mp;
122
123         mp = (struct mount *)mem;
124         mtx_init(&mp->mnt_mtx, "struct mount mtx", NULL, MTX_DEF);
125         mtx_init(&mp->mnt_listmtx, "struct mount vlist mtx", NULL, MTX_DEF);
126         lockinit(&mp->mnt_explock, PVFS, "explock", 0, 0);
127         mp->mnt_thread_in_ops_pcpu = uma_zalloc_pcpu(pcpu_zone_int,
128             M_WAITOK | M_ZERO);
129         mp->mnt_ref_pcpu = uma_zalloc_pcpu(pcpu_zone_int,
130             M_WAITOK | M_ZERO);
131         mp->mnt_lockref_pcpu = uma_zalloc_pcpu(pcpu_zone_int,
132             M_WAITOK | M_ZERO);
133         mp->mnt_writeopcount_pcpu = uma_zalloc_pcpu(pcpu_zone_int,
134             M_WAITOK | M_ZERO);
135         mp->mnt_ref = 0;
136         mp->mnt_vfs_ops = 1;
137         return (0);
138 }
139
140 static void
141 mount_fini(void *mem, int size)
142 {
143         struct mount *mp;
144
145         mp = (struct mount *)mem;
146         uma_zfree_pcpu(pcpu_zone_int, mp->mnt_writeopcount_pcpu);
147         uma_zfree_pcpu(pcpu_zone_int, mp->mnt_lockref_pcpu);
148         uma_zfree_pcpu(pcpu_zone_int, mp->mnt_ref_pcpu);
149         uma_zfree_pcpu(pcpu_zone_int, mp->mnt_thread_in_ops_pcpu);
150         lockdestroy(&mp->mnt_explock);
151         mtx_destroy(&mp->mnt_listmtx);
152         mtx_destroy(&mp->mnt_mtx);
153 }
154
155 static void
156 vfs_mount_init(void *dummy __unused)
157 {
158
159         mount_zone = uma_zcreate("Mountpoints", sizeof(struct mount), NULL,
160             NULL, mount_init, mount_fini, UMA_ALIGN_CACHE, UMA_ZONE_NOFREE);
161 }
162 SYSINIT(vfs_mount, SI_SUB_VFS, SI_ORDER_ANY, vfs_mount_init, NULL);
163
164 /*
165  * ---------------------------------------------------------------------
166  * Functions for building and sanitizing the mount options
167  */
168
169 /* Remove one mount option. */
170 static void
171 vfs_freeopt(struct vfsoptlist *opts, struct vfsopt *opt)
172 {
173
174         TAILQ_REMOVE(opts, opt, link);
175         free(opt->name, M_MOUNT);
176         if (opt->value != NULL)
177                 free(opt->value, M_MOUNT);
178         free(opt, M_MOUNT);
179 }
180
181 /* Release all resources related to the mount options. */
182 void
183 vfs_freeopts(struct vfsoptlist *opts)
184 {
185         struct vfsopt *opt;
186
187         while (!TAILQ_EMPTY(opts)) {
188                 opt = TAILQ_FIRST(opts);
189                 vfs_freeopt(opts, opt);
190         }
191         free(opts, M_MOUNT);
192 }
193
194 void
195 vfs_deleteopt(struct vfsoptlist *opts, const char *name)
196 {
197         struct vfsopt *opt, *temp;
198
199         if (opts == NULL)
200                 return;
201         TAILQ_FOREACH_SAFE(opt, opts, link, temp)  {
202                 if (strcmp(opt->name, name) == 0)
203                         vfs_freeopt(opts, opt);
204         }
205 }
206
207 static int
208 vfs_isopt_ro(const char *opt)
209 {
210
211         if (strcmp(opt, "ro") == 0 || strcmp(opt, "rdonly") == 0 ||
212             strcmp(opt, "norw") == 0)
213                 return (1);
214         return (0);
215 }
216
217 static int
218 vfs_isopt_rw(const char *opt)
219 {
220
221         if (strcmp(opt, "rw") == 0 || strcmp(opt, "noro") == 0)
222                 return (1);
223         return (0);
224 }
225
226 /*
227  * Check if options are equal (with or without the "no" prefix).
228  */
229 static int
230 vfs_equalopts(const char *opt1, const char *opt2)
231 {
232         char *p;
233
234         /* "opt" vs. "opt" or "noopt" vs. "noopt" */
235         if (strcmp(opt1, opt2) == 0)
236                 return (1);
237         /* "noopt" vs. "opt" */
238         if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
239                 return (1);
240         /* "opt" vs. "noopt" */
241         if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
242                 return (1);
243         while ((p = strchr(opt1, '.')) != NULL &&
244             !strncmp(opt1, opt2, ++p - opt1)) {
245                 opt2 += p - opt1;
246                 opt1 = p;
247                 /* "foo.noopt" vs. "foo.opt" */
248                 if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
249                         return (1);
250                 /* "foo.opt" vs. "foo.noopt" */
251                 if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
252                         return (1);
253         }
254         /* "ro" / "rdonly" / "norw" / "rw" / "noro" */
255         if ((vfs_isopt_ro(opt1) || vfs_isopt_rw(opt1)) &&
256             (vfs_isopt_ro(opt2) || vfs_isopt_rw(opt2)))
257                 return (1);
258         return (0);
259 }
260
261 /*
262  * If a mount option is specified several times,
263  * (with or without the "no" prefix) only keep
264  * the last occurrence of it.
265  */
266 static void
267 vfs_sanitizeopts(struct vfsoptlist *opts)
268 {
269         struct vfsopt *opt, *opt2, *tmp;
270
271         TAILQ_FOREACH_REVERSE(opt, opts, vfsoptlist, link) {
272                 opt2 = TAILQ_PREV(opt, vfsoptlist, link);
273                 while (opt2 != NULL) {
274                         if (vfs_equalopts(opt->name, opt2->name)) {
275                                 tmp = TAILQ_PREV(opt2, vfsoptlist, link);
276                                 vfs_freeopt(opts, opt2);
277                                 opt2 = tmp;
278                         } else {
279                                 opt2 = TAILQ_PREV(opt2, vfsoptlist, link);
280                         }
281                 }
282         }
283 }
284
285 /*
286  * Build a linked list of mount options from a struct uio.
287  */
288 int
289 vfs_buildopts(struct uio *auio, struct vfsoptlist **options)
290 {
291         struct vfsoptlist *opts;
292         struct vfsopt *opt;
293         size_t memused, namelen, optlen;
294         unsigned int i, iovcnt;
295         int error;
296
297         opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
298         TAILQ_INIT(opts);
299         memused = 0;
300         iovcnt = auio->uio_iovcnt;
301         for (i = 0; i < iovcnt; i += 2) {
302                 namelen = auio->uio_iov[i].iov_len;
303                 optlen = auio->uio_iov[i + 1].iov_len;
304                 memused += sizeof(struct vfsopt) + optlen + namelen;
305                 /*
306                  * Avoid consuming too much memory, and attempts to overflow
307                  * memused.
308                  */
309                 if (memused > VFS_MOUNTARG_SIZE_MAX ||
310                     optlen > VFS_MOUNTARG_SIZE_MAX ||
311                     namelen > VFS_MOUNTARG_SIZE_MAX) {
312                         error = EINVAL;
313                         goto bad;
314                 }
315
316                 opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
317                 opt->name = malloc(namelen, M_MOUNT, M_WAITOK);
318                 opt->value = NULL;
319                 opt->len = 0;
320                 opt->pos = i / 2;
321                 opt->seen = 0;
322
323                 /*
324                  * Do this early, so jumps to "bad" will free the current
325                  * option.
326                  */
327                 TAILQ_INSERT_TAIL(opts, opt, link);
328
329                 if (auio->uio_segflg == UIO_SYSSPACE) {
330                         bcopy(auio->uio_iov[i].iov_base, opt->name, namelen);
331                 } else {
332                         error = copyin(auio->uio_iov[i].iov_base, opt->name,
333                             namelen);
334                         if (error)
335                                 goto bad;
336                 }
337                 /* Ensure names are null-terminated strings. */
338                 if (namelen == 0 || opt->name[namelen - 1] != '\0') {
339                         error = EINVAL;
340                         goto bad;
341                 }
342                 if (optlen != 0) {
343                         opt->len = optlen;
344                         opt->value = malloc(optlen, M_MOUNT, M_WAITOK);
345                         if (auio->uio_segflg == UIO_SYSSPACE) {
346                                 bcopy(auio->uio_iov[i + 1].iov_base, opt->value,
347                                     optlen);
348                         } else {
349                                 error = copyin(auio->uio_iov[i + 1].iov_base,
350                                     opt->value, optlen);
351                                 if (error)
352                                         goto bad;
353                         }
354                 }
355         }
356         vfs_sanitizeopts(opts);
357         *options = opts;
358         return (0);
359 bad:
360         vfs_freeopts(opts);
361         return (error);
362 }
363
364 /*
365  * Merge the old mount options with the new ones passed
366  * in the MNT_UPDATE case.
367  *
368  * XXX: This function will keep a "nofoo" option in the new
369  * options.  E.g, if the option's canonical name is "foo",
370  * "nofoo" ends up in the mount point's active options.
371  */
372 static void
373 vfs_mergeopts(struct vfsoptlist *toopts, struct vfsoptlist *oldopts)
374 {
375         struct vfsopt *opt, *new;
376
377         TAILQ_FOREACH(opt, oldopts, link) {
378                 new = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
379                 new->name = strdup(opt->name, M_MOUNT);
380                 if (opt->len != 0) {
381                         new->value = malloc(opt->len, M_MOUNT, M_WAITOK);
382                         bcopy(opt->value, new->value, opt->len);
383                 } else
384                         new->value = NULL;
385                 new->len = opt->len;
386                 new->seen = opt->seen;
387                 TAILQ_INSERT_HEAD(toopts, new, link);
388         }
389         vfs_sanitizeopts(toopts);
390 }
391
392 /*
393  * Mount a filesystem.
394  */
395 #ifndef _SYS_SYSPROTO_H_
396 struct nmount_args {
397         struct iovec *iovp;
398         unsigned int iovcnt;
399         int flags;
400 };
401 #endif
402 int
403 sys_nmount(struct thread *td, struct nmount_args *uap)
404 {
405         struct uio *auio;
406         int error;
407         u_int iovcnt;
408         uint64_t flags;
409
410         /*
411          * Mount flags are now 64-bits. On 32-bit archtectures only
412          * 32-bits are passed in, but from here on everything handles
413          * 64-bit flags correctly.
414          */
415         flags = uap->flags;
416
417         AUDIT_ARG_FFLAGS(flags);
418         CTR4(KTR_VFS, "%s: iovp %p with iovcnt %d and flags %d", __func__,
419             uap->iovp, uap->iovcnt, flags);
420
421         /*
422          * Filter out MNT_ROOTFS.  We do not want clients of nmount() in
423          * userspace to set this flag, but we must filter it out if we want
424          * MNT_UPDATE on the root file system to work.
425          * MNT_ROOTFS should only be set by the kernel when mounting its
426          * root file system.
427          */
428         flags &= ~MNT_ROOTFS;
429
430         iovcnt = uap->iovcnt;
431         /*
432          * Check that we have an even number of iovec's
433          * and that we have at least two options.
434          */
435         if ((iovcnt & 1) || (iovcnt < 4)) {
436                 CTR2(KTR_VFS, "%s: failed for invalid iovcnt %d", __func__,
437                     uap->iovcnt);
438                 return (EINVAL);
439         }
440
441         error = copyinuio(uap->iovp, iovcnt, &auio);
442         if (error) {
443                 CTR2(KTR_VFS, "%s: failed for invalid uio op with %d errno",
444                     __func__, error);
445                 return (error);
446         }
447         error = vfs_donmount(td, flags, auio);
448
449         free(auio, M_IOV);
450         return (error);
451 }
452
453 /*
454  * ---------------------------------------------------------------------
455  * Various utility functions
456  */
457
458 void
459 vfs_ref(struct mount *mp)
460 {
461
462         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
463         if (vfs_op_thread_enter(mp)) {
464                 vfs_mp_count_add_pcpu(mp, ref, 1);
465                 vfs_op_thread_exit(mp);
466                 return;
467         }
468
469         MNT_ILOCK(mp);
470         MNT_REF(mp);
471         MNT_IUNLOCK(mp);
472 }
473
474 void
475 vfs_rel(struct mount *mp)
476 {
477
478         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
479         if (vfs_op_thread_enter(mp)) {
480                 vfs_mp_count_sub_pcpu(mp, ref, 1);
481                 vfs_op_thread_exit(mp);
482                 return;
483         }
484
485         MNT_ILOCK(mp);
486         MNT_REL(mp);
487         MNT_IUNLOCK(mp);
488 }
489
490 /*
491  * Allocate and initialize the mount point struct.
492  */
493 struct mount *
494 vfs_mount_alloc(struct vnode *vp, struct vfsconf *vfsp, const char *fspath,
495     struct ucred *cred)
496 {
497         struct mount *mp;
498
499         mp = uma_zalloc(mount_zone, M_WAITOK);
500         bzero(&mp->mnt_startzero,
501             __rangeof(struct mount, mnt_startzero, mnt_endzero));
502         TAILQ_INIT(&mp->mnt_nvnodelist);
503         mp->mnt_nvnodelistsize = 0;
504         TAILQ_INIT(&mp->mnt_activevnodelist);
505         mp->mnt_activevnodelistsize = 0;
506         TAILQ_INIT(&mp->mnt_tmpfreevnodelist);
507         mp->mnt_tmpfreevnodelistsize = 0;
508         if (mp->mnt_ref != 0 || mp->mnt_lockref != 0 ||
509             mp->mnt_writeopcount != 0)
510                 panic("%s: non-zero counters on new mp %p\n", __func__, mp);
511         if (mp->mnt_vfs_ops != 1)
512                 panic("%s: vfs_ops should be 1 but %d found\n", __func__,
513                     mp->mnt_vfs_ops);
514         (void) vfs_busy(mp, MBF_NOWAIT);
515         atomic_add_acq_int(&vfsp->vfc_refcount, 1);
516         mp->mnt_op = vfsp->vfc_vfsops;
517         mp->mnt_vfc = vfsp;
518         mp->mnt_stat.f_type = vfsp->vfc_typenum;
519         mp->mnt_gen++;
520         strlcpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
521         mp->mnt_vnodecovered = vp;
522         mp->mnt_cred = crdup(cred);
523         mp->mnt_stat.f_owner = cred->cr_uid;
524         strlcpy(mp->mnt_stat.f_mntonname, fspath, MNAMELEN);
525         mp->mnt_iosize_max = DFLTPHYS;
526 #ifdef MAC
527         mac_mount_init(mp);
528         mac_mount_create(cred, mp);
529 #endif
530         arc4rand(&mp->mnt_hashseed, sizeof mp->mnt_hashseed, 0);
531         TAILQ_INIT(&mp->mnt_uppers);
532         return (mp);
533 }
534
535 /*
536  * Destroy the mount struct previously allocated by vfs_mount_alloc().
537  */
538 void
539 vfs_mount_destroy(struct mount *mp)
540 {
541
542         if (mp->mnt_vfs_ops == 0)
543                 panic("%s: entered with zero vfs_ops\n", __func__);
544
545         vfs_assert_mount_counters(mp);
546
547         MNT_ILOCK(mp);
548         mp->mnt_kern_flag |= MNTK_REFEXPIRE;
549         if (mp->mnt_kern_flag & MNTK_MWAIT) {
550                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
551                 wakeup(mp);
552         }
553         while (mp->mnt_ref)
554                 msleep(mp, MNT_MTX(mp), PVFS, "mntref", 0);
555         KASSERT(mp->mnt_ref == 0,
556             ("%s: invalid refcount in the drain path @ %s:%d", __func__,
557             __FILE__, __LINE__));
558         if (mp->mnt_writeopcount != 0)
559                 panic("vfs_mount_destroy: nonzero writeopcount");
560         if (mp->mnt_secondary_writes != 0)
561                 panic("vfs_mount_destroy: nonzero secondary_writes");
562         atomic_subtract_rel_int(&mp->mnt_vfc->vfc_refcount, 1);
563         if (!TAILQ_EMPTY(&mp->mnt_nvnodelist)) {
564                 struct vnode *vp;
565
566                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes)
567                         vn_printf(vp, "dangling vnode ");
568                 panic("unmount: dangling vnode");
569         }
570         KASSERT(TAILQ_EMPTY(&mp->mnt_uppers), ("mnt_uppers"));
571         if (mp->mnt_nvnodelistsize != 0)
572                 panic("vfs_mount_destroy: nonzero nvnodelistsize");
573         if (mp->mnt_activevnodelistsize != 0)
574                 panic("vfs_mount_destroy: nonzero activevnodelistsize");
575         if (mp->mnt_tmpfreevnodelistsize != 0)
576                 panic("vfs_mount_destroy: nonzero tmpfreevnodelistsize");
577         if (mp->mnt_lockref != 0)
578                 panic("vfs_mount_destroy: nonzero lock refcount");
579         MNT_IUNLOCK(mp);
580
581         if (mp->mnt_vfs_ops != 1)
582                 panic("%s: vfs_ops should be 1 but %d found\n", __func__,
583                     mp->mnt_vfs_ops);
584
585         if (mp->mnt_vnodecovered != NULL)
586                 vrele(mp->mnt_vnodecovered);
587 #ifdef MAC
588         mac_mount_destroy(mp);
589 #endif
590         if (mp->mnt_opt != NULL)
591                 vfs_freeopts(mp->mnt_opt);
592         crfree(mp->mnt_cred);
593         uma_zfree(mount_zone, mp);
594 }
595
596 static bool
597 vfs_should_downgrade_to_ro_mount(uint64_t fsflags, int error)
598 {
599         /* This is an upgrade of an exisiting mount. */
600         if ((fsflags & MNT_UPDATE) != 0)
601                 return (false);
602         /* This is already an R/O mount. */
603         if ((fsflags & MNT_RDONLY) != 0)
604                 return (false);
605
606         switch (error) {
607         case ENODEV:    /* generic, geom, ... */
608         case EACCES:    /* cam/scsi, ... */
609         case EROFS:     /* md, mmcsd, ... */
610                 /*
611                  * These errors can be returned by the storage layer to signal
612                  * that the media is read-only.  No harm in the R/O mount
613                  * attempt if the error was returned for some other reason.
614                  */
615                 return (true);
616         default:
617                 return (false);
618         }
619 }
620
621 int
622 vfs_donmount(struct thread *td, uint64_t fsflags, struct uio *fsoptions)
623 {
624         struct vfsoptlist *optlist;
625         struct vfsopt *opt, *tmp_opt;
626         char *fstype, *fspath, *errmsg;
627         int error, fstypelen, fspathlen, errmsg_len, errmsg_pos;
628         bool autoro;
629
630         errmsg = fspath = NULL;
631         errmsg_len = fspathlen = 0;
632         errmsg_pos = -1;
633         autoro = default_autoro;
634
635         error = vfs_buildopts(fsoptions, &optlist);
636         if (error)
637                 return (error);
638
639         if (vfs_getopt(optlist, "errmsg", (void **)&errmsg, &errmsg_len) == 0)
640                 errmsg_pos = vfs_getopt_pos(optlist, "errmsg");
641
642         /*
643          * We need these two options before the others,
644          * and they are mandatory for any filesystem.
645          * Ensure they are NUL terminated as well.
646          */
647         fstypelen = 0;
648         error = vfs_getopt(optlist, "fstype", (void **)&fstype, &fstypelen);
649         if (error || fstype[fstypelen - 1] != '\0') {
650                 error = EINVAL;
651                 if (errmsg != NULL)
652                         strncpy(errmsg, "Invalid fstype", errmsg_len);
653                 goto bail;
654         }
655         fspathlen = 0;
656         error = vfs_getopt(optlist, "fspath", (void **)&fspath, &fspathlen);
657         if (error || fspath[fspathlen - 1] != '\0') {
658                 error = EINVAL;
659                 if (errmsg != NULL)
660                         strncpy(errmsg, "Invalid fspath", errmsg_len);
661                 goto bail;
662         }
663
664         /*
665          * We need to see if we have the "update" option
666          * before we call vfs_domount(), since vfs_domount() has special
667          * logic based on MNT_UPDATE.  This is very important
668          * when we want to update the root filesystem.
669          */
670         TAILQ_FOREACH_SAFE(opt, optlist, link, tmp_opt) {
671                 int do_freeopt = 0;
672
673                 if (strcmp(opt->name, "update") == 0) {
674                         fsflags |= MNT_UPDATE;
675                         do_freeopt = 1;
676                 }
677                 else if (strcmp(opt->name, "async") == 0)
678                         fsflags |= MNT_ASYNC;
679                 else if (strcmp(opt->name, "force") == 0) {
680                         fsflags |= MNT_FORCE;
681                         do_freeopt = 1;
682                 }
683                 else if (strcmp(opt->name, "reload") == 0) {
684                         fsflags |= MNT_RELOAD;
685                         do_freeopt = 1;
686                 }
687                 else if (strcmp(opt->name, "multilabel") == 0)
688                         fsflags |= MNT_MULTILABEL;
689                 else if (strcmp(opt->name, "noasync") == 0)
690                         fsflags &= ~MNT_ASYNC;
691                 else if (strcmp(opt->name, "noatime") == 0)
692                         fsflags |= MNT_NOATIME;
693                 else if (strcmp(opt->name, "atime") == 0) {
694                         free(opt->name, M_MOUNT);
695                         opt->name = strdup("nonoatime", M_MOUNT);
696                 }
697                 else if (strcmp(opt->name, "noclusterr") == 0)
698                         fsflags |= MNT_NOCLUSTERR;
699                 else if (strcmp(opt->name, "clusterr") == 0) {
700                         free(opt->name, M_MOUNT);
701                         opt->name = strdup("nonoclusterr", M_MOUNT);
702                 }
703                 else if (strcmp(opt->name, "noclusterw") == 0)
704                         fsflags |= MNT_NOCLUSTERW;
705                 else if (strcmp(opt->name, "clusterw") == 0) {
706                         free(opt->name, M_MOUNT);
707                         opt->name = strdup("nonoclusterw", M_MOUNT);
708                 }
709                 else if (strcmp(opt->name, "noexec") == 0)
710                         fsflags |= MNT_NOEXEC;
711                 else if (strcmp(opt->name, "exec") == 0) {
712                         free(opt->name, M_MOUNT);
713                         opt->name = strdup("nonoexec", M_MOUNT);
714                 }
715                 else if (strcmp(opt->name, "nosuid") == 0)
716                         fsflags |= MNT_NOSUID;
717                 else if (strcmp(opt->name, "suid") == 0) {
718                         free(opt->name, M_MOUNT);
719                         opt->name = strdup("nonosuid", M_MOUNT);
720                 }
721                 else if (strcmp(opt->name, "nosymfollow") == 0)
722                         fsflags |= MNT_NOSYMFOLLOW;
723                 else if (strcmp(opt->name, "symfollow") == 0) {
724                         free(opt->name, M_MOUNT);
725                         opt->name = strdup("nonosymfollow", M_MOUNT);
726                 }
727                 else if (strcmp(opt->name, "noro") == 0) {
728                         fsflags &= ~MNT_RDONLY;
729                         autoro = false;
730                 }
731                 else if (strcmp(opt->name, "rw") == 0) {
732                         fsflags &= ~MNT_RDONLY;
733                         autoro = false;
734                 }
735                 else if (strcmp(opt->name, "ro") == 0) {
736                         fsflags |= MNT_RDONLY;
737                         autoro = false;
738                 }
739                 else if (strcmp(opt->name, "rdonly") == 0) {
740                         free(opt->name, M_MOUNT);
741                         opt->name = strdup("ro", M_MOUNT);
742                         fsflags |= MNT_RDONLY;
743                         autoro = false;
744                 }
745                 else if (strcmp(opt->name, "autoro") == 0) {
746                         do_freeopt = 1;
747                         autoro = true;
748                 }
749                 else if (strcmp(opt->name, "suiddir") == 0)
750                         fsflags |= MNT_SUIDDIR;
751                 else if (strcmp(opt->name, "sync") == 0)
752                         fsflags |= MNT_SYNCHRONOUS;
753                 else if (strcmp(opt->name, "union") == 0)
754                         fsflags |= MNT_UNION;
755                 else if (strcmp(opt->name, "automounted") == 0) {
756                         fsflags |= MNT_AUTOMOUNTED;
757                         do_freeopt = 1;
758                 } else if (strcmp(opt->name, "nocover") == 0) {
759                         fsflags |= MNT_NOCOVER;
760                         do_freeopt = 1;
761                 } else if (strcmp(opt->name, "cover") == 0) {
762                         fsflags &= ~MNT_NOCOVER;
763                         do_freeopt = 1;
764                 } else if (strcmp(opt->name, "emptydir") == 0) {
765                         fsflags |= MNT_EMPTYDIR;
766                         do_freeopt = 1;
767                 } else if (strcmp(opt->name, "noemptydir") == 0) {
768                         fsflags &= ~MNT_EMPTYDIR;
769                         do_freeopt = 1;
770                 }
771                 if (do_freeopt)
772                         vfs_freeopt(optlist, opt);
773         }
774
775         /*
776          * Be ultra-paranoid about making sure the type and fspath
777          * variables will fit in our mp buffers, including the
778          * terminating NUL.
779          */
780         if (fstypelen > MFSNAMELEN || fspathlen > MNAMELEN) {
781                 error = ENAMETOOLONG;
782                 goto bail;
783         }
784
785         error = vfs_domount(td, fstype, fspath, fsflags, &optlist);
786
787         /*
788          * See if we can mount in the read-only mode if the error code suggests
789          * that it could be possible and the mount options allow for that.
790          * Never try it if "[no]{ro|rw}" has been explicitly requested and not
791          * overridden by "autoro".
792          */
793         if (autoro && vfs_should_downgrade_to_ro_mount(fsflags, error)) {
794                 printf("%s: R/W mount failed, possibly R/O media,"
795                     " trying R/O mount\n", __func__);
796                 fsflags |= MNT_RDONLY;
797                 error = vfs_domount(td, fstype, fspath, fsflags, &optlist);
798         }
799 bail:
800         /* copyout the errmsg */
801         if (errmsg_pos != -1 && ((2 * errmsg_pos + 1) < fsoptions->uio_iovcnt)
802             && errmsg_len > 0 && errmsg != NULL) {
803                 if (fsoptions->uio_segflg == UIO_SYSSPACE) {
804                         bcopy(errmsg,
805                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
806                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
807                 } else {
808                         copyout(errmsg,
809                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
810                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
811                 }
812         }
813
814         if (optlist != NULL)
815                 vfs_freeopts(optlist);
816         return (error);
817 }
818
819 /*
820  * Old mount API.
821  */
822 #ifndef _SYS_SYSPROTO_H_
823 struct mount_args {
824         char    *type;
825         char    *path;
826         int     flags;
827         caddr_t data;
828 };
829 #endif
830 /* ARGSUSED */
831 int
832 sys_mount(struct thread *td, struct mount_args *uap)
833 {
834         char *fstype;
835         struct vfsconf *vfsp = NULL;
836         struct mntarg *ma = NULL;
837         uint64_t flags;
838         int error;
839
840         /*
841          * Mount flags are now 64-bits. On 32-bit architectures only
842          * 32-bits are passed in, but from here on everything handles
843          * 64-bit flags correctly.
844          */
845         flags = uap->flags;
846
847         AUDIT_ARG_FFLAGS(flags);
848
849         /*
850          * Filter out MNT_ROOTFS.  We do not want clients of mount() in
851          * userspace to set this flag, but we must filter it out if we want
852          * MNT_UPDATE on the root file system to work.
853          * MNT_ROOTFS should only be set by the kernel when mounting its
854          * root file system.
855          */
856         flags &= ~MNT_ROOTFS;
857
858         fstype = malloc(MFSNAMELEN, M_TEMP, M_WAITOK);
859         error = copyinstr(uap->type, fstype, MFSNAMELEN, NULL);
860         if (error) {
861                 free(fstype, M_TEMP);
862                 return (error);
863         }
864
865         AUDIT_ARG_TEXT(fstype);
866         vfsp = vfs_byname_kld(fstype, td, &error);
867         free(fstype, M_TEMP);
868         if (vfsp == NULL)
869                 return (ENOENT);
870         if (((vfsp->vfc_flags & VFCF_SBDRY) != 0 &&
871             vfsp->vfc_vfsops_sd->vfs_cmount == NULL) ||
872             ((vfsp->vfc_flags & VFCF_SBDRY) == 0 &&
873             vfsp->vfc_vfsops->vfs_cmount == NULL))
874                 return (EOPNOTSUPP);
875
876         ma = mount_argsu(ma, "fstype", uap->type, MFSNAMELEN);
877         ma = mount_argsu(ma, "fspath", uap->path, MNAMELEN);
878         ma = mount_argb(ma, flags & MNT_RDONLY, "noro");
879         ma = mount_argb(ma, !(flags & MNT_NOSUID), "nosuid");
880         ma = mount_argb(ma, !(flags & MNT_NOEXEC), "noexec");
881
882         if ((vfsp->vfc_flags & VFCF_SBDRY) != 0)
883                 return (vfsp->vfc_vfsops_sd->vfs_cmount(ma, uap->data, flags));
884         return (vfsp->vfc_vfsops->vfs_cmount(ma, uap->data, flags));
885 }
886
887 /*
888  * vfs_domount_first(): first file system mount (not update)
889  */
890 static int
891 vfs_domount_first(
892         struct thread *td,              /* Calling thread. */
893         struct vfsconf *vfsp,           /* File system type. */
894         char *fspath,                   /* Mount path. */
895         struct vnode *vp,               /* Vnode to be covered. */
896         uint64_t fsflags,               /* Flags common to all filesystems. */
897         struct vfsoptlist **optlist     /* Options local to the filesystem. */
898         )
899 {
900         struct vattr va;
901         struct mount *mp;
902         struct vnode *newdp;
903         int error, error1;
904
905         ASSERT_VOP_ELOCKED(vp, __func__);
906         KASSERT((fsflags & MNT_UPDATE) == 0, ("MNT_UPDATE shouldn't be here"));
907
908         if ((fsflags & MNT_EMPTYDIR) != 0) {
909                 error = vfs_emptydir(vp);
910                 if (error != 0) {
911                         vput(vp);
912                         return (error);
913                 }
914         }
915
916         /*
917          * If the jail of the calling thread lacks permission for this type of
918          * file system, deny immediately.
919          */
920         if (jailed(td->td_ucred) && !prison_allow(td->td_ucred,
921             vfsp->vfc_prison_flag)) {
922                 vput(vp);
923                 return (EPERM);
924         }
925
926         /*
927          * If the user is not root, ensure that they own the directory
928          * onto which we are attempting to mount.
929          */
930         error = VOP_GETATTR(vp, &va, td->td_ucred);
931         if (error == 0 && va.va_uid != td->td_ucred->cr_uid)
932                 error = priv_check_cred(td->td_ucred, PRIV_VFS_ADMIN);
933         if (error == 0)
934                 error = vinvalbuf(vp, V_SAVE, 0, 0);
935         if (error == 0 && vp->v_type != VDIR)
936                 error = ENOTDIR;
937         if (error == 0) {
938                 VI_LOCK(vp);
939                 if ((vp->v_iflag & VI_MOUNT) == 0 && vp->v_mountedhere == NULL)
940                         vp->v_iflag |= VI_MOUNT;
941                 else
942                         error = EBUSY;
943                 VI_UNLOCK(vp);
944         }
945         if (error != 0) {
946                 vput(vp);
947                 return (error);
948         }
949         VOP_UNLOCK(vp, 0);
950
951         /* Allocate and initialize the filesystem. */
952         mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
953         /* XXXMAC: pass to vfs_mount_alloc? */
954         mp->mnt_optnew = *optlist;
955         /* Set the mount level flags. */
956         mp->mnt_flag = (fsflags & (MNT_UPDATEMASK | MNT_ROOTFS | MNT_RDONLY));
957
958         /*
959          * Mount the filesystem.
960          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
961          * get.  No freeing of cn_pnbuf.
962          */
963         error1 = 0;
964         if ((error = VFS_MOUNT(mp)) != 0 ||
965             (error1 = VFS_STATFS(mp, &mp->mnt_stat)) != 0 ||
966             (error1 = VFS_ROOT(mp, LK_EXCLUSIVE, &newdp)) != 0) {
967                 if (error1 != 0) {
968                         error = error1;
969                         if ((error1 = VFS_UNMOUNT(mp, 0)) != 0)
970                                 printf("VFS_UNMOUNT returned %d\n", error1);
971                 }
972                 vfs_unbusy(mp);
973                 mp->mnt_vnodecovered = NULL;
974                 vfs_mount_destroy(mp);
975                 VI_LOCK(vp);
976                 vp->v_iflag &= ~VI_MOUNT;
977                 VI_UNLOCK(vp);
978                 vrele(vp);
979                 return (error);
980         }
981         VOP_UNLOCK(newdp, 0);
982
983         if (mp->mnt_opt != NULL)
984                 vfs_freeopts(mp->mnt_opt);
985         mp->mnt_opt = mp->mnt_optnew;
986         *optlist = NULL;
987
988         /*
989          * Prevent external consumers of mount options from reading mnt_optnew.
990          */
991         mp->mnt_optnew = NULL;
992
993         MNT_ILOCK(mp);
994         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
995             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
996                 mp->mnt_kern_flag |= MNTK_ASYNC;
997         else
998                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
999         MNT_IUNLOCK(mp);
1000
1001         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1002         cache_purge(vp);
1003         VI_LOCK(vp);
1004         vp->v_iflag &= ~VI_MOUNT;
1005         VI_UNLOCK(vp);
1006         vp->v_mountedhere = mp;
1007         /* Place the new filesystem at the end of the mount list. */
1008         mtx_lock(&mountlist_mtx);
1009         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1010         mtx_unlock(&mountlist_mtx);
1011         vfs_event_signal(NULL, VQ_MOUNT, 0);
1012         vn_lock(newdp, LK_EXCLUSIVE | LK_RETRY);
1013         VOP_UNLOCK(vp, 0);
1014         EVENTHANDLER_DIRECT_INVOKE(vfs_mounted, mp, newdp, td);
1015         VOP_UNLOCK(newdp, 0);
1016         mountcheckdirs(vp, newdp);
1017         vrele(newdp);
1018         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1019                 vfs_allocate_syncvnode(mp);
1020         vfs_op_exit(mp);
1021         vfs_unbusy(mp);
1022         return (0);
1023 }
1024
1025 /*
1026  * vfs_domount_update(): update of mounted file system
1027  */
1028 static int
1029 vfs_domount_update(
1030         struct thread *td,              /* Calling thread. */
1031         struct vnode *vp,               /* Mount point vnode. */
1032         uint64_t fsflags,               /* Flags common to all filesystems. */
1033         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1034         )
1035 {
1036         struct export_args export;
1037         void *bufp;
1038         struct mount *mp;
1039         int error, export_error, len;
1040         uint64_t flag;
1041
1042         ASSERT_VOP_ELOCKED(vp, __func__);
1043         KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1044         mp = vp->v_mount;
1045
1046         if ((vp->v_vflag & VV_ROOT) == 0) {
1047                 if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1048                     == 0)
1049                         error = EXDEV;
1050                 else
1051                         error = EINVAL;
1052                 vput(vp);
1053                 return (error);
1054         }
1055
1056         /*
1057          * We only allow the filesystem to be reloaded if it
1058          * is currently mounted read-only.
1059          */
1060         flag = mp->mnt_flag;
1061         if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1062                 vput(vp);
1063                 return (EOPNOTSUPP);    /* Needs translation */
1064         }
1065         /*
1066          * Only privileged root, or (if MNT_USER is set) the user that
1067          * did the original mount is permitted to update it.
1068          */
1069         error = vfs_suser(mp, td);
1070         if (error != 0) {
1071                 vput(vp);
1072                 return (error);
1073         }
1074         if (vfs_busy(mp, MBF_NOWAIT)) {
1075                 vput(vp);
1076                 return (EBUSY);
1077         }
1078         VI_LOCK(vp);
1079         if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1080                 VI_UNLOCK(vp);
1081                 vfs_unbusy(mp);
1082                 vput(vp);
1083                 return (EBUSY);
1084         }
1085         vp->v_iflag |= VI_MOUNT;
1086         VI_UNLOCK(vp);
1087         VOP_UNLOCK(vp, 0);
1088
1089         vfs_op_enter(mp);
1090
1091         MNT_ILOCK(mp);
1092         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1093                 MNT_IUNLOCK(mp);
1094                 error = EBUSY;
1095                 goto end;
1096         }
1097         mp->mnt_flag &= ~MNT_UPDATEMASK;
1098         mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1099             MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1100         if ((mp->mnt_flag & MNT_ASYNC) == 0)
1101                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1102         MNT_IUNLOCK(mp);
1103         mp->mnt_optnew = *optlist;
1104         vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1105
1106         /*
1107          * Mount the filesystem.
1108          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1109          * get.  No freeing of cn_pnbuf.
1110          */
1111         error = VFS_MOUNT(mp);
1112
1113         export_error = 0;
1114         /* Process the export option. */
1115         if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1116             &len) == 0) {
1117                 /* Assume that there is only 1 ABI for each length. */
1118                 switch (len) {
1119                 case (sizeof(struct oexport_args)):
1120                         bzero(&export, sizeof(export));
1121                         /* FALLTHROUGH */
1122                 case (sizeof(export)):
1123                         bcopy(bufp, &export, len);
1124                         export_error = vfs_export(mp, &export);
1125                         break;
1126                 default:
1127                         export_error = EINVAL;
1128                         break;
1129                 }
1130         }
1131
1132         MNT_ILOCK(mp);
1133         if (error == 0) {
1134                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1135                     MNT_SNAPSHOT);
1136         } else {
1137                 /*
1138                  * If we fail, restore old mount flags. MNT_QUOTA is special,
1139                  * because it is not part of MNT_UPDATEMASK, but it could have
1140                  * changed in the meantime if quotactl(2) was called.
1141                  * All in all we want current value of MNT_QUOTA, not the old
1142                  * one.
1143                  */
1144                 mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1145         }
1146         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1147             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1148                 mp->mnt_kern_flag |= MNTK_ASYNC;
1149         else
1150                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1151         MNT_IUNLOCK(mp);
1152
1153         if (error != 0)
1154                 goto end;
1155
1156         if (mp->mnt_opt != NULL)
1157                 vfs_freeopts(mp->mnt_opt);
1158         mp->mnt_opt = mp->mnt_optnew;
1159         *optlist = NULL;
1160         (void)VFS_STATFS(mp, &mp->mnt_stat);
1161         /*
1162          * Prevent external consumers of mount options from reading
1163          * mnt_optnew.
1164          */
1165         mp->mnt_optnew = NULL;
1166
1167         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1168                 vfs_allocate_syncvnode(mp);
1169         else
1170                 vfs_deallocate_syncvnode(mp);
1171 end:
1172         vfs_op_exit(mp);
1173         vfs_unbusy(mp);
1174         VI_LOCK(vp);
1175         vp->v_iflag &= ~VI_MOUNT;
1176         VI_UNLOCK(vp);
1177         vrele(vp);
1178         return (error != 0 ? error : export_error);
1179 }
1180
1181 /*
1182  * vfs_domount(): actually attempt a filesystem mount.
1183  */
1184 static int
1185 vfs_domount(
1186         struct thread *td,              /* Calling thread. */
1187         const char *fstype,             /* Filesystem type. */
1188         char *fspath,                   /* Mount path. */
1189         uint64_t fsflags,               /* Flags common to all filesystems. */
1190         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1191         )
1192 {
1193         struct vfsconf *vfsp;
1194         struct nameidata nd;
1195         struct vnode *vp;
1196         char *pathbuf;
1197         int error;
1198
1199         /*
1200          * Be ultra-paranoid about making sure the type and fspath
1201          * variables will fit in our mp buffers, including the
1202          * terminating NUL.
1203          */
1204         if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1205                 return (ENAMETOOLONG);
1206
1207         if (jailed(td->td_ucred) || usermount == 0) {
1208                 if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1209                         return (error);
1210         }
1211
1212         /*
1213          * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1214          */
1215         if (fsflags & MNT_EXPORTED) {
1216                 error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1217                 if (error)
1218                         return (error);
1219         }
1220         if (fsflags & MNT_SUIDDIR) {
1221                 error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1222                 if (error)
1223                         return (error);
1224         }
1225         /*
1226          * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1227          */
1228         if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1229                 if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1230                         fsflags |= MNT_NOSUID | MNT_USER;
1231         }
1232
1233         /* Load KLDs before we lock the covered vnode to avoid reversals. */
1234         vfsp = NULL;
1235         if ((fsflags & MNT_UPDATE) == 0) {
1236                 /* Don't try to load KLDs if we're mounting the root. */
1237                 if (fsflags & MNT_ROOTFS)
1238                         vfsp = vfs_byname(fstype);
1239                 else
1240                         vfsp = vfs_byname_kld(fstype, td, &error);
1241                 if (vfsp == NULL)
1242                         return (ENODEV);
1243         }
1244
1245         /*
1246          * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1247          */
1248         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1249             UIO_SYSSPACE, fspath, td);
1250         error = namei(&nd);
1251         if (error != 0)
1252                 return (error);
1253         NDFREE(&nd, NDF_ONLY_PNBUF);
1254         vp = nd.ni_vp;
1255         if ((fsflags & MNT_UPDATE) == 0) {
1256                 if ((vp->v_vflag & VV_ROOT) != 0 &&
1257                     (fsflags & MNT_NOCOVER) != 0) {
1258                         vput(vp);
1259                         return (EBUSY);
1260                 }
1261                 pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1262                 strcpy(pathbuf, fspath);
1263                 error = vn_path_to_global_path(td, vp, pathbuf, MNAMELEN);
1264                 /* debug.disablefullpath == 1 results in ENODEV */
1265                 if (error == 0 || error == ENODEV) {
1266                         error = vfs_domount_first(td, vfsp, pathbuf, vp,
1267                             fsflags, optlist);
1268                 }
1269                 free(pathbuf, M_TEMP);
1270         } else
1271                 error = vfs_domount_update(td, vp, fsflags, optlist);
1272
1273         return (error);
1274 }
1275
1276 /*
1277  * Unmount a filesystem.
1278  *
1279  * Note: unmount takes a path to the vnode mounted on as argument, not
1280  * special file (as before).
1281  */
1282 #ifndef _SYS_SYSPROTO_H_
1283 struct unmount_args {
1284         char    *path;
1285         int     flags;
1286 };
1287 #endif
1288 /* ARGSUSED */
1289 int
1290 sys_unmount(struct thread *td, struct unmount_args *uap)
1291 {
1292         struct nameidata nd;
1293         struct mount *mp;
1294         char *pathbuf;
1295         int error, id0, id1;
1296
1297         AUDIT_ARG_VALUE(uap->flags);
1298         if (jailed(td->td_ucred) || usermount == 0) {
1299                 error = priv_check(td, PRIV_VFS_UNMOUNT);
1300                 if (error)
1301                         return (error);
1302         }
1303
1304         pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1305         error = copyinstr(uap->path, pathbuf, MNAMELEN, NULL);
1306         if (error) {
1307                 free(pathbuf, M_TEMP);
1308                 return (error);
1309         }
1310         if (uap->flags & MNT_BYFSID) {
1311                 AUDIT_ARG_TEXT(pathbuf);
1312                 /* Decode the filesystem ID. */
1313                 if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
1314                         free(pathbuf, M_TEMP);
1315                         return (EINVAL);
1316                 }
1317
1318                 mtx_lock(&mountlist_mtx);
1319                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1320                         if (mp->mnt_stat.f_fsid.val[0] == id0 &&
1321                             mp->mnt_stat.f_fsid.val[1] == id1) {
1322                                 vfs_ref(mp);
1323                                 break;
1324                         }
1325                 }
1326                 mtx_unlock(&mountlist_mtx);
1327         } else {
1328                 /*
1329                  * Try to find global path for path argument.
1330                  */
1331                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1332                     UIO_SYSSPACE, pathbuf, td);
1333                 if (namei(&nd) == 0) {
1334                         NDFREE(&nd, NDF_ONLY_PNBUF);
1335                         error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1336                             MNAMELEN);
1337                         if (error == 0 || error == ENODEV)
1338                                 vput(nd.ni_vp);
1339                 }
1340                 mtx_lock(&mountlist_mtx);
1341                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1342                         if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1343                                 vfs_ref(mp);
1344                                 break;
1345                         }
1346                 }
1347                 mtx_unlock(&mountlist_mtx);
1348         }
1349         free(pathbuf, M_TEMP);
1350         if (mp == NULL) {
1351                 /*
1352                  * Previously we returned ENOENT for a nonexistent path and
1353                  * EINVAL for a non-mountpoint.  We cannot tell these apart
1354                  * now, so in the !MNT_BYFSID case return the more likely
1355                  * EINVAL for compatibility.
1356                  */
1357                 return ((uap->flags & MNT_BYFSID) ? ENOENT : EINVAL);
1358         }
1359
1360         /*
1361          * Don't allow unmounting the root filesystem.
1362          */
1363         if (mp->mnt_flag & MNT_ROOTFS) {
1364                 vfs_rel(mp);
1365                 return (EINVAL);
1366         }
1367         error = dounmount(mp, uap->flags, td);
1368         return (error);
1369 }
1370
1371 /*
1372  * Return error if any of the vnodes, ignoring the root vnode
1373  * and the syncer vnode, have non-zero usecount.
1374  *
1375  * This function is purely advisory - it can return false positives
1376  * and negatives.
1377  */
1378 static int
1379 vfs_check_usecounts(struct mount *mp)
1380 {
1381         struct vnode *vp, *mvp;
1382
1383         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1384                 if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1385                     vp->v_usecount != 0) {
1386                         VI_UNLOCK(vp);
1387                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1388                         return (EBUSY);
1389                 }
1390                 VI_UNLOCK(vp);
1391         }
1392
1393         return (0);
1394 }
1395
1396 static void
1397 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1398 {
1399
1400         mtx_assert(MNT_MTX(mp), MA_OWNED);
1401         mp->mnt_kern_flag &= ~mntkflags;
1402         if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1403                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
1404                 wakeup(mp);
1405         }
1406         vfs_op_exit_locked(mp);
1407         MNT_IUNLOCK(mp);
1408         if (coveredvp != NULL) {
1409                 VOP_UNLOCK(coveredvp, 0);
1410                 vdrop(coveredvp);
1411         }
1412         vn_finished_write(mp);
1413 }
1414
1415 /*
1416  * There are various reference counters associated with the mount point.
1417  * Normally it is permitted to modify them without taking the mnt ilock,
1418  * but this behavior can be temporarily disabled if stable value is needed
1419  * or callers are expected to block (e.g. to not allow new users during
1420  * forced unmount).
1421  */
1422 void
1423 vfs_op_enter(struct mount *mp)
1424 {
1425         int cpu;
1426
1427         MNT_ILOCK(mp);
1428         mp->mnt_vfs_ops++;
1429         if (mp->mnt_vfs_ops > 1) {
1430                 MNT_IUNLOCK(mp);
1431                 return;
1432         }
1433         /*
1434          * Paired with a fence in vfs_op_thread_enter(). See the comment
1435          * above it for details.
1436          */
1437         atomic_thread_fence_seq_cst();
1438         vfs_op_barrier_wait(mp);
1439         /*
1440          * Paired with a fence in vfs_op_thread_exit().
1441          */
1442         atomic_thread_fence_acq();
1443         CPU_FOREACH(cpu) {
1444                 mp->mnt_ref +=
1445                     zpcpu_replace_cpu(mp->mnt_ref_pcpu, 0, cpu);
1446                 mp->mnt_lockref +=
1447                     zpcpu_replace_cpu(mp->mnt_lockref_pcpu, 0, cpu);
1448                 mp->mnt_writeopcount +=
1449                     zpcpu_replace_cpu(mp->mnt_writeopcount_pcpu, 0, cpu);
1450         }
1451         MNT_IUNLOCK(mp);
1452         vfs_assert_mount_counters(mp);
1453 }
1454
1455 void
1456 vfs_op_exit_locked(struct mount *mp)
1457 {
1458
1459         mtx_assert(MNT_MTX(mp), MA_OWNED);
1460
1461         if (mp->mnt_vfs_ops <= 0)
1462                 panic("%s: invalid vfs_ops count %d for mp %p\n",
1463                     __func__, mp->mnt_vfs_ops, mp);
1464         mp->mnt_vfs_ops--;
1465 }
1466
1467 void
1468 vfs_op_exit(struct mount *mp)
1469 {
1470
1471         MNT_ILOCK(mp);
1472         vfs_op_exit_locked(mp);
1473         MNT_IUNLOCK(mp);
1474 }
1475
1476 /*
1477  * It is assumed the caller already posted at least an acquire barrier.
1478  */
1479 void
1480 vfs_op_barrier_wait(struct mount *mp)
1481 {
1482         int *in_op;
1483         int cpu;
1484
1485         CPU_FOREACH(cpu) {
1486                 in_op = zpcpu_get_cpu(mp->mnt_thread_in_ops_pcpu, cpu);
1487                 while (atomic_load_int(in_op))
1488                         cpu_spinwait();
1489         }
1490 }
1491
1492 #ifdef DIAGNOSTIC
1493 void
1494 vfs_assert_mount_counters(struct mount *mp)
1495 {
1496         int cpu;
1497
1498         if (mp->mnt_vfs_ops == 0)
1499                 return;
1500
1501         CPU_FOREACH(cpu) {
1502                 if (*(int *)zpcpu_get_cpu(mp->mnt_ref_pcpu, cpu) != 0 ||
1503                     *(int *)zpcpu_get_cpu(mp->mnt_lockref_pcpu, cpu) != 0 ||
1504                     *(int *)zpcpu_get_cpu(mp->mnt_writeopcount_pcpu, cpu) != 0)
1505                         vfs_dump_mount_counters(mp);
1506         }
1507 }
1508
1509 void
1510 vfs_dump_mount_counters(struct mount *mp)
1511 {
1512         int cpu, *count;
1513         int ref, lockref, writeopcount;
1514
1515         printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1516
1517         printf("        ref : ");
1518         ref = mp->mnt_ref;
1519         CPU_FOREACH(cpu) {
1520                 count = zpcpu_get_cpu(mp->mnt_ref_pcpu, cpu);
1521                 printf("%d ", *count);
1522                 ref += *count;
1523         }
1524         printf("\n");
1525         printf("    lockref : ");
1526         lockref = mp->mnt_lockref;
1527         CPU_FOREACH(cpu) {
1528                 count = zpcpu_get_cpu(mp->mnt_lockref_pcpu, cpu);
1529                 printf("%d ", *count);
1530                 lockref += *count;
1531         }
1532         printf("\n");
1533         printf("writeopcount: ");
1534         writeopcount = mp->mnt_writeopcount;
1535         CPU_FOREACH(cpu) {
1536                 count = zpcpu_get_cpu(mp->mnt_writeopcount_pcpu, cpu);
1537                 printf("%d ", *count);
1538                 writeopcount += *count;
1539         }
1540         printf("\n");
1541
1542         printf("counter       struct total\n");
1543         printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1544         printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1545         printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1546
1547         panic("invalid counts on struct mount");
1548 }
1549 #endif
1550
1551 int
1552 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1553 {
1554         int *base, *pcpu;
1555         int cpu, sum;
1556
1557         switch (which) {
1558         case MNT_COUNT_REF:
1559                 base = &mp->mnt_ref;
1560                 pcpu = mp->mnt_ref_pcpu;
1561                 break;
1562         case MNT_COUNT_LOCKREF:
1563                 base = &mp->mnt_lockref;
1564                 pcpu = mp->mnt_lockref_pcpu;
1565                 break;
1566         case MNT_COUNT_WRITEOPCOUNT:
1567                 base = &mp->mnt_writeopcount;
1568                 pcpu = mp->mnt_writeopcount_pcpu;
1569                 break;
1570         }
1571
1572         sum = *base;
1573         CPU_FOREACH(cpu) {
1574                 sum += *(int *)zpcpu_get_cpu(pcpu, cpu);
1575         }
1576         return (sum);
1577 }
1578
1579 /*
1580  * Do the actual filesystem unmount.
1581  */
1582 int
1583 dounmount(struct mount *mp, int flags, struct thread *td)
1584 {
1585         struct vnode *coveredvp;
1586         int error;
1587         uint64_t async_flag;
1588         int mnt_gen_r;
1589
1590         if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
1591                 mnt_gen_r = mp->mnt_gen;
1592                 VI_LOCK(coveredvp);
1593                 vholdl(coveredvp);
1594                 vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
1595                 /*
1596                  * Check for mp being unmounted while waiting for the
1597                  * covered vnode lock.
1598                  */
1599                 if (coveredvp->v_mountedhere != mp ||
1600                     coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
1601                         VOP_UNLOCK(coveredvp, 0);
1602                         vdrop(coveredvp);
1603                         vfs_rel(mp);
1604                         return (EBUSY);
1605                 }
1606         }
1607
1608         /*
1609          * Only privileged root, or (if MNT_USER is set) the user that did the
1610          * original mount is permitted to unmount this filesystem.
1611          */
1612         error = vfs_suser(mp, td);
1613         if (error != 0) {
1614                 if (coveredvp != NULL) {
1615                         VOP_UNLOCK(coveredvp, 0);
1616                         vdrop(coveredvp);
1617                 }
1618                 vfs_rel(mp);
1619                 return (error);
1620         }
1621
1622         vfs_op_enter(mp);
1623
1624         vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
1625         MNT_ILOCK(mp);
1626         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
1627             (mp->mnt_flag & MNT_UPDATE) != 0 ||
1628             !TAILQ_EMPTY(&mp->mnt_uppers)) {
1629                 dounmount_cleanup(mp, coveredvp, 0);
1630                 return (EBUSY);
1631         }
1632         mp->mnt_kern_flag |= MNTK_UNMOUNT;
1633         if (flags & MNT_NONBUSY) {
1634                 MNT_IUNLOCK(mp);
1635                 error = vfs_check_usecounts(mp);
1636                 MNT_ILOCK(mp);
1637                 if (error != 0) {
1638                         dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
1639                         return (error);
1640                 }
1641         }
1642         /* Allow filesystems to detect that a forced unmount is in progress. */
1643         if (flags & MNT_FORCE) {
1644                 mp->mnt_kern_flag |= MNTK_UNMOUNTF;
1645                 MNT_IUNLOCK(mp);
1646                 /*
1647                  * Must be done after setting MNTK_UNMOUNTF and before
1648                  * waiting for mnt_lockref to become 0.
1649                  */
1650                 VFS_PURGE(mp);
1651                 MNT_ILOCK(mp);
1652         }
1653         error = 0;
1654         if (mp->mnt_lockref) {
1655                 mp->mnt_kern_flag |= MNTK_DRAINING;
1656                 error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
1657                     "mount drain", 0);
1658         }
1659         MNT_IUNLOCK(mp);
1660         KASSERT(mp->mnt_lockref == 0,
1661             ("%s: invalid lock refcount in the drain path @ %s:%d",
1662             __func__, __FILE__, __LINE__));
1663         KASSERT(error == 0,
1664             ("%s: invalid return value for msleep in the drain path @ %s:%d",
1665             __func__, __FILE__, __LINE__));
1666
1667         if (mp->mnt_flag & MNT_EXPUBLIC)
1668                 vfs_setpublicfs(NULL, NULL, NULL);
1669
1670         /*
1671          * From now, we can claim that the use reference on the
1672          * coveredvp is ours, and the ref can be released only by
1673          * successfull unmount by us, or left for later unmount
1674          * attempt.  The previously acquired hold reference is no
1675          * longer needed to protect the vnode from reuse.
1676          */
1677         if (coveredvp != NULL)
1678                 vdrop(coveredvp);
1679
1680         vfs_msync(mp, MNT_WAIT);
1681         MNT_ILOCK(mp);
1682         async_flag = mp->mnt_flag & MNT_ASYNC;
1683         mp->mnt_flag &= ~MNT_ASYNC;
1684         mp->mnt_kern_flag &= ~MNTK_ASYNC;
1685         MNT_IUNLOCK(mp);
1686         cache_purgevfs(mp, false); /* remove cache entries for this file sys */
1687         vfs_deallocate_syncvnode(mp);
1688         if ((mp->mnt_flag & MNT_RDONLY) != 0 || (flags & MNT_FORCE) != 0 ||
1689             (error = VFS_SYNC(mp, MNT_WAIT)) == 0)
1690                 error = VFS_UNMOUNT(mp, flags);
1691         vn_finished_write(mp);
1692         /*
1693          * If we failed to flush the dirty blocks for this mount point,
1694          * undo all the cdir/rdir and rootvnode changes we made above.
1695          * Unless we failed to do so because the device is reporting that
1696          * it doesn't exist anymore.
1697          */
1698         if (error && error != ENXIO) {
1699                 MNT_ILOCK(mp);
1700                 if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1701                         MNT_IUNLOCK(mp);
1702                         vfs_allocate_syncvnode(mp);
1703                         MNT_ILOCK(mp);
1704                 }
1705                 mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
1706                 mp->mnt_flag |= async_flag;
1707                 if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1708                     (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1709                         mp->mnt_kern_flag |= MNTK_ASYNC;
1710                 if (mp->mnt_kern_flag & MNTK_MWAIT) {
1711                         mp->mnt_kern_flag &= ~MNTK_MWAIT;
1712                         wakeup(mp);
1713                 }
1714                 vfs_op_exit_locked(mp);
1715                 MNT_IUNLOCK(mp);
1716                 if (coveredvp)
1717                         VOP_UNLOCK(coveredvp, 0);
1718                 return (error);
1719         }
1720         mtx_lock(&mountlist_mtx);
1721         TAILQ_REMOVE(&mountlist, mp, mnt_list);
1722         mtx_unlock(&mountlist_mtx);
1723         EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
1724         if (coveredvp != NULL) {
1725                 coveredvp->v_mountedhere = NULL;
1726                 VOP_UNLOCK(coveredvp, 0);
1727         }
1728         vfs_event_signal(NULL, VQ_UNMOUNT, 0);
1729         if (rootvnode != NULL && mp == rootvnode->v_mount) {
1730                 vrele(rootvnode);
1731                 rootvnode = NULL;
1732         }
1733         if (mp == rootdevmp)
1734                 rootdevmp = NULL;
1735         vfs_mount_destroy(mp);
1736         return (0);
1737 }
1738
1739 /*
1740  * Report errors during filesystem mounting.
1741  */
1742 void
1743 vfs_mount_error(struct mount *mp, const char *fmt, ...)
1744 {
1745         struct vfsoptlist *moptlist = mp->mnt_optnew;
1746         va_list ap;
1747         int error, len;
1748         char *errmsg;
1749
1750         error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
1751         if (error || errmsg == NULL || len <= 0)
1752                 return;
1753
1754         va_start(ap, fmt);
1755         vsnprintf(errmsg, (size_t)len, fmt, ap);
1756         va_end(ap);
1757 }
1758
1759 void
1760 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
1761 {
1762         va_list ap;
1763         int error, len;
1764         char *errmsg;
1765
1766         error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
1767         if (error || errmsg == NULL || len <= 0)
1768                 return;
1769
1770         va_start(ap, fmt);
1771         vsnprintf(errmsg, (size_t)len, fmt, ap);
1772         va_end(ap);
1773 }
1774
1775 /*
1776  * ---------------------------------------------------------------------
1777  * Functions for querying mount options/arguments from filesystems.
1778  */
1779
1780 /*
1781  * Check that no unknown options are given
1782  */
1783 int
1784 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1785 {
1786         struct vfsopt *opt;
1787         char errmsg[255];
1788         const char **t, *p, *q;
1789         int ret = 0;
1790
1791         TAILQ_FOREACH(opt, opts, link) {
1792                 p = opt->name;
1793                 q = NULL;
1794                 if (p[0] == 'n' && p[1] == 'o')
1795                         q = p + 2;
1796                 for(t = global_opts; *t != NULL; t++) {
1797                         if (strcmp(*t, p) == 0)
1798                                 break;
1799                         if (q != NULL) {
1800                                 if (strcmp(*t, q) == 0)
1801                                         break;
1802                         }
1803                 }
1804                 if (*t != NULL)
1805                         continue;
1806                 for(t = legal; *t != NULL; t++) {
1807                         if (strcmp(*t, p) == 0)
1808                                 break;
1809                         if (q != NULL) {
1810                                 if (strcmp(*t, q) == 0)
1811                                         break;
1812                         }
1813                 }
1814                 if (*t != NULL)
1815                         continue;
1816                 snprintf(errmsg, sizeof(errmsg),
1817                     "mount option <%s> is unknown", p);
1818                 ret = EINVAL;
1819         }
1820         if (ret != 0) {
1821                 TAILQ_FOREACH(opt, opts, link) {
1822                         if (strcmp(opt->name, "errmsg") == 0) {
1823                                 strncpy((char *)opt->value, errmsg, opt->len);
1824                                 break;
1825                         }
1826                 }
1827                 if (opt == NULL)
1828                         printf("%s\n", errmsg);
1829         }
1830         return (ret);
1831 }
1832
1833 /*
1834  * Get a mount option by its name.
1835  *
1836  * Return 0 if the option was found, ENOENT otherwise.
1837  * If len is non-NULL it will be filled with the length
1838  * of the option. If buf is non-NULL, it will be filled
1839  * with the address of the option.
1840  */
1841 int
1842 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
1843 {
1844         struct vfsopt *opt;
1845
1846         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1847
1848         TAILQ_FOREACH(opt, opts, link) {
1849                 if (strcmp(name, opt->name) == 0) {
1850                         opt->seen = 1;
1851                         if (len != NULL)
1852                                 *len = opt->len;
1853                         if (buf != NULL)
1854                                 *buf = opt->value;
1855                         return (0);
1856                 }
1857         }
1858         return (ENOENT);
1859 }
1860
1861 int
1862 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
1863 {
1864         struct vfsopt *opt;
1865
1866         if (opts == NULL)
1867                 return (-1);
1868
1869         TAILQ_FOREACH(opt, opts, link) {
1870                 if (strcmp(name, opt->name) == 0) {
1871                         opt->seen = 1;
1872                         return (opt->pos);
1873                 }
1874         }
1875         return (-1);
1876 }
1877
1878 int
1879 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
1880 {
1881         char *opt_value, *vtp;
1882         quad_t iv;
1883         int error, opt_len;
1884
1885         error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
1886         if (error != 0)
1887                 return (error);
1888         if (opt_len == 0 || opt_value == NULL)
1889                 return (EINVAL);
1890         if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
1891                 return (EINVAL);
1892         iv = strtoq(opt_value, &vtp, 0);
1893         if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
1894                 return (EINVAL);
1895         if (iv < 0)
1896                 return (EINVAL);
1897         switch (vtp[0]) {
1898         case 't': case 'T':
1899                 iv *= 1024;
1900                 /* FALLTHROUGH */
1901         case 'g': case 'G':
1902                 iv *= 1024;
1903                 /* FALLTHROUGH */
1904         case 'm': case 'M':
1905                 iv *= 1024;
1906                 /* FALLTHROUGH */
1907         case 'k': case 'K':
1908                 iv *= 1024;
1909         case '\0':
1910                 break;
1911         default:
1912                 return (EINVAL);
1913         }
1914         *value = iv;
1915
1916         return (0);
1917 }
1918
1919 char *
1920 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
1921 {
1922         struct vfsopt *opt;
1923
1924         *error = 0;
1925         TAILQ_FOREACH(opt, opts, link) {
1926                 if (strcmp(name, opt->name) != 0)
1927                         continue;
1928                 opt->seen = 1;
1929                 if (opt->len == 0 ||
1930                     ((char *)opt->value)[opt->len - 1] != '\0') {
1931                         *error = EINVAL;
1932                         return (NULL);
1933                 }
1934                 return (opt->value);
1935         }
1936         *error = ENOENT;
1937         return (NULL);
1938 }
1939
1940 int
1941 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
1942         uint64_t val)
1943 {
1944         struct vfsopt *opt;
1945
1946         TAILQ_FOREACH(opt, opts, link) {
1947                 if (strcmp(name, opt->name) == 0) {
1948                         opt->seen = 1;
1949                         if (w != NULL)
1950                                 *w |= val;
1951                         return (1);
1952                 }
1953         }
1954         if (w != NULL)
1955                 *w &= ~val;
1956         return (0);
1957 }
1958
1959 int
1960 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
1961 {
1962         va_list ap;
1963         struct vfsopt *opt;
1964         int ret;
1965
1966         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1967
1968         TAILQ_FOREACH(opt, opts, link) {
1969                 if (strcmp(name, opt->name) != 0)
1970                         continue;
1971                 opt->seen = 1;
1972                 if (opt->len == 0 || opt->value == NULL)
1973                         return (0);
1974                 if (((char *)opt->value)[opt->len - 1] != '\0')
1975                         return (0);
1976                 va_start(ap, fmt);
1977                 ret = vsscanf(opt->value, fmt, ap);
1978                 va_end(ap);
1979                 return (ret);
1980         }
1981         return (0);
1982 }
1983
1984 int
1985 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
1986 {
1987         struct vfsopt *opt;
1988
1989         TAILQ_FOREACH(opt, opts, link) {
1990                 if (strcmp(name, opt->name) != 0)
1991                         continue;
1992                 opt->seen = 1;
1993                 if (opt->value == NULL)
1994                         opt->len = len;
1995                 else {
1996                         if (opt->len != len)
1997                                 return (EINVAL);
1998                         bcopy(value, opt->value, len);
1999                 }
2000                 return (0);
2001         }
2002         return (ENOENT);
2003 }
2004
2005 int
2006 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2007 {
2008         struct vfsopt *opt;
2009
2010         TAILQ_FOREACH(opt, opts, link) {
2011                 if (strcmp(name, opt->name) != 0)
2012                         continue;
2013                 opt->seen = 1;
2014                 if (opt->value == NULL)
2015                         opt->len = len;
2016                 else {
2017                         if (opt->len < len)
2018                                 return (EINVAL);
2019                         opt->len = len;
2020                         bcopy(value, opt->value, len);
2021                 }
2022                 return (0);
2023         }
2024         return (ENOENT);
2025 }
2026
2027 int
2028 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2029 {
2030         struct vfsopt *opt;
2031
2032         TAILQ_FOREACH(opt, opts, link) {
2033                 if (strcmp(name, opt->name) != 0)
2034                         continue;
2035                 opt->seen = 1;
2036                 if (opt->value == NULL)
2037                         opt->len = strlen(value) + 1;
2038                 else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2039                         return (EINVAL);
2040                 return (0);
2041         }
2042         return (ENOENT);
2043 }
2044
2045 /*
2046  * Find and copy a mount option.
2047  *
2048  * The size of the buffer has to be specified
2049  * in len, if it is not the same length as the
2050  * mount option, EINVAL is returned.
2051  * Returns ENOENT if the option is not found.
2052  */
2053 int
2054 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2055 {
2056         struct vfsopt *opt;
2057
2058         KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2059
2060         TAILQ_FOREACH(opt, opts, link) {
2061                 if (strcmp(name, opt->name) == 0) {
2062                         opt->seen = 1;
2063                         if (len != opt->len)
2064                                 return (EINVAL);
2065                         bcopy(opt->value, dest, opt->len);
2066                         return (0);
2067                 }
2068         }
2069         return (ENOENT);
2070 }
2071
2072 int
2073 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2074 {
2075
2076         /*
2077          * Filesystems only fill in part of the structure for updates, we
2078          * have to read the entirety first to get all content.
2079          */
2080         memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2081
2082         /*
2083          * Set these in case the underlying filesystem fails to do so.
2084          */
2085         sbp->f_version = STATFS_VERSION;
2086         sbp->f_namemax = NAME_MAX;
2087         sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2088
2089         return (mp->mnt_op->vfs_statfs(mp, sbp));
2090 }
2091
2092 void
2093 vfs_mountedfrom(struct mount *mp, const char *from)
2094 {
2095
2096         bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2097         strlcpy(mp->mnt_stat.f_mntfromname, from,
2098             sizeof mp->mnt_stat.f_mntfromname);
2099 }
2100
2101 /*
2102  * ---------------------------------------------------------------------
2103  * This is the api for building mount args and mounting filesystems from
2104  * inside the kernel.
2105  *
2106  * The API works by accumulation of individual args.  First error is
2107  * latched.
2108  *
2109  * XXX: should be documented in new manpage kernel_mount(9)
2110  */
2111
2112 /* A memory allocation which must be freed when we are done */
2113 struct mntaarg {
2114         SLIST_ENTRY(mntaarg)    next;
2115 };
2116
2117 /* The header for the mount arguments */
2118 struct mntarg {
2119         struct iovec *v;
2120         int len;
2121         int error;
2122         SLIST_HEAD(, mntaarg)   list;
2123 };
2124
2125 /*
2126  * Add a boolean argument.
2127  *
2128  * flag is the boolean value.
2129  * name must start with "no".
2130  */
2131 struct mntarg *
2132 mount_argb(struct mntarg *ma, int flag, const char *name)
2133 {
2134
2135         KASSERT(name[0] == 'n' && name[1] == 'o',
2136             ("mount_argb(...,%s): name must start with 'no'", name));
2137
2138         return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2139 }
2140
2141 /*
2142  * Add an argument printf style
2143  */
2144 struct mntarg *
2145 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2146 {
2147         va_list ap;
2148         struct mntaarg *maa;
2149         struct sbuf *sb;
2150         int len;
2151
2152         if (ma == NULL) {
2153                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2154                 SLIST_INIT(&ma->list);
2155         }
2156         if (ma->error)
2157                 return (ma);
2158
2159         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2160             M_MOUNT, M_WAITOK);
2161         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2162         ma->v[ma->len].iov_len = strlen(name) + 1;
2163         ma->len++;
2164
2165         sb = sbuf_new_auto();
2166         va_start(ap, fmt);
2167         sbuf_vprintf(sb, fmt, ap);
2168         va_end(ap);
2169         sbuf_finish(sb);
2170         len = sbuf_len(sb) + 1;
2171         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2172         SLIST_INSERT_HEAD(&ma->list, maa, next);
2173         bcopy(sbuf_data(sb), maa + 1, len);
2174         sbuf_delete(sb);
2175
2176         ma->v[ma->len].iov_base = maa + 1;
2177         ma->v[ma->len].iov_len = len;
2178         ma->len++;
2179
2180         return (ma);
2181 }
2182
2183 /*
2184  * Add an argument which is a userland string.
2185  */
2186 struct mntarg *
2187 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2188 {
2189         struct mntaarg *maa;
2190         char *tbuf;
2191
2192         if (val == NULL)
2193                 return (ma);
2194         if (ma == NULL) {
2195                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2196                 SLIST_INIT(&ma->list);
2197         }
2198         if (ma->error)
2199                 return (ma);
2200         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2201         SLIST_INSERT_HEAD(&ma->list, maa, next);
2202         tbuf = (void *)(maa + 1);
2203         ma->error = copyinstr(val, tbuf, len, NULL);
2204         return (mount_arg(ma, name, tbuf, -1));
2205 }
2206
2207 /*
2208  * Plain argument.
2209  *
2210  * If length is -1, treat value as a C string.
2211  */
2212 struct mntarg *
2213 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2214 {
2215
2216         if (ma == NULL) {
2217                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2218                 SLIST_INIT(&ma->list);
2219         }
2220         if (ma->error)
2221                 return (ma);
2222
2223         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2224             M_MOUNT, M_WAITOK);
2225         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2226         ma->v[ma->len].iov_len = strlen(name) + 1;
2227         ma->len++;
2228
2229         ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2230         if (len < 0)
2231                 ma->v[ma->len].iov_len = strlen(val) + 1;
2232         else
2233                 ma->v[ma->len].iov_len = len;
2234         ma->len++;
2235         return (ma);
2236 }
2237
2238 /*
2239  * Free a mntarg structure
2240  */
2241 static void
2242 free_mntarg(struct mntarg *ma)
2243 {
2244         struct mntaarg *maa;
2245
2246         while (!SLIST_EMPTY(&ma->list)) {
2247                 maa = SLIST_FIRST(&ma->list);
2248                 SLIST_REMOVE_HEAD(&ma->list, next);
2249                 free(maa, M_MOUNT);
2250         }
2251         free(ma->v, M_MOUNT);
2252         free(ma, M_MOUNT);
2253 }
2254
2255 /*
2256  * Mount a filesystem
2257  */
2258 int
2259 kernel_mount(struct mntarg *ma, uint64_t flags)
2260 {
2261         struct uio auio;
2262         int error;
2263
2264         KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2265         KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
2266         KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2267
2268         auio.uio_iov = ma->v;
2269         auio.uio_iovcnt = ma->len;
2270         auio.uio_segflg = UIO_SYSSPACE;
2271
2272         error = ma->error;
2273         if (!error)
2274                 error = vfs_donmount(curthread, flags, &auio);
2275         free_mntarg(ma);
2276         return (error);
2277 }
2278
2279 /*
2280  * A printflike function to mount a filesystem.
2281  */
2282 int
2283 kernel_vmount(int flags, ...)
2284 {
2285         struct mntarg *ma = NULL;
2286         va_list ap;
2287         const char *cp;
2288         const void *vp;
2289         int error;
2290
2291         va_start(ap, flags);
2292         for (;;) {
2293                 cp = va_arg(ap, const char *);
2294                 if (cp == NULL)
2295                         break;
2296                 vp = va_arg(ap, const void *);
2297                 ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2298         }
2299         va_end(ap);
2300
2301         error = kernel_mount(ma, flags);
2302         return (error);
2303 }
2304
2305 void
2306 vfs_oexport_conv(const struct oexport_args *oexp, struct export_args *exp)
2307 {
2308
2309         bcopy(oexp, exp, sizeof(*oexp));
2310         exp->ex_numsecflavors = 0;
2311 }