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