xref: /freebsd/sys/kern/vfs_mount.c (revision 56e766af41cd68310f5583bb893b13c006fcb44f)
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;
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 	VOP_UNLOCK(vp);
951 
952 	/* Allocate and initialize the filesystem. */
953 	mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
954 	/* XXXMAC: pass to vfs_mount_alloc? */
955 	mp->mnt_optnew = *optlist;
956 	/* Set the mount level flags. */
957 	mp->mnt_flag = (fsflags & (MNT_UPDATEMASK | MNT_ROOTFS | MNT_RDONLY));
958 
959 	/*
960 	 * Mount the filesystem.
961 	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
962 	 * get.  No freeing of cn_pnbuf.
963 	 */
964 	error1 = 0;
965 	if ((error = VFS_MOUNT(mp)) != 0 ||
966 	    (error1 = VFS_STATFS(mp, &mp->mnt_stat)) != 0 ||
967 	    (error1 = VFS_ROOT(mp, LK_EXCLUSIVE, &newdp)) != 0) {
968 		if (error1 != 0) {
969 			error = error1;
970 			if ((error1 = VFS_UNMOUNT(mp, 0)) != 0)
971 				printf("VFS_UNMOUNT returned %d\n", error1);
972 		}
973 		vfs_unbusy(mp);
974 		mp->mnt_vnodecovered = NULL;
975 		vfs_mount_destroy(mp);
976 		VI_LOCK(vp);
977 		vp->v_iflag &= ~VI_MOUNT;
978 		VI_UNLOCK(vp);
979 		vrele(vp);
980 		return (error);
981 	}
982 	VOP_UNLOCK(newdp);
983 
984 	if (mp->mnt_opt != NULL)
985 		vfs_freeopts(mp->mnt_opt);
986 	mp->mnt_opt = mp->mnt_optnew;
987 	*optlist = NULL;
988 
989 	/*
990 	 * Prevent external consumers of mount options from reading mnt_optnew.
991 	 */
992 	mp->mnt_optnew = NULL;
993 
994 	MNT_ILOCK(mp);
995 	if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
996 	    (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
997 		mp->mnt_kern_flag |= MNTK_ASYNC;
998 	else
999 		mp->mnt_kern_flag &= ~MNTK_ASYNC;
1000 	MNT_IUNLOCK(mp);
1001 
1002 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1003 	cache_purge(vp);
1004 	VI_LOCK(vp);
1005 	vp->v_iflag &= ~VI_MOUNT;
1006 	VI_UNLOCK(vp);
1007 	vp->v_mountedhere = mp;
1008 	/* Place the new filesystem at the end of the mount list. */
1009 	mtx_lock(&mountlist_mtx);
1010 	TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1011 	mtx_unlock(&mountlist_mtx);
1012 	vfs_event_signal(NULL, VQ_MOUNT, 0);
1013 	vn_lock(newdp, LK_EXCLUSIVE | LK_RETRY);
1014 	VOP_UNLOCK(vp);
1015 	EVENTHANDLER_DIRECT_INVOKE(vfs_mounted, mp, newdp, td);
1016 	VOP_UNLOCK(newdp);
1017 	mountcheckdirs(vp, newdp);
1018 	vrele(newdp);
1019 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
1020 		vfs_allocate_syncvnode(mp);
1021 	vfs_op_exit(mp);
1022 	vfs_unbusy(mp);
1023 	return (0);
1024 }
1025 
1026 /*
1027  * vfs_domount_update(): update of mounted file system
1028  */
1029 static int
1030 vfs_domount_update(
1031 	struct thread *td,		/* Calling thread. */
1032 	struct vnode *vp,		/* Mount point vnode. */
1033 	uint64_t fsflags,		/* Flags common to all filesystems. */
1034 	struct vfsoptlist **optlist	/* Options local to the filesystem. */
1035 	)
1036 {
1037 	struct export_args export;
1038 	struct vnode *rootvp;
1039 	void *bufp;
1040 	struct mount *mp;
1041 	int error, export_error, len;
1042 	uint64_t flag;
1043 
1044 	ASSERT_VOP_ELOCKED(vp, __func__);
1045 	KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1046 	mp = vp->v_mount;
1047 
1048 	if ((vp->v_vflag & VV_ROOT) == 0) {
1049 		if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1050 		    == 0)
1051 			error = EXDEV;
1052 		else
1053 			error = EINVAL;
1054 		vput(vp);
1055 		return (error);
1056 	}
1057 
1058 	/*
1059 	 * We only allow the filesystem to be reloaded if it
1060 	 * is currently mounted read-only.
1061 	 */
1062 	flag = mp->mnt_flag;
1063 	if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1064 		vput(vp);
1065 		return (EOPNOTSUPP);	/* Needs translation */
1066 	}
1067 	/*
1068 	 * Only privileged root, or (if MNT_USER is set) the user that
1069 	 * did the original mount is permitted to update it.
1070 	 */
1071 	error = vfs_suser(mp, td);
1072 	if (error != 0) {
1073 		vput(vp);
1074 		return (error);
1075 	}
1076 	if (vfs_busy(mp, MBF_NOWAIT)) {
1077 		vput(vp);
1078 		return (EBUSY);
1079 	}
1080 	VI_LOCK(vp);
1081 	if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1082 		VI_UNLOCK(vp);
1083 		vfs_unbusy(mp);
1084 		vput(vp);
1085 		return (EBUSY);
1086 	}
1087 	vp->v_iflag |= VI_MOUNT;
1088 	VI_UNLOCK(vp);
1089 	VOP_UNLOCK(vp);
1090 
1091 	vfs_op_enter(mp);
1092 
1093 	MNT_ILOCK(mp);
1094 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1095 		MNT_IUNLOCK(mp);
1096 		error = EBUSY;
1097 		goto end;
1098 	}
1099 	mp->mnt_flag &= ~MNT_UPDATEMASK;
1100 	mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1101 	    MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1102 	if ((mp->mnt_flag & MNT_ASYNC) == 0)
1103 		mp->mnt_kern_flag &= ~MNTK_ASYNC;
1104 	rootvp = vfs_cache_root_clear(mp);
1105 	MNT_IUNLOCK(mp);
1106 	if (rootvp != NULL)
1107 		vrele(rootvp);
1108 	mp->mnt_optnew = *optlist;
1109 	vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1110 
1111 	/*
1112 	 * Mount the filesystem.
1113 	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1114 	 * get.  No freeing of cn_pnbuf.
1115 	 */
1116 	error = VFS_MOUNT(mp);
1117 
1118 	export_error = 0;
1119 	/* Process the export option. */
1120 	if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1121 	    &len) == 0) {
1122 		/* Assume that there is only 1 ABI for each length. */
1123 		switch (len) {
1124 		case (sizeof(struct oexport_args)):
1125 			bzero(&export, sizeof(export));
1126 			/* FALLTHROUGH */
1127 		case (sizeof(export)):
1128 			bcopy(bufp, &export, len);
1129 			export_error = vfs_export(mp, &export);
1130 			break;
1131 		default:
1132 			export_error = EINVAL;
1133 			break;
1134 		}
1135 	}
1136 
1137 	MNT_ILOCK(mp);
1138 	if (error == 0) {
1139 		mp->mnt_flag &=	~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1140 		    MNT_SNAPSHOT);
1141 	} else {
1142 		/*
1143 		 * If we fail, restore old mount flags. MNT_QUOTA is special,
1144 		 * because it is not part of MNT_UPDATEMASK, but it could have
1145 		 * changed in the meantime if quotactl(2) was called.
1146 		 * All in all we want current value of MNT_QUOTA, not the old
1147 		 * one.
1148 		 */
1149 		mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1150 	}
1151 	if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1152 	    (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1153 		mp->mnt_kern_flag |= MNTK_ASYNC;
1154 	else
1155 		mp->mnt_kern_flag &= ~MNTK_ASYNC;
1156 	MNT_IUNLOCK(mp);
1157 
1158 	if (error != 0)
1159 		goto end;
1160 
1161 	if (mp->mnt_opt != NULL)
1162 		vfs_freeopts(mp->mnt_opt);
1163 	mp->mnt_opt = mp->mnt_optnew;
1164 	*optlist = NULL;
1165 	(void)VFS_STATFS(mp, &mp->mnt_stat);
1166 	/*
1167 	 * Prevent external consumers of mount options from reading
1168 	 * mnt_optnew.
1169 	 */
1170 	mp->mnt_optnew = NULL;
1171 
1172 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
1173 		vfs_allocate_syncvnode(mp);
1174 	else
1175 		vfs_deallocate_syncvnode(mp);
1176 end:
1177 	vfs_op_exit(mp);
1178 	vfs_unbusy(mp);
1179 	VI_LOCK(vp);
1180 	vp->v_iflag &= ~VI_MOUNT;
1181 	VI_UNLOCK(vp);
1182 	vrele(vp);
1183 	return (error != 0 ? error : export_error);
1184 }
1185 
1186 /*
1187  * vfs_domount(): actually attempt a filesystem mount.
1188  */
1189 static int
1190 vfs_domount(
1191 	struct thread *td,		/* Calling thread. */
1192 	const char *fstype,		/* Filesystem type. */
1193 	char *fspath,			/* Mount path. */
1194 	uint64_t fsflags,		/* Flags common to all filesystems. */
1195 	struct vfsoptlist **optlist	/* Options local to the filesystem. */
1196 	)
1197 {
1198 	struct vfsconf *vfsp;
1199 	struct nameidata nd;
1200 	struct vnode *vp;
1201 	char *pathbuf;
1202 	int error;
1203 
1204 	/*
1205 	 * Be ultra-paranoid about making sure the type and fspath
1206 	 * variables will fit in our mp buffers, including the
1207 	 * terminating NUL.
1208 	 */
1209 	if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1210 		return (ENAMETOOLONG);
1211 
1212 	if (jailed(td->td_ucred) || usermount == 0) {
1213 		if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1214 			return (error);
1215 	}
1216 
1217 	/*
1218 	 * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1219 	 */
1220 	if (fsflags & MNT_EXPORTED) {
1221 		error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1222 		if (error)
1223 			return (error);
1224 	}
1225 	if (fsflags & MNT_SUIDDIR) {
1226 		error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1227 		if (error)
1228 			return (error);
1229 	}
1230 	/*
1231 	 * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1232 	 */
1233 	if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1234 		if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1235 			fsflags |= MNT_NOSUID | MNT_USER;
1236 	}
1237 
1238 	/* Load KLDs before we lock the covered vnode to avoid reversals. */
1239 	vfsp = NULL;
1240 	if ((fsflags & MNT_UPDATE) == 0) {
1241 		/* Don't try to load KLDs if we're mounting the root. */
1242 		if (fsflags & MNT_ROOTFS)
1243 			vfsp = vfs_byname(fstype);
1244 		else
1245 			vfsp = vfs_byname_kld(fstype, td, &error);
1246 		if (vfsp == NULL)
1247 			return (ENODEV);
1248 	}
1249 
1250 	/*
1251 	 * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1252 	 */
1253 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1254 	    UIO_SYSSPACE, fspath, td);
1255 	error = namei(&nd);
1256 	if (error != 0)
1257 		return (error);
1258 	NDFREE(&nd, NDF_ONLY_PNBUF);
1259 	vp = nd.ni_vp;
1260 	if ((fsflags & MNT_UPDATE) == 0) {
1261 		if ((vp->v_vflag & VV_ROOT) != 0 &&
1262 		    (fsflags & MNT_NOCOVER) != 0) {
1263 			vput(vp);
1264 			return (EBUSY);
1265 		}
1266 		pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1267 		strcpy(pathbuf, fspath);
1268 		error = vn_path_to_global_path(td, vp, pathbuf, MNAMELEN);
1269 		/* debug.disablefullpath == 1 results in ENODEV */
1270 		if (error == 0 || error == ENODEV) {
1271 			error = vfs_domount_first(td, vfsp, pathbuf, vp,
1272 			    fsflags, optlist);
1273 		}
1274 		free(pathbuf, M_TEMP);
1275 	} else
1276 		error = vfs_domount_update(td, vp, fsflags, optlist);
1277 
1278 	return (error);
1279 }
1280 
1281 /*
1282  * Unmount a filesystem.
1283  *
1284  * Note: unmount takes a path to the vnode mounted on as argument, not
1285  * special file (as before).
1286  */
1287 #ifndef _SYS_SYSPROTO_H_
1288 struct unmount_args {
1289 	char	*path;
1290 	int	flags;
1291 };
1292 #endif
1293 /* ARGSUSED */
1294 int
1295 sys_unmount(struct thread *td, struct unmount_args *uap)
1296 {
1297 
1298 	return (kern_unmount(td, uap->path, uap->flags));
1299 }
1300 
1301 int
1302 kern_unmount(struct thread *td, const char *path, int flags)
1303 {
1304 	struct nameidata nd;
1305 	struct mount *mp;
1306 	char *pathbuf;
1307 	int error, id0, id1;
1308 
1309 	AUDIT_ARG_VALUE(flags);
1310 	if (jailed(td->td_ucred) || usermount == 0) {
1311 		error = priv_check(td, PRIV_VFS_UNMOUNT);
1312 		if (error)
1313 			return (error);
1314 	}
1315 
1316 	pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1317 	error = copyinstr(path, pathbuf, MNAMELEN, NULL);
1318 	if (error) {
1319 		free(pathbuf, M_TEMP);
1320 		return (error);
1321 	}
1322 	if (flags & MNT_BYFSID) {
1323 		AUDIT_ARG_TEXT(pathbuf);
1324 		/* Decode the filesystem ID. */
1325 		if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
1326 			free(pathbuf, M_TEMP);
1327 			return (EINVAL);
1328 		}
1329 
1330 		mtx_lock(&mountlist_mtx);
1331 		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1332 			if (mp->mnt_stat.f_fsid.val[0] == id0 &&
1333 			    mp->mnt_stat.f_fsid.val[1] == id1) {
1334 				vfs_ref(mp);
1335 				break;
1336 			}
1337 		}
1338 		mtx_unlock(&mountlist_mtx);
1339 	} else {
1340 		/*
1341 		 * Try to find global path for path argument.
1342 		 */
1343 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1344 		    UIO_SYSSPACE, pathbuf, td);
1345 		if (namei(&nd) == 0) {
1346 			NDFREE(&nd, NDF_ONLY_PNBUF);
1347 			error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1348 			    MNAMELEN);
1349 			if (error == 0 || error == ENODEV)
1350 				vput(nd.ni_vp);
1351 		}
1352 		mtx_lock(&mountlist_mtx);
1353 		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1354 			if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1355 				vfs_ref(mp);
1356 				break;
1357 			}
1358 		}
1359 		mtx_unlock(&mountlist_mtx);
1360 	}
1361 	free(pathbuf, M_TEMP);
1362 	if (mp == NULL) {
1363 		/*
1364 		 * Previously we returned ENOENT for a nonexistent path and
1365 		 * EINVAL for a non-mountpoint.  We cannot tell these apart
1366 		 * now, so in the !MNT_BYFSID case return the more likely
1367 		 * EINVAL for compatibility.
1368 		 */
1369 		return ((flags & MNT_BYFSID) ? ENOENT : EINVAL);
1370 	}
1371 
1372 	/*
1373 	 * Don't allow unmounting the root filesystem.
1374 	 */
1375 	if (mp->mnt_flag & MNT_ROOTFS) {
1376 		vfs_rel(mp);
1377 		return (EINVAL);
1378 	}
1379 	error = dounmount(mp, flags, td);
1380 	return (error);
1381 }
1382 
1383 /*
1384  * Return error if any of the vnodes, ignoring the root vnode
1385  * and the syncer vnode, have non-zero usecount.
1386  *
1387  * This function is purely advisory - it can return false positives
1388  * and negatives.
1389  */
1390 static int
1391 vfs_check_usecounts(struct mount *mp)
1392 {
1393 	struct vnode *vp, *mvp;
1394 
1395 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1396 		if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1397 		    vp->v_usecount != 0) {
1398 			VI_UNLOCK(vp);
1399 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1400 			return (EBUSY);
1401 		}
1402 		VI_UNLOCK(vp);
1403 	}
1404 
1405 	return (0);
1406 }
1407 
1408 static void
1409 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1410 {
1411 
1412 	mtx_assert(MNT_MTX(mp), MA_OWNED);
1413 	mp->mnt_kern_flag &= ~mntkflags;
1414 	if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1415 		mp->mnt_kern_flag &= ~MNTK_MWAIT;
1416 		wakeup(mp);
1417 	}
1418 	vfs_op_exit_locked(mp);
1419 	MNT_IUNLOCK(mp);
1420 	if (coveredvp != NULL) {
1421 		VOP_UNLOCK(coveredvp);
1422 		vdrop(coveredvp);
1423 	}
1424 	vn_finished_write(mp);
1425 }
1426 
1427 /*
1428  * There are various reference counters associated with the mount point.
1429  * Normally it is permitted to modify them without taking the mnt ilock,
1430  * but this behavior can be temporarily disabled if stable value is needed
1431  * or callers are expected to block (e.g. to not allow new users during
1432  * forced unmount).
1433  */
1434 void
1435 vfs_op_enter(struct mount *mp)
1436 {
1437 	int cpu;
1438 
1439 	MNT_ILOCK(mp);
1440 	mp->mnt_vfs_ops++;
1441 	if (mp->mnt_vfs_ops > 1) {
1442 		MNT_IUNLOCK(mp);
1443 		return;
1444 	}
1445 	/*
1446 	 * Paired with a fence in vfs_op_thread_enter(). See the comment
1447 	 * above it for details.
1448 	 */
1449 	atomic_thread_fence_seq_cst();
1450 	vfs_op_barrier_wait(mp);
1451 	/*
1452 	 * Paired with a fence in vfs_op_thread_exit().
1453 	 */
1454 	atomic_thread_fence_acq();
1455 	CPU_FOREACH(cpu) {
1456 		mp->mnt_ref +=
1457 		    zpcpu_replace_cpu(mp->mnt_ref_pcpu, 0, cpu);
1458 		mp->mnt_lockref +=
1459 		    zpcpu_replace_cpu(mp->mnt_lockref_pcpu, 0, cpu);
1460 		mp->mnt_writeopcount +=
1461 		    zpcpu_replace_cpu(mp->mnt_writeopcount_pcpu, 0, cpu);
1462 	}
1463 	MNT_IUNLOCK(mp);
1464 	vfs_assert_mount_counters(mp);
1465 }
1466 
1467 void
1468 vfs_op_exit_locked(struct mount *mp)
1469 {
1470 
1471 	mtx_assert(MNT_MTX(mp), MA_OWNED);
1472 
1473 	if (mp->mnt_vfs_ops <= 0)
1474 		panic("%s: invalid vfs_ops count %d for mp %p\n",
1475 		    __func__, mp->mnt_vfs_ops, mp);
1476 	mp->mnt_vfs_ops--;
1477 }
1478 
1479 void
1480 vfs_op_exit(struct mount *mp)
1481 {
1482 
1483 	MNT_ILOCK(mp);
1484 	vfs_op_exit_locked(mp);
1485 	MNT_IUNLOCK(mp);
1486 }
1487 
1488 /*
1489  * It is assumed the caller already posted at least an acquire barrier.
1490  */
1491 void
1492 vfs_op_barrier_wait(struct mount *mp)
1493 {
1494 	int *in_op;
1495 	int cpu;
1496 
1497 	CPU_FOREACH(cpu) {
1498 		in_op = zpcpu_get_cpu(mp->mnt_thread_in_ops_pcpu, cpu);
1499 		while (atomic_load_int(in_op))
1500 			cpu_spinwait();
1501 	}
1502 }
1503 
1504 #ifdef DIAGNOSTIC
1505 void
1506 vfs_assert_mount_counters(struct mount *mp)
1507 {
1508 	int cpu;
1509 
1510 	if (mp->mnt_vfs_ops == 0)
1511 		return;
1512 
1513 	CPU_FOREACH(cpu) {
1514 		if (*(int *)zpcpu_get_cpu(mp->mnt_ref_pcpu, cpu) != 0 ||
1515 		    *(int *)zpcpu_get_cpu(mp->mnt_lockref_pcpu, cpu) != 0 ||
1516 		    *(int *)zpcpu_get_cpu(mp->mnt_writeopcount_pcpu, cpu) != 0)
1517 			vfs_dump_mount_counters(mp);
1518 	}
1519 }
1520 
1521 void
1522 vfs_dump_mount_counters(struct mount *mp)
1523 {
1524 	int cpu, *count;
1525 	int ref, lockref, writeopcount;
1526 
1527 	printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1528 
1529 	printf("        ref : ");
1530 	ref = mp->mnt_ref;
1531 	CPU_FOREACH(cpu) {
1532 		count = zpcpu_get_cpu(mp->mnt_ref_pcpu, cpu);
1533 		printf("%d ", *count);
1534 		ref += *count;
1535 	}
1536 	printf("\n");
1537 	printf("    lockref : ");
1538 	lockref = mp->mnt_lockref;
1539 	CPU_FOREACH(cpu) {
1540 		count = zpcpu_get_cpu(mp->mnt_lockref_pcpu, cpu);
1541 		printf("%d ", *count);
1542 		lockref += *count;
1543 	}
1544 	printf("\n");
1545 	printf("writeopcount: ");
1546 	writeopcount = mp->mnt_writeopcount;
1547 	CPU_FOREACH(cpu) {
1548 		count = zpcpu_get_cpu(mp->mnt_writeopcount_pcpu, cpu);
1549 		printf("%d ", *count);
1550 		writeopcount += *count;
1551 	}
1552 	printf("\n");
1553 
1554 	printf("counter       struct total\n");
1555 	printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1556 	printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1557 	printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1558 
1559 	panic("invalid counts on struct mount");
1560 }
1561 #endif
1562 
1563 int
1564 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1565 {
1566 	int *base, *pcpu;
1567 	int cpu, sum;
1568 
1569 	switch (which) {
1570 	case MNT_COUNT_REF:
1571 		base = &mp->mnt_ref;
1572 		pcpu = mp->mnt_ref_pcpu;
1573 		break;
1574 	case MNT_COUNT_LOCKREF:
1575 		base = &mp->mnt_lockref;
1576 		pcpu = mp->mnt_lockref_pcpu;
1577 		break;
1578 	case MNT_COUNT_WRITEOPCOUNT:
1579 		base = &mp->mnt_writeopcount;
1580 		pcpu = mp->mnt_writeopcount_pcpu;
1581 		break;
1582 	}
1583 
1584 	sum = *base;
1585 	CPU_FOREACH(cpu) {
1586 		sum += *(int *)zpcpu_get_cpu(pcpu, cpu);
1587 	}
1588 	return (sum);
1589 }
1590 
1591 /*
1592  * Do the actual filesystem unmount.
1593  */
1594 int
1595 dounmount(struct mount *mp, int flags, struct thread *td)
1596 {
1597 	struct vnode *coveredvp, *rootvp;
1598 	int error;
1599 	uint64_t async_flag;
1600 	int mnt_gen_r;
1601 
1602 	if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
1603 		mnt_gen_r = mp->mnt_gen;
1604 		VI_LOCK(coveredvp);
1605 		vholdl(coveredvp);
1606 		vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
1607 		/*
1608 		 * Check for mp being unmounted while waiting for the
1609 		 * covered vnode lock.
1610 		 */
1611 		if (coveredvp->v_mountedhere != mp ||
1612 		    coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
1613 			VOP_UNLOCK(coveredvp);
1614 			vdrop(coveredvp);
1615 			vfs_rel(mp);
1616 			return (EBUSY);
1617 		}
1618 	}
1619 
1620 	/*
1621 	 * Only privileged root, or (if MNT_USER is set) the user that did the
1622 	 * original mount is permitted to unmount this filesystem.
1623 	 */
1624 	error = vfs_suser(mp, td);
1625 	if (error != 0) {
1626 		if (coveredvp != NULL) {
1627 			VOP_UNLOCK(coveredvp);
1628 			vdrop(coveredvp);
1629 		}
1630 		vfs_rel(mp);
1631 		return (error);
1632 	}
1633 
1634 	vfs_op_enter(mp);
1635 
1636 	vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
1637 	MNT_ILOCK(mp);
1638 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
1639 	    (mp->mnt_flag & MNT_UPDATE) != 0 ||
1640 	    !TAILQ_EMPTY(&mp->mnt_uppers)) {
1641 		dounmount_cleanup(mp, coveredvp, 0);
1642 		return (EBUSY);
1643 	}
1644 	mp->mnt_kern_flag |= MNTK_UNMOUNT;
1645 	rootvp = vfs_cache_root_clear(mp);
1646 	if (flags & MNT_NONBUSY) {
1647 		MNT_IUNLOCK(mp);
1648 		error = vfs_check_usecounts(mp);
1649 		MNT_ILOCK(mp);
1650 		if (error != 0) {
1651 			dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
1652 			if (rootvp != NULL)
1653 				vrele(rootvp);
1654 			return (error);
1655 		}
1656 	}
1657 	/* Allow filesystems to detect that a forced unmount is in progress. */
1658 	if (flags & MNT_FORCE) {
1659 		mp->mnt_kern_flag |= MNTK_UNMOUNTF;
1660 		MNT_IUNLOCK(mp);
1661 		/*
1662 		 * Must be done after setting MNTK_UNMOUNTF and before
1663 		 * waiting for mnt_lockref to become 0.
1664 		 */
1665 		VFS_PURGE(mp);
1666 		MNT_ILOCK(mp);
1667 	}
1668 	error = 0;
1669 	if (mp->mnt_lockref) {
1670 		mp->mnt_kern_flag |= MNTK_DRAINING;
1671 		error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
1672 		    "mount drain", 0);
1673 	}
1674 	MNT_IUNLOCK(mp);
1675 	KASSERT(mp->mnt_lockref == 0,
1676 	    ("%s: invalid lock refcount in the drain path @ %s:%d",
1677 	    __func__, __FILE__, __LINE__));
1678 	KASSERT(error == 0,
1679 	    ("%s: invalid return value for msleep in the drain path @ %s:%d",
1680 	    __func__, __FILE__, __LINE__));
1681 
1682 	if (rootvp != NULL)
1683 		vrele(rootvp);
1684 
1685 	if (mp->mnt_flag & MNT_EXPUBLIC)
1686 		vfs_setpublicfs(NULL, NULL, NULL);
1687 
1688 	/*
1689 	 * From now, we can claim that the use reference on the
1690 	 * coveredvp is ours, and the ref can be released only by
1691 	 * successfull unmount by us, or left for later unmount
1692 	 * attempt.  The previously acquired hold reference is no
1693 	 * longer needed to protect the vnode from reuse.
1694 	 */
1695 	if (coveredvp != NULL)
1696 		vdrop(coveredvp);
1697 
1698 	vfs_periodic(mp, MNT_WAIT);
1699 	MNT_ILOCK(mp);
1700 	async_flag = mp->mnt_flag & MNT_ASYNC;
1701 	mp->mnt_flag &= ~MNT_ASYNC;
1702 	mp->mnt_kern_flag &= ~MNTK_ASYNC;
1703 	MNT_IUNLOCK(mp);
1704 	cache_purgevfs(mp, false); /* remove cache entries for this file sys */
1705 	vfs_deallocate_syncvnode(mp);
1706 	error = VFS_UNMOUNT(mp, flags);
1707 	vn_finished_write(mp);
1708 	/*
1709 	 * If we failed to flush the dirty blocks for this mount point,
1710 	 * undo all the cdir/rdir and rootvnode changes we made above.
1711 	 * Unless we failed to do so because the device is reporting that
1712 	 * it doesn't exist anymore.
1713 	 */
1714 	if (error && error != ENXIO) {
1715 		MNT_ILOCK(mp);
1716 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
1717 			MNT_IUNLOCK(mp);
1718 			vfs_allocate_syncvnode(mp);
1719 			MNT_ILOCK(mp);
1720 		}
1721 		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
1722 		mp->mnt_flag |= async_flag;
1723 		if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1724 		    (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1725 			mp->mnt_kern_flag |= MNTK_ASYNC;
1726 		if (mp->mnt_kern_flag & MNTK_MWAIT) {
1727 			mp->mnt_kern_flag &= ~MNTK_MWAIT;
1728 			wakeup(mp);
1729 		}
1730 		vfs_op_exit_locked(mp);
1731 		MNT_IUNLOCK(mp);
1732 		if (coveredvp)
1733 			VOP_UNLOCK(coveredvp);
1734 		return (error);
1735 	}
1736 	mtx_lock(&mountlist_mtx);
1737 	TAILQ_REMOVE(&mountlist, mp, mnt_list);
1738 	mtx_unlock(&mountlist_mtx);
1739 	EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
1740 	if (coveredvp != NULL) {
1741 		coveredvp->v_mountedhere = NULL;
1742 		VOP_UNLOCK(coveredvp);
1743 	}
1744 	vfs_event_signal(NULL, VQ_UNMOUNT, 0);
1745 	if (rootvnode != NULL && mp == rootvnode->v_mount) {
1746 		vrele(rootvnode);
1747 		rootvnode = NULL;
1748 	}
1749 	if (mp == rootdevmp)
1750 		rootdevmp = NULL;
1751 	vfs_mount_destroy(mp);
1752 	return (0);
1753 }
1754 
1755 /*
1756  * Report errors during filesystem mounting.
1757  */
1758 void
1759 vfs_mount_error(struct mount *mp, const char *fmt, ...)
1760 {
1761 	struct vfsoptlist *moptlist = mp->mnt_optnew;
1762 	va_list ap;
1763 	int error, len;
1764 	char *errmsg;
1765 
1766 	error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
1767 	if (error || errmsg == NULL || len <= 0)
1768 		return;
1769 
1770 	va_start(ap, fmt);
1771 	vsnprintf(errmsg, (size_t)len, fmt, ap);
1772 	va_end(ap);
1773 }
1774 
1775 void
1776 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
1777 {
1778 	va_list ap;
1779 	int error, len;
1780 	char *errmsg;
1781 
1782 	error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
1783 	if (error || errmsg == NULL || len <= 0)
1784 		return;
1785 
1786 	va_start(ap, fmt);
1787 	vsnprintf(errmsg, (size_t)len, fmt, ap);
1788 	va_end(ap);
1789 }
1790 
1791 /*
1792  * ---------------------------------------------------------------------
1793  * Functions for querying mount options/arguments from filesystems.
1794  */
1795 
1796 /*
1797  * Check that no unknown options are given
1798  */
1799 int
1800 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1801 {
1802 	struct vfsopt *opt;
1803 	char errmsg[255];
1804 	const char **t, *p, *q;
1805 	int ret = 0;
1806 
1807 	TAILQ_FOREACH(opt, opts, link) {
1808 		p = opt->name;
1809 		q = NULL;
1810 		if (p[0] == 'n' && p[1] == 'o')
1811 			q = p + 2;
1812 		for(t = global_opts; *t != NULL; t++) {
1813 			if (strcmp(*t, p) == 0)
1814 				break;
1815 			if (q != NULL) {
1816 				if (strcmp(*t, q) == 0)
1817 					break;
1818 			}
1819 		}
1820 		if (*t != NULL)
1821 			continue;
1822 		for(t = legal; *t != NULL; t++) {
1823 			if (strcmp(*t, p) == 0)
1824 				break;
1825 			if (q != NULL) {
1826 				if (strcmp(*t, q) == 0)
1827 					break;
1828 			}
1829 		}
1830 		if (*t != NULL)
1831 			continue;
1832 		snprintf(errmsg, sizeof(errmsg),
1833 		    "mount option <%s> is unknown", p);
1834 		ret = EINVAL;
1835 	}
1836 	if (ret != 0) {
1837 		TAILQ_FOREACH(opt, opts, link) {
1838 			if (strcmp(opt->name, "errmsg") == 0) {
1839 				strncpy((char *)opt->value, errmsg, opt->len);
1840 				break;
1841 			}
1842 		}
1843 		if (opt == NULL)
1844 			printf("%s\n", errmsg);
1845 	}
1846 	return (ret);
1847 }
1848 
1849 /*
1850  * Get a mount option by its name.
1851  *
1852  * Return 0 if the option was found, ENOENT otherwise.
1853  * If len is non-NULL it will be filled with the length
1854  * of the option. If buf is non-NULL, it will be filled
1855  * with the address of the option.
1856  */
1857 int
1858 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
1859 {
1860 	struct vfsopt *opt;
1861 
1862 	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1863 
1864 	TAILQ_FOREACH(opt, opts, link) {
1865 		if (strcmp(name, opt->name) == 0) {
1866 			opt->seen = 1;
1867 			if (len != NULL)
1868 				*len = opt->len;
1869 			if (buf != NULL)
1870 				*buf = opt->value;
1871 			return (0);
1872 		}
1873 	}
1874 	return (ENOENT);
1875 }
1876 
1877 int
1878 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
1879 {
1880 	struct vfsopt *opt;
1881 
1882 	if (opts == NULL)
1883 		return (-1);
1884 
1885 	TAILQ_FOREACH(opt, opts, link) {
1886 		if (strcmp(name, opt->name) == 0) {
1887 			opt->seen = 1;
1888 			return (opt->pos);
1889 		}
1890 	}
1891 	return (-1);
1892 }
1893 
1894 int
1895 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
1896 {
1897 	char *opt_value, *vtp;
1898 	quad_t iv;
1899 	int error, opt_len;
1900 
1901 	error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
1902 	if (error != 0)
1903 		return (error);
1904 	if (opt_len == 0 || opt_value == NULL)
1905 		return (EINVAL);
1906 	if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
1907 		return (EINVAL);
1908 	iv = strtoq(opt_value, &vtp, 0);
1909 	if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
1910 		return (EINVAL);
1911 	if (iv < 0)
1912 		return (EINVAL);
1913 	switch (vtp[0]) {
1914 	case 't': case 'T':
1915 		iv *= 1024;
1916 		/* FALLTHROUGH */
1917 	case 'g': case 'G':
1918 		iv *= 1024;
1919 		/* FALLTHROUGH */
1920 	case 'm': case 'M':
1921 		iv *= 1024;
1922 		/* FALLTHROUGH */
1923 	case 'k': case 'K':
1924 		iv *= 1024;
1925 	case '\0':
1926 		break;
1927 	default:
1928 		return (EINVAL);
1929 	}
1930 	*value = iv;
1931 
1932 	return (0);
1933 }
1934 
1935 char *
1936 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
1937 {
1938 	struct vfsopt *opt;
1939 
1940 	*error = 0;
1941 	TAILQ_FOREACH(opt, opts, link) {
1942 		if (strcmp(name, opt->name) != 0)
1943 			continue;
1944 		opt->seen = 1;
1945 		if (opt->len == 0 ||
1946 		    ((char *)opt->value)[opt->len - 1] != '\0') {
1947 			*error = EINVAL;
1948 			return (NULL);
1949 		}
1950 		return (opt->value);
1951 	}
1952 	*error = ENOENT;
1953 	return (NULL);
1954 }
1955 
1956 int
1957 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
1958 	uint64_t val)
1959 {
1960 	struct vfsopt *opt;
1961 
1962 	TAILQ_FOREACH(opt, opts, link) {
1963 		if (strcmp(name, opt->name) == 0) {
1964 			opt->seen = 1;
1965 			if (w != NULL)
1966 				*w |= val;
1967 			return (1);
1968 		}
1969 	}
1970 	if (w != NULL)
1971 		*w &= ~val;
1972 	return (0);
1973 }
1974 
1975 int
1976 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
1977 {
1978 	va_list ap;
1979 	struct vfsopt *opt;
1980 	int ret;
1981 
1982 	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1983 
1984 	TAILQ_FOREACH(opt, opts, link) {
1985 		if (strcmp(name, opt->name) != 0)
1986 			continue;
1987 		opt->seen = 1;
1988 		if (opt->len == 0 || opt->value == NULL)
1989 			return (0);
1990 		if (((char *)opt->value)[opt->len - 1] != '\0')
1991 			return (0);
1992 		va_start(ap, fmt);
1993 		ret = vsscanf(opt->value, fmt, ap);
1994 		va_end(ap);
1995 		return (ret);
1996 	}
1997 	return (0);
1998 }
1999 
2000 int
2001 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
2002 {
2003 	struct vfsopt *opt;
2004 
2005 	TAILQ_FOREACH(opt, opts, link) {
2006 		if (strcmp(name, opt->name) != 0)
2007 			continue;
2008 		opt->seen = 1;
2009 		if (opt->value == NULL)
2010 			opt->len = len;
2011 		else {
2012 			if (opt->len != len)
2013 				return (EINVAL);
2014 			bcopy(value, opt->value, len);
2015 		}
2016 		return (0);
2017 	}
2018 	return (ENOENT);
2019 }
2020 
2021 int
2022 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2023 {
2024 	struct vfsopt *opt;
2025 
2026 	TAILQ_FOREACH(opt, opts, link) {
2027 		if (strcmp(name, opt->name) != 0)
2028 			continue;
2029 		opt->seen = 1;
2030 		if (opt->value == NULL)
2031 			opt->len = len;
2032 		else {
2033 			if (opt->len < len)
2034 				return (EINVAL);
2035 			opt->len = len;
2036 			bcopy(value, opt->value, len);
2037 		}
2038 		return (0);
2039 	}
2040 	return (ENOENT);
2041 }
2042 
2043 int
2044 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2045 {
2046 	struct vfsopt *opt;
2047 
2048 	TAILQ_FOREACH(opt, opts, link) {
2049 		if (strcmp(name, opt->name) != 0)
2050 			continue;
2051 		opt->seen = 1;
2052 		if (opt->value == NULL)
2053 			opt->len = strlen(value) + 1;
2054 		else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2055 			return (EINVAL);
2056 		return (0);
2057 	}
2058 	return (ENOENT);
2059 }
2060 
2061 /*
2062  * Find and copy a mount option.
2063  *
2064  * The size of the buffer has to be specified
2065  * in len, if it is not the same length as the
2066  * mount option, EINVAL is returned.
2067  * Returns ENOENT if the option is not found.
2068  */
2069 int
2070 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2071 {
2072 	struct vfsopt *opt;
2073 
2074 	KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2075 
2076 	TAILQ_FOREACH(opt, opts, link) {
2077 		if (strcmp(name, opt->name) == 0) {
2078 			opt->seen = 1;
2079 			if (len != opt->len)
2080 				return (EINVAL);
2081 			bcopy(opt->value, dest, opt->len);
2082 			return (0);
2083 		}
2084 	}
2085 	return (ENOENT);
2086 }
2087 
2088 int
2089 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2090 {
2091 
2092 	/*
2093 	 * Filesystems only fill in part of the structure for updates, we
2094 	 * have to read the entirety first to get all content.
2095 	 */
2096 	memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2097 
2098 	/*
2099 	 * Set these in case the underlying filesystem fails to do so.
2100 	 */
2101 	sbp->f_version = STATFS_VERSION;
2102 	sbp->f_namemax = NAME_MAX;
2103 	sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2104 
2105 	return (mp->mnt_op->vfs_statfs(mp, sbp));
2106 }
2107 
2108 void
2109 vfs_mountedfrom(struct mount *mp, const char *from)
2110 {
2111 
2112 	bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2113 	strlcpy(mp->mnt_stat.f_mntfromname, from,
2114 	    sizeof mp->mnt_stat.f_mntfromname);
2115 }
2116 
2117 /*
2118  * ---------------------------------------------------------------------
2119  * This is the api for building mount args and mounting filesystems from
2120  * inside the kernel.
2121  *
2122  * The API works by accumulation of individual args.  First error is
2123  * latched.
2124  *
2125  * XXX: should be documented in new manpage kernel_mount(9)
2126  */
2127 
2128 /* A memory allocation which must be freed when we are done */
2129 struct mntaarg {
2130 	SLIST_ENTRY(mntaarg)	next;
2131 };
2132 
2133 /* The header for the mount arguments */
2134 struct mntarg {
2135 	struct iovec *v;
2136 	int len;
2137 	int error;
2138 	SLIST_HEAD(, mntaarg)	list;
2139 };
2140 
2141 /*
2142  * Add a boolean argument.
2143  *
2144  * flag is the boolean value.
2145  * name must start with "no".
2146  */
2147 struct mntarg *
2148 mount_argb(struct mntarg *ma, int flag, const char *name)
2149 {
2150 
2151 	KASSERT(name[0] == 'n' && name[1] == 'o',
2152 	    ("mount_argb(...,%s): name must start with 'no'", name));
2153 
2154 	return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2155 }
2156 
2157 /*
2158  * Add an argument printf style
2159  */
2160 struct mntarg *
2161 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2162 {
2163 	va_list ap;
2164 	struct mntaarg *maa;
2165 	struct sbuf *sb;
2166 	int len;
2167 
2168 	if (ma == NULL) {
2169 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2170 		SLIST_INIT(&ma->list);
2171 	}
2172 	if (ma->error)
2173 		return (ma);
2174 
2175 	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2176 	    M_MOUNT, M_WAITOK);
2177 	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2178 	ma->v[ma->len].iov_len = strlen(name) + 1;
2179 	ma->len++;
2180 
2181 	sb = sbuf_new_auto();
2182 	va_start(ap, fmt);
2183 	sbuf_vprintf(sb, fmt, ap);
2184 	va_end(ap);
2185 	sbuf_finish(sb);
2186 	len = sbuf_len(sb) + 1;
2187 	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2188 	SLIST_INSERT_HEAD(&ma->list, maa, next);
2189 	bcopy(sbuf_data(sb), maa + 1, len);
2190 	sbuf_delete(sb);
2191 
2192 	ma->v[ma->len].iov_base = maa + 1;
2193 	ma->v[ma->len].iov_len = len;
2194 	ma->len++;
2195 
2196 	return (ma);
2197 }
2198 
2199 /*
2200  * Add an argument which is a userland string.
2201  */
2202 struct mntarg *
2203 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2204 {
2205 	struct mntaarg *maa;
2206 	char *tbuf;
2207 
2208 	if (val == NULL)
2209 		return (ma);
2210 	if (ma == NULL) {
2211 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2212 		SLIST_INIT(&ma->list);
2213 	}
2214 	if (ma->error)
2215 		return (ma);
2216 	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2217 	SLIST_INSERT_HEAD(&ma->list, maa, next);
2218 	tbuf = (void *)(maa + 1);
2219 	ma->error = copyinstr(val, tbuf, len, NULL);
2220 	return (mount_arg(ma, name, tbuf, -1));
2221 }
2222 
2223 /*
2224  * Plain argument.
2225  *
2226  * If length is -1, treat value as a C string.
2227  */
2228 struct mntarg *
2229 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2230 {
2231 
2232 	if (ma == NULL) {
2233 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2234 		SLIST_INIT(&ma->list);
2235 	}
2236 	if (ma->error)
2237 		return (ma);
2238 
2239 	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2240 	    M_MOUNT, M_WAITOK);
2241 	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2242 	ma->v[ma->len].iov_len = strlen(name) + 1;
2243 	ma->len++;
2244 
2245 	ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2246 	if (len < 0)
2247 		ma->v[ma->len].iov_len = strlen(val) + 1;
2248 	else
2249 		ma->v[ma->len].iov_len = len;
2250 	ma->len++;
2251 	return (ma);
2252 }
2253 
2254 /*
2255  * Free a mntarg structure
2256  */
2257 static void
2258 free_mntarg(struct mntarg *ma)
2259 {
2260 	struct mntaarg *maa;
2261 
2262 	while (!SLIST_EMPTY(&ma->list)) {
2263 		maa = SLIST_FIRST(&ma->list);
2264 		SLIST_REMOVE_HEAD(&ma->list, next);
2265 		free(maa, M_MOUNT);
2266 	}
2267 	free(ma->v, M_MOUNT);
2268 	free(ma, M_MOUNT);
2269 }
2270 
2271 /*
2272  * Mount a filesystem
2273  */
2274 int
2275 kernel_mount(struct mntarg *ma, uint64_t flags)
2276 {
2277 	struct uio auio;
2278 	int error;
2279 
2280 	KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2281 	KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
2282 	KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2283 
2284 	auio.uio_iov = ma->v;
2285 	auio.uio_iovcnt = ma->len;
2286 	auio.uio_segflg = UIO_SYSSPACE;
2287 
2288 	error = ma->error;
2289 	if (!error)
2290 		error = vfs_donmount(curthread, flags, &auio);
2291 	free_mntarg(ma);
2292 	return (error);
2293 }
2294 
2295 /*
2296  * A printflike function to mount a filesystem.
2297  */
2298 int
2299 kernel_vmount(int flags, ...)
2300 {
2301 	struct mntarg *ma = NULL;
2302 	va_list ap;
2303 	const char *cp;
2304 	const void *vp;
2305 	int error;
2306 
2307 	va_start(ap, flags);
2308 	for (;;) {
2309 		cp = va_arg(ap, const char *);
2310 		if (cp == NULL)
2311 			break;
2312 		vp = va_arg(ap, const void *);
2313 		ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2314 	}
2315 	va_end(ap);
2316 
2317 	error = kernel_mount(ma, flags);
2318 	return (error);
2319 }
2320 
2321 void
2322 vfs_oexport_conv(const struct oexport_args *oexp, struct export_args *exp)
2323 {
2324 
2325 	bcopy(oexp, exp, sizeof(*oexp));
2326 	exp->ex_numsecflavors = 0;
2327 }
2328