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