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