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