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