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