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