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