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