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