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