]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_mount.c
Add VFS FS events for mount and unmount to devctl/devd
[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/bus.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 dev_vfs_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                 if (error1 != 0) {
973                         error = error1;
974                         rootvp = vfs_cache_root_clear(mp);
975                         if (rootvp != NULL)
976                                 vrele(rootvp);
977                         if ((error1 = VFS_UNMOUNT(mp, 0)) != 0)
978                                 printf("VFS_UNMOUNT returned %d\n", error1);
979                 }
980                 vfs_unbusy(mp);
981                 mp->mnt_vnodecovered = NULL;
982                 vfs_mount_destroy(mp);
983                 VI_LOCK(vp);
984                 vp->v_iflag &= ~VI_MOUNT;
985                 VI_UNLOCK(vp);
986                 vn_seqc_write_end(vp);
987                 vrele(vp);
988                 return (error);
989         }
990         vn_seqc_write_begin(newdp);
991         VOP_UNLOCK(newdp);
992
993         if (mp->mnt_opt != NULL)
994                 vfs_freeopts(mp->mnt_opt);
995         mp->mnt_opt = mp->mnt_optnew;
996         *optlist = NULL;
997
998         /*
999          * Prevent external consumers of mount options from reading mnt_optnew.
1000          */
1001         mp->mnt_optnew = NULL;
1002
1003         MNT_ILOCK(mp);
1004         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1005             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1006                 mp->mnt_kern_flag |= MNTK_ASYNC;
1007         else
1008                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1009         MNT_IUNLOCK(mp);
1010
1011         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1012         cache_purge(vp);
1013         VI_LOCK(vp);
1014         vp->v_iflag &= ~VI_MOUNT;
1015         VI_UNLOCK(vp);
1016         vp->v_mountedhere = mp;
1017         /* Place the new filesystem at the end of the mount list. */
1018         mtx_lock(&mountlist_mtx);
1019         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1020         mtx_unlock(&mountlist_mtx);
1021         vfs_event_signal(NULL, VQ_MOUNT, 0);
1022         vn_lock(newdp, LK_EXCLUSIVE | LK_RETRY);
1023         VOP_UNLOCK(vp);
1024         EVENTHANDLER_DIRECT_INVOKE(vfs_mounted, mp, newdp, td);
1025         VOP_UNLOCK(newdp);
1026         dev_vfs_event("MOUNT", mp, false);
1027         mountcheckdirs(vp, newdp);
1028         vn_seqc_write_end(vp);
1029         vn_seqc_write_end(newdp);
1030         vrele(newdp);
1031         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1032                 vfs_allocate_syncvnode(mp);
1033         vfs_op_exit(mp);
1034         vfs_unbusy(mp);
1035         return (0);
1036 }
1037
1038 /*
1039  * vfs_domount_update(): update of mounted file system
1040  */
1041 static int
1042 vfs_domount_update(
1043         struct thread *td,              /* Calling thread. */
1044         struct vnode *vp,               /* Mount point vnode. */
1045         uint64_t fsflags,               /* Flags common to all filesystems. */
1046         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1047         )
1048 {
1049         struct export_args export;
1050         struct o2export_args o2export;
1051         struct vnode *rootvp;
1052         void *bufp;
1053         struct mount *mp;
1054         int error, export_error, i, len;
1055         uint64_t flag;
1056         gid_t *grps;
1057
1058         ASSERT_VOP_ELOCKED(vp, __func__);
1059         KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1060         mp = vp->v_mount;
1061
1062         if ((vp->v_vflag & VV_ROOT) == 0) {
1063                 if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1064                     == 0)
1065                         error = EXDEV;
1066                 else
1067                         error = EINVAL;
1068                 vput(vp);
1069                 return (error);
1070         }
1071
1072         /*
1073          * We only allow the filesystem to be reloaded if it
1074          * is currently mounted read-only.
1075          */
1076         flag = mp->mnt_flag;
1077         if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1078                 vput(vp);
1079                 return (EOPNOTSUPP);    /* Needs translation */
1080         }
1081         /*
1082          * Only privileged root, or (if MNT_USER is set) the user that
1083          * did the original mount is permitted to update it.
1084          */
1085         error = vfs_suser(mp, td);
1086         if (error != 0) {
1087                 vput(vp);
1088                 return (error);
1089         }
1090         if (vfs_busy(mp, MBF_NOWAIT)) {
1091                 vput(vp);
1092                 return (EBUSY);
1093         }
1094         VI_LOCK(vp);
1095         if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1096                 VI_UNLOCK(vp);
1097                 vfs_unbusy(mp);
1098                 vput(vp);
1099                 return (EBUSY);
1100         }
1101         vp->v_iflag |= VI_MOUNT;
1102         VI_UNLOCK(vp);
1103         VOP_UNLOCK(vp);
1104
1105         vfs_op_enter(mp);
1106         vn_seqc_write_begin(vp);
1107
1108         rootvp = NULL;
1109         MNT_ILOCK(mp);
1110         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1111                 MNT_IUNLOCK(mp);
1112                 error = EBUSY;
1113                 goto end;
1114         }
1115         mp->mnt_flag &= ~MNT_UPDATEMASK;
1116         mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1117             MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1118         if ((mp->mnt_flag & MNT_ASYNC) == 0)
1119                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1120         rootvp = vfs_cache_root_clear(mp);
1121         MNT_IUNLOCK(mp);
1122         mp->mnt_optnew = *optlist;
1123         vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1124
1125         /*
1126          * Mount the filesystem.
1127          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1128          * get.  No freeing of cn_pnbuf.
1129          */
1130         error = VFS_MOUNT(mp);
1131
1132         export_error = 0;
1133         /* Process the export option. */
1134         if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1135             &len) == 0) {
1136                 /* Assume that there is only 1 ABI for each length. */
1137                 switch (len) {
1138                 case (sizeof(struct oexport_args)):
1139                         bzero(&o2export, sizeof(o2export));
1140                         /* FALLTHROUGH */
1141                 case (sizeof(o2export)):
1142                         bcopy(bufp, &o2export, len);
1143                         export.ex_flags = (uint64_t)o2export.ex_flags;
1144                         export.ex_root = o2export.ex_root;
1145                         export.ex_uid = o2export.ex_anon.cr_uid;
1146                         export.ex_groups = NULL;
1147                         export.ex_ngroups = o2export.ex_anon.cr_ngroups;
1148                         if (export.ex_ngroups > 0) {
1149                                 if (export.ex_ngroups <= XU_NGROUPS) {
1150                                         export.ex_groups = malloc(
1151                                             export.ex_ngroups * sizeof(gid_t),
1152                                             M_TEMP, M_WAITOK);
1153                                         for (i = 0; i < export.ex_ngroups; i++)
1154                                                 export.ex_groups[i] =
1155                                                   o2export.ex_anon.cr_groups[i];
1156                                 } else
1157                                         export_error = EINVAL;
1158                         } else if (export.ex_ngroups < 0)
1159                                 export_error = EINVAL;
1160                         export.ex_addr = o2export.ex_addr;
1161                         export.ex_addrlen = o2export.ex_addrlen;
1162                         export.ex_mask = o2export.ex_mask;
1163                         export.ex_masklen = o2export.ex_masklen;
1164                         export.ex_indexfile = o2export.ex_indexfile;
1165                         export.ex_numsecflavors = o2export.ex_numsecflavors;
1166                         if (export.ex_numsecflavors < MAXSECFLAVORS) {
1167                                 for (i = 0; i < export.ex_numsecflavors; i++)
1168                                         export.ex_secflavors[i] =
1169                                             o2export.ex_secflavors[i];
1170                         } else
1171                                 export_error = EINVAL;
1172                         if (export_error == 0)
1173                                 export_error = vfs_export(mp, &export);
1174                         free(export.ex_groups, M_TEMP);
1175                         break;
1176                 case (sizeof(export)):
1177                         bcopy(bufp, &export, len);
1178                         grps = NULL;
1179                         if (export.ex_ngroups > 0) {
1180                                 if (export.ex_ngroups <= NGROUPS_MAX) {
1181                                         grps = malloc(export.ex_ngroups *
1182                                             sizeof(gid_t), M_TEMP, M_WAITOK);
1183                                         export_error = copyin(export.ex_groups,
1184                                             grps, export.ex_ngroups *
1185                                             sizeof(gid_t));
1186                                         if (export_error == 0)
1187                                                 export.ex_groups = grps;
1188                                 } else
1189                                         export_error = EINVAL;
1190                         } else if (export.ex_ngroups == 0)
1191                                 export.ex_groups = NULL;
1192                         else
1193                                 export_error = EINVAL;
1194                         if (export_error == 0)
1195                                 export_error = vfs_export(mp, &export);
1196                         free(grps, M_TEMP);
1197                         break;
1198                 default:
1199                         export_error = EINVAL;
1200                         break;
1201                 }
1202         }
1203
1204         MNT_ILOCK(mp);
1205         if (error == 0) {
1206                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1207                     MNT_SNAPSHOT);
1208         } else {
1209                 /*
1210                  * If we fail, restore old mount flags. MNT_QUOTA is special,
1211                  * because it is not part of MNT_UPDATEMASK, but it could have
1212                  * changed in the meantime if quotactl(2) was called.
1213                  * All in all we want current value of MNT_QUOTA, not the old
1214                  * one.
1215                  */
1216                 mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1217         }
1218         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1219             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1220                 mp->mnt_kern_flag |= MNTK_ASYNC;
1221         else
1222                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1223         MNT_IUNLOCK(mp);
1224
1225         if (error != 0)
1226                 goto end;
1227
1228         dev_vfs_event("REMOUNT", mp, true);
1229         if (mp->mnt_opt != NULL)
1230                 vfs_freeopts(mp->mnt_opt);
1231         mp->mnt_opt = mp->mnt_optnew;
1232         *optlist = NULL;
1233         (void)VFS_STATFS(mp, &mp->mnt_stat);
1234         /*
1235          * Prevent external consumers of mount options from reading
1236          * mnt_optnew.
1237          */
1238         mp->mnt_optnew = NULL;
1239
1240         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1241                 vfs_allocate_syncvnode(mp);
1242         else
1243                 vfs_deallocate_syncvnode(mp);
1244 end:
1245         vfs_op_exit(mp);
1246         if (rootvp != NULL) {
1247                 vn_seqc_write_end(rootvp);
1248                 vrele(rootvp);
1249         }
1250         vn_seqc_write_end(vp);
1251         vfs_unbusy(mp);
1252         VI_LOCK(vp);
1253         vp->v_iflag &= ~VI_MOUNT;
1254         VI_UNLOCK(vp);
1255         vrele(vp);
1256         return (error != 0 ? error : export_error);
1257 }
1258
1259 /*
1260  * vfs_domount(): actually attempt a filesystem mount.
1261  */
1262 static int
1263 vfs_domount(
1264         struct thread *td,              /* Calling thread. */
1265         const char *fstype,             /* Filesystem type. */
1266         char *fspath,                   /* Mount path. */
1267         uint64_t fsflags,               /* Flags common to all filesystems. */
1268         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1269         )
1270 {
1271         struct vfsconf *vfsp;
1272         struct nameidata nd;
1273         struct vnode *vp;
1274         char *pathbuf;
1275         int error;
1276
1277         /*
1278          * Be ultra-paranoid about making sure the type and fspath
1279          * variables will fit in our mp buffers, including the
1280          * terminating NUL.
1281          */
1282         if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1283                 return (ENAMETOOLONG);
1284
1285         if (jailed(td->td_ucred) || usermount == 0) {
1286                 if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1287                         return (error);
1288         }
1289
1290         /*
1291          * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1292          */
1293         if (fsflags & MNT_EXPORTED) {
1294                 error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1295                 if (error)
1296                         return (error);
1297         }
1298         if (fsflags & MNT_SUIDDIR) {
1299                 error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1300                 if (error)
1301                         return (error);
1302         }
1303         /*
1304          * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1305          */
1306         if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1307                 if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1308                         fsflags |= MNT_NOSUID | MNT_USER;
1309         }
1310
1311         /* Load KLDs before we lock the covered vnode to avoid reversals. */
1312         vfsp = NULL;
1313         if ((fsflags & MNT_UPDATE) == 0) {
1314                 /* Don't try to load KLDs if we're mounting the root. */
1315                 if (fsflags & MNT_ROOTFS)
1316                         vfsp = vfs_byname(fstype);
1317                 else
1318                         vfsp = vfs_byname_kld(fstype, td, &error);
1319                 if (vfsp == NULL)
1320                         return (ENODEV);
1321         }
1322
1323         /*
1324          * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1325          */
1326         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1327             UIO_SYSSPACE, fspath, td);
1328         error = namei(&nd);
1329         if (error != 0)
1330                 return (error);
1331         NDFREE(&nd, NDF_ONLY_PNBUF);
1332         vp = nd.ni_vp;
1333         if ((fsflags & MNT_UPDATE) == 0) {
1334                 if ((vp->v_vflag & VV_ROOT) != 0 &&
1335                     (fsflags & MNT_NOCOVER) != 0) {
1336                         vput(vp);
1337                         return (EBUSY);
1338                 }
1339                 pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1340                 strcpy(pathbuf, fspath);
1341                 error = vn_path_to_global_path(td, vp, pathbuf, MNAMELEN);
1342                 if (error == 0) {
1343                         error = vfs_domount_first(td, vfsp, pathbuf, vp,
1344                             fsflags, optlist);
1345                 }
1346                 free(pathbuf, M_TEMP);
1347         } else
1348                 error = vfs_domount_update(td, vp, fsflags, optlist);
1349
1350         return (error);
1351 }
1352
1353 /*
1354  * Unmount a filesystem.
1355  *
1356  * Note: unmount takes a path to the vnode mounted on as argument, not
1357  * special file (as before).
1358  */
1359 #ifndef _SYS_SYSPROTO_H_
1360 struct unmount_args {
1361         char    *path;
1362         int     flags;
1363 };
1364 #endif
1365 /* ARGSUSED */
1366 int
1367 sys_unmount(struct thread *td, struct unmount_args *uap)
1368 {
1369
1370         return (kern_unmount(td, uap->path, uap->flags));
1371 }
1372
1373 int
1374 kern_unmount(struct thread *td, const char *path, int flags)
1375 {
1376         struct nameidata nd;
1377         struct mount *mp;
1378         char *pathbuf;
1379         int error, id0, id1;
1380
1381         AUDIT_ARG_VALUE(flags);
1382         if (jailed(td->td_ucred) || usermount == 0) {
1383                 error = priv_check(td, PRIV_VFS_UNMOUNT);
1384                 if (error)
1385                         return (error);
1386         }
1387
1388         pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1389         error = copyinstr(path, pathbuf, MNAMELEN, NULL);
1390         if (error) {
1391                 free(pathbuf, M_TEMP);
1392                 return (error);
1393         }
1394         if (flags & MNT_BYFSID) {
1395                 AUDIT_ARG_TEXT(pathbuf);
1396                 /* Decode the filesystem ID. */
1397                 if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
1398                         free(pathbuf, M_TEMP);
1399                         return (EINVAL);
1400                 }
1401
1402                 mtx_lock(&mountlist_mtx);
1403                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1404                         if (mp->mnt_stat.f_fsid.val[0] == id0 &&
1405                             mp->mnt_stat.f_fsid.val[1] == id1) {
1406                                 vfs_ref(mp);
1407                                 break;
1408                         }
1409                 }
1410                 mtx_unlock(&mountlist_mtx);
1411         } else {
1412                 /*
1413                  * Try to find global path for path argument.
1414                  */
1415                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1416                     UIO_SYSSPACE, pathbuf, td);
1417                 if (namei(&nd) == 0) {
1418                         NDFREE(&nd, NDF_ONLY_PNBUF);
1419                         error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1420                             MNAMELEN);
1421                         if (error == 0)
1422                                 vput(nd.ni_vp);
1423                 }
1424                 mtx_lock(&mountlist_mtx);
1425                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1426                         if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1427                                 vfs_ref(mp);
1428                                 break;
1429                         }
1430                 }
1431                 mtx_unlock(&mountlist_mtx);
1432         }
1433         free(pathbuf, M_TEMP);
1434         if (mp == NULL) {
1435                 /*
1436                  * Previously we returned ENOENT for a nonexistent path and
1437                  * EINVAL for a non-mountpoint.  We cannot tell these apart
1438                  * now, so in the !MNT_BYFSID case return the more likely
1439                  * EINVAL for compatibility.
1440                  */
1441                 return ((flags & MNT_BYFSID) ? ENOENT : EINVAL);
1442         }
1443
1444         /*
1445          * Don't allow unmounting the root filesystem.
1446          */
1447         if (mp->mnt_flag & MNT_ROOTFS) {
1448                 vfs_rel(mp);
1449                 return (EINVAL);
1450         }
1451         error = dounmount(mp, flags, td);
1452         return (error);
1453 }
1454
1455 /*
1456  * Return error if any of the vnodes, ignoring the root vnode
1457  * and the syncer vnode, have non-zero usecount.
1458  *
1459  * This function is purely advisory - it can return false positives
1460  * and negatives.
1461  */
1462 static int
1463 vfs_check_usecounts(struct mount *mp)
1464 {
1465         struct vnode *vp, *mvp;
1466
1467         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1468                 if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1469                     vp->v_usecount != 0) {
1470                         VI_UNLOCK(vp);
1471                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1472                         return (EBUSY);
1473                 }
1474                 VI_UNLOCK(vp);
1475         }
1476
1477         return (0);
1478 }
1479
1480 static void
1481 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1482 {
1483
1484         mtx_assert(MNT_MTX(mp), MA_OWNED);
1485         mp->mnt_kern_flag &= ~mntkflags;
1486         if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1487                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
1488                 wakeup(mp);
1489         }
1490         vfs_op_exit_locked(mp);
1491         MNT_IUNLOCK(mp);
1492         if (coveredvp != NULL) {
1493                 VOP_UNLOCK(coveredvp);
1494                 vdrop(coveredvp);
1495         }
1496         vn_finished_write(mp);
1497 }
1498
1499 /*
1500  * There are various reference counters associated with the mount point.
1501  * Normally it is permitted to modify them without taking the mnt ilock,
1502  * but this behavior can be temporarily disabled if stable value is needed
1503  * or callers are expected to block (e.g. to not allow new users during
1504  * forced unmount).
1505  */
1506 void
1507 vfs_op_enter(struct mount *mp)
1508 {
1509         int cpu;
1510
1511         MNT_ILOCK(mp);
1512         mp->mnt_vfs_ops++;
1513         if (mp->mnt_vfs_ops > 1) {
1514                 MNT_IUNLOCK(mp);
1515                 return;
1516         }
1517         vfs_op_barrier_wait(mp);
1518         CPU_FOREACH(cpu) {
1519                 mp->mnt_ref +=
1520                     zpcpu_replace_cpu(mp->mnt_ref_pcpu, 0, cpu);
1521                 mp->mnt_lockref +=
1522                     zpcpu_replace_cpu(mp->mnt_lockref_pcpu, 0, cpu);
1523                 mp->mnt_writeopcount +=
1524                     zpcpu_replace_cpu(mp->mnt_writeopcount_pcpu, 0, cpu);
1525         }
1526         if (mp->mnt_ref <= 0 || mp->mnt_lockref < 0 || mp->mnt_writeopcount < 0)
1527                 panic("%s: invalid count(s) on mp %p: ref %d lockref %d writeopcount %d\n",
1528                     __func__, mp, mp->mnt_ref, mp->mnt_lockref, mp->mnt_writeopcount);
1529         MNT_IUNLOCK(mp);
1530         vfs_assert_mount_counters(mp);
1531 }
1532
1533 void
1534 vfs_op_exit_locked(struct mount *mp)
1535 {
1536
1537         mtx_assert(MNT_MTX(mp), MA_OWNED);
1538
1539         if (mp->mnt_vfs_ops <= 0)
1540                 panic("%s: invalid vfs_ops count %d for mp %p\n",
1541                     __func__, mp->mnt_vfs_ops, mp);
1542         mp->mnt_vfs_ops--;
1543 }
1544
1545 void
1546 vfs_op_exit(struct mount *mp)
1547 {
1548
1549         MNT_ILOCK(mp);
1550         vfs_op_exit_locked(mp);
1551         MNT_IUNLOCK(mp);
1552 }
1553
1554 struct vfs_op_barrier_ipi {
1555         struct mount *mp;
1556         struct smp_rendezvous_cpus_retry_arg srcra;
1557 };
1558
1559 static void
1560 vfs_op_action_func(void *arg)
1561 {
1562         struct vfs_op_barrier_ipi *vfsopipi;
1563         struct mount *mp;
1564
1565         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1566         mp = vfsopipi->mp;
1567
1568         if (!vfs_op_thread_entered(mp))
1569                 smp_rendezvous_cpus_done(arg);
1570 }
1571
1572 static void
1573 vfs_op_wait_func(void *arg, int cpu)
1574 {
1575         struct vfs_op_barrier_ipi *vfsopipi;
1576         struct mount *mp;
1577         int *in_op;
1578
1579         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1580         mp = vfsopipi->mp;
1581
1582         in_op = zpcpu_get_cpu(mp->mnt_thread_in_ops_pcpu, cpu);
1583         while (atomic_load_int(in_op))
1584                 cpu_spinwait();
1585 }
1586
1587 void
1588 vfs_op_barrier_wait(struct mount *mp)
1589 {
1590         struct vfs_op_barrier_ipi vfsopipi;
1591
1592         vfsopipi.mp = mp;
1593
1594         smp_rendezvous_cpus_retry(all_cpus,
1595             smp_no_rendezvous_barrier,
1596             vfs_op_action_func,
1597             smp_no_rendezvous_barrier,
1598             vfs_op_wait_func,
1599             &vfsopipi.srcra);
1600 }
1601
1602 #ifdef DIAGNOSTIC
1603 void
1604 vfs_assert_mount_counters(struct mount *mp)
1605 {
1606         int cpu;
1607
1608         if (mp->mnt_vfs_ops == 0)
1609                 return;
1610
1611         CPU_FOREACH(cpu) {
1612                 if (*zpcpu_get_cpu(mp->mnt_ref_pcpu, cpu) != 0 ||
1613                     *zpcpu_get_cpu(mp->mnt_lockref_pcpu, cpu) != 0 ||
1614                     *zpcpu_get_cpu(mp->mnt_writeopcount_pcpu, cpu) != 0)
1615                         vfs_dump_mount_counters(mp);
1616         }
1617 }
1618
1619 void
1620 vfs_dump_mount_counters(struct mount *mp)
1621 {
1622         int cpu, *count;
1623         int ref, lockref, writeopcount;
1624
1625         printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1626
1627         printf("        ref : ");
1628         ref = mp->mnt_ref;
1629         CPU_FOREACH(cpu) {
1630                 count = zpcpu_get_cpu(mp->mnt_ref_pcpu, cpu);
1631                 printf("%d ", *count);
1632                 ref += *count;
1633         }
1634         printf("\n");
1635         printf("    lockref : ");
1636         lockref = mp->mnt_lockref;
1637         CPU_FOREACH(cpu) {
1638                 count = zpcpu_get_cpu(mp->mnt_lockref_pcpu, cpu);
1639                 printf("%d ", *count);
1640                 lockref += *count;
1641         }
1642         printf("\n");
1643         printf("writeopcount: ");
1644         writeopcount = mp->mnt_writeopcount;
1645         CPU_FOREACH(cpu) {
1646                 count = zpcpu_get_cpu(mp->mnt_writeopcount_pcpu, cpu);
1647                 printf("%d ", *count);
1648                 writeopcount += *count;
1649         }
1650         printf("\n");
1651
1652         printf("counter       struct total\n");
1653         printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1654         printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1655         printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1656
1657         panic("invalid counts on struct mount");
1658 }
1659 #endif
1660
1661 int
1662 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1663 {
1664         int *base, *pcpu;
1665         int cpu, sum;
1666
1667         switch (which) {
1668         case MNT_COUNT_REF:
1669                 base = &mp->mnt_ref;
1670                 pcpu = mp->mnt_ref_pcpu;
1671                 break;
1672         case MNT_COUNT_LOCKREF:
1673                 base = &mp->mnt_lockref;
1674                 pcpu = mp->mnt_lockref_pcpu;
1675                 break;
1676         case MNT_COUNT_WRITEOPCOUNT:
1677                 base = &mp->mnt_writeopcount;
1678                 pcpu = mp->mnt_writeopcount_pcpu;
1679                 break;
1680         }
1681
1682         sum = *base;
1683         CPU_FOREACH(cpu) {
1684                 sum += *zpcpu_get_cpu(pcpu, cpu);
1685         }
1686         return (sum);
1687 }
1688
1689 /*
1690  * Do the actual filesystem unmount.
1691  */
1692 int
1693 dounmount(struct mount *mp, int flags, struct thread *td)
1694 {
1695         struct vnode *coveredvp, *rootvp;
1696         int error;
1697         uint64_t async_flag;
1698         int mnt_gen_r;
1699
1700         if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
1701                 mnt_gen_r = mp->mnt_gen;
1702                 VI_LOCK(coveredvp);
1703                 vholdl(coveredvp);
1704                 vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
1705                 /*
1706                  * Check for mp being unmounted while waiting for the
1707                  * covered vnode lock.
1708                  */
1709                 if (coveredvp->v_mountedhere != mp ||
1710                     coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
1711                         VOP_UNLOCK(coveredvp);
1712                         vdrop(coveredvp);
1713                         vfs_rel(mp);
1714                         return (EBUSY);
1715                 }
1716         }
1717
1718         /*
1719          * Only privileged root, or (if MNT_USER is set) the user that did the
1720          * original mount is permitted to unmount this filesystem.
1721          */
1722         error = vfs_suser(mp, td);
1723         if (error != 0) {
1724                 if (coveredvp != NULL) {
1725                         VOP_UNLOCK(coveredvp);
1726                         vdrop(coveredvp);
1727                 }
1728                 vfs_rel(mp);
1729                 return (error);
1730         }
1731
1732         vfs_op_enter(mp);
1733
1734         vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
1735         MNT_ILOCK(mp);
1736         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
1737             (mp->mnt_flag & MNT_UPDATE) != 0 ||
1738             !TAILQ_EMPTY(&mp->mnt_uppers)) {
1739                 dounmount_cleanup(mp, coveredvp, 0);
1740                 return (EBUSY);
1741         }
1742         mp->mnt_kern_flag |= MNTK_UNMOUNT;
1743         rootvp = vfs_cache_root_clear(mp);
1744         if (coveredvp != NULL)
1745                 vn_seqc_write_begin(coveredvp);
1746         if (flags & MNT_NONBUSY) {
1747                 MNT_IUNLOCK(mp);
1748                 error = vfs_check_usecounts(mp);
1749                 MNT_ILOCK(mp);
1750                 if (error != 0) {
1751                         vn_seqc_write_end(coveredvp);
1752                         dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
1753                         if (rootvp != NULL) {
1754                                 vn_seqc_write_end(rootvp);
1755                                 vrele(rootvp);
1756                         }
1757                         return (error);
1758                 }
1759         }
1760         /* Allow filesystems to detect that a forced unmount is in progress. */
1761         if (flags & MNT_FORCE) {
1762                 mp->mnt_kern_flag |= MNTK_UNMOUNTF;
1763                 MNT_IUNLOCK(mp);
1764                 /*
1765                  * Must be done after setting MNTK_UNMOUNTF and before
1766                  * waiting for mnt_lockref to become 0.
1767                  */
1768                 VFS_PURGE(mp);
1769                 MNT_ILOCK(mp);
1770         }
1771         error = 0;
1772         if (mp->mnt_lockref) {
1773                 mp->mnt_kern_flag |= MNTK_DRAINING;
1774                 error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
1775                     "mount drain", 0);
1776         }
1777         MNT_IUNLOCK(mp);
1778         KASSERT(mp->mnt_lockref == 0,
1779             ("%s: invalid lock refcount in the drain path @ %s:%d",
1780             __func__, __FILE__, __LINE__));
1781         KASSERT(error == 0,
1782             ("%s: invalid return value for msleep in the drain path @ %s:%d",
1783             __func__, __FILE__, __LINE__));
1784
1785         /*
1786          * We want to keep the vnode around so that we can vn_seqc_write_end
1787          * after we are done with unmount. Downgrade our reference to a mere
1788          * hold count so that we don't interefere with anything.
1789          */
1790         if (rootvp != NULL) {
1791                 vhold(rootvp);
1792                 vrele(rootvp);
1793         }
1794
1795         if (mp->mnt_flag & MNT_EXPUBLIC)
1796                 vfs_setpublicfs(NULL, NULL, NULL);
1797
1798         vfs_periodic(mp, MNT_WAIT);
1799         MNT_ILOCK(mp);
1800         async_flag = mp->mnt_flag & MNT_ASYNC;
1801         mp->mnt_flag &= ~MNT_ASYNC;
1802         mp->mnt_kern_flag &= ~MNTK_ASYNC;
1803         MNT_IUNLOCK(mp);
1804         cache_purgevfs(mp, false); /* remove cache entries for this file sys */
1805         vfs_deallocate_syncvnode(mp);
1806         error = VFS_UNMOUNT(mp, flags);
1807         vn_finished_write(mp);
1808         /*
1809          * If we failed to flush the dirty blocks for this mount point,
1810          * undo all the cdir/rdir and rootvnode changes we made above.
1811          * Unless we failed to do so because the device is reporting that
1812          * it doesn't exist anymore.
1813          */
1814         if (error && error != ENXIO) {
1815                 MNT_ILOCK(mp);
1816                 if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1817                         MNT_IUNLOCK(mp);
1818                         vfs_allocate_syncvnode(mp);
1819                         MNT_ILOCK(mp);
1820                 }
1821                 mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
1822                 mp->mnt_flag |= async_flag;
1823                 if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1824                     (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1825                         mp->mnt_kern_flag |= MNTK_ASYNC;
1826                 if (mp->mnt_kern_flag & MNTK_MWAIT) {
1827                         mp->mnt_kern_flag &= ~MNTK_MWAIT;
1828                         wakeup(mp);
1829                 }
1830                 vfs_op_exit_locked(mp);
1831                 MNT_IUNLOCK(mp);
1832                 if (coveredvp) {
1833                         vn_seqc_write_end(coveredvp);
1834                         VOP_UNLOCK(coveredvp);
1835                         vdrop(coveredvp);
1836                 }
1837                 if (rootvp != NULL) {
1838                         vn_seqc_write_end(rootvp);
1839                         vdrop(rootvp);
1840                 }
1841                 return (error);
1842         }
1843         mtx_lock(&mountlist_mtx);
1844         TAILQ_REMOVE(&mountlist, mp, mnt_list);
1845         mtx_unlock(&mountlist_mtx);
1846         EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
1847         dev_vfs_event("UNMOUNT", mp, false);
1848         if (coveredvp != NULL) {
1849                 coveredvp->v_mountedhere = NULL;
1850                 vn_seqc_write_end(coveredvp);
1851                 VOP_UNLOCK(coveredvp);
1852                 vdrop(coveredvp);
1853         }
1854         if (rootvp != NULL) {
1855                 vn_seqc_write_end(rootvp);
1856                 vdrop(rootvp);
1857         }
1858         vfs_event_signal(NULL, VQ_UNMOUNT, 0);
1859         if (rootvnode != NULL && mp == rootvnode->v_mount) {
1860                 vrele(rootvnode);
1861                 rootvnode = NULL;
1862         }
1863         if (mp == rootdevmp)
1864                 rootdevmp = NULL;
1865         vfs_mount_destroy(mp);
1866         return (0);
1867 }
1868
1869 /*
1870  * Report errors during filesystem mounting.
1871  */
1872 void
1873 vfs_mount_error(struct mount *mp, const char *fmt, ...)
1874 {
1875         struct vfsoptlist *moptlist = mp->mnt_optnew;
1876         va_list ap;
1877         int error, len;
1878         char *errmsg;
1879
1880         error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
1881         if (error || errmsg == NULL || len <= 0)
1882                 return;
1883
1884         va_start(ap, fmt);
1885         vsnprintf(errmsg, (size_t)len, fmt, ap);
1886         va_end(ap);
1887 }
1888
1889 void
1890 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
1891 {
1892         va_list ap;
1893         int error, len;
1894         char *errmsg;
1895
1896         error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
1897         if (error || errmsg == NULL || len <= 0)
1898                 return;
1899
1900         va_start(ap, fmt);
1901         vsnprintf(errmsg, (size_t)len, fmt, ap);
1902         va_end(ap);
1903 }
1904
1905 /*
1906  * ---------------------------------------------------------------------
1907  * Functions for querying mount options/arguments from filesystems.
1908  */
1909
1910 /*
1911  * Check that no unknown options are given
1912  */
1913 int
1914 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1915 {
1916         struct vfsopt *opt;
1917         char errmsg[255];
1918         const char **t, *p, *q;
1919         int ret = 0;
1920
1921         TAILQ_FOREACH(opt, opts, link) {
1922                 p = opt->name;
1923                 q = NULL;
1924                 if (p[0] == 'n' && p[1] == 'o')
1925                         q = p + 2;
1926                 for(t = global_opts; *t != NULL; t++) {
1927                         if (strcmp(*t, p) == 0)
1928                                 break;
1929                         if (q != NULL) {
1930                                 if (strcmp(*t, q) == 0)
1931                                         break;
1932                         }
1933                 }
1934                 if (*t != NULL)
1935                         continue;
1936                 for(t = legal; *t != NULL; t++) {
1937                         if (strcmp(*t, p) == 0)
1938                                 break;
1939                         if (q != NULL) {
1940                                 if (strcmp(*t, q) == 0)
1941                                         break;
1942                         }
1943                 }
1944                 if (*t != NULL)
1945                         continue;
1946                 snprintf(errmsg, sizeof(errmsg),
1947                     "mount option <%s> is unknown", p);
1948                 ret = EINVAL;
1949         }
1950         if (ret != 0) {
1951                 TAILQ_FOREACH(opt, opts, link) {
1952                         if (strcmp(opt->name, "errmsg") == 0) {
1953                                 strncpy((char *)opt->value, errmsg, opt->len);
1954                                 break;
1955                         }
1956                 }
1957                 if (opt == NULL)
1958                         printf("%s\n", errmsg);
1959         }
1960         return (ret);
1961 }
1962
1963 /*
1964  * Get a mount option by its name.
1965  *
1966  * Return 0 if the option was found, ENOENT otherwise.
1967  * If len is non-NULL it will be filled with the length
1968  * of the option. If buf is non-NULL, it will be filled
1969  * with the address of the option.
1970  */
1971 int
1972 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
1973 {
1974         struct vfsopt *opt;
1975
1976         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1977
1978         TAILQ_FOREACH(opt, opts, link) {
1979                 if (strcmp(name, opt->name) == 0) {
1980                         opt->seen = 1;
1981                         if (len != NULL)
1982                                 *len = opt->len;
1983                         if (buf != NULL)
1984                                 *buf = opt->value;
1985                         return (0);
1986                 }
1987         }
1988         return (ENOENT);
1989 }
1990
1991 int
1992 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
1993 {
1994         struct vfsopt *opt;
1995
1996         if (opts == NULL)
1997                 return (-1);
1998
1999         TAILQ_FOREACH(opt, opts, link) {
2000                 if (strcmp(name, opt->name) == 0) {
2001                         opt->seen = 1;
2002                         return (opt->pos);
2003                 }
2004         }
2005         return (-1);
2006 }
2007
2008 int
2009 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
2010 {
2011         char *opt_value, *vtp;
2012         quad_t iv;
2013         int error, opt_len;
2014
2015         error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
2016         if (error != 0)
2017                 return (error);
2018         if (opt_len == 0 || opt_value == NULL)
2019                 return (EINVAL);
2020         if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
2021                 return (EINVAL);
2022         iv = strtoq(opt_value, &vtp, 0);
2023         if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
2024                 return (EINVAL);
2025         if (iv < 0)
2026                 return (EINVAL);
2027         switch (vtp[0]) {
2028         case 't': case 'T':
2029                 iv *= 1024;
2030                 /* FALLTHROUGH */
2031         case 'g': case 'G':
2032                 iv *= 1024;
2033                 /* FALLTHROUGH */
2034         case 'm': case 'M':
2035                 iv *= 1024;
2036                 /* FALLTHROUGH */
2037         case 'k': case 'K':
2038                 iv *= 1024;
2039         case '\0':
2040                 break;
2041         default:
2042                 return (EINVAL);
2043         }
2044         *value = iv;
2045
2046         return (0);
2047 }
2048
2049 char *
2050 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
2051 {
2052         struct vfsopt *opt;
2053
2054         *error = 0;
2055         TAILQ_FOREACH(opt, opts, link) {
2056                 if (strcmp(name, opt->name) != 0)
2057                         continue;
2058                 opt->seen = 1;
2059                 if (opt->len == 0 ||
2060                     ((char *)opt->value)[opt->len - 1] != '\0') {
2061                         *error = EINVAL;
2062                         return (NULL);
2063                 }
2064                 return (opt->value);
2065         }
2066         *error = ENOENT;
2067         return (NULL);
2068 }
2069
2070 int
2071 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
2072         uint64_t val)
2073 {
2074         struct vfsopt *opt;
2075
2076         TAILQ_FOREACH(opt, opts, link) {
2077                 if (strcmp(name, opt->name) == 0) {
2078                         opt->seen = 1;
2079                         if (w != NULL)
2080                                 *w |= val;
2081                         return (1);
2082                 }
2083         }
2084         if (w != NULL)
2085                 *w &= ~val;
2086         return (0);
2087 }
2088
2089 int
2090 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
2091 {
2092         va_list ap;
2093         struct vfsopt *opt;
2094         int ret;
2095
2096         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2097
2098         TAILQ_FOREACH(opt, opts, link) {
2099                 if (strcmp(name, opt->name) != 0)
2100                         continue;
2101                 opt->seen = 1;
2102                 if (opt->len == 0 || opt->value == NULL)
2103                         return (0);
2104                 if (((char *)opt->value)[opt->len - 1] != '\0')
2105                         return (0);
2106                 va_start(ap, fmt);
2107                 ret = vsscanf(opt->value, fmt, ap);
2108                 va_end(ap);
2109                 return (ret);
2110         }
2111         return (0);
2112 }
2113
2114 int
2115 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
2116 {
2117         struct vfsopt *opt;
2118
2119         TAILQ_FOREACH(opt, opts, link) {
2120                 if (strcmp(name, opt->name) != 0)
2121                         continue;
2122                 opt->seen = 1;
2123                 if (opt->value == NULL)
2124                         opt->len = len;
2125                 else {
2126                         if (opt->len != len)
2127                                 return (EINVAL);
2128                         bcopy(value, opt->value, len);
2129                 }
2130                 return (0);
2131         }
2132         return (ENOENT);
2133 }
2134
2135 int
2136 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2137 {
2138         struct vfsopt *opt;
2139
2140         TAILQ_FOREACH(opt, opts, link) {
2141                 if (strcmp(name, opt->name) != 0)
2142                         continue;
2143                 opt->seen = 1;
2144                 if (opt->value == NULL)
2145                         opt->len = len;
2146                 else {
2147                         if (opt->len < len)
2148                                 return (EINVAL);
2149                         opt->len = len;
2150                         bcopy(value, opt->value, len);
2151                 }
2152                 return (0);
2153         }
2154         return (ENOENT);
2155 }
2156
2157 int
2158 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2159 {
2160         struct vfsopt *opt;
2161
2162         TAILQ_FOREACH(opt, opts, link) {
2163                 if (strcmp(name, opt->name) != 0)
2164                         continue;
2165                 opt->seen = 1;
2166                 if (opt->value == NULL)
2167                         opt->len = strlen(value) + 1;
2168                 else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2169                         return (EINVAL);
2170                 return (0);
2171         }
2172         return (ENOENT);
2173 }
2174
2175 /*
2176  * Find and copy a mount option.
2177  *
2178  * The size of the buffer has to be specified
2179  * in len, if it is not the same length as the
2180  * mount option, EINVAL is returned.
2181  * Returns ENOENT if the option is not found.
2182  */
2183 int
2184 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2185 {
2186         struct vfsopt *opt;
2187
2188         KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2189
2190         TAILQ_FOREACH(opt, opts, link) {
2191                 if (strcmp(name, opt->name) == 0) {
2192                         opt->seen = 1;
2193                         if (len != opt->len)
2194                                 return (EINVAL);
2195                         bcopy(opt->value, dest, opt->len);
2196                         return (0);
2197                 }
2198         }
2199         return (ENOENT);
2200 }
2201
2202 int
2203 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2204 {
2205
2206         /*
2207          * Filesystems only fill in part of the structure for updates, we
2208          * have to read the entirety first to get all content.
2209          */
2210         if (sbp != &mp->mnt_stat)
2211                 memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2212
2213         /*
2214          * Set these in case the underlying filesystem fails to do so.
2215          */
2216         sbp->f_version = STATFS_VERSION;
2217         sbp->f_namemax = NAME_MAX;
2218         sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2219
2220         return (mp->mnt_op->vfs_statfs(mp, sbp));
2221 }
2222
2223 void
2224 vfs_mountedfrom(struct mount *mp, const char *from)
2225 {
2226
2227         bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2228         strlcpy(mp->mnt_stat.f_mntfromname, from,
2229             sizeof mp->mnt_stat.f_mntfromname);
2230 }
2231
2232 /*
2233  * ---------------------------------------------------------------------
2234  * This is the api for building mount args and mounting filesystems from
2235  * inside the kernel.
2236  *
2237  * The API works by accumulation of individual args.  First error is
2238  * latched.
2239  *
2240  * XXX: should be documented in new manpage kernel_mount(9)
2241  */
2242
2243 /* A memory allocation which must be freed when we are done */
2244 struct mntaarg {
2245         SLIST_ENTRY(mntaarg)    next;
2246 };
2247
2248 /* The header for the mount arguments */
2249 struct mntarg {
2250         struct iovec *v;
2251         int len;
2252         int error;
2253         SLIST_HEAD(, mntaarg)   list;
2254 };
2255
2256 /*
2257  * Add a boolean argument.
2258  *
2259  * flag is the boolean value.
2260  * name must start with "no".
2261  */
2262 struct mntarg *
2263 mount_argb(struct mntarg *ma, int flag, const char *name)
2264 {
2265
2266         KASSERT(name[0] == 'n' && name[1] == 'o',
2267             ("mount_argb(...,%s): name must start with 'no'", name));
2268
2269         return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2270 }
2271
2272 /*
2273  * Add an argument printf style
2274  */
2275 struct mntarg *
2276 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2277 {
2278         va_list ap;
2279         struct mntaarg *maa;
2280         struct sbuf *sb;
2281         int len;
2282
2283         if (ma == NULL) {
2284                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2285                 SLIST_INIT(&ma->list);
2286         }
2287         if (ma->error)
2288                 return (ma);
2289
2290         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2291             M_MOUNT, M_WAITOK);
2292         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2293         ma->v[ma->len].iov_len = strlen(name) + 1;
2294         ma->len++;
2295
2296         sb = sbuf_new_auto();
2297         va_start(ap, fmt);
2298         sbuf_vprintf(sb, fmt, ap);
2299         va_end(ap);
2300         sbuf_finish(sb);
2301         len = sbuf_len(sb) + 1;
2302         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2303         SLIST_INSERT_HEAD(&ma->list, maa, next);
2304         bcopy(sbuf_data(sb), maa + 1, len);
2305         sbuf_delete(sb);
2306
2307         ma->v[ma->len].iov_base = maa + 1;
2308         ma->v[ma->len].iov_len = len;
2309         ma->len++;
2310
2311         return (ma);
2312 }
2313
2314 /*
2315  * Add an argument which is a userland string.
2316  */
2317 struct mntarg *
2318 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2319 {
2320         struct mntaarg *maa;
2321         char *tbuf;
2322
2323         if (val == NULL)
2324                 return (ma);
2325         if (ma == NULL) {
2326                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2327                 SLIST_INIT(&ma->list);
2328         }
2329         if (ma->error)
2330                 return (ma);
2331         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2332         SLIST_INSERT_HEAD(&ma->list, maa, next);
2333         tbuf = (void *)(maa + 1);
2334         ma->error = copyinstr(val, tbuf, len, NULL);
2335         return (mount_arg(ma, name, tbuf, -1));
2336 }
2337
2338 /*
2339  * Plain argument.
2340  *
2341  * If length is -1, treat value as a C string.
2342  */
2343 struct mntarg *
2344 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2345 {
2346
2347         if (ma == NULL) {
2348                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2349                 SLIST_INIT(&ma->list);
2350         }
2351         if (ma->error)
2352                 return (ma);
2353
2354         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2355             M_MOUNT, M_WAITOK);
2356         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2357         ma->v[ma->len].iov_len = strlen(name) + 1;
2358         ma->len++;
2359
2360         ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2361         if (len < 0)
2362                 ma->v[ma->len].iov_len = strlen(val) + 1;
2363         else
2364                 ma->v[ma->len].iov_len = len;
2365         ma->len++;
2366         return (ma);
2367 }
2368
2369 /*
2370  * Free a mntarg structure
2371  */
2372 static void
2373 free_mntarg(struct mntarg *ma)
2374 {
2375         struct mntaarg *maa;
2376
2377         while (!SLIST_EMPTY(&ma->list)) {
2378                 maa = SLIST_FIRST(&ma->list);
2379                 SLIST_REMOVE_HEAD(&ma->list, next);
2380                 free(maa, M_MOUNT);
2381         }
2382         free(ma->v, M_MOUNT);
2383         free(ma, M_MOUNT);
2384 }
2385
2386 /*
2387  * Mount a filesystem
2388  */
2389 int
2390 kernel_mount(struct mntarg *ma, uint64_t flags)
2391 {
2392         struct uio auio;
2393         int error;
2394
2395         KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2396         KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
2397         KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2398
2399         auio.uio_iov = ma->v;
2400         auio.uio_iovcnt = ma->len;
2401         auio.uio_segflg = UIO_SYSSPACE;
2402
2403         error = ma->error;
2404         if (!error)
2405                 error = vfs_donmount(curthread, flags, &auio);
2406         free_mntarg(ma);
2407         return (error);
2408 }
2409
2410 /*
2411  * A printflike function to mount a filesystem.
2412  */
2413 int
2414 kernel_vmount(int flags, ...)
2415 {
2416         struct mntarg *ma = NULL;
2417         va_list ap;
2418         const char *cp;
2419         const void *vp;
2420         int error;
2421
2422         va_start(ap, flags);
2423         for (;;) {
2424                 cp = va_arg(ap, const char *);
2425                 if (cp == NULL)
2426                         break;
2427                 vp = va_arg(ap, const void *);
2428                 ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2429         }
2430         va_end(ap);
2431
2432         error = kernel_mount(ma, flags);
2433         return (error);
2434 }
2435
2436 /* Map from mount options to printable formats. */
2437 static struct mntoptnames optnames[] = {
2438         MNTOPT_NAMES
2439 };
2440
2441 static void
2442 dev_vfs_event_mntopt(struct sbuf *sb, const char *what, struct vfsoptlist *opts)
2443 {
2444         struct vfsopt *opt;
2445
2446         if (opts == NULL || TAILQ_EMPTY(opts))
2447                 return;
2448         sbuf_printf(sb, " %s=\"", what);
2449         TAILQ_FOREACH(opt, opts, link) {
2450                 if (opt->name[0] == '\0' || (opt->len > 0 && *(char *)opt->value == '\0'))
2451                         continue;
2452                 devctl_safe_quote_sb(sb, opt->name);
2453                 if (opt->len > 0) {
2454                         sbuf_putc(sb, '=');
2455                         devctl_safe_quote_sb(sb, opt->value);
2456                 }
2457                 sbuf_putc(sb, ';');
2458         }
2459         sbuf_putc(sb, '"');
2460 }
2461
2462 #define DEVCTL_LEN 1024
2463 static void
2464 dev_vfs_event(const char *type, struct mount *mp, bool donew)
2465 {
2466         const uint8_t *cp;
2467         struct mntoptnames *fp;
2468         struct sbuf sb;
2469         struct statfs *sfp = &mp->mnt_stat;
2470         char *buf;
2471
2472         buf = malloc(DEVCTL_LEN, M_MOUNT, M_WAITOK);
2473         if (buf == NULL)
2474                 return;
2475         sbuf_new(&sb, buf, DEVCTL_LEN, SBUF_FIXEDLEN);
2476         sbuf_cpy(&sb, "mount-point=\"");
2477         devctl_safe_quote_sb(&sb, sfp->f_mntonname);
2478         sbuf_cat(&sb, "\" mount-dev=\"");
2479         devctl_safe_quote_sb(&sb, sfp->f_mntfromname);
2480         sbuf_cat(&sb, "\" mount-type=\"");
2481         devctl_safe_quote_sb(&sb, sfp->f_fstypename);
2482         sbuf_cat(&sb, "\" fsid=0x");
2483         cp = (const uint8_t *)&sfp->f_fsid.val[0];
2484         for (int i = 0; i < sizeof(sfp->f_fsid); i++)
2485                 sbuf_printf(&sb, "%02x", cp[i]);
2486         sbuf_printf(&sb, " owner=%u flags=\"", sfp->f_owner);
2487         for (fp = optnames; fp->o_opt != 0; fp++) {
2488                 if ((mp->mnt_flag & fp->o_opt) != 0) {
2489                         sbuf_cat(&sb, fp->o_name);
2490                         sbuf_putc(&sb, ';');
2491                 }
2492         }
2493         sbuf_putc(&sb, '"');
2494         dev_vfs_event_mntopt(&sb, "opt", mp->mnt_opt);
2495         if (donew)
2496                 dev_vfs_event_mntopt(&sb, "optnew", mp->mnt_optnew);
2497         sbuf_finish(&sb);
2498
2499         devctl_notify("VFS", "FS", type, sbuf_data(&sb));
2500         sbuf_delete(&sb);
2501         free(buf, M_MOUNT);
2502 }