vfs_mount.c revision 177785
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 177785 2008-03-31 12:01:21Z kib $");
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
1493/*
1494 * Mount /devfs as our root filesystem, but do not put it on the mountlist
1495 * yet.  Create a /dev -> / symlink so that absolute pathnames will lookup.
1496 */
1497
1498static void
1499devfs_first(void)
1500{
1501	struct thread *td = curthread;
1502	struct vfsoptlist *opts;
1503	struct vfsconf *vfsp;
1504	struct mount *mp = NULL;
1505	int error;
1506
1507	vfsp = vfs_byname("devfs");
1508	KASSERT(vfsp != NULL, ("Could not find devfs by name"));
1509	if (vfsp == NULL)
1510		return;
1511
1512	mp = vfs_mount_alloc(NULLVP, vfsp, "/dev", td);
1513
1514	error = VFS_MOUNT(mp, td);
1515	KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
1516	if (error)
1517		return;
1518
1519	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
1520	TAILQ_INIT(opts);
1521	mp->mnt_opt = opts;
1522
1523	mtx_lock(&mountlist_mtx);
1524	TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
1525	mtx_unlock(&mountlist_mtx);
1526
1527	set_rootvnode(td);
1528
1529	error = kern_symlink(td, "/", "dev", UIO_SYSSPACE);
1530	if (error)
1531		printf("kern_symlink /dev -> / returns %d\n", error);
1532}
1533
1534/*
1535 * Surgically move our devfs to be mounted on /dev.
1536 */
1537
1538static void
1539devfs_fixup(struct thread *td)
1540{
1541	struct nameidata nd;
1542	int error;
1543	struct vnode *vp, *dvp;
1544	struct mount *mp;
1545
1546	/* Remove our devfs mount from the mountlist and purge the cache */
1547	mtx_lock(&mountlist_mtx);
1548	mp = TAILQ_FIRST(&mountlist);
1549	TAILQ_REMOVE(&mountlist, mp, mnt_list);
1550	mtx_unlock(&mountlist_mtx);
1551	cache_purgevfs(mp);
1552
1553	VFS_ROOT(mp, LK_EXCLUSIVE, &dvp, td);
1554	VI_LOCK(dvp);
1555	dvp->v_iflag &= ~VI_MOUNT;
1556	VI_UNLOCK(dvp);
1557	dvp->v_mountedhere = NULL;
1558
1559	/* Set up the real rootvnode, and purge the cache */
1560	TAILQ_FIRST(&mountlist)->mnt_vnodecovered = NULL;
1561	set_rootvnode(td);
1562	cache_purgevfs(rootvnode->v_mount);
1563
1564	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
1565	error = namei(&nd);
1566	if (error) {
1567		printf("Lookup of /dev for devfs, error: %d\n", error);
1568		return;
1569	}
1570	NDFREE(&nd, NDF_ONLY_PNBUF);
1571	vp = nd.ni_vp;
1572	if (vp->v_type != VDIR) {
1573		vput(vp);
1574	}
1575	error = vinvalbuf(vp, V_SAVE, td, 0, 0);
1576	if (error) {
1577		vput(vp);
1578	}
1579	cache_purge(vp);
1580	mp->mnt_vnodecovered = vp;
1581	vp->v_mountedhere = mp;
1582	mtx_lock(&mountlist_mtx);
1583	TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1584	mtx_unlock(&mountlist_mtx);
1585	VOP_UNLOCK(vp, 0);
1586	vput(dvp);
1587	vfs_unbusy(mp, td);
1588
1589	/* Unlink the no longer needed /dev/dev -> / symlink */
1590	kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
1591}
1592
1593/*
1594 * Report errors during filesystem mounting.
1595 */
1596void
1597vfs_mount_error(struct mount *mp, const char *fmt, ...)
1598{
1599	struct vfsoptlist *moptlist = mp->mnt_optnew;
1600	va_list ap;
1601	int error, len;
1602	char *errmsg;
1603
1604	error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
1605	if (error || errmsg == NULL || len <= 0)
1606		return;
1607
1608	va_start(ap, fmt);
1609	vsnprintf(errmsg, (size_t)len, fmt, ap);
1610	va_end(ap);
1611}
1612
1613/*
1614 * Find and mount the root filesystem
1615 */
1616void
1617vfs_mountroot(void)
1618{
1619	char *cp;
1620	int error, i, asked = 0;
1621
1622	root_mount_prepare();
1623
1624	mount_zone = uma_zcreate("Mountpoints", sizeof(struct mount),
1625	    NULL, NULL, mount_init, mount_fini,
1626	    UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1627	devfs_first();
1628
1629	/*
1630	 * We are booted with instructions to prompt for the root filesystem.
1631	 */
1632	if (boothowto & RB_ASKNAME) {
1633		if (!vfs_mountroot_ask())
1634			goto mounted;
1635		asked = 1;
1636	}
1637
1638	/*
1639	 * The root filesystem information is compiled in, and we are
1640	 * booted with instructions to use it.
1641	 */
1642	if (ctrootdevname != NULL && (boothowto & RB_DFLTROOT)) {
1643		if (!vfs_mountroot_try(ctrootdevname))
1644			goto mounted;
1645		ctrootdevname = NULL;
1646	}
1647
1648	/*
1649	 * We've been given the generic "use CDROM as root" flag.  This is
1650	 * necessary because one media may be used in many different
1651	 * devices, so we need to search for them.
1652	 */
1653	if (boothowto & RB_CDROM) {
1654		for (i = 0; cdrom_rootdevnames[i] != NULL; i++) {
1655			if (!vfs_mountroot_try(cdrom_rootdevnames[i]))
1656				goto mounted;
1657		}
1658	}
1659
1660	/*
1661	 * Try to use the value read by the loader from /etc/fstab, or
1662	 * supplied via some other means.  This is the preferred
1663	 * mechanism.
1664	 */
1665	cp = getenv("vfs.root.mountfrom");
1666	if (cp != NULL) {
1667		error = vfs_mountroot_try(cp);
1668		freeenv(cp);
1669		if (!error)
1670			goto mounted;
1671	}
1672
1673	/*
1674	 * Try values that may have been computed by code during boot
1675	 */
1676	if (!vfs_mountroot_try(rootdevnames[0]))
1677		goto mounted;
1678	if (!vfs_mountroot_try(rootdevnames[1]))
1679		goto mounted;
1680
1681	/*
1682	 * If we (still) have a compiled-in default, try it.
1683	 */
1684	if (ctrootdevname != NULL)
1685		if (!vfs_mountroot_try(ctrootdevname))
1686			goto mounted;
1687	/*
1688	 * Everything so far has failed, prompt on the console if we haven't
1689	 * already tried that.
1690	 */
1691	if (!asked)
1692		if (!vfs_mountroot_ask())
1693			goto mounted;
1694
1695	panic("Root mount failed, startup aborted.");
1696
1697mounted:
1698	root_mount_done();
1699}
1700
1701/*
1702 * Mount (mountfrom) as the root filesystem.
1703 */
1704static int
1705vfs_mountroot_try(const char *mountfrom)
1706{
1707	struct mount	*mp;
1708	char		*vfsname, *path;
1709	time_t		timebase;
1710	int		error;
1711	char		patt[32];
1712
1713	vfsname = NULL;
1714	path    = NULL;
1715	mp      = NULL;
1716	error   = EINVAL;
1717
1718	if (mountfrom == NULL)
1719		return (error);		/* don't complain */
1720	printf("Trying to mount root from %s\n", mountfrom);
1721
1722	/* parse vfs name and path */
1723	vfsname = malloc(MFSNAMELEN, M_MOUNT, M_WAITOK);
1724	path = malloc(MNAMELEN, M_MOUNT, M_WAITOK);
1725	vfsname[0] = path[0] = 0;
1726	sprintf(patt, "%%%d[a-z0-9]:%%%ds", MFSNAMELEN, MNAMELEN);
1727	if (sscanf(mountfrom, patt, vfsname, path) < 1)
1728		goto out;
1729
1730	if (path[0] == '\0')
1731		strcpy(path, ROOTNAME);
1732
1733	error = kernel_vmount(
1734	    MNT_RDONLY | MNT_ROOTFS,
1735	    "fstype", vfsname,
1736	    "fspath", "/",
1737	    "from", path,
1738	    NULL);
1739	if (error == 0) {
1740		/*
1741		 * We mount devfs prior to mounting the / FS, so the first
1742		 * entry will typically be devfs.
1743		 */
1744		mp = TAILQ_FIRST(&mountlist);
1745		KASSERT(mp != NULL, ("%s: mountlist is empty", __func__));
1746
1747		/*
1748		 * Iterate over all currently mounted file systems and use
1749		 * the time stamp found to check and/or initialize the RTC.
1750		 * Typically devfs has no time stamp and the only other FS
1751		 * is the actual / FS.
1752		 * Call inittodr() only once and pass it the largest of the
1753		 * timestamps we encounter.
1754		 */
1755		timebase = 0;
1756		do {
1757			if (mp->mnt_time > timebase)
1758				timebase = mp->mnt_time;
1759			mp = TAILQ_NEXT(mp, mnt_list);
1760		} while (mp != NULL);
1761		inittodr(timebase);
1762
1763		devfs_fixup(curthread);
1764	}
1765out:
1766	free(path, M_MOUNT);
1767	free(vfsname, M_MOUNT);
1768	return (error);
1769}
1770
1771/*
1772 * ---------------------------------------------------------------------
1773 * Interactive root filesystem selection code.
1774 */
1775
1776static int
1777vfs_mountroot_ask(void)
1778{
1779	char name[128];
1780
1781	for(;;) {
1782		printf("\nManual root filesystem specification:\n");
1783		printf("  <fstype>:<device>  Mount <device> using filesystem <fstype>\n");
1784#if defined(__amd64__) || defined(__i386__) || defined(__ia64__)
1785		printf("                       eg. ufs:da0s1a\n");
1786#else
1787		printf("                       eg. ufs:/dev/da0a\n");
1788#endif
1789		printf("  ?                  List valid disk boot devices\n");
1790		printf("  <empty line>       Abort manual input\n");
1791		printf("\nmountroot> ");
1792		gets(name, sizeof(name), 1);
1793		if (name[0] == '\0')
1794			return (1);
1795		if (name[0] == '?') {
1796			printf("\nList of GEOM managed disk devices:\n  ");
1797			g_dev_print();
1798			continue;
1799		}
1800		if (!vfs_mountroot_try(name))
1801			return (0);
1802	}
1803}
1804
1805/*
1806 * ---------------------------------------------------------------------
1807 * Functions for querying mount options/arguments from filesystems.
1808 */
1809
1810/*
1811 * Check that no unknown options are given
1812 */
1813int
1814vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1815{
1816	struct vfsopt *opt;
1817	char errmsg[255];
1818	const char **t, *p, *q;
1819	int ret = 0;
1820
1821	TAILQ_FOREACH(opt, opts, link) {
1822		p = opt->name;
1823		q = NULL;
1824		if (p[0] == 'n' && p[1] == 'o')
1825			q = p + 2;
1826		for(t = global_opts; *t != NULL; t++) {
1827			if (strcmp(*t, p) == 0)
1828				break;
1829			if (q != NULL) {
1830				if (strcmp(*t, q) == 0)
1831					break;
1832			}
1833		}
1834		if (*t != NULL)
1835			continue;
1836		for(t = legal; *t != NULL; t++) {
1837			if (strcmp(*t, p) == 0)
1838				break;
1839			if (q != NULL) {
1840				if (strcmp(*t, q) == 0)
1841					break;
1842			}
1843		}
1844		if (*t != NULL)
1845			continue;
1846		sprintf(errmsg, "mount option <%s> is unknown", p);
1847		printf("%s\n", errmsg);
1848		ret = EINVAL;
1849	}
1850	if (ret != 0) {
1851		TAILQ_FOREACH(opt, opts, link) {
1852			if (strcmp(opt->name, "errmsg") == 0) {
1853				strncpy((char *)opt->value, errmsg, opt->len);
1854			}
1855		}
1856	}
1857	return (ret);
1858}
1859
1860/*
1861 * Get a mount option by its name.
1862 *
1863 * Return 0 if the option was found, ENOENT otherwise.
1864 * If len is non-NULL it will be filled with the length
1865 * of the option. If buf is non-NULL, it will be filled
1866 * with the address of the option.
1867 */
1868int
1869vfs_getopt(opts, name, buf, len)
1870	struct vfsoptlist *opts;
1871	const char *name;
1872	void **buf;
1873	int *len;
1874{
1875	struct vfsopt *opt;
1876
1877	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1878
1879	TAILQ_FOREACH(opt, opts, link) {
1880		if (strcmp(name, opt->name) == 0) {
1881			if (len != NULL)
1882				*len = opt->len;
1883			if (buf != NULL)
1884				*buf = opt->value;
1885			return (0);
1886		}
1887	}
1888	return (ENOENT);
1889}
1890
1891static int
1892vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
1893{
1894	struct vfsopt *opt;
1895	int i;
1896
1897	if (opts == NULL)
1898		return (-1);
1899
1900	i = 0;
1901	TAILQ_FOREACH(opt, opts, link) {
1902		if (strcmp(name, opt->name) == 0)
1903			return (i);
1904		++i;
1905	}
1906	return (-1);
1907}
1908
1909char *
1910vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
1911{
1912	struct vfsopt *opt;
1913
1914	*error = 0;
1915	TAILQ_FOREACH(opt, opts, link) {
1916		if (strcmp(name, opt->name) != 0)
1917			continue;
1918		if (((char *)opt->value)[opt->len - 1] != '\0') {
1919			*error = EINVAL;
1920			return (NULL);
1921		}
1922		return (opt->value);
1923	}
1924	*error = ENOENT;
1925	return (NULL);
1926}
1927
1928int
1929vfs_flagopt(struct vfsoptlist *opts, const char *name, u_int *w, u_int val)
1930{
1931	struct vfsopt *opt;
1932
1933	TAILQ_FOREACH(opt, opts, link) {
1934		if (strcmp(name, opt->name) == 0) {
1935			if (w != NULL)
1936				*w |= val;
1937			return (1);
1938		}
1939	}
1940	if (w != NULL)
1941		*w &= ~val;
1942	return (0);
1943}
1944
1945int
1946vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
1947{
1948	va_list ap;
1949	struct vfsopt *opt;
1950	int ret;
1951
1952	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1953
1954	TAILQ_FOREACH(opt, opts, link) {
1955		if (strcmp(name, opt->name) != 0)
1956			continue;
1957		if (opt->len == 0 || opt->value == NULL)
1958			return (0);
1959		if (((char *)opt->value)[opt->len - 1] != '\0')
1960			return (0);
1961		va_start(ap, fmt);
1962		ret = vsscanf(opt->value, fmt, ap);
1963		va_end(ap);
1964		return (ret);
1965	}
1966	return (0);
1967}
1968
1969/*
1970 * Find and copy a mount option.
1971 *
1972 * The size of the buffer has to be specified
1973 * in len, if it is not the same length as the
1974 * mount option, EINVAL is returned.
1975 * Returns ENOENT if the option is not found.
1976 */
1977int
1978vfs_copyopt(opts, name, dest, len)
1979	struct vfsoptlist *opts;
1980	const char *name;
1981	void *dest;
1982	int len;
1983{
1984	struct vfsopt *opt;
1985
1986	KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
1987
1988	TAILQ_FOREACH(opt, opts, link) {
1989		if (strcmp(name, opt->name) == 0) {
1990			if (len != opt->len)
1991				return (EINVAL);
1992			bcopy(opt->value, dest, opt->len);
1993			return (0);
1994		}
1995	}
1996	return (ENOENT);
1997}
1998
1999/*
2000 * This is a helper function for filesystems to traverse their
2001 * vnodes.  See MNT_VNODE_FOREACH() in sys/mount.h
2002 */
2003
2004struct vnode *
2005__mnt_vnode_next(struct vnode **mvp, struct mount *mp)
2006{
2007	struct vnode *vp;
2008
2009	mtx_assert(MNT_MTX(mp), MA_OWNED);
2010
2011	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
2012	if ((*mvp)->v_yield++ == 500) {
2013		MNT_IUNLOCK(mp);
2014		(*mvp)->v_yield = 0;
2015		uio_yield();
2016		MNT_ILOCK(mp);
2017	}
2018	vp = TAILQ_NEXT(*mvp, v_nmntvnodes);
2019	while (vp != NULL && vp->v_type == VMARKER)
2020		vp = TAILQ_NEXT(vp, v_nmntvnodes);
2021
2022	/* Check if we are done */
2023	if (vp == NULL) {
2024		__mnt_vnode_markerfree(mvp, mp);
2025		return (NULL);
2026	}
2027	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
2028	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
2029	return (vp);
2030}
2031
2032struct vnode *
2033__mnt_vnode_first(struct vnode **mvp, struct mount *mp)
2034{
2035	struct vnode *vp;
2036
2037	mtx_assert(MNT_MTX(mp), MA_OWNED);
2038
2039	vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
2040	while (vp != NULL && vp->v_type == VMARKER)
2041		vp = TAILQ_NEXT(vp, v_nmntvnodes);
2042
2043	/* Check if we are done */
2044	if (vp == NULL) {
2045		*mvp = NULL;
2046		return (NULL);
2047	}
2048	mp->mnt_holdcnt++;
2049	MNT_IUNLOCK(mp);
2050	*mvp = (struct vnode *) malloc(sizeof(struct vnode),
2051				       M_VNODE_MARKER,
2052				       M_WAITOK | M_ZERO);
2053	MNT_ILOCK(mp);
2054	(*mvp)->v_type = VMARKER;
2055
2056	vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
2057	while (vp != NULL && vp->v_type == VMARKER)
2058		vp = TAILQ_NEXT(vp, v_nmntvnodes);
2059
2060	/* Check if we are done */
2061	if (vp == NULL) {
2062		MNT_IUNLOCK(mp);
2063		free(*mvp, M_VNODE_MARKER);
2064		MNT_ILOCK(mp);
2065		*mvp = NULL;
2066		mp->mnt_holdcnt--;
2067		if (mp->mnt_holdcnt == 0 && mp->mnt_holdcntwaiters != 0)
2068			wakeup(&mp->mnt_holdcnt);
2069		return (NULL);
2070	}
2071	mp->mnt_markercnt++;
2072	(*mvp)->v_mount = mp;
2073	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
2074	return (vp);
2075}
2076
2077
2078void
2079__mnt_vnode_markerfree(struct vnode **mvp, struct mount *mp)
2080{
2081
2082	if (*mvp == NULL)
2083		return;
2084
2085	mtx_assert(MNT_MTX(mp), MA_OWNED);
2086
2087	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
2088	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
2089	MNT_IUNLOCK(mp);
2090	free(*mvp, M_VNODE_MARKER);
2091	MNT_ILOCK(mp);
2092	*mvp = NULL;
2093
2094	mp->mnt_markercnt--;
2095	mp->mnt_holdcnt--;
2096	if (mp->mnt_holdcnt == 0 && mp->mnt_holdcntwaiters != 0)
2097		wakeup(&mp->mnt_holdcnt);
2098}
2099
2100
2101int
2102__vfs_statfs(struct mount *mp, struct statfs *sbp, struct thread *td)
2103{
2104	int error;
2105
2106	error = mp->mnt_op->vfs_statfs(mp, &mp->mnt_stat, td);
2107	if (sbp != &mp->mnt_stat)
2108		*sbp = mp->mnt_stat;
2109	return (error);
2110}
2111
2112void
2113vfs_mountedfrom(struct mount *mp, const char *from)
2114{
2115
2116	bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2117	strlcpy(mp->mnt_stat.f_mntfromname, from,
2118	    sizeof mp->mnt_stat.f_mntfromname);
2119}
2120
2121/*
2122 * ---------------------------------------------------------------------
2123 * This is the api for building mount args and mounting filesystems from
2124 * inside the kernel.
2125 *
2126 * The API works by accumulation of individual args.  First error is
2127 * latched.
2128 *
2129 * XXX: should be documented in new manpage kernel_mount(9)
2130 */
2131
2132/* A memory allocation which must be freed when we are done */
2133struct mntaarg {
2134	SLIST_ENTRY(mntaarg)	next;
2135};
2136
2137/* The header for the mount arguments */
2138struct mntarg {
2139	struct iovec *v;
2140	int len;
2141	int error;
2142	SLIST_HEAD(, mntaarg)	list;
2143};
2144
2145/*
2146 * Add a boolean argument.
2147 *
2148 * flag is the boolean value.
2149 * name must start with "no".
2150 */
2151struct mntarg *
2152mount_argb(struct mntarg *ma, int flag, const char *name)
2153{
2154
2155	KASSERT(name[0] == 'n' && name[1] == 'o',
2156	    ("mount_argb(...,%s): name must start with 'no'", name));
2157
2158	return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2159}
2160
2161/*
2162 * Add an argument printf style
2163 */
2164struct mntarg *
2165mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2166{
2167	va_list ap;
2168	struct mntaarg *maa;
2169	struct sbuf *sb;
2170	int len;
2171
2172	if (ma == NULL) {
2173		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2174		SLIST_INIT(&ma->list);
2175	}
2176	if (ma->error)
2177		return (ma);
2178
2179	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2180	    M_MOUNT, M_WAITOK);
2181	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2182	ma->v[ma->len].iov_len = strlen(name) + 1;
2183	ma->len++;
2184
2185	sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
2186	va_start(ap, fmt);
2187	sbuf_vprintf(sb, fmt, ap);
2188	va_end(ap);
2189	sbuf_finish(sb);
2190	len = sbuf_len(sb) + 1;
2191	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2192	SLIST_INSERT_HEAD(&ma->list, maa, next);
2193	bcopy(sbuf_data(sb), maa + 1, len);
2194	sbuf_delete(sb);
2195
2196	ma->v[ma->len].iov_base = maa + 1;
2197	ma->v[ma->len].iov_len = len;
2198	ma->len++;
2199
2200	return (ma);
2201}
2202
2203/*
2204 * Add an argument which is a userland string.
2205 */
2206struct mntarg *
2207mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2208{
2209	struct mntaarg *maa;
2210	char *tbuf;
2211
2212	if (val == NULL)
2213		return (ma);
2214	if (ma == NULL) {
2215		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2216		SLIST_INIT(&ma->list);
2217	}
2218	if (ma->error)
2219		return (ma);
2220	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2221	SLIST_INSERT_HEAD(&ma->list, maa, next);
2222	tbuf = (void *)(maa + 1);
2223	ma->error = copyinstr(val, tbuf, len, NULL);
2224	return (mount_arg(ma, name, tbuf, -1));
2225}
2226
2227/*
2228 * Plain argument.
2229 *
2230 * If length is -1, treat value as a C string.
2231 */
2232struct mntarg *
2233mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2234{
2235
2236	if (ma == NULL) {
2237		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2238		SLIST_INIT(&ma->list);
2239	}
2240	if (ma->error)
2241		return (ma);
2242
2243	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2244	    M_MOUNT, M_WAITOK);
2245	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2246	ma->v[ma->len].iov_len = strlen(name) + 1;
2247	ma->len++;
2248
2249	ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2250	if (len < 0)
2251		ma->v[ma->len].iov_len = strlen(val) + 1;
2252	else
2253		ma->v[ma->len].iov_len = len;
2254	ma->len++;
2255	return (ma);
2256}
2257
2258/*
2259 * Free a mntarg structure
2260 */
2261static void
2262free_mntarg(struct mntarg *ma)
2263{
2264	struct mntaarg *maa;
2265
2266	while (!SLIST_EMPTY(&ma->list)) {
2267		maa = SLIST_FIRST(&ma->list);
2268		SLIST_REMOVE_HEAD(&ma->list, next);
2269		free(maa, M_MOUNT);
2270	}
2271	free(ma->v, M_MOUNT);
2272	free(ma, M_MOUNT);
2273}
2274
2275/*
2276 * Mount a filesystem
2277 */
2278int
2279kernel_mount(struct mntarg *ma, int flags)
2280{
2281	struct uio auio;
2282	int error;
2283
2284	KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2285	KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
2286	KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2287
2288	auio.uio_iov = ma->v;
2289	auio.uio_iovcnt = ma->len;
2290	auio.uio_segflg = UIO_SYSSPACE;
2291
2292	error = ma->error;
2293	if (!error)
2294		error = vfs_donmount(curthread, flags, &auio);
2295	free_mntarg(ma);
2296	return (error);
2297}
2298
2299/*
2300 * A printflike function to mount a filesystem.
2301 */
2302int
2303kernel_vmount(int flags, ...)
2304{
2305	struct mntarg *ma = NULL;
2306	va_list ap;
2307	const char *cp;
2308	const void *vp;
2309	int error;
2310
2311	va_start(ap, flags);
2312	for (;;) {
2313		cp = va_arg(ap, const char *);
2314		if (cp == NULL)
2315			break;
2316		vp = va_arg(ap, const void *);
2317		ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2318	}
2319	va_end(ap);
2320
2321	error = kernel_mount(ma, flags);
2322	return (error);
2323}
2324