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