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