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