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