]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_mount.c
vfs_mount.c: fix vfs_domount() for PRIV_VFS_MOUNT_EXPORTED
[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         crfree(mp->mnt_cred);
622         uma_zfree(mount_zone, mp);
623 }
624
625 static bool
626 vfs_should_downgrade_to_ro_mount(uint64_t fsflags, int error)
627 {
628         /* This is an upgrade of an exisiting mount. */
629         if ((fsflags & MNT_UPDATE) != 0)
630                 return (false);
631         /* This is already an R/O mount. */
632         if ((fsflags & MNT_RDONLY) != 0)
633                 return (false);
634
635         switch (error) {
636         case ENODEV:    /* generic, geom, ... */
637         case EACCES:    /* cam/scsi, ... */
638         case EROFS:     /* md, mmcsd, ... */
639                 /*
640                  * These errors can be returned by the storage layer to signal
641                  * that the media is read-only.  No harm in the R/O mount
642                  * attempt if the error was returned for some other reason.
643                  */
644                 return (true);
645         default:
646                 return (false);
647         }
648 }
649
650 int
651 vfs_donmount(struct thread *td, uint64_t fsflags, struct uio *fsoptions)
652 {
653         struct vfsoptlist *optlist;
654         struct vfsopt *opt, *tmp_opt;
655         char *fstype, *fspath, *errmsg;
656         int error, fstypelen, fspathlen, errmsg_len, errmsg_pos;
657         bool autoro;
658
659         errmsg = fspath = NULL;
660         errmsg_len = fspathlen = 0;
661         errmsg_pos = -1;
662         autoro = default_autoro;
663
664         error = vfs_buildopts(fsoptions, &optlist);
665         if (error)
666                 return (error);
667
668         if (vfs_getopt(optlist, "errmsg", (void **)&errmsg, &errmsg_len) == 0)
669                 errmsg_pos = vfs_getopt_pos(optlist, "errmsg");
670
671         /*
672          * We need these two options before the others,
673          * and they are mandatory for any filesystem.
674          * Ensure they are NUL terminated as well.
675          */
676         fstypelen = 0;
677         error = vfs_getopt(optlist, "fstype", (void **)&fstype, &fstypelen);
678         if (error || fstypelen <= 0 || fstype[fstypelen - 1] != '\0') {
679                 error = EINVAL;
680                 if (errmsg != NULL)
681                         strncpy(errmsg, "Invalid fstype", errmsg_len);
682                 goto bail;
683         }
684         fspathlen = 0;
685         error = vfs_getopt(optlist, "fspath", (void **)&fspath, &fspathlen);
686         if (error || fspathlen <= 0 || fspath[fspathlen - 1] != '\0') {
687                 error = EINVAL;
688                 if (errmsg != NULL)
689                         strncpy(errmsg, "Invalid fspath", errmsg_len);
690                 goto bail;
691         }
692
693         /*
694          * We need to see if we have the "update" option
695          * before we call vfs_domount(), since vfs_domount() has special
696          * logic based on MNT_UPDATE.  This is very important
697          * when we want to update the root filesystem.
698          */
699         TAILQ_FOREACH_SAFE(opt, optlist, link, tmp_opt) {
700                 int do_freeopt = 0;
701
702                 if (strcmp(opt->name, "update") == 0) {
703                         fsflags |= MNT_UPDATE;
704                         do_freeopt = 1;
705                 }
706                 else if (strcmp(opt->name, "async") == 0)
707                         fsflags |= MNT_ASYNC;
708                 else if (strcmp(opt->name, "force") == 0) {
709                         fsflags |= MNT_FORCE;
710                         do_freeopt = 1;
711                 }
712                 else if (strcmp(opt->name, "reload") == 0) {
713                         fsflags |= MNT_RELOAD;
714                         do_freeopt = 1;
715                 }
716                 else if (strcmp(opt->name, "multilabel") == 0)
717                         fsflags |= MNT_MULTILABEL;
718                 else if (strcmp(opt->name, "noasync") == 0)
719                         fsflags &= ~MNT_ASYNC;
720                 else if (strcmp(opt->name, "noatime") == 0)
721                         fsflags |= MNT_NOATIME;
722                 else if (strcmp(opt->name, "atime") == 0) {
723                         free(opt->name, M_MOUNT);
724                         opt->name = strdup("nonoatime", M_MOUNT);
725                 }
726                 else if (strcmp(opt->name, "noclusterr") == 0)
727                         fsflags |= MNT_NOCLUSTERR;
728                 else if (strcmp(opt->name, "clusterr") == 0) {
729                         free(opt->name, M_MOUNT);
730                         opt->name = strdup("nonoclusterr", M_MOUNT);
731                 }
732                 else if (strcmp(opt->name, "noclusterw") == 0)
733                         fsflags |= MNT_NOCLUSTERW;
734                 else if (strcmp(opt->name, "clusterw") == 0) {
735                         free(opt->name, M_MOUNT);
736                         opt->name = strdup("nonoclusterw", M_MOUNT);
737                 }
738                 else if (strcmp(opt->name, "noexec") == 0)
739                         fsflags |= MNT_NOEXEC;
740                 else if (strcmp(opt->name, "exec") == 0) {
741                         free(opt->name, M_MOUNT);
742                         opt->name = strdup("nonoexec", M_MOUNT);
743                 }
744                 else if (strcmp(opt->name, "nosuid") == 0)
745                         fsflags |= MNT_NOSUID;
746                 else if (strcmp(opt->name, "suid") == 0) {
747                         free(opt->name, M_MOUNT);
748                         opt->name = strdup("nonosuid", M_MOUNT);
749                 }
750                 else if (strcmp(opt->name, "nosymfollow") == 0)
751                         fsflags |= MNT_NOSYMFOLLOW;
752                 else if (strcmp(opt->name, "symfollow") == 0) {
753                         free(opt->name, M_MOUNT);
754                         opt->name = strdup("nonosymfollow", M_MOUNT);
755                 }
756                 else if (strcmp(opt->name, "noro") == 0) {
757                         fsflags &= ~MNT_RDONLY;
758                         autoro = false;
759                 }
760                 else if (strcmp(opt->name, "rw") == 0) {
761                         fsflags &= ~MNT_RDONLY;
762                         autoro = false;
763                 }
764                 else if (strcmp(opt->name, "ro") == 0) {
765                         fsflags |= MNT_RDONLY;
766                         autoro = false;
767                 }
768                 else if (strcmp(opt->name, "rdonly") == 0) {
769                         free(opt->name, M_MOUNT);
770                         opt->name = strdup("ro", M_MOUNT);
771                         fsflags |= MNT_RDONLY;
772                         autoro = false;
773                 }
774                 else if (strcmp(opt->name, "autoro") == 0) {
775                         do_freeopt = 1;
776                         autoro = true;
777                 }
778                 else if (strcmp(opt->name, "suiddir") == 0)
779                         fsflags |= MNT_SUIDDIR;
780                 else if (strcmp(opt->name, "sync") == 0)
781                         fsflags |= MNT_SYNCHRONOUS;
782                 else if (strcmp(opt->name, "union") == 0)
783                         fsflags |= MNT_UNION;
784                 else if (strcmp(opt->name, "export") == 0)
785                         fsflags |= MNT_EXPORTED;
786                 else if (strcmp(opt->name, "automounted") == 0) {
787                         fsflags |= MNT_AUTOMOUNTED;
788                         do_freeopt = 1;
789                 } else if (strcmp(opt->name, "nocover") == 0) {
790                         fsflags |= MNT_NOCOVER;
791                         do_freeopt = 1;
792                 } else if (strcmp(opt->name, "cover") == 0) {
793                         fsflags &= ~MNT_NOCOVER;
794                         do_freeopt = 1;
795                 } else if (strcmp(opt->name, "emptydir") == 0) {
796                         fsflags |= MNT_EMPTYDIR;
797                         do_freeopt = 1;
798                 } else if (strcmp(opt->name, "noemptydir") == 0) {
799                         fsflags &= ~MNT_EMPTYDIR;
800                         do_freeopt = 1;
801                 }
802                 if (do_freeopt)
803                         vfs_freeopt(optlist, opt);
804         }
805
806         /*
807          * Be ultra-paranoid about making sure the type and fspath
808          * variables will fit in our mp buffers, including the
809          * terminating NUL.
810          */
811         if (fstypelen > MFSNAMELEN || fspathlen > MNAMELEN) {
812                 error = ENAMETOOLONG;
813                 goto bail;
814         }
815
816         error = vfs_domount(td, fstype, fspath, fsflags, &optlist);
817         if (error == ENOENT) {
818                 error = EINVAL;
819                 if (errmsg != NULL)
820                         strncpy(errmsg, "Invalid fstype", errmsg_len);
821                 goto bail;
822         }
823
824         /*
825          * See if we can mount in the read-only mode if the error code suggests
826          * that it could be possible and the mount options allow for that.
827          * Never try it if "[no]{ro|rw}" has been explicitly requested and not
828          * overridden by "autoro".
829          */
830         if (autoro && vfs_should_downgrade_to_ro_mount(fsflags, error)) {
831                 printf("%s: R/W mount failed, possibly R/O media,"
832                     " trying R/O mount\n", __func__);
833                 fsflags |= MNT_RDONLY;
834                 error = vfs_domount(td, fstype, fspath, fsflags, &optlist);
835         }
836 bail:
837         /* copyout the errmsg */
838         if (errmsg_pos != -1 && ((2 * errmsg_pos + 1) < fsoptions->uio_iovcnt)
839             && errmsg_len > 0 && errmsg != NULL) {
840                 if (fsoptions->uio_segflg == UIO_SYSSPACE) {
841                         bcopy(errmsg,
842                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
843                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
844                 } else {
845                         copyout(errmsg,
846                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
847                             fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
848                 }
849         }
850
851         if (optlist != NULL)
852                 vfs_freeopts(optlist);
853         return (error);
854 }
855
856 /*
857  * Old mount API.
858  */
859 #ifndef _SYS_SYSPROTO_H_
860 struct mount_args {
861         char    *type;
862         char    *path;
863         int     flags;
864         caddr_t data;
865 };
866 #endif
867 /* ARGSUSED */
868 int
869 sys_mount(struct thread *td, struct mount_args *uap)
870 {
871         char *fstype;
872         struct vfsconf *vfsp = NULL;
873         struct mntarg *ma = NULL;
874         uint64_t flags;
875         int error;
876
877         /*
878          * Mount flags are now 64-bits. On 32-bit architectures only
879          * 32-bits are passed in, but from here on everything handles
880          * 64-bit flags correctly.
881          */
882         flags = uap->flags;
883
884         AUDIT_ARG_FFLAGS(flags);
885
886         /*
887          * Filter out MNT_ROOTFS.  We do not want clients of mount() in
888          * userspace to set this flag, but we must filter it out if we want
889          * MNT_UPDATE on the root file system to work.
890          * MNT_ROOTFS should only be set by the kernel when mounting its
891          * root file system.
892          */
893         flags &= ~MNT_ROOTFS;
894
895         fstype = malloc(MFSNAMELEN, M_TEMP, M_WAITOK);
896         error = copyinstr(uap->type, fstype, MFSNAMELEN, NULL);
897         if (error) {
898                 free(fstype, M_TEMP);
899                 return (error);
900         }
901
902         AUDIT_ARG_TEXT(fstype);
903         vfsp = vfs_byname_kld(fstype, td, &error);
904         free(fstype, M_TEMP);
905         if (vfsp == NULL)
906                 return (ENOENT);
907         if (((vfsp->vfc_flags & VFCF_SBDRY) != 0 &&
908             vfsp->vfc_vfsops_sd->vfs_cmount == NULL) ||
909             ((vfsp->vfc_flags & VFCF_SBDRY) == 0 &&
910             vfsp->vfc_vfsops->vfs_cmount == NULL))
911                 return (EOPNOTSUPP);
912
913         ma = mount_argsu(ma, "fstype", uap->type, MFSNAMELEN);
914         ma = mount_argsu(ma, "fspath", uap->path, MNAMELEN);
915         ma = mount_argb(ma, flags & MNT_RDONLY, "noro");
916         ma = mount_argb(ma, !(flags & MNT_NOSUID), "nosuid");
917         ma = mount_argb(ma, !(flags & MNT_NOEXEC), "noexec");
918
919         if ((vfsp->vfc_flags & VFCF_SBDRY) != 0)
920                 return (vfsp->vfc_vfsops_sd->vfs_cmount(ma, uap->data, flags));
921         return (vfsp->vfc_vfsops->vfs_cmount(ma, uap->data, flags));
922 }
923
924 /*
925  * vfs_domount_first(): first file system mount (not update)
926  */
927 static int
928 vfs_domount_first(
929         struct thread *td,              /* Calling thread. */
930         struct vfsconf *vfsp,           /* File system type. */
931         char *fspath,                   /* Mount path. */
932         struct vnode *vp,               /* Vnode to be covered. */
933         uint64_t fsflags,               /* Flags common to all filesystems. */
934         struct vfsoptlist **optlist     /* Options local to the filesystem. */
935         )
936 {
937         struct vattr va;
938         struct mount *mp;
939         struct vnode *newdp, *rootvp;
940         int error, error1;
941         bool unmounted;
942
943         ASSERT_VOP_ELOCKED(vp, __func__);
944         KASSERT((fsflags & MNT_UPDATE) == 0, ("MNT_UPDATE shouldn't be here"));
945
946         /*
947          * If the jail of the calling thread lacks permission for this type of
948          * file system, or is trying to cover its own root, deny immediately.
949          */
950         if (jailed(td->td_ucred) && (!prison_allow(td->td_ucred,
951             vfsp->vfc_prison_flag) || vp == td->td_ucred->cr_prison->pr_root)) {
952                 vput(vp);
953                 return (EPERM);
954         }
955
956         /*
957          * If the user is not root, ensure that they own the directory
958          * onto which we are attempting to mount.
959          */
960         error = VOP_GETATTR(vp, &va, td->td_ucred);
961         if (error == 0 && va.va_uid != td->td_ucred->cr_uid)
962                 error = priv_check_cred(td->td_ucred, PRIV_VFS_ADMIN);
963         if (error == 0)
964                 error = vinvalbuf(vp, V_SAVE, 0, 0);
965         if (error == 0 && vp->v_type != VDIR)
966                 error = ENOTDIR;
967         if (error == 0 && (fsflags & MNT_EMPTYDIR) != 0)
968                 error = vfs_emptydir(vp);
969         if (error == 0) {
970                 VI_LOCK(vp);
971                 if ((vp->v_iflag & VI_MOUNT) == 0 && vp->v_mountedhere == NULL)
972                         vp->v_iflag |= VI_MOUNT;
973                 else
974                         error = EBUSY;
975                 VI_UNLOCK(vp);
976         }
977         if (error != 0) {
978                 vput(vp);
979                 return (error);
980         }
981         vn_seqc_write_begin(vp);
982         VOP_UNLOCK(vp);
983
984         /* Allocate and initialize the filesystem. */
985         mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
986         /* XXXMAC: pass to vfs_mount_alloc? */
987         mp->mnt_optnew = *optlist;
988         /* Set the mount level flags. */
989         mp->mnt_flag = (fsflags & (MNT_UPDATEMASK | MNT_ROOTFS | MNT_RDONLY));
990
991         /*
992          * Mount the filesystem.
993          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
994          * get.  No freeing of cn_pnbuf.
995          */
996         error1 = 0;
997         unmounted = true;
998         if ((error = VFS_MOUNT(mp)) != 0 ||
999             (error1 = VFS_STATFS(mp, &mp->mnt_stat)) != 0 ||
1000             (error1 = VFS_ROOT(mp, LK_EXCLUSIVE, &newdp)) != 0) {
1001                 rootvp = NULL;
1002                 if (error1 != 0) {
1003                         MPASS(error == 0);
1004                         rootvp = vfs_cache_root_clear(mp);
1005                         if (rootvp != NULL) {
1006                                 vhold(rootvp);
1007                                 vrele(rootvp);
1008                         }
1009                         (void)vn_start_write(NULL, &mp, V_WAIT);
1010                         MNT_ILOCK(mp);
1011                         mp->mnt_kern_flag |= MNTK_UNMOUNT | MNTK_UNMOUNTF;
1012                         MNT_IUNLOCK(mp);
1013                         VFS_PURGE(mp);
1014                         error = VFS_UNMOUNT(mp, 0);
1015                         vn_finished_write(mp);
1016                         if (error != 0) {
1017                                 printf(
1018                     "failed post-mount (%d): rollback unmount returned %d\n",
1019                                     error1, error);
1020                                 unmounted = false;
1021                         }
1022                         error = error1;
1023                 }
1024                 vfs_unbusy(mp);
1025                 mp->mnt_vnodecovered = NULL;
1026                 if (unmounted) {
1027                         /* XXXKIB wait for mnt_lockref drain? */
1028                         vfs_mount_destroy(mp);
1029                 }
1030                 VI_LOCK(vp);
1031                 vp->v_iflag &= ~VI_MOUNT;
1032                 VI_UNLOCK(vp);
1033                 if (rootvp != NULL) {
1034                         vn_seqc_write_end(rootvp);
1035                         vdrop(rootvp);
1036                 }
1037                 vn_seqc_write_end(vp);
1038                 vrele(vp);
1039                 return (error);
1040         }
1041         vn_seqc_write_begin(newdp);
1042         VOP_UNLOCK(newdp);
1043
1044         if (mp->mnt_opt != NULL)
1045                 vfs_freeopts(mp->mnt_opt);
1046         mp->mnt_opt = mp->mnt_optnew;
1047         *optlist = NULL;
1048
1049         /*
1050          * Prevent external consumers of mount options from reading mnt_optnew.
1051          */
1052         mp->mnt_optnew = NULL;
1053
1054         MNT_ILOCK(mp);
1055         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1056             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1057                 mp->mnt_kern_flag |= MNTK_ASYNC;
1058         else
1059                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1060         MNT_IUNLOCK(mp);
1061
1062         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1063         cache_purge(vp);
1064         VI_LOCK(vp);
1065         vp->v_iflag &= ~VI_MOUNT;
1066         vn_irflag_set_locked(vp, VIRF_MOUNTPOINT);
1067         vp->v_mountedhere = mp;
1068         VI_UNLOCK(vp);
1069         /* Place the new filesystem at the end of the mount list. */
1070         mtx_lock(&mountlist_mtx);
1071         TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1072         mtx_unlock(&mountlist_mtx);
1073         vfs_event_signal(NULL, VQ_MOUNT, 0);
1074         vn_lock(newdp, LK_EXCLUSIVE | LK_RETRY);
1075         VOP_UNLOCK(vp);
1076         EVENTHANDLER_DIRECT_INVOKE(vfs_mounted, mp, newdp, td);
1077         VOP_UNLOCK(newdp);
1078         mount_devctl_event("MOUNT", mp, false);
1079         mountcheckdirs(vp, newdp);
1080         vn_seqc_write_end(vp);
1081         vn_seqc_write_end(newdp);
1082         vrele(newdp);
1083         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1084                 vfs_allocate_syncvnode(mp);
1085         vfs_op_exit(mp);
1086         vfs_unbusy(mp);
1087         return (0);
1088 }
1089
1090 /*
1091  * vfs_domount_update(): update of mounted file system
1092  */
1093 static int
1094 vfs_domount_update(
1095         struct thread *td,              /* Calling thread. */
1096         struct vnode *vp,               /* Mount point vnode. */
1097         uint64_t fsflags,               /* Flags common to all filesystems. */
1098         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1099         )
1100 {
1101         struct export_args export;
1102         struct o2export_args o2export;
1103         struct vnode *rootvp;
1104         void *bufp;
1105         struct mount *mp;
1106         int error, export_error, i, len;
1107         uint64_t flag;
1108         gid_t *grps;
1109
1110         ASSERT_VOP_ELOCKED(vp, __func__);
1111         KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1112         mp = vp->v_mount;
1113
1114         if ((vp->v_vflag & VV_ROOT) == 0) {
1115                 if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1116                     == 0)
1117                         error = EXDEV;
1118                 else
1119                         error = EINVAL;
1120                 vput(vp);
1121                 return (error);
1122         }
1123
1124         /*
1125          * We only allow the filesystem to be reloaded if it
1126          * is currently mounted read-only.
1127          */
1128         flag = mp->mnt_flag;
1129         if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1130                 vput(vp);
1131                 return (EOPNOTSUPP);    /* Needs translation */
1132         }
1133         /*
1134          * Only privileged root, or (if MNT_USER is set) the user that
1135          * did the original mount is permitted to update it.
1136          */
1137         error = vfs_suser(mp, td);
1138         if (error != 0) {
1139                 vput(vp);
1140                 return (error);
1141         }
1142         if (vfs_busy(mp, MBF_NOWAIT)) {
1143                 vput(vp);
1144                 return (EBUSY);
1145         }
1146         VI_LOCK(vp);
1147         if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1148                 VI_UNLOCK(vp);
1149                 vfs_unbusy(mp);
1150                 vput(vp);
1151                 return (EBUSY);
1152         }
1153         vp->v_iflag |= VI_MOUNT;
1154         VI_UNLOCK(vp);
1155         VOP_UNLOCK(vp);
1156
1157         vfs_op_enter(mp);
1158         vn_seqc_write_begin(vp);
1159
1160         rootvp = NULL;
1161         MNT_ILOCK(mp);
1162         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1163                 MNT_IUNLOCK(mp);
1164                 error = EBUSY;
1165                 goto end;
1166         }
1167         mp->mnt_flag &= ~MNT_UPDATEMASK;
1168         mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1169             MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1170         if ((mp->mnt_flag & MNT_ASYNC) == 0)
1171                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1172         rootvp = vfs_cache_root_clear(mp);
1173         MNT_IUNLOCK(mp);
1174         mp->mnt_optnew = *optlist;
1175         vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1176
1177         /*
1178          * Mount the filesystem.
1179          * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1180          * get.  No freeing of cn_pnbuf.
1181          */
1182         error = VFS_MOUNT(mp);
1183
1184         export_error = 0;
1185         /* Process the export option. */
1186         if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1187             &len) == 0) {
1188                 /* Assume that there is only 1 ABI for each length. */
1189                 switch (len) {
1190                 case (sizeof(struct oexport_args)):
1191                         bzero(&o2export, sizeof(o2export));
1192                         /* FALLTHROUGH */
1193                 case (sizeof(o2export)):
1194                         bcopy(bufp, &o2export, len);
1195                         export.ex_flags = (uint64_t)o2export.ex_flags;
1196                         export.ex_root = o2export.ex_root;
1197                         export.ex_uid = o2export.ex_anon.cr_uid;
1198                         export.ex_groups = NULL;
1199                         export.ex_ngroups = o2export.ex_anon.cr_ngroups;
1200                         if (export.ex_ngroups > 0) {
1201                                 if (export.ex_ngroups <= XU_NGROUPS) {
1202                                         export.ex_groups = malloc(
1203                                             export.ex_ngroups * sizeof(gid_t),
1204                                             M_TEMP, M_WAITOK);
1205                                         for (i = 0; i < export.ex_ngroups; i++)
1206                                                 export.ex_groups[i] =
1207                                                   o2export.ex_anon.cr_groups[i];
1208                                 } else
1209                                         export_error = EINVAL;
1210                         } else if (export.ex_ngroups < 0)
1211                                 export_error = EINVAL;
1212                         export.ex_addr = o2export.ex_addr;
1213                         export.ex_addrlen = o2export.ex_addrlen;
1214                         export.ex_mask = o2export.ex_mask;
1215                         export.ex_masklen = o2export.ex_masklen;
1216                         export.ex_indexfile = o2export.ex_indexfile;
1217                         export.ex_numsecflavors = o2export.ex_numsecflavors;
1218                         if (export.ex_numsecflavors < MAXSECFLAVORS) {
1219                                 for (i = 0; i < export.ex_numsecflavors; i++)
1220                                         export.ex_secflavors[i] =
1221                                             o2export.ex_secflavors[i];
1222                         } else
1223                                 export_error = EINVAL;
1224                         if (export_error == 0)
1225                                 export_error = vfs_export(mp, &export);
1226                         free(export.ex_groups, M_TEMP);
1227                         break;
1228                 case (sizeof(export)):
1229                         bcopy(bufp, &export, len);
1230                         grps = NULL;
1231                         if (export.ex_ngroups > 0) {
1232                                 if (export.ex_ngroups <= NGROUPS_MAX) {
1233                                         grps = malloc(export.ex_ngroups *
1234                                             sizeof(gid_t), M_TEMP, M_WAITOK);
1235                                         export_error = copyin(export.ex_groups,
1236                                             grps, export.ex_ngroups *
1237                                             sizeof(gid_t));
1238                                         if (export_error == 0)
1239                                                 export.ex_groups = grps;
1240                                 } else
1241                                         export_error = EINVAL;
1242                         } else if (export.ex_ngroups == 0)
1243                                 export.ex_groups = NULL;
1244                         else
1245                                 export_error = EINVAL;
1246                         if (export_error == 0)
1247                                 export_error = vfs_export(mp, &export);
1248                         free(grps, M_TEMP);
1249                         break;
1250                 default:
1251                         export_error = EINVAL;
1252                         break;
1253                 }
1254         }
1255
1256         MNT_ILOCK(mp);
1257         if (error == 0) {
1258                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1259                     MNT_SNAPSHOT);
1260         } else {
1261                 /*
1262                  * If we fail, restore old mount flags. MNT_QUOTA is special,
1263                  * because it is not part of MNT_UPDATEMASK, but it could have
1264                  * changed in the meantime if quotactl(2) was called.
1265                  * All in all we want current value of MNT_QUOTA, not the old
1266                  * one.
1267                  */
1268                 mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1269         }
1270         if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1271             (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1272                 mp->mnt_kern_flag |= MNTK_ASYNC;
1273         else
1274                 mp->mnt_kern_flag &= ~MNTK_ASYNC;
1275         MNT_IUNLOCK(mp);
1276
1277         if (error != 0)
1278                 goto end;
1279
1280         mount_devctl_event("REMOUNT", mp, true);
1281         if (mp->mnt_opt != NULL)
1282                 vfs_freeopts(mp->mnt_opt);
1283         mp->mnt_opt = mp->mnt_optnew;
1284         *optlist = NULL;
1285         (void)VFS_STATFS(mp, &mp->mnt_stat);
1286         /*
1287          * Prevent external consumers of mount options from reading
1288          * mnt_optnew.
1289          */
1290         mp->mnt_optnew = NULL;
1291
1292         if ((mp->mnt_flag & MNT_RDONLY) == 0)
1293                 vfs_allocate_syncvnode(mp);
1294         else
1295                 vfs_deallocate_syncvnode(mp);
1296 end:
1297         vfs_op_exit(mp);
1298         if (rootvp != NULL) {
1299                 vn_seqc_write_end(rootvp);
1300                 vrele(rootvp);
1301         }
1302         vn_seqc_write_end(vp);
1303         vfs_unbusy(mp);
1304         VI_LOCK(vp);
1305         vp->v_iflag &= ~VI_MOUNT;
1306         VI_UNLOCK(vp);
1307         vrele(vp);
1308         return (error != 0 ? error : export_error);
1309 }
1310
1311 /*
1312  * vfs_domount(): actually attempt a filesystem mount.
1313  */
1314 static int
1315 vfs_domount(
1316         struct thread *td,              /* Calling thread. */
1317         const char *fstype,             /* Filesystem type. */
1318         char *fspath,                   /* Mount path. */
1319         uint64_t fsflags,               /* Flags common to all filesystems. */
1320         struct vfsoptlist **optlist     /* Options local to the filesystem. */
1321         )
1322 {
1323         struct vfsconf *vfsp;
1324         struct nameidata nd;
1325         struct vnode *vp;
1326         char *pathbuf;
1327         int error;
1328
1329         /*
1330          * Be ultra-paranoid about making sure the type and fspath
1331          * variables will fit in our mp buffers, including the
1332          * terminating NUL.
1333          */
1334         if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1335                 return (ENAMETOOLONG);
1336
1337         if (jailed(td->td_ucred) || usermount == 0) {
1338                 if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1339                         return (error);
1340         }
1341
1342         /*
1343          * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1344          */
1345         if (fsflags & MNT_EXPORTED) {
1346                 error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1347                 if (error)
1348                         return (error);
1349         }
1350         if (fsflags & MNT_SUIDDIR) {
1351                 error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1352                 if (error)
1353                         return (error);
1354         }
1355         /*
1356          * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1357          */
1358         if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1359                 if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1360                         fsflags |= MNT_NOSUID | MNT_USER;
1361         }
1362
1363         /* Load KLDs before we lock the covered vnode to avoid reversals. */
1364         vfsp = NULL;
1365         if ((fsflags & MNT_UPDATE) == 0) {
1366                 /* Don't try to load KLDs if we're mounting the root. */
1367                 if (fsflags & MNT_ROOTFS) {
1368                         if ((vfsp = vfs_byname(fstype)) == NULL)
1369                                 return (ENODEV);
1370                 } else {
1371                         if ((vfsp = vfs_byname_kld(fstype, td, &error)) == NULL)
1372                                 return (error);
1373                 }
1374         }
1375
1376         /*
1377          * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1378          */
1379         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1380             UIO_SYSSPACE, fspath, td);
1381         error = namei(&nd);
1382         if (error != 0)
1383                 return (error);
1384         NDFREE(&nd, NDF_ONLY_PNBUF);
1385         vp = nd.ni_vp;
1386         if ((fsflags & MNT_UPDATE) == 0) {
1387                 if ((vp->v_vflag & VV_ROOT) != 0 &&
1388                     (fsflags & MNT_NOCOVER) != 0) {
1389                         vput(vp);
1390                         return (EBUSY);
1391                 }
1392                 pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1393                 strcpy(pathbuf, fspath);
1394                 error = vn_path_to_global_path(td, vp, pathbuf, MNAMELEN);
1395                 if (error == 0) {
1396                         error = vfs_domount_first(td, vfsp, pathbuf, vp,
1397                             fsflags, optlist);
1398                 }
1399                 free(pathbuf, M_TEMP);
1400         } else
1401                 error = vfs_domount_update(td, vp, fsflags, optlist);
1402
1403         return (error);
1404 }
1405
1406 /*
1407  * Unmount a filesystem.
1408  *
1409  * Note: unmount takes a path to the vnode mounted on as argument, not
1410  * special file (as before).
1411  */
1412 #ifndef _SYS_SYSPROTO_H_
1413 struct unmount_args {
1414         char    *path;
1415         int     flags;
1416 };
1417 #endif
1418 /* ARGSUSED */
1419 int
1420 sys_unmount(struct thread *td, struct unmount_args *uap)
1421 {
1422
1423         return (kern_unmount(td, uap->path, uap->flags));
1424 }
1425
1426 int
1427 kern_unmount(struct thread *td, const char *path, int flags)
1428 {
1429         struct nameidata nd;
1430         struct mount *mp;
1431         char *pathbuf;
1432         int error, id0, id1;
1433
1434         AUDIT_ARG_VALUE(flags);
1435         if (jailed(td->td_ucred) || usermount == 0) {
1436                 error = priv_check(td, PRIV_VFS_UNMOUNT);
1437                 if (error)
1438                         return (error);
1439         }
1440
1441         pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1442         error = copyinstr(path, pathbuf, MNAMELEN, NULL);
1443         if (error) {
1444                 free(pathbuf, M_TEMP);
1445                 return (error);
1446         }
1447         if (flags & MNT_BYFSID) {
1448                 AUDIT_ARG_TEXT(pathbuf);
1449                 /* Decode the filesystem ID. */
1450                 if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
1451                         free(pathbuf, M_TEMP);
1452                         return (EINVAL);
1453                 }
1454
1455                 mtx_lock(&mountlist_mtx);
1456                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1457                         if (mp->mnt_stat.f_fsid.val[0] == id0 &&
1458                             mp->mnt_stat.f_fsid.val[1] == id1) {
1459                                 vfs_ref(mp);
1460                                 break;
1461                         }
1462                 }
1463                 mtx_unlock(&mountlist_mtx);
1464         } else {
1465                 /*
1466                  * Try to find global path for path argument.
1467                  */
1468                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1469                     UIO_SYSSPACE, pathbuf, td);
1470                 if (namei(&nd) == 0) {
1471                         NDFREE(&nd, NDF_ONLY_PNBUF);
1472                         error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1473                             MNAMELEN);
1474                         if (error == 0)
1475                                 vput(nd.ni_vp);
1476                 }
1477                 mtx_lock(&mountlist_mtx);
1478                 TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1479                         if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1480                                 vfs_ref(mp);
1481                                 break;
1482                         }
1483                 }
1484                 mtx_unlock(&mountlist_mtx);
1485         }
1486         free(pathbuf, M_TEMP);
1487         if (mp == NULL) {
1488                 /*
1489                  * Previously we returned ENOENT for a nonexistent path and
1490                  * EINVAL for a non-mountpoint.  We cannot tell these apart
1491                  * now, so in the !MNT_BYFSID case return the more likely
1492                  * EINVAL for compatibility.
1493                  */
1494                 return ((flags & MNT_BYFSID) ? ENOENT : EINVAL);
1495         }
1496
1497         /*
1498          * Don't allow unmounting the root filesystem.
1499          */
1500         if (mp->mnt_flag & MNT_ROOTFS) {
1501                 vfs_rel(mp);
1502                 return (EINVAL);
1503         }
1504         error = dounmount(mp, flags, td);
1505         return (error);
1506 }
1507
1508 /*
1509  * Return error if any of the vnodes, ignoring the root vnode
1510  * and the syncer vnode, have non-zero usecount.
1511  *
1512  * This function is purely advisory - it can return false positives
1513  * and negatives.
1514  */
1515 static int
1516 vfs_check_usecounts(struct mount *mp)
1517 {
1518         struct vnode *vp, *mvp;
1519
1520         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1521                 if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1522                     vp->v_usecount != 0) {
1523                         VI_UNLOCK(vp);
1524                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1525                         return (EBUSY);
1526                 }
1527                 VI_UNLOCK(vp);
1528         }
1529
1530         return (0);
1531 }
1532
1533 static void
1534 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1535 {
1536
1537         mtx_assert(MNT_MTX(mp), MA_OWNED);
1538         mp->mnt_kern_flag &= ~mntkflags;
1539         if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1540                 mp->mnt_kern_flag &= ~MNTK_MWAIT;
1541                 wakeup(mp);
1542         }
1543         vfs_op_exit_locked(mp);
1544         MNT_IUNLOCK(mp);
1545         if (coveredvp != NULL) {
1546                 VOP_UNLOCK(coveredvp);
1547                 vdrop(coveredvp);
1548         }
1549         vn_finished_write(mp);
1550 }
1551
1552 /*
1553  * There are various reference counters associated with the mount point.
1554  * Normally it is permitted to modify them without taking the mnt ilock,
1555  * but this behavior can be temporarily disabled if stable value is needed
1556  * or callers are expected to block (e.g. to not allow new users during
1557  * forced unmount).
1558  */
1559 void
1560 vfs_op_enter(struct mount *mp)
1561 {
1562         struct mount_pcpu *mpcpu;
1563         int cpu;
1564
1565         MNT_ILOCK(mp);
1566         mp->mnt_vfs_ops++;
1567         if (mp->mnt_vfs_ops > 1) {
1568                 MNT_IUNLOCK(mp);
1569                 return;
1570         }
1571         vfs_op_barrier_wait(mp);
1572         CPU_FOREACH(cpu) {
1573                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1574
1575                 mp->mnt_ref += mpcpu->mntp_ref;
1576                 mpcpu->mntp_ref = 0;
1577
1578                 mp->mnt_lockref += mpcpu->mntp_lockref;
1579                 mpcpu->mntp_lockref = 0;
1580
1581                 mp->mnt_writeopcount += mpcpu->mntp_writeopcount;
1582                 mpcpu->mntp_writeopcount = 0;
1583         }
1584         MPASSERT(mp->mnt_ref > 0 && mp->mnt_lockref >= 0 &&
1585             mp->mnt_writeopcount >= 0, mp,
1586             ("invalid count(s): ref %d lockref %d writeopcount %d",
1587             mp->mnt_ref, mp->mnt_lockref, mp->mnt_writeopcount));
1588         MNT_IUNLOCK(mp);
1589         vfs_assert_mount_counters(mp);
1590 }
1591
1592 void
1593 vfs_op_exit_locked(struct mount *mp)
1594 {
1595
1596         mtx_assert(MNT_MTX(mp), MA_OWNED);
1597
1598         MPASSERT(mp->mnt_vfs_ops > 0, mp,
1599             ("invalid vfs_ops count %d", mp->mnt_vfs_ops));
1600         MPASSERT(mp->mnt_vfs_ops > 1 ||
1601             (mp->mnt_kern_flag & (MNTK_UNMOUNT | MNTK_SUSPEND)) == 0, mp,
1602             ("vfs_ops too low %d in unmount or suspend", mp->mnt_vfs_ops));
1603         mp->mnt_vfs_ops--;
1604 }
1605
1606 void
1607 vfs_op_exit(struct mount *mp)
1608 {
1609
1610         MNT_ILOCK(mp);
1611         vfs_op_exit_locked(mp);
1612         MNT_IUNLOCK(mp);
1613 }
1614
1615 struct vfs_op_barrier_ipi {
1616         struct mount *mp;
1617         struct smp_rendezvous_cpus_retry_arg srcra;
1618 };
1619
1620 static void
1621 vfs_op_action_func(void *arg)
1622 {
1623         struct vfs_op_barrier_ipi *vfsopipi;
1624         struct mount *mp;
1625
1626         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1627         mp = vfsopipi->mp;
1628
1629         if (!vfs_op_thread_entered(mp))
1630                 smp_rendezvous_cpus_done(arg);
1631 }
1632
1633 static void
1634 vfs_op_wait_func(void *arg, int cpu)
1635 {
1636         struct vfs_op_barrier_ipi *vfsopipi;
1637         struct mount *mp;
1638         struct mount_pcpu *mpcpu;
1639
1640         vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1641         mp = vfsopipi->mp;
1642
1643         mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1644         while (atomic_load_int(&mpcpu->mntp_thread_in_ops))
1645                 cpu_spinwait();
1646 }
1647
1648 void
1649 vfs_op_barrier_wait(struct mount *mp)
1650 {
1651         struct vfs_op_barrier_ipi vfsopipi;
1652
1653         vfsopipi.mp = mp;
1654
1655         smp_rendezvous_cpus_retry(all_cpus,
1656             smp_no_rendezvous_barrier,
1657             vfs_op_action_func,
1658             smp_no_rendezvous_barrier,
1659             vfs_op_wait_func,
1660             &vfsopipi.srcra);
1661 }
1662
1663 #ifdef DIAGNOSTIC
1664 void
1665 vfs_assert_mount_counters(struct mount *mp)
1666 {
1667         struct mount_pcpu *mpcpu;
1668         int cpu;
1669
1670         if (mp->mnt_vfs_ops == 0)
1671                 return;
1672
1673         CPU_FOREACH(cpu) {
1674                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1675                 if (mpcpu->mntp_ref != 0 ||
1676                     mpcpu->mntp_lockref != 0 ||
1677                     mpcpu->mntp_writeopcount != 0)
1678                         vfs_dump_mount_counters(mp);
1679         }
1680 }
1681
1682 void
1683 vfs_dump_mount_counters(struct mount *mp)
1684 {
1685         struct mount_pcpu *mpcpu;
1686         int ref, lockref, writeopcount;
1687         int cpu;
1688
1689         printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1690
1691         printf("        ref : ");
1692         ref = mp->mnt_ref;
1693         CPU_FOREACH(cpu) {
1694                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1695                 printf("%d ", mpcpu->mntp_ref);
1696                 ref += mpcpu->mntp_ref;
1697         }
1698         printf("\n");
1699         printf("    lockref : ");
1700         lockref = mp->mnt_lockref;
1701         CPU_FOREACH(cpu) {
1702                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1703                 printf("%d ", mpcpu->mntp_lockref);
1704                 lockref += mpcpu->mntp_lockref;
1705         }
1706         printf("\n");
1707         printf("writeopcount: ");
1708         writeopcount = mp->mnt_writeopcount;
1709         CPU_FOREACH(cpu) {
1710                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1711                 printf("%d ", mpcpu->mntp_writeopcount);
1712                 writeopcount += mpcpu->mntp_writeopcount;
1713         }
1714         printf("\n");
1715
1716         printf("counter       struct total\n");
1717         printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1718         printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1719         printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1720
1721         panic("invalid counts on struct mount");
1722 }
1723 #endif
1724
1725 int
1726 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1727 {
1728         struct mount_pcpu *mpcpu;
1729         int cpu, sum;
1730
1731         switch (which) {
1732         case MNT_COUNT_REF:
1733                 sum = mp->mnt_ref;
1734                 break;
1735         case MNT_COUNT_LOCKREF:
1736                 sum = mp->mnt_lockref;
1737                 break;
1738         case MNT_COUNT_WRITEOPCOUNT:
1739                 sum = mp->mnt_writeopcount;
1740                 break;
1741         }
1742
1743         CPU_FOREACH(cpu) {
1744                 mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1745                 switch (which) {
1746                 case MNT_COUNT_REF:
1747                         sum += mpcpu->mntp_ref;
1748                         break;
1749                 case MNT_COUNT_LOCKREF:
1750                         sum += mpcpu->mntp_lockref;
1751                         break;
1752                 case MNT_COUNT_WRITEOPCOUNT:
1753                         sum += mpcpu->mntp_writeopcount;
1754                         break;
1755                 }
1756         }
1757         return (sum);
1758 }
1759
1760 /*
1761  * Do the actual filesystem unmount.
1762  */
1763 int
1764 dounmount(struct mount *mp, int flags, struct thread *td)
1765 {
1766         struct vnode *coveredvp, *rootvp;
1767         int error;
1768         uint64_t async_flag;
1769         int mnt_gen_r;
1770
1771         if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
1772                 mnt_gen_r = mp->mnt_gen;
1773                 VI_LOCK(coveredvp);
1774                 vholdl(coveredvp);
1775                 vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
1776                 /*
1777                  * Check for mp being unmounted while waiting for the
1778                  * covered vnode lock.
1779                  */
1780                 if (coveredvp->v_mountedhere != mp ||
1781                     coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
1782                         VOP_UNLOCK(coveredvp);
1783                         vdrop(coveredvp);
1784                         vfs_rel(mp);
1785                         return (EBUSY);
1786                 }
1787         }
1788
1789         /*
1790          * Only privileged root, or (if MNT_USER is set) the user that did the
1791          * original mount is permitted to unmount this filesystem.
1792          */
1793         error = vfs_suser(mp, td);
1794         if (error != 0) {
1795                 if (coveredvp != NULL) {
1796                         VOP_UNLOCK(coveredvp);
1797                         vdrop(coveredvp);
1798                 }
1799                 vfs_rel(mp);
1800                 return (error);
1801         }
1802
1803         vfs_op_enter(mp);
1804
1805         vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
1806         MNT_ILOCK(mp);
1807         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
1808             (mp->mnt_flag & MNT_UPDATE) != 0 ||
1809             !TAILQ_EMPTY(&mp->mnt_uppers)) {
1810                 dounmount_cleanup(mp, coveredvp, 0);
1811                 return (EBUSY);
1812         }
1813         mp->mnt_kern_flag |= MNTK_UNMOUNT;
1814         rootvp = vfs_cache_root_clear(mp);
1815         if (coveredvp != NULL)
1816                 vn_seqc_write_begin(coveredvp);
1817         if (flags & MNT_NONBUSY) {
1818                 MNT_IUNLOCK(mp);
1819                 error = vfs_check_usecounts(mp);
1820                 MNT_ILOCK(mp);
1821                 if (error != 0) {
1822                         vn_seqc_write_end(coveredvp);
1823                         dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
1824                         if (rootvp != NULL) {
1825                                 vn_seqc_write_end(rootvp);
1826                                 vrele(rootvp);
1827                         }
1828                         return (error);
1829                 }
1830         }
1831         /* Allow filesystems to detect that a forced unmount is in progress. */
1832         if (flags & MNT_FORCE) {
1833                 mp->mnt_kern_flag |= MNTK_UNMOUNTF;
1834                 MNT_IUNLOCK(mp);
1835                 /*
1836                  * Must be done after setting MNTK_UNMOUNTF and before
1837                  * waiting for mnt_lockref to become 0.
1838                  */
1839                 VFS_PURGE(mp);
1840                 MNT_ILOCK(mp);
1841         }
1842         error = 0;
1843         if (mp->mnt_lockref) {
1844                 mp->mnt_kern_flag |= MNTK_DRAINING;
1845                 error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
1846                     "mount drain", 0);
1847         }
1848         MNT_IUNLOCK(mp);
1849         KASSERT(mp->mnt_lockref == 0,
1850             ("%s: invalid lock refcount in the drain path @ %s:%d",
1851             __func__, __FILE__, __LINE__));
1852         KASSERT(error == 0,
1853             ("%s: invalid return value for msleep in the drain path @ %s:%d",
1854             __func__, __FILE__, __LINE__));
1855
1856         /*
1857          * We want to keep the vnode around so that we can vn_seqc_write_end
1858          * after we are done with unmount. Downgrade our reference to a mere
1859          * hold count so that we don't interefere with anything.
1860          */
1861         if (rootvp != NULL) {
1862                 vhold(rootvp);
1863                 vrele(rootvp);
1864         }
1865
1866         if (mp->mnt_flag & MNT_EXPUBLIC)
1867                 vfs_setpublicfs(NULL, NULL, NULL);
1868
1869         vfs_periodic(mp, MNT_WAIT);
1870         MNT_ILOCK(mp);
1871         async_flag = mp->mnt_flag & MNT_ASYNC;
1872         mp->mnt_flag &= ~MNT_ASYNC;
1873         mp->mnt_kern_flag &= ~MNTK_ASYNC;
1874         MNT_IUNLOCK(mp);
1875         vfs_deallocate_syncvnode(mp);
1876         error = VFS_UNMOUNT(mp, flags);
1877         vn_finished_write(mp);
1878         /*
1879          * If we failed to flush the dirty blocks for this mount point,
1880          * undo all the cdir/rdir and rootvnode changes we made above.
1881          * Unless we failed to do so because the device is reporting that
1882          * it doesn't exist anymore.
1883          */
1884         if (error && error != ENXIO) {
1885                 MNT_ILOCK(mp);
1886                 if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1887                         MNT_IUNLOCK(mp);
1888                         vfs_allocate_syncvnode(mp);
1889                         MNT_ILOCK(mp);
1890                 }
1891                 mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
1892                 mp->mnt_flag |= async_flag;
1893                 if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1894                     (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1895                         mp->mnt_kern_flag |= MNTK_ASYNC;
1896                 if (mp->mnt_kern_flag & MNTK_MWAIT) {
1897                         mp->mnt_kern_flag &= ~MNTK_MWAIT;
1898                         wakeup(mp);
1899                 }
1900                 vfs_op_exit_locked(mp);
1901                 MNT_IUNLOCK(mp);
1902                 if (coveredvp) {
1903                         vn_seqc_write_end(coveredvp);
1904                         VOP_UNLOCK(coveredvp);
1905                         vdrop(coveredvp);
1906                 }
1907                 if (rootvp != NULL) {
1908                         vn_seqc_write_end(rootvp);
1909                         vdrop(rootvp);
1910                 }
1911                 return (error);
1912         }
1913         mtx_lock(&mountlist_mtx);
1914         TAILQ_REMOVE(&mountlist, mp, mnt_list);
1915         mtx_unlock(&mountlist_mtx);
1916         EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
1917         if (coveredvp != NULL) {
1918                 VI_LOCK(coveredvp);
1919                 vn_irflag_unset_locked(coveredvp, VIRF_MOUNTPOINT);
1920                 coveredvp->v_mountedhere = NULL;
1921                 vn_seqc_write_end_locked(coveredvp);
1922                 VI_UNLOCK(coveredvp);
1923                 VOP_UNLOCK(coveredvp);
1924                 vdrop(coveredvp);
1925         }
1926         mount_devctl_event("UNMOUNT", mp, false);
1927         if (rootvp != NULL) {
1928                 vn_seqc_write_end(rootvp);
1929                 vdrop(rootvp);
1930         }
1931         vfs_event_signal(NULL, VQ_UNMOUNT, 0);
1932         if (rootvnode != NULL && mp == rootvnode->v_mount) {
1933                 vrele(rootvnode);
1934                 rootvnode = NULL;
1935         }
1936         if (mp == rootdevmp)
1937                 rootdevmp = NULL;
1938         vfs_mount_destroy(mp);
1939         return (0);
1940 }
1941
1942 /*
1943  * Report errors during filesystem mounting.
1944  */
1945 void
1946 vfs_mount_error(struct mount *mp, const char *fmt, ...)
1947 {
1948         struct vfsoptlist *moptlist = mp->mnt_optnew;
1949         va_list ap;
1950         int error, len;
1951         char *errmsg;
1952
1953         error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
1954         if (error || errmsg == NULL || len <= 0)
1955                 return;
1956
1957         va_start(ap, fmt);
1958         vsnprintf(errmsg, (size_t)len, fmt, ap);
1959         va_end(ap);
1960 }
1961
1962 void
1963 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
1964 {
1965         va_list ap;
1966         int error, len;
1967         char *errmsg;
1968
1969         error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
1970         if (error || errmsg == NULL || len <= 0)
1971                 return;
1972
1973         va_start(ap, fmt);
1974         vsnprintf(errmsg, (size_t)len, fmt, ap);
1975         va_end(ap);
1976 }
1977
1978 /*
1979  * ---------------------------------------------------------------------
1980  * Functions for querying mount options/arguments from filesystems.
1981  */
1982
1983 /*
1984  * Check that no unknown options are given
1985  */
1986 int
1987 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1988 {
1989         struct vfsopt *opt;
1990         char errmsg[255];
1991         const char **t, *p, *q;
1992         int ret = 0;
1993
1994         TAILQ_FOREACH(opt, opts, link) {
1995                 p = opt->name;
1996                 q = NULL;
1997                 if (p[0] == 'n' && p[1] == 'o')
1998                         q = p + 2;
1999                 for(t = global_opts; *t != NULL; t++) {
2000                         if (strcmp(*t, p) == 0)
2001                                 break;
2002                         if (q != NULL) {
2003                                 if (strcmp(*t, q) == 0)
2004                                         break;
2005                         }
2006                 }
2007                 if (*t != NULL)
2008                         continue;
2009                 for(t = legal; *t != NULL; t++) {
2010                         if (strcmp(*t, p) == 0)
2011                                 break;
2012                         if (q != NULL) {
2013                                 if (strcmp(*t, q) == 0)
2014                                         break;
2015                         }
2016                 }
2017                 if (*t != NULL)
2018                         continue;
2019                 snprintf(errmsg, sizeof(errmsg),
2020                     "mount option <%s> is unknown", p);
2021                 ret = EINVAL;
2022         }
2023         if (ret != 0) {
2024                 TAILQ_FOREACH(opt, opts, link) {
2025                         if (strcmp(opt->name, "errmsg") == 0) {
2026                                 strncpy((char *)opt->value, errmsg, opt->len);
2027                                 break;
2028                         }
2029                 }
2030                 if (opt == NULL)
2031                         printf("%s\n", errmsg);
2032         }
2033         return (ret);
2034 }
2035
2036 /*
2037  * Get a mount option by its name.
2038  *
2039  * Return 0 if the option was found, ENOENT otherwise.
2040  * If len is non-NULL it will be filled with the length
2041  * of the option. If buf is non-NULL, it will be filled
2042  * with the address of the option.
2043  */
2044 int
2045 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
2046 {
2047         struct vfsopt *opt;
2048
2049         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2050
2051         TAILQ_FOREACH(opt, opts, link) {
2052                 if (strcmp(name, opt->name) == 0) {
2053                         opt->seen = 1;
2054                         if (len != NULL)
2055                                 *len = opt->len;
2056                         if (buf != NULL)
2057                                 *buf = opt->value;
2058                         return (0);
2059                 }
2060         }
2061         return (ENOENT);
2062 }
2063
2064 int
2065 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
2066 {
2067         struct vfsopt *opt;
2068
2069         if (opts == NULL)
2070                 return (-1);
2071
2072         TAILQ_FOREACH(opt, opts, link) {
2073                 if (strcmp(name, opt->name) == 0) {
2074                         opt->seen = 1;
2075                         return (opt->pos);
2076                 }
2077         }
2078         return (-1);
2079 }
2080
2081 int
2082 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
2083 {
2084         char *opt_value, *vtp;
2085         quad_t iv;
2086         int error, opt_len;
2087
2088         error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
2089         if (error != 0)
2090                 return (error);
2091         if (opt_len == 0 || opt_value == NULL)
2092                 return (EINVAL);
2093         if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
2094                 return (EINVAL);
2095         iv = strtoq(opt_value, &vtp, 0);
2096         if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
2097                 return (EINVAL);
2098         if (iv < 0)
2099                 return (EINVAL);
2100         switch (vtp[0]) {
2101         case 't': case 'T':
2102                 iv *= 1024;
2103                 /* FALLTHROUGH */
2104         case 'g': case 'G':
2105                 iv *= 1024;
2106                 /* FALLTHROUGH */
2107         case 'm': case 'M':
2108                 iv *= 1024;
2109                 /* FALLTHROUGH */
2110         case 'k': case 'K':
2111                 iv *= 1024;
2112         case '\0':
2113                 break;
2114         default:
2115                 return (EINVAL);
2116         }
2117         *value = iv;
2118
2119         return (0);
2120 }
2121
2122 char *
2123 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
2124 {
2125         struct vfsopt *opt;
2126
2127         *error = 0;
2128         TAILQ_FOREACH(opt, opts, link) {
2129                 if (strcmp(name, opt->name) != 0)
2130                         continue;
2131                 opt->seen = 1;
2132                 if (opt->len == 0 ||
2133                     ((char *)opt->value)[opt->len - 1] != '\0') {
2134                         *error = EINVAL;
2135                         return (NULL);
2136                 }
2137                 return (opt->value);
2138         }
2139         *error = ENOENT;
2140         return (NULL);
2141 }
2142
2143 int
2144 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
2145         uint64_t val)
2146 {
2147         struct vfsopt *opt;
2148
2149         TAILQ_FOREACH(opt, opts, link) {
2150                 if (strcmp(name, opt->name) == 0) {
2151                         opt->seen = 1;
2152                         if (w != NULL)
2153                                 *w |= val;
2154                         return (1);
2155                 }
2156         }
2157         if (w != NULL)
2158                 *w &= ~val;
2159         return (0);
2160 }
2161
2162 int
2163 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
2164 {
2165         va_list ap;
2166         struct vfsopt *opt;
2167         int ret;
2168
2169         KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2170
2171         TAILQ_FOREACH(opt, opts, link) {
2172                 if (strcmp(name, opt->name) != 0)
2173                         continue;
2174                 opt->seen = 1;
2175                 if (opt->len == 0 || opt->value == NULL)
2176                         return (0);
2177                 if (((char *)opt->value)[opt->len - 1] != '\0')
2178                         return (0);
2179                 va_start(ap, fmt);
2180                 ret = vsscanf(opt->value, fmt, ap);
2181                 va_end(ap);
2182                 return (ret);
2183         }
2184         return (0);
2185 }
2186
2187 int
2188 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
2189 {
2190         struct vfsopt *opt;
2191
2192         TAILQ_FOREACH(opt, opts, link) {
2193                 if (strcmp(name, opt->name) != 0)
2194                         continue;
2195                 opt->seen = 1;
2196                 if (opt->value == NULL)
2197                         opt->len = len;
2198                 else {
2199                         if (opt->len != len)
2200                                 return (EINVAL);
2201                         bcopy(value, opt->value, len);
2202                 }
2203                 return (0);
2204         }
2205         return (ENOENT);
2206 }
2207
2208 int
2209 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2210 {
2211         struct vfsopt *opt;
2212
2213         TAILQ_FOREACH(opt, opts, link) {
2214                 if (strcmp(name, opt->name) != 0)
2215                         continue;
2216                 opt->seen = 1;
2217                 if (opt->value == NULL)
2218                         opt->len = len;
2219                 else {
2220                         if (opt->len < len)
2221                                 return (EINVAL);
2222                         opt->len = len;
2223                         bcopy(value, opt->value, len);
2224                 }
2225                 return (0);
2226         }
2227         return (ENOENT);
2228 }
2229
2230 int
2231 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2232 {
2233         struct vfsopt *opt;
2234
2235         TAILQ_FOREACH(opt, opts, link) {
2236                 if (strcmp(name, opt->name) != 0)
2237                         continue;
2238                 opt->seen = 1;
2239                 if (opt->value == NULL)
2240                         opt->len = strlen(value) + 1;
2241                 else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2242                         return (EINVAL);
2243                 return (0);
2244         }
2245         return (ENOENT);
2246 }
2247
2248 /*
2249  * Find and copy a mount option.
2250  *
2251  * The size of the buffer has to be specified
2252  * in len, if it is not the same length as the
2253  * mount option, EINVAL is returned.
2254  * Returns ENOENT if the option is not found.
2255  */
2256 int
2257 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2258 {
2259         struct vfsopt *opt;
2260
2261         KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2262
2263         TAILQ_FOREACH(opt, opts, link) {
2264                 if (strcmp(name, opt->name) == 0) {
2265                         opt->seen = 1;
2266                         if (len != opt->len)
2267                                 return (EINVAL);
2268                         bcopy(opt->value, dest, opt->len);
2269                         return (0);
2270                 }
2271         }
2272         return (ENOENT);
2273 }
2274
2275 int
2276 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2277 {
2278
2279         /*
2280          * Filesystems only fill in part of the structure for updates, we
2281          * have to read the entirety first to get all content.
2282          */
2283         if (sbp != &mp->mnt_stat)
2284                 memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2285
2286         /*
2287          * Set these in case the underlying filesystem fails to do so.
2288          */
2289         sbp->f_version = STATFS_VERSION;
2290         sbp->f_namemax = NAME_MAX;
2291         sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2292
2293         return (mp->mnt_op->vfs_statfs(mp, sbp));
2294 }
2295
2296 void
2297 vfs_mountedfrom(struct mount *mp, const char *from)
2298 {
2299
2300         bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2301         strlcpy(mp->mnt_stat.f_mntfromname, from,
2302             sizeof mp->mnt_stat.f_mntfromname);
2303 }
2304
2305 /*
2306  * ---------------------------------------------------------------------
2307  * This is the api for building mount args and mounting filesystems from
2308  * inside the kernel.
2309  *
2310  * The API works by accumulation of individual args.  First error is
2311  * latched.
2312  *
2313  * XXX: should be documented in new manpage kernel_mount(9)
2314  */
2315
2316 /* A memory allocation which must be freed when we are done */
2317 struct mntaarg {
2318         SLIST_ENTRY(mntaarg)    next;
2319 };
2320
2321 /* The header for the mount arguments */
2322 struct mntarg {
2323         struct iovec *v;
2324         int len;
2325         int error;
2326         SLIST_HEAD(, mntaarg)   list;
2327 };
2328
2329 /*
2330  * Add a boolean argument.
2331  *
2332  * flag is the boolean value.
2333  * name must start with "no".
2334  */
2335 struct mntarg *
2336 mount_argb(struct mntarg *ma, int flag, const char *name)
2337 {
2338
2339         KASSERT(name[0] == 'n' && name[1] == 'o',
2340             ("mount_argb(...,%s): name must start with 'no'", name));
2341
2342         return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2343 }
2344
2345 /*
2346  * Add an argument printf style
2347  */
2348 struct mntarg *
2349 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2350 {
2351         va_list ap;
2352         struct mntaarg *maa;
2353         struct sbuf *sb;
2354         int len;
2355
2356         if (ma == NULL) {
2357                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2358                 SLIST_INIT(&ma->list);
2359         }
2360         if (ma->error)
2361                 return (ma);
2362
2363         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2364             M_MOUNT, M_WAITOK);
2365         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2366         ma->v[ma->len].iov_len = strlen(name) + 1;
2367         ma->len++;
2368
2369         sb = sbuf_new_auto();
2370         va_start(ap, fmt);
2371         sbuf_vprintf(sb, fmt, ap);
2372         va_end(ap);
2373         sbuf_finish(sb);
2374         len = sbuf_len(sb) + 1;
2375         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2376         SLIST_INSERT_HEAD(&ma->list, maa, next);
2377         bcopy(sbuf_data(sb), maa + 1, len);
2378         sbuf_delete(sb);
2379
2380         ma->v[ma->len].iov_base = maa + 1;
2381         ma->v[ma->len].iov_len = len;
2382         ma->len++;
2383
2384         return (ma);
2385 }
2386
2387 /*
2388  * Add an argument which is a userland string.
2389  */
2390 struct mntarg *
2391 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2392 {
2393         struct mntaarg *maa;
2394         char *tbuf;
2395
2396         if (val == NULL)
2397                 return (ma);
2398         if (ma == NULL) {
2399                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2400                 SLIST_INIT(&ma->list);
2401         }
2402         if (ma->error)
2403                 return (ma);
2404         maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2405         SLIST_INSERT_HEAD(&ma->list, maa, next);
2406         tbuf = (void *)(maa + 1);
2407         ma->error = copyinstr(val, tbuf, len, NULL);
2408         return (mount_arg(ma, name, tbuf, -1));
2409 }
2410
2411 /*
2412  * Plain argument.
2413  *
2414  * If length is -1, treat value as a C string.
2415  */
2416 struct mntarg *
2417 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2418 {
2419
2420         if (ma == NULL) {
2421                 ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2422                 SLIST_INIT(&ma->list);
2423         }
2424         if (ma->error)
2425                 return (ma);
2426
2427         ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2428             M_MOUNT, M_WAITOK);
2429         ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2430         ma->v[ma->len].iov_len = strlen(name) + 1;
2431         ma->len++;
2432
2433         ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2434         if (len < 0)
2435                 ma->v[ma->len].iov_len = strlen(val) + 1;
2436         else
2437                 ma->v[ma->len].iov_len = len;
2438         ma->len++;
2439         return (ma);
2440 }
2441
2442 /*
2443  * Free a mntarg structure
2444  */
2445 static void
2446 free_mntarg(struct mntarg *ma)
2447 {
2448         struct mntaarg *maa;
2449
2450         while (!SLIST_EMPTY(&ma->list)) {
2451                 maa = SLIST_FIRST(&ma->list);
2452                 SLIST_REMOVE_HEAD(&ma->list, next);
2453                 free(maa, M_MOUNT);
2454         }
2455         free(ma->v, M_MOUNT);
2456         free(ma, M_MOUNT);
2457 }
2458
2459 /*
2460  * Mount a filesystem
2461  */
2462 int
2463 kernel_mount(struct mntarg *ma, uint64_t flags)
2464 {
2465         struct uio auio;
2466         int error;
2467
2468         KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2469         KASSERT(ma->error != 0 || ma->v != NULL, ("kernel_mount NULL ma->v"));
2470         KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2471
2472         error = ma->error;
2473         if (error == 0) {
2474                 auio.uio_iov = ma->v;
2475                 auio.uio_iovcnt = ma->len;
2476                 auio.uio_segflg = UIO_SYSSPACE;
2477                 error = vfs_donmount(curthread, flags, &auio);
2478         }
2479         free_mntarg(ma);
2480         return (error);
2481 }
2482
2483 /*
2484  * A printflike function to mount a filesystem.
2485  */
2486 int
2487 kernel_vmount(int flags, ...)
2488 {
2489         struct mntarg *ma = NULL;
2490         va_list ap;
2491         const char *cp;
2492         const void *vp;
2493         int error;
2494
2495         va_start(ap, flags);
2496         for (;;) {
2497                 cp = va_arg(ap, const char *);
2498                 if (cp == NULL)
2499                         break;
2500                 vp = va_arg(ap, const void *);
2501                 ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2502         }
2503         va_end(ap);
2504
2505         error = kernel_mount(ma, flags);
2506         return (error);
2507 }
2508
2509 /* Map from mount options to printable formats. */
2510 static struct mntoptnames optnames[] = {
2511         MNTOPT_NAMES
2512 };
2513
2514 #define DEVCTL_LEN 1024
2515 static void
2516 mount_devctl_event(const char *type, struct mount *mp, bool donew)
2517 {
2518         const uint8_t *cp;
2519         struct mntoptnames *fp;
2520         struct sbuf sb;
2521         struct statfs *sfp = &mp->mnt_stat;
2522         char *buf;
2523
2524         buf = malloc(DEVCTL_LEN, M_MOUNT, M_NOWAIT);
2525         if (buf == NULL)
2526                 return;
2527         sbuf_new(&sb, buf, DEVCTL_LEN, SBUF_FIXEDLEN);
2528         sbuf_cpy(&sb, "mount-point=\"");
2529         devctl_safe_quote_sb(&sb, sfp->f_mntonname);
2530         sbuf_cat(&sb, "\" mount-dev=\"");
2531         devctl_safe_quote_sb(&sb, sfp->f_mntfromname);
2532         sbuf_cat(&sb, "\" mount-type=\"");
2533         devctl_safe_quote_sb(&sb, sfp->f_fstypename);
2534         sbuf_cat(&sb, "\" fsid=0x");
2535         cp = (const uint8_t *)&sfp->f_fsid.val[0];
2536         for (int i = 0; i < sizeof(sfp->f_fsid); i++)
2537                 sbuf_printf(&sb, "%02x", cp[i]);
2538         sbuf_printf(&sb, " owner=%u flags=\"", sfp->f_owner);
2539         for (fp = optnames; fp->o_opt != 0; fp++) {
2540                 if ((mp->mnt_flag & fp->o_opt) != 0) {
2541                         sbuf_cat(&sb, fp->o_name);
2542                         sbuf_putc(&sb, ';');
2543                 }
2544         }
2545         sbuf_putc(&sb, '"');
2546         sbuf_finish(&sb);
2547
2548         /*
2549          * Options are not published because the form of the options depends on
2550          * the file system and may include binary data. In addition, they don't
2551          * necessarily provide enough useful information to be actionable when
2552          * devd processes them.
2553          */
2554
2555         if (sbuf_error(&sb) == 0)
2556                 devctl_notify("VFS", "FS", type, sbuf_data(&sb));
2557         sbuf_delete(&sb);
2558         free(buf, M_MOUNT);
2559 }
2560
2561 /*
2562  * Force remount specified mount point to read-only.  The argument
2563  * must be busied to avoid parallel unmount attempts.
2564  *
2565  * Intended use is to prevent further writes if some metadata
2566  * inconsistency is detected.  Note that the function still flushes
2567  * all cached metadata and data for the mount point, which might be
2568  * not always suitable.
2569  */
2570 int
2571 vfs_remount_ro(struct mount *mp)
2572 {
2573         struct vfsoptlist *opts;
2574         struct vfsopt *opt;
2575         struct vnode *vp_covered, *rootvp;
2576         int error;
2577
2578         KASSERT(mp->mnt_lockref > 0,
2579             ("vfs_remount_ro: mp %p is not busied", mp));
2580         KASSERT((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0,
2581             ("vfs_remount_ro: mp %p is being unmounted (and busy?)", mp));
2582
2583         rootvp = NULL;
2584         vp_covered = mp->mnt_vnodecovered;
2585         error = vget(vp_covered, LK_EXCLUSIVE | LK_NOWAIT);
2586         if (error != 0)
2587                 return (error);
2588         VI_LOCK(vp_covered);
2589         if ((vp_covered->v_iflag & VI_MOUNT) != 0) {
2590                 VI_UNLOCK(vp_covered);
2591                 vput(vp_covered);
2592                 return (EBUSY);
2593         }
2594         vp_covered->v_iflag |= VI_MOUNT;
2595         VI_UNLOCK(vp_covered);
2596         vfs_op_enter(mp);
2597         vn_seqc_write_begin(vp_covered);
2598
2599         MNT_ILOCK(mp);
2600         if ((mp->mnt_flag & MNT_RDONLY) != 0) {
2601                 MNT_IUNLOCK(mp);
2602                 error = EBUSY;
2603                 goto out;
2604         }
2605         mp->mnt_flag |= MNT_UPDATE | MNT_FORCE | MNT_RDONLY;
2606         rootvp = vfs_cache_root_clear(mp);
2607         MNT_IUNLOCK(mp);
2608
2609         opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK | M_ZERO);
2610         TAILQ_INIT(opts);
2611         opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK | M_ZERO);
2612         opt->name = strdup("ro", M_MOUNT);
2613         opt->value = NULL;
2614         TAILQ_INSERT_TAIL(opts, opt, link);
2615         vfs_mergeopts(opts, mp->mnt_opt);
2616         mp->mnt_optnew = opts;
2617
2618         error = VFS_MOUNT(mp);
2619
2620         if (error == 0) {
2621                 MNT_ILOCK(mp);
2622                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_FORCE);
2623                 MNT_IUNLOCK(mp);
2624                 vfs_deallocate_syncvnode(mp);
2625                 if (mp->mnt_opt != NULL)
2626                         vfs_freeopts(mp->mnt_opt);
2627                 mp->mnt_opt = mp->mnt_optnew;
2628         } else {
2629                 MNT_ILOCK(mp);
2630                 mp->mnt_flag &= ~(MNT_UPDATE | MNT_FORCE | MNT_RDONLY);
2631                 MNT_IUNLOCK(mp);
2632                 vfs_freeopts(mp->mnt_optnew);
2633         }
2634         mp->mnt_optnew = NULL;
2635
2636 out:
2637         vfs_op_exit(mp);
2638         VI_LOCK(vp_covered);
2639         vp_covered->v_iflag &= ~VI_MOUNT;
2640         VI_UNLOCK(vp_covered);
2641         vput(vp_covered);
2642         vn_seqc_write_end(vp_covered);
2643         if (rootvp != NULL) {
2644                 vn_seqc_write_end(rootvp);
2645                 vrele(rootvp);
2646         }
2647         return (error);
2648 }
2649
2650 /*
2651  * Suspend write operations on all local writeable filesystems.  Does
2652  * full sync of them in the process.
2653  *
2654  * Iterate over the mount points in reverse order, suspending most
2655  * recently mounted filesystems first.  It handles a case where a
2656  * filesystem mounted from a md(4) vnode-backed device should be
2657  * suspended before the filesystem that owns the vnode.
2658  */
2659 void
2660 suspend_all_fs(void)
2661 {
2662         struct mount *mp;
2663         int error;
2664
2665         mtx_lock(&mountlist_mtx);
2666         TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
2667                 error = vfs_busy(mp, MBF_MNTLSTLOCK | MBF_NOWAIT);
2668                 if (error != 0)
2669                         continue;
2670                 if ((mp->mnt_flag & (MNT_RDONLY | MNT_LOCAL)) != MNT_LOCAL ||
2671                     (mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2672                         mtx_lock(&mountlist_mtx);
2673                         vfs_unbusy(mp);
2674                         continue;
2675                 }
2676                 error = vfs_write_suspend(mp, 0);
2677                 if (error == 0) {
2678                         MNT_ILOCK(mp);
2679                         MPASS((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0);
2680                         mp->mnt_kern_flag |= MNTK_SUSPEND_ALL;
2681                         MNT_IUNLOCK(mp);
2682                         mtx_lock(&mountlist_mtx);
2683                 } else {
2684                         printf("suspend of %s failed, error %d\n",
2685                             mp->mnt_stat.f_mntonname, error);
2686                         mtx_lock(&mountlist_mtx);
2687                         vfs_unbusy(mp);
2688                 }
2689         }
2690         mtx_unlock(&mountlist_mtx);
2691 }
2692
2693 void
2694 resume_all_fs(void)
2695 {
2696         struct mount *mp;
2697
2698         mtx_lock(&mountlist_mtx);
2699         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2700                 if ((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0)
2701                         continue;
2702                 mtx_unlock(&mountlist_mtx);
2703                 MNT_ILOCK(mp);
2704                 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) != 0);
2705                 mp->mnt_kern_flag &= ~MNTK_SUSPEND_ALL;
2706                 MNT_IUNLOCK(mp);
2707                 vfs_write_resume(mp, 0);
2708                 mtx_lock(&mountlist_mtx);
2709                 vfs_unbusy(mp);
2710         }
2711         mtx_unlock(&mountlist_mtx);
2712 }