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