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