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