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