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