vfs_mount.c revision 138679
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 138679 2004-12-11 12:48:37Z phk $");
39
40#include <sys/param.h>
41#include <sys/conf.h>
42#include <sys/cons.h>
43#include <sys/jail.h>
44#include <sys/kernel.h>
45#include <sys/mac.h>
46#include <sys/malloc.h>
47#include <sys/mount.h>
48#include <sys/mutex.h>
49#include <sys/namei.h>
50#include <sys/proc.h>
51#include <sys/filedesc.h>
52#include <sys/reboot.h>
53#include <sys/syscallsubr.h>
54#include <sys/sysproto.h>
55#include <sys/sx.h>
56#include <sys/sysctl.h>
57#include <sys/sysent.h>
58#include <sys/systm.h>
59#include <sys/vnode.h>
60
61#include <geom/geom.h>
62
63#include <machine/stdarg.h>
64
65#include "opt_rootdevname.h"
66#include "opt_ddb.h"
67#include "opt_mac.h"
68
69#ifdef DDB
70#include <ddb/ddb.h>
71#endif
72
73#define	ROOTNAME		"root_device"
74#define	VFS_MOUNTARG_SIZE_MAX	(1024 * 64)
75
76static void	checkdirs(struct vnode *olddp, struct vnode *newdp);
77static void	gets(char *cp);
78static int	vfs_domount(struct thread *td, const char *fstype,
79		    char *fspath, int fsflags, void *fsdata);
80static int	vfs_mount_alloc(struct vnode *dvp, struct vfsconf *vfsp,
81		    const char *fspath, struct thread *td, struct mount **mpp);
82static int	vfs_mountroot_ask(void);
83static int	vfs_mountroot_try(const char *mountfrom);
84static int	vfs_donmount(struct thread *td, int fsflags,
85		    struct uio *fsoptions);
86
87static int	usermount = 0;
88SYSCTL_INT(_vfs, OID_AUTO, usermount, CTLFLAG_RW, &usermount, 0,
89    "Unprivileged users may mount and unmount file systems");
90
91MALLOC_DEFINE(M_MOUNT, "mount", "vfs mount structure");
92
93/* List of mounted filesystems. */
94struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
95
96/* For any iteration/modification of mountlist */
97struct mtx mountlist_mtx;
98
99TAILQ_HEAD(vfsoptlist, vfsopt);
100struct vfsopt {
101	TAILQ_ENTRY(vfsopt) link;
102	char	*name;
103	void	*value;
104	int	len;
105};
106
107/*
108 * The vnode of the system's root (/ in the filesystem, without chroot
109 * active.)
110 */
111struct vnode	*rootvnode;
112
113/*
114 * The root filesystem is detailed in the kernel environment variable
115 * vfs.root.mountfrom, which is expected to be in the general format
116 *
117 * <vfsname>:[<path>]
118 * vfsname   := the name of a VFS known to the kernel and capable
119 *              of being mounted as root
120 * path      := disk device name or other data used by the filesystem
121 *              to locate its physical store
122 */
123
124/*
125 * Global opts, taken by all filesystems
126 */
127static const char *global_opts[] = {
128	"fstype",
129	"fspath",
130	"ro",
131	"suid",
132	"exec",
133	NULL
134};
135
136/*
137 * The root specifiers we will try if RB_CDROM is specified.
138 */
139static char *cdrom_rootdevnames[] = {
140	"cd9660:cd0",
141	"cd9660:acd0",
142	NULL
143};
144
145/* legacy find-root code */
146char		*rootdevnames[2] = {NULL, NULL};
147#ifndef ROOTDEVNAME
148#  define ROOTDEVNAME NULL
149#endif
150const char	*ctrootdevname = ROOTDEVNAME;
151
152/*
153 * ---------------------------------------------------------------------
154 * Functions for building and sanitizing the mount options
155 */
156
157/* Remove one mount option. */
158static void
159vfs_freeopt(struct vfsoptlist *opts, struct vfsopt *opt)
160{
161
162	TAILQ_REMOVE(opts, opt, link);
163	free(opt->name, M_MOUNT);
164	if (opt->value != NULL)
165		free(opt->value, M_MOUNT);
166#ifdef INVARIANTS
167	else if (opt->len != 0)
168		panic("%s: mount option with NULL value but length != 0",
169		    __func__);
170#endif
171	free(opt, M_MOUNT);
172}
173
174/* Release all resources related to the mount options. */
175static void
176vfs_freeopts(struct vfsoptlist *opts)
177{
178	struct vfsopt *opt;
179
180	while (!TAILQ_EMPTY(opts)) {
181		opt = TAILQ_FIRST(opts);
182		vfs_freeopt(opts, opt);
183	}
184	free(opts, M_MOUNT);
185}
186
187/*
188 * Check if options are equal (with or without the "no" prefix).
189 */
190static int
191vfs_equalopts(const char *opt1, const char *opt2)
192{
193
194	/* "opt" vs. "opt" or "noopt" vs. "noopt" */
195	if (strcmp(opt1, opt2) == 0)
196		return (1);
197	/* "noopt" vs. "opt" */
198	if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
199		return (1);
200	/* "opt" vs. "noopt" */
201	if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
202		return (1);
203	return (0);
204}
205
206/*
207 * If a mount option is specified several times,
208 * (with or without the "no" prefix) only keep
209 * the last occurence of it.
210 */
211static void
212vfs_sanitizeopts(struct vfsoptlist *opts)
213{
214	struct vfsopt *opt, *opt2, *tmp;
215
216	TAILQ_FOREACH_REVERSE(opt, opts, vfsoptlist, link) {
217		opt2 = TAILQ_PREV(opt, vfsoptlist, link);
218		while (opt2 != NULL) {
219			if (vfs_equalopts(opt->name, opt2->name)) {
220				tmp = TAILQ_PREV(opt2, vfsoptlist, link);
221				vfs_freeopt(opts, opt2);
222				opt2 = tmp;
223			} else {
224				opt2 = TAILQ_PREV(opt2, vfsoptlist, link);
225			}
226		}
227	}
228}
229
230/*
231 * Build a linked list of mount options from a struct uio.
232 */
233static int
234vfs_buildopts(struct uio *auio, struct vfsoptlist **options)
235{
236	struct vfsoptlist *opts;
237	struct vfsopt *opt;
238	size_t memused;
239	unsigned int i, iovcnt;
240	int error, namelen, optlen;
241
242	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
243	TAILQ_INIT(opts);
244	memused = 0;
245	iovcnt = auio->uio_iovcnt;
246	for (i = 0; i < iovcnt; i += 2) {
247		opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
248		namelen = auio->uio_iov[i].iov_len;
249		optlen = auio->uio_iov[i + 1].iov_len;
250		opt->name = malloc(namelen, M_MOUNT, M_WAITOK);
251		opt->value = NULL;
252		opt->len = 0;
253
254		/*
255		 * Do this early, so jumps to "bad" will free the current
256		 * option.
257		 */
258		TAILQ_INSERT_TAIL(opts, opt, link);
259		memused += sizeof(struct vfsopt) + optlen + namelen;
260
261		/*
262		 * Avoid consuming too much memory, and attempts to overflow
263		 * memused.
264		 */
265		if (memused > VFS_MOUNTARG_SIZE_MAX ||
266		    optlen > VFS_MOUNTARG_SIZE_MAX ||
267		    namelen > VFS_MOUNTARG_SIZE_MAX) {
268			error = EINVAL;
269			goto bad;
270		}
271
272		if (auio->uio_segflg == UIO_SYSSPACE) {
273			bcopy(auio->uio_iov[i].iov_base, opt->name, namelen);
274		} else {
275			error = copyin(auio->uio_iov[i].iov_base, opt->name,
276			    namelen);
277			if (error)
278				goto bad;
279		}
280		/* Ensure names are null-terminated strings. */
281		if (opt->name[namelen - 1] != '\0') {
282			error = EINVAL;
283			goto bad;
284		}
285		if (optlen != 0) {
286			opt->len = optlen;
287			opt->value = malloc(optlen, M_MOUNT, M_WAITOK);
288			if (auio->uio_segflg == UIO_SYSSPACE) {
289				bcopy(auio->uio_iov[i + 1].iov_base, opt->value,
290				    optlen);
291			} else {
292				error = copyin(auio->uio_iov[i + 1].iov_base,
293				    opt->value, optlen);
294				if (error)
295					goto bad;
296			}
297		}
298	}
299	vfs_sanitizeopts(opts);
300	*options = opts;
301	return (0);
302bad:
303	vfs_freeopts(opts);
304	return (error);
305}
306
307/*
308 * Merge the old mount options with the new ones passed
309 * in the MNT_UPDATE case.
310 */
311static void
312vfs_mergeopts(struct vfsoptlist *toopts, struct vfsoptlist *opts)
313{
314	struct vfsopt *opt, *opt2, *new;
315
316	TAILQ_FOREACH(opt, opts, link) {
317		/*
318		 * Check that this option hasn't been redefined
319		 * nor cancelled with a "no" mount option.
320		 */
321		opt2 = TAILQ_FIRST(toopts);
322		while (opt2 != NULL) {
323			if (strcmp(opt2->name, opt->name) == 0)
324				goto next;
325			if (strncmp(opt2->name, "no", 2) == 0 &&
326			    strcmp(opt2->name + 2, opt->name) == 0) {
327				vfs_freeopt(toopts, opt2);
328				goto next;
329			}
330			opt2 = TAILQ_NEXT(opt2, link);
331		}
332		/* We want this option, duplicate it. */
333		new = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
334		new->name = malloc(strlen(opt->name) + 1, M_MOUNT, M_WAITOK);
335		strcpy(new->name, opt->name);
336		if (opt->len != 0) {
337			new->value = malloc(opt->len, M_MOUNT, M_WAITOK);
338			bcopy(opt->value, new->value, opt->len);
339		} else {
340			new->value = NULL;
341		}
342		new->len = opt->len;
343		TAILQ_INSERT_TAIL(toopts, new, link);
344next:
345		continue;
346	}
347}
348
349/*
350 * ---------------------------------------------------------------------
351 * Mount a filesystem
352 */
353int
354nmount(td, uap)
355	struct thread *td;
356	struct nmount_args /* {
357		struct iovec *iovp;
358		unsigned int iovcnt;
359		int flags;
360	} */ *uap;
361{
362	struct uio *auio;
363	struct iovec *iov;
364	unsigned int i;
365	int error;
366	u_int iovcnt;
367
368	/* Kick out MNT_ROOTFS early as it is legal internally */
369	if (uap->flags & MNT_ROOTFS)
370		return (EINVAL);
371
372	iovcnt = uap->iovcnt;
373	/*
374	 * Check that we have an even number of iovec's
375	 * and that we have at least two options.
376	 */
377	if ((iovcnt & 1) || (iovcnt < 4))
378		return (EINVAL);
379
380	error = copyinuio(uap->iovp, iovcnt, &auio);
381	if (error)
382		return (error);
383	iov = auio->uio_iov;
384	for (i = 0; i < iovcnt; i++) {
385		if (iov->iov_len > MMAXOPTIONLEN) {
386			free(auio, M_IOV);
387			return (EINVAL);
388		}
389		iov++;
390	}
391	error = vfs_donmount(td, uap->flags, auio);
392	free(auio, M_IOV);
393	return (error);
394}
395
396/*
397 * ---------------------------------------------------------------------
398 * Various utility functions
399 */
400
401/*
402 * Allocate and initialize the mount point struct.
403 */
404static int
405vfs_mount_alloc(struct vnode *vp, struct vfsconf *vfsp,
406    const char *fspath, struct thread *td, struct mount **mpp)
407{
408	struct mount *mp;
409
410	mp = malloc(sizeof(struct mount), M_MOUNT, M_WAITOK | M_ZERO);
411	TAILQ_INIT(&mp->mnt_nvnodelist);
412	mp->mnt_nvnodelistsize = 0;
413	mtx_init(&mp->mnt_mtx, "struct mount mtx", NULL, MTX_DEF);
414	lockinit(&mp->mnt_lock, PVFS, "vfslock", 0, LK_NOPAUSE);
415	vfs_busy(mp, LK_NOWAIT, 0, td);
416	mp->mnt_op = vfsp->vfc_vfsops;
417	mp->mnt_vfc = vfsp;
418	vfsp->vfc_refcount++;
419	mp->mnt_stat.f_type = vfsp->vfc_typenum;
420	mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
421	strlcpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
422	mp->mnt_vnodecovered = vp;
423	mp->mnt_cred = crdup(td->td_ucred);
424	mp->mnt_stat.f_owner = td->td_ucred->cr_uid;
425	strlcpy(mp->mnt_stat.f_mntonname, fspath, MNAMELEN);
426	mp->mnt_iosize_max = DFLTPHYS;
427#ifdef MAC
428	mac_init_mount(mp);
429	mac_create_mount(td->td_ucred, mp);
430#endif
431	*mpp = mp;
432	return (0);
433}
434
435/*
436 * Destroy the mount struct previously allocated by vfs_mount_alloc().
437 */
438void
439vfs_mount_destroy(struct mount *mp, struct thread *td)
440{
441
442	mp->mnt_vfc->vfc_refcount--;
443	if (!TAILQ_EMPTY(&mp->mnt_nvnodelist))
444		panic("unmount: dangling vnode");
445	vfs_unbusy(mp,td);
446	lockdestroy(&mp->mnt_lock);
447	mtx_destroy(&mp->mnt_mtx);
448	if (mp->mnt_kern_flag & MNTK_MWAIT)
449		wakeup(mp);
450#ifdef MAC
451	mac_destroy_mount(mp);
452#endif
453	if (mp->mnt_opt != NULL)
454		vfs_freeopts(mp->mnt_opt);
455	crfree(mp->mnt_cred);
456	free(mp, M_MOUNT);
457}
458
459static int
460vfs_donmount(struct thread *td, int fsflags, struct uio *fsoptions)
461{
462	struct vfsoptlist *optlist;
463	char *fstype, *fspath;
464	int error, fstypelen, fspathlen;
465
466	error = vfs_buildopts(fsoptions, &optlist);
467	if (error)
468		return (error);
469
470	/*
471	 * We need these two options before the others,
472	 * and they are mandatory for any filesystem.
473	 * Ensure they are NUL terminated as well.
474	 */
475	fstypelen = 0;
476	error = vfs_getopt(optlist, "fstype", (void **)&fstype, &fstypelen);
477	if (error || fstype[fstypelen - 1] != '\0') {
478		error = EINVAL;
479		goto bail;
480	}
481	fspathlen = 0;
482	error = vfs_getopt(optlist, "fspath", (void **)&fspath, &fspathlen);
483	if (error || fspath[fspathlen - 1] != '\0') {
484		error = EINVAL;
485		goto bail;
486	}
487
488	/*
489	 * Be ultra-paranoid about making sure the type and fspath
490	 * variables will fit in our mp buffers, including the
491	 * terminating NUL.
492	 */
493	if (fstypelen >= MFSNAMELEN - 1 || fspathlen >= MNAMELEN - 1) {
494		error = ENAMETOOLONG;
495		goto bail;
496	}
497
498	mtx_lock(&Giant);
499	error = vfs_domount(td, fstype, fspath, fsflags, optlist);
500	mtx_unlock(&Giant);
501bail:
502	if (error)
503		vfs_freeopts(optlist);
504	return (error);
505}
506
507/*
508 * ---------------------------------------------------------------------
509 * Old mount API.
510 */
511#ifndef _SYS_SYSPROTO_H_
512struct mount_args {
513	char	*type;
514	char	*path;
515	int	flags;
516	caddr_t	data;
517};
518#endif
519/* ARGSUSED */
520int
521mount(td, uap)
522	struct thread *td;
523	struct mount_args /* {
524		char *type;
525		char *path;
526		int flags;
527		caddr_t data;
528	} */ *uap;
529{
530	char *fstype;
531	struct vfsconf *vfsp = NULL;
532	struct mntarg *ma = NULL;
533	int error;
534
535	/* Kick out MNT_ROOTFS early as it is legal internally */
536	uap->flags &= ~MNT_ROOTFS;
537
538	if (uap->data == NULL)
539		return (EINVAL);
540
541	fstype = malloc(MFSNAMELEN, M_TEMP, M_WAITOK);
542	error = copyinstr(uap->type, fstype, MFSNAMELEN, NULL);
543	if (!error) {
544		mtx_lock(&Giant);	/* XXX ? */
545		vfsp = vfs_byname_kld(fstype, td, &error);
546		mtx_unlock(&Giant);
547	}
548	free(fstype, M_TEMP);
549	if (error)
550		return (error);
551	if (vfsp == NULL)
552		return (ENOENT);
553	if (vfsp->vfc_vfsops->vfs_cmount == NULL)
554		return (EOPNOTSUPP);
555
556	ma = mount_argsu(ma, "fstype", uap->type, MNAMELEN);
557	ma = mount_argsu(ma, "fspath", uap->path, MNAMELEN);
558	ma = mount_argb(ma, uap->flags & MNT_RDONLY, "noro");
559	ma = mount_argb(ma, !(uap->flags & MNT_NOSUID), "nosuid");
560	ma = mount_argb(ma, !(uap->flags & MNT_NOEXEC), "noexec");
561
562	error = vfsp->vfc_vfsops->vfs_cmount(ma, uap->data, uap->flags, td);
563	return (error);
564}
565
566
567/*
568 * vfs_domount(): actually attempt a filesystem mount.
569 */
570static int
571vfs_domount(
572	struct thread *td,	/* Flags common to all filesystems. */
573	const char *fstype,	/* Filesystem type. */
574	char *fspath,		/* Mount path. */
575	int fsflags,		/* Flags common to all filesystems. */
576	void *fsdata		/* Options local to the filesystem. */
577	)
578{
579	struct vnode *vp;
580	struct mount *mp;
581	struct vfsconf *vfsp;
582	int error, flag = 0, kern_flag = 0;
583	struct vattr va;
584	struct nameidata nd;
585
586	mtx_assert(&Giant, MA_OWNED);
587
588	/*
589	 * Be ultra-paranoid about making sure the type and fspath
590	 * variables will fit in our mp buffers, including the
591	 * terminating NUL.
592	 */
593	if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
594		return (ENAMETOOLONG);
595
596	if (jailed(td->td_ucred))
597		return (EPERM);
598	if (usermount == 0) {
599		if ((error = suser(td)) != 0)
600			return (error);
601	}
602
603	/*
604	 * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
605	 */
606	if (fsflags & (MNT_EXPORTED | MNT_SUIDDIR)) {
607		if ((error = suser(td)) != 0)
608			return (error);
609	}
610	/*
611	 * Silently enforce MNT_NOSUID and MNT_USER for
612	 * unprivileged users.
613	 */
614	if (suser(td) != 0)
615		fsflags |= MNT_NOSUID | MNT_USER;
616	/*
617	 * Get vnode to be covered
618	 */
619	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, fspath, td);
620	if ((error = namei(&nd)) != 0)
621		return (error);
622	NDFREE(&nd, NDF_ONLY_PNBUF);
623	vp = nd.ni_vp;
624	if (fsflags & MNT_UPDATE) {
625		if ((vp->v_vflag & VV_ROOT) == 0) {
626			vput(vp);
627			return (EINVAL);
628		}
629		mp = vp->v_mount;
630		flag = mp->mnt_flag;
631		kern_flag = mp->mnt_kern_flag;
632		/*
633		 * We only allow the filesystem to be reloaded if it
634		 * is currently mounted read-only.
635		 */
636		if ((fsflags & MNT_RELOAD) &&
637		    ((mp->mnt_flag & MNT_RDONLY) == 0)) {
638			vput(vp);
639			return (EOPNOTSUPP);	/* Needs translation */
640		}
641		/*
642		 * Only privileged root, or (if MNT_USER is set) the user that
643		 * did the original mount is permitted to update it.
644		 */
645		error = vfs_suser(mp, td);
646		if (error) {
647			vput(vp);
648			return (error);
649		}
650		if (vfs_busy(mp, LK_NOWAIT, 0, td)) {
651			vput(vp);
652			return (EBUSY);
653		}
654		VI_LOCK(vp);
655		if ((vp->v_iflag & VI_MOUNT) != 0 ||
656		    vp->v_mountedhere != NULL) {
657			VI_UNLOCK(vp);
658			vfs_unbusy(mp, td);
659			vput(vp);
660			return (EBUSY);
661		}
662		vp->v_iflag |= VI_MOUNT;
663		VI_UNLOCK(vp);
664		mp->mnt_flag |= fsflags &
665		    (MNT_RELOAD | MNT_FORCE | MNT_UPDATE | MNT_SNAPSHOT | MNT_ROOTFS);
666		VOP_UNLOCK(vp, 0, td);
667		mp->mnt_optnew = fsdata;
668		vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
669	} else {
670		/*
671		 * If the user is not root, ensure that they own the directory
672		 * onto which we are attempting to mount.
673		 */
674		error = VOP_GETATTR(vp, &va, td->td_ucred, td);
675		if (error) {
676			vput(vp);
677			return (error);
678		}
679		if (va.va_uid != td->td_ucred->cr_uid) {
680			if ((error = suser(td)) != 0) {
681				vput(vp);
682				return (error);
683			}
684		}
685		error = vinvalbuf(vp, V_SAVE, td->td_ucred, td, 0, 0);
686		if (error != 0) {
687			vput(vp);
688			return (error);
689		}
690		if (vp->v_type != VDIR) {
691			vput(vp);
692			return (ENOTDIR);
693		}
694		vfsp = vfs_byname_kld(fstype, td, &error);
695		if (vfsp == NULL) {
696			vput(vp);
697			return (error);
698		}
699		VI_LOCK(vp);
700		if ((vp->v_iflag & VI_MOUNT) != 0 ||
701		    vp->v_mountedhere != NULL) {
702			VI_UNLOCK(vp);
703			vput(vp);
704			return (EBUSY);
705		}
706		vp->v_iflag |= VI_MOUNT;
707		VI_UNLOCK(vp);
708
709		/*
710		 * Allocate and initialize the filesystem.
711		 */
712		error = vfs_mount_alloc(vp, vfsp, fspath, td, &mp);
713		if (error) {
714			vput(vp);
715			return (error);
716		}
717		VOP_UNLOCK(vp, 0, td);
718
719		/* XXXMAC: pass to vfs_mount_alloc? */
720		mp->mnt_optnew = fsdata;
721	}
722
723	/*
724	 * Set the mount level flags.
725	 */
726	if (fsflags & MNT_RDONLY)
727		mp->mnt_flag |= MNT_RDONLY;
728	mp->mnt_flag &=~ MNT_UPDATEMASK;
729	mp->mnt_flag |= fsflags & (MNT_UPDATEMASK | MNT_FORCE | MNT_ROOTFS);
730	/*
731	 * Mount the filesystem.
732	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
733	 * get.  No freeing of cn_pnbuf.
734	 */
735        error = VFS_MOUNT(mp, td);
736	if (!error) {
737		if (mp->mnt_opt != NULL)
738			vfs_freeopts(mp->mnt_opt);
739		mp->mnt_opt = mp->mnt_optnew;
740		VFS_STATFS(mp, &mp->mnt_stat, td);
741	}
742	/*
743	 * Prevent external consumers of mount options from reading
744	 * mnt_optnew.
745	*/
746	mp->mnt_optnew = NULL;
747	if (mp->mnt_flag & MNT_UPDATE) {
748		mp->mnt_flag &=
749		    ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE | MNT_SNAPSHOT);
750		if (error) {
751			mp->mnt_flag = flag;
752			mp->mnt_kern_flag = kern_flag;
753		}
754		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
755			if (mp->mnt_syncer == NULL)
756				error = vfs_allocate_syncvnode(mp);
757		} else {
758			if (mp->mnt_syncer != NULL)
759				vrele(mp->mnt_syncer);
760			mp->mnt_syncer = NULL;
761		}
762		vfs_unbusy(mp, td);
763		VI_LOCK(vp);
764		vp->v_iflag &= ~VI_MOUNT;
765		VI_UNLOCK(vp);
766		vrele(vp);
767		return (error);
768	}
769	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
770	/*
771	 * Put the new filesystem on the mount list after root.
772	 */
773	cache_purge(vp);
774	if (!error) {
775		struct vnode *newdp;
776
777		VI_LOCK(vp);
778		vp->v_iflag &= ~VI_MOUNT;
779		VI_UNLOCK(vp);
780		vp->v_mountedhere = mp;
781		mtx_lock(&mountlist_mtx);
782		TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
783		mtx_unlock(&mountlist_mtx);
784		vfs_event_signal(NULL, VQ_MOUNT, 0);
785		if (VFS_ROOT(mp, &newdp, td))
786			panic("mount: lost mount");
787		checkdirs(vp, newdp);
788		vput(newdp);
789		VOP_UNLOCK(vp, 0, td);
790		if ((mp->mnt_flag & MNT_RDONLY) == 0)
791			error = vfs_allocate_syncvnode(mp);
792		vfs_unbusy(mp, td);
793		if (error || (error = VFS_START(mp, 0, td)) != 0)
794			vrele(vp);
795	} else {
796		VI_LOCK(vp);
797		vp->v_iflag &= ~VI_MOUNT;
798		VI_UNLOCK(vp);
799		vfs_mount_destroy(mp, td);
800		vput(vp);
801	}
802	return (error);
803}
804
805/*
806 * Scan all active processes to see if any of them have a current
807 * or root directory of `olddp'. If so, replace them with the new
808 * mount point.
809 */
810static void
811checkdirs(olddp, newdp)
812	struct vnode *olddp, *newdp;
813{
814	struct filedesc *fdp;
815	struct proc *p;
816	int nrele;
817
818	if (vrefcnt(olddp) == 1)
819		return;
820	sx_slock(&allproc_lock);
821	LIST_FOREACH(p, &allproc, p_list) {
822		mtx_lock(&fdesc_mtx);
823		fdp = p->p_fd;
824		if (fdp == NULL) {
825			mtx_unlock(&fdesc_mtx);
826			continue;
827		}
828		nrele = 0;
829		FILEDESC_LOCK_FAST(fdp);
830		if (fdp->fd_cdir == olddp) {
831			vref(newdp);
832			fdp->fd_cdir = newdp;
833			nrele++;
834		}
835		if (fdp->fd_rdir == olddp) {
836			vref(newdp);
837			fdp->fd_rdir = newdp;
838			nrele++;
839		}
840		FILEDESC_UNLOCK_FAST(fdp);
841		mtx_unlock(&fdesc_mtx);
842		while (nrele--)
843			vrele(olddp);
844	}
845	sx_sunlock(&allproc_lock);
846	if (rootvnode == olddp) {
847		vrele(rootvnode);
848		vref(newdp);
849		rootvnode = newdp;
850	}
851}
852
853/*
854 * ---------------------------------------------------------------------
855 * Unmount a filesystem.
856 *
857 * Note: unmount takes a path to the vnode mounted on as argument,
858 * not special file (as before).
859 */
860#ifndef _SYS_SYSPROTO_H_
861struct unmount_args {
862	char	*path;
863	int	flags;
864};
865#endif
866/* ARGSUSED */
867int
868unmount(td, uap)
869	struct thread *td;
870	register struct unmount_args /* {
871		char *path;
872		int flags;
873	} */ *uap;
874{
875	struct mount *mp;
876	char *pathbuf;
877	int error, id0, id1;
878
879	if (jailed(td->td_ucred))
880		return (EPERM);
881	if (usermount == 0) {
882		if ((error = suser(td)) != 0)
883			return (error);
884	}
885
886	pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
887	error = copyinstr(uap->path, pathbuf, MNAMELEN, NULL);
888	if (error) {
889		free(pathbuf, M_TEMP);
890		return (error);
891	}
892	if (uap->flags & MNT_BYFSID) {
893		/* Decode the filesystem ID. */
894		if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
895			free(pathbuf, M_TEMP);
896			return (EINVAL);
897		}
898
899		mtx_lock(&mountlist_mtx);
900		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
901			if (mp->mnt_stat.f_fsid.val[0] == id0 &&
902			    mp->mnt_stat.f_fsid.val[1] == id1)
903				break;
904		}
905		mtx_unlock(&mountlist_mtx);
906	} else {
907		mtx_lock(&mountlist_mtx);
908		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
909			if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0)
910				break;
911		}
912		mtx_unlock(&mountlist_mtx);
913	}
914	free(pathbuf, M_TEMP);
915	if (mp == NULL) {
916		/*
917		 * Previously we returned ENOENT for a nonexistent path and
918		 * EINVAL for a non-mountpoint.  We cannot tell these apart
919		 * now, so in the !MNT_BYFSID case return the more likely
920		 * EINVAL for compatibility.
921		 */
922		return ((uap->flags & MNT_BYFSID) ? ENOENT : EINVAL);
923	}
924
925	/*
926	 * Only privileged root, or (if MNT_USER is set) the user that did the
927	 * original mount is permitted to unmount this filesystem.
928	 */
929	error = vfs_suser(mp, td);
930	if (error)
931		return (error);
932
933	/*
934	 * Don't allow unmounting the root filesystem.
935	 */
936	if (mp->mnt_flag & MNT_ROOTFS)
937		return (EINVAL);
938	mtx_lock(&Giant);
939	error = dounmount(mp, uap->flags, td);
940	mtx_unlock(&Giant);
941	return (error);
942}
943
944/*
945 * Do the actual filesystem unmount.
946 */
947int
948dounmount(mp, flags, td)
949	struct mount *mp;
950	int flags;
951	struct thread *td;
952{
953	struct vnode *coveredvp, *fsrootvp;
954	int error;
955	int async_flag;
956
957	mtx_assert(&Giant, MA_OWNED);
958
959	mtx_lock(&mountlist_mtx);
960	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
961		mtx_unlock(&mountlist_mtx);
962		return (EBUSY);
963	}
964	mp->mnt_kern_flag |= MNTK_UNMOUNT;
965	/* Allow filesystems to detect that a forced unmount is in progress. */
966	if (flags & MNT_FORCE)
967		mp->mnt_kern_flag |= MNTK_UNMOUNTF;
968	error = lockmgr(&mp->mnt_lock, LK_DRAIN | LK_INTERLOCK |
969	    ((flags & MNT_FORCE) ? 0 : LK_NOWAIT), &mountlist_mtx, td);
970	if (error) {
971		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
972		if (mp->mnt_kern_flag & MNTK_MWAIT)
973			wakeup(mp);
974		return (error);
975	}
976	vn_start_write(NULL, &mp, V_WAIT);
977
978	if (mp->mnt_flag & MNT_EXPUBLIC)
979		vfs_setpublicfs(NULL, NULL, NULL);
980
981	vfs_msync(mp, MNT_WAIT);
982	async_flag = mp->mnt_flag & MNT_ASYNC;
983	mp->mnt_flag &= ~MNT_ASYNC;
984	cache_purgevfs(mp);	/* remove cache entries for this file sys */
985	if (mp->mnt_syncer != NULL)
986		vrele(mp->mnt_syncer);
987	/*
988	 * For forced unmounts, move process cdir/rdir refs on the fs root
989	 * vnode to the covered vnode.  For non-forced unmounts we want
990	 * such references to cause an EBUSY error.
991	 */
992	if ((flags & MNT_FORCE) && VFS_ROOT(mp, &fsrootvp, td) == 0) {
993		if (mp->mnt_vnodecovered != NULL)
994			checkdirs(fsrootvp, mp->mnt_vnodecovered);
995		if (fsrootvp == rootvnode) {
996			vrele(rootvnode);
997			rootvnode = NULL;
998		}
999		vput(fsrootvp);
1000	}
1001	if (((mp->mnt_flag & MNT_RDONLY) ||
1002	     (error = VFS_SYNC(mp, MNT_WAIT, td->td_ucred, td)) == 0) ||
1003	    (flags & MNT_FORCE)) {
1004		error = VFS_UNMOUNT(mp, flags, td);
1005	}
1006	vn_finished_write(mp);
1007	if (error) {
1008		/* Undo cdir/rdir and rootvnode changes made above. */
1009		if ((flags & MNT_FORCE) && VFS_ROOT(mp, &fsrootvp, td) == 0) {
1010			if (mp->mnt_vnodecovered != NULL)
1011				checkdirs(mp->mnt_vnodecovered, fsrootvp);
1012			if (rootvnode == NULL) {
1013				rootvnode = fsrootvp;
1014				vref(rootvnode);
1015			}
1016			vput(fsrootvp);
1017		}
1018		if ((mp->mnt_flag & MNT_RDONLY) == 0 && mp->mnt_syncer == NULL)
1019			(void) vfs_allocate_syncvnode(mp);
1020		mtx_lock(&mountlist_mtx);
1021		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
1022		mp->mnt_flag |= async_flag;
1023		lockmgr(&mp->mnt_lock, LK_RELEASE | LK_INTERLOCK,
1024		    &mountlist_mtx, td);
1025		if (mp->mnt_kern_flag & MNTK_MWAIT)
1026			wakeup(mp);
1027		return (error);
1028	}
1029	mtx_lock(&mountlist_mtx);
1030	TAILQ_REMOVE(&mountlist, mp, mnt_list);
1031	if ((coveredvp = mp->mnt_vnodecovered) != NULL)
1032		coveredvp->v_mountedhere = NULL;
1033	mtx_unlock(&mountlist_mtx);
1034	vfs_event_signal(NULL, VQ_UNMOUNT, 0);
1035	vfs_mount_destroy(mp, td);
1036	if (coveredvp != NULL)
1037		vrele(coveredvp);
1038	return (0);
1039}
1040
1041/*
1042 * ---------------------------------------------------------------------
1043 * Mounting of root filesystem
1044 *
1045 */
1046
1047static void
1048set_rootvnode(struct thread *td)
1049{
1050	struct proc *p;
1051
1052	if (VFS_ROOT(TAILQ_FIRST(&mountlist), &rootvnode, td))
1053		panic("Cannot find root vnode");
1054
1055	p = td->td_proc;
1056	FILEDESC_LOCK(p->p_fd);
1057
1058	if (p->p_fd->fd_cdir != NULL)
1059		vrele(p->p_fd->fd_cdir);
1060	p->p_fd->fd_cdir = rootvnode;
1061	VREF(rootvnode);
1062
1063	if (p->p_fd->fd_rdir != NULL)
1064		vrele(p->p_fd->fd_rdir);
1065	p->p_fd->fd_rdir = rootvnode;
1066	VREF(rootvnode);
1067
1068	FILEDESC_UNLOCK(p->p_fd);
1069
1070	VOP_UNLOCK(rootvnode, 0, td);
1071}
1072
1073/*
1074 * Mount /devfs as our root filesystem, but do not put it on the mountlist
1075 * yet.  Create a /dev -> / symlink so that absolute pathnames will lookup.
1076 */
1077
1078static struct mount *
1079devfs_first(void)
1080{
1081	struct thread *td = curthread;
1082	struct vfsconf *vfsp;
1083	struct mount *mp = NULL;
1084	int error;
1085
1086	vfsp = vfs_byname("devfs");
1087	KASSERT(vfsp != NULL, ("Could not find devfs by name"));
1088	if (vfsp == NULL)
1089		return(NULL);
1090
1091	error = vfs_mount_alloc(NULLVP, vfsp, "/dev", td, &mp);
1092	KASSERT(error == 0, ("vfs_mount_alloc failed %d", error));
1093	if (error)
1094		return (NULL);
1095
1096	error = VFS_MOUNT(mp, curthread);
1097	KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
1098	if (error)
1099		return (NULL);
1100
1101	VFS_START(mp, 0, td);
1102
1103	mtx_lock(&mountlist_mtx);
1104	TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
1105	mtx_unlock(&mountlist_mtx);
1106
1107	set_rootvnode(td);
1108
1109	error = kern_symlink(td, "/", "dev", UIO_SYSSPACE);
1110	printf("kern_symlink  = %d\n", error);
1111
1112	return (mp);
1113}
1114
1115/*
1116 * Surgically move our devfs to be mounted on /dev.
1117 */
1118
1119static void
1120devfs_fixup(struct thread *td)
1121{
1122	struct nameidata nd;
1123	int error;
1124	struct vnode *vp, *dvp;
1125	struct mount *mp;
1126
1127	/* Remove our devfs mount from the mountlist and purge the cache */
1128	mtx_lock(&mountlist_mtx);
1129	mp = TAILQ_FIRST(&mountlist);
1130	TAILQ_REMOVE(&mountlist, mp, mnt_list);
1131	mtx_unlock(&mountlist_mtx);
1132	cache_purgevfs(mp);
1133
1134	VFS_ROOT(mp, &dvp, td);
1135	VI_LOCK(dvp);
1136	dvp->v_iflag &= ~VI_MOUNT;
1137	dvp->v_mountedhere = NULL;
1138	VI_UNLOCK(dvp);
1139
1140	/* Set up the real rootvnode, and purge the cache */
1141	TAILQ_FIRST(&mountlist)->mnt_vnodecovered = NULL;
1142	set_rootvnode(td);
1143	cache_purgevfs(rootvnode->v_mount);
1144
1145
1146#if 0
1147	/* We may have a chance... */
1148	error = kern_mkdir(td, "/dev", UIO_SYSSPACE, 0700);
1149	printf("kern_mkdir = %d\n", error);
1150#endif
1151
1152	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
1153	error = namei(&nd);
1154	if (error) {
1155		printf("Lookup /dev -> %d\n", error);
1156		return;
1157	}
1158	NDFREE(&nd, NDF_ONLY_PNBUF);
1159	vp = nd.ni_vp;
1160	if (vp->v_type != VDIR) {
1161		vput(vp);
1162	}
1163	error = vinvalbuf(vp, V_SAVE, td->td_ucred, td, 0, 0);
1164	if (error) {
1165		vput(vp);
1166	}
1167	cache_purge(vp);
1168	mp->mnt_vnodecovered = vp;
1169	vp->v_mountedhere = mp;
1170	mtx_lock(&mountlist_mtx);
1171	TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1172	mtx_unlock(&mountlist_mtx);
1173	VOP_UNLOCK(vp, 0, td);
1174	vfs_unbusy(mp, td);
1175	VREF(vp);
1176	vput(vp);
1177	vput(dvp);
1178
1179	/* Unlink the no longer needed /dev/dev -> / symlink */
1180	 kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
1181}
1182
1183/*
1184 * Find and mount the root filesystem
1185 */
1186void
1187vfs_mountroot(void)
1188{
1189	char *cp;
1190	int error, i, asked = 0;
1191	struct mount *mp;
1192
1193	/*
1194	 * Wait for GEOM to settle down
1195	 */
1196	DROP_GIANT();
1197	g_waitidle();
1198	PICKUP_GIANT();
1199
1200	mp = devfs_first();
1201
1202	/*
1203	 * We are booted with instructions to prompt for the root filesystem.
1204	 */
1205	if (boothowto & RB_ASKNAME) {
1206		if (!vfs_mountroot_ask())
1207			return;
1208		asked = 1;
1209	}
1210
1211	/*
1212	 * The root filesystem information is compiled in, and we are
1213	 * booted with instructions to use it.
1214	 */
1215	if (ctrootdevname != NULL && (boothowto & RB_DFLTROOT)) {
1216		if (!vfs_mountroot_try(ctrootdevname))
1217			return;
1218		ctrootdevname = NULL;
1219	}
1220
1221	/*
1222	 * We've been given the generic "use CDROM as root" flag.  This is
1223	 * necessary because one media may be used in many different
1224	 * devices, so we need to search for them.
1225	 */
1226	if (boothowto & RB_CDROM) {
1227		for (i = 0; cdrom_rootdevnames[i] != NULL; i++) {
1228			if (!vfs_mountroot_try(cdrom_rootdevnames[i]))
1229				return;
1230		}
1231	}
1232
1233	/*
1234	 * Try to use the value read by the loader from /etc/fstab, or
1235	 * supplied via some other means.  This is the preferred
1236	 * mechanism.
1237	 */
1238	cp = getenv("vfs.root.mountfrom");
1239	if (cp != NULL) {
1240		error = vfs_mountroot_try(cp);
1241		freeenv(cp);
1242		if (!error)
1243			return;
1244	}
1245
1246	/*
1247	 * Try values that may have been computed by code during boot
1248	 */
1249	if (!vfs_mountroot_try(rootdevnames[0]))
1250		return;
1251	if (!vfs_mountroot_try(rootdevnames[1]))
1252		return;
1253
1254	/*
1255	 * If we (still) have a compiled-in default, try it.
1256	 */
1257	if (ctrootdevname != NULL)
1258		if (!vfs_mountroot_try(ctrootdevname))
1259			return;
1260	/*
1261	 * Everything so far has failed, prompt on the console if we haven't
1262	 * already tried that.
1263	 */
1264	if (!asked)
1265		if (!vfs_mountroot_ask())
1266			return;
1267
1268	panic("Root mount failed, startup aborted.");
1269}
1270
1271/*
1272 * Mount (mountfrom) as the root filesystem.
1273 */
1274static int
1275vfs_mountroot_try(const char *mountfrom)
1276{
1277        struct mount	*mp;
1278	char		*vfsname, *path;
1279	int		error;
1280	char		patt[32];
1281	int		s;
1282
1283	vfsname = NULL;
1284	path    = NULL;
1285	mp      = NULL;
1286	error   = EINVAL;
1287
1288	if (mountfrom == NULL)
1289		return (error);		/* don't complain */
1290
1291	s = splcam();			/* Overkill, but annoying without it */
1292	printf("Trying to mount root from %s\n", mountfrom);
1293	splx(s);
1294
1295	/* parse vfs name and path */
1296	vfsname = malloc(MFSNAMELEN, M_MOUNT, M_WAITOK);
1297	path = malloc(MNAMELEN, M_MOUNT, M_WAITOK);
1298	vfsname[0] = path[0] = 0;
1299	sprintf(patt, "%%%d[a-z0-9]:%%%ds", MFSNAMELEN, MNAMELEN);
1300	if (sscanf(mountfrom, patt, vfsname, path) < 1)
1301		return (error);
1302
1303	if (path[0] == '\0')
1304		strcpy(path, ROOTNAME);
1305
1306	error = kernel_vmount(
1307	    MNT_RDONLY | MNT_ROOTFS,
1308	    "fstype", vfsname,
1309	    "fspath", "/",
1310	    "from", path,
1311	    NULL);
1312	printf("kernel_vmount = %d\n", error);
1313	if (error == 0) {
1314		mp = TAILQ_FIRST(&mountlist);
1315
1316		/* sanity check system clock against root fs timestamp */
1317		inittodr(mp->mnt_time);
1318		vfs_unbusy(mp, curthread);
1319		error = VFS_START(mp, 0, curthread);
1320
1321		devfs_fixup(curthread);
1322	}
1323	return (error);
1324}
1325
1326/*
1327 * ---------------------------------------------------------------------
1328 * Interactive root filesystem selection code.
1329 */
1330
1331static int
1332vfs_mountroot_ask(void)
1333{
1334	char name[128];
1335
1336	for(;;) {
1337		printf("\nManual root filesystem specification:\n");
1338		printf("  <fstype>:<device>  Mount <device> using filesystem <fstype>\n");
1339#if defined(__i386__) || defined(__ia64__)
1340		printf("                       eg. ufs:da0s1a\n");
1341#else
1342		printf("                       eg. ufs:/dev/da0a\n");
1343#endif
1344		printf("  ?                  List valid disk boot devices\n");
1345		printf("  <empty line>       Abort manual input\n");
1346		printf("\nmountroot> ");
1347		gets(name);
1348		if (name[0] == '\0')
1349			return (1);
1350		if (name[0] == '?') {
1351			printf("\nList of GEOM managed disk devices:\n  ");
1352			g_dev_print();
1353			continue;
1354		}
1355		if (!vfs_mountroot_try(name))
1356			return (0);
1357	}
1358}
1359
1360/*
1361 * Local helper function for vfs_mountroot_ask.
1362 */
1363static void
1364gets(char *cp)
1365{
1366	char *lp;
1367	int c;
1368
1369	lp = cp;
1370	for (;;) {
1371		printf("%c", c = cngetc() & 0177);
1372		switch (c) {
1373		case -1:
1374		case '\n':
1375		case '\r':
1376			*lp++ = '\0';
1377			return;
1378		case '\b':
1379		case '\177':
1380			if (lp > cp) {
1381				printf(" \b");
1382				lp--;
1383			}
1384			continue;
1385		case '#':
1386			lp--;
1387			if (lp < cp)
1388				lp = cp;
1389			continue;
1390		case '@':
1391		case 'u' & 037:
1392			lp = cp;
1393			printf("%c", '\n');
1394			continue;
1395		default:
1396			*lp++ = c;
1397		}
1398	}
1399}
1400
1401/*
1402 * ---------------------------------------------------------------------
1403 * Functions for querying mount options/arguments from filesystems.
1404 */
1405
1406/*
1407 * Check that no unknown options are given
1408 */
1409int
1410vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1411{
1412	struct vfsopt *opt;
1413	const char **t, *p;
1414
1415
1416	TAILQ_FOREACH(opt, opts, link) {
1417		p = opt->name;
1418		if (p[0] == 'n' && p[1] == 'o')
1419			p += 2;
1420		for(t = global_opts; *t != NULL; t++)
1421			if (!strcmp(*t, p))
1422				break;
1423		if (*t != NULL)
1424			continue;
1425		for(t = legal; *t != NULL; t++)
1426			if (!strcmp(*t, p))
1427				break;
1428		if (*t != NULL)
1429			continue;
1430		printf("mount option <%s> is unknown\n", p);
1431		return (EINVAL);
1432	}
1433	return (0);
1434}
1435
1436/*
1437 * Get a mount option by its name.
1438 *
1439 * Return 0 if the option was found, ENOENT otherwise.
1440 * If len is non-NULL it will be filled with the length
1441 * of the option. If buf is non-NULL, it will be filled
1442 * with the address of the option.
1443 */
1444int
1445vfs_getopt(opts, name, buf, len)
1446	struct vfsoptlist *opts;
1447	const char *name;
1448	void **buf;
1449	int *len;
1450{
1451	struct vfsopt *opt;
1452
1453	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1454
1455	TAILQ_FOREACH(opt, opts, link) {
1456		if (strcmp(name, opt->name) == 0) {
1457			if (len != NULL)
1458				*len = opt->len;
1459			if (buf != NULL)
1460				*buf = opt->value;
1461			return (0);
1462		}
1463	}
1464	return (ENOENT);
1465}
1466
1467char *
1468vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
1469{
1470	struct vfsopt *opt;
1471
1472	*error = 0;
1473	TAILQ_FOREACH(opt, opts, link) {
1474		if (strcmp(name, opt->name) != 0)
1475			continue;
1476		if (((char *)opt->value)[opt->len - 1] != '\0') {
1477			*error = EINVAL;
1478			return (NULL);
1479		}
1480		return (opt->value);
1481	}
1482	return (NULL);
1483}
1484
1485int
1486vfs_flagopt(struct vfsoptlist *opts, const char *name, u_int *w, u_int val)
1487{
1488	struct vfsopt *opt;
1489
1490	TAILQ_FOREACH(opt, opts, link) {
1491		if (strcmp(name, opt->name) == 0) {
1492			if (w != NULL)
1493				*w |= val;
1494			return (1);
1495		}
1496	}
1497	if (w != NULL)
1498		*w &= ~val;
1499	return (0);
1500}
1501
1502int
1503vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
1504{
1505	va_list ap;
1506	struct vfsopt *opt;
1507	int ret;
1508
1509	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1510
1511	TAILQ_FOREACH(opt, opts, link) {
1512		if (strcmp(name, opt->name) != 0)
1513			continue;
1514		if (((char *)opt->value)[opt->len - 1] != '\0')
1515			return (0);
1516		va_start(ap, fmt);
1517		ret = vsscanf(opt->value, fmt, ap);
1518		va_end(ap);
1519		return (ret);
1520	}
1521	return (0);
1522}
1523
1524/*
1525 * Find and copy a mount option.
1526 *
1527 * The size of the buffer has to be specified
1528 * in len, if it is not the same length as the
1529 * mount option, EINVAL is returned.
1530 * Returns ENOENT if the option is not found.
1531 */
1532int
1533vfs_copyopt(opts, name, dest, len)
1534	struct vfsoptlist *opts;
1535	const char *name;
1536	void *dest;
1537	int len;
1538{
1539	struct vfsopt *opt;
1540
1541	KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
1542
1543	TAILQ_FOREACH(opt, opts, link) {
1544		if (strcmp(name, opt->name) == 0) {
1545			if (len != opt->len)
1546				return (EINVAL);
1547			bcopy(opt->value, dest, opt->len);
1548			return (0);
1549		}
1550	}
1551	return (ENOENT);
1552}
1553
1554/*
1555 * This is a helper function for filesystems to traverse their
1556 * vnodes.  See MNT_VNODE_FOREACH() in sys/mount.h
1557 */
1558
1559struct vnode *
1560__mnt_vnode_next(struct vnode **nvp, struct mount *mp)
1561{
1562	struct vnode *vp;
1563
1564	mtx_assert(&mp->mnt_mtx, MA_OWNED);
1565
1566	vp = *nvp;
1567	/* Check if we are done */
1568	if (vp == NULL)
1569		return (NULL);
1570	/* If our next vnode is no longer ours, start over */
1571	if (vp->v_mount != mp)
1572		vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
1573	/* Save pointer to next vnode in list */
1574	if (vp != NULL)
1575		*nvp = TAILQ_NEXT(vp, v_nmntvnodes);
1576	else
1577		*nvp = NULL;
1578	return (vp);
1579}
1580
1581int
1582__vfs_statfs(struct mount *mp, struct statfs *sbp, struct thread *td)
1583{
1584	int error;
1585
1586	error = mp->mnt_op->vfs_statfs(mp, &mp->mnt_stat, td);
1587	if (sbp != &mp->mnt_stat)
1588		memcpy(sbp, &mp->mnt_stat, sizeof sbp);
1589	return (error);
1590}
1591
1592void
1593vfs_mountedfrom(struct mount *mp, const char *from)
1594{
1595
1596	bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
1597	strlcpy(mp->mnt_stat.f_mntfromname, from,
1598	    sizeof mp->mnt_stat.f_mntfromname);
1599}
1600
1601/*
1602 * ---------------------------------------------------------------------
1603 * This is the api for building mount args and mounting filesystems from
1604 * inside the kernel.
1605 *
1606 * The API works by accumulation of individual args.  First error is
1607 * latched.
1608 *
1609 * XXX: should be documented in new manpage kernel_mount(9)
1610 */
1611
1612/* A memory allocation which must be freed when we are done */
1613struct mntaarg {
1614	SLIST_ENTRY(mntaarg)	next;
1615};
1616
1617/* The header for the mount arguments */
1618struct mntarg {
1619	struct iovec *v;
1620	int len;
1621	int error;
1622	SLIST_HEAD(, mntaarg)	list;
1623};
1624
1625/*
1626 * Add a boolean argument.
1627 *
1628 * flag is the boolean value.
1629 * name must start with "no".
1630 */
1631struct mntarg *
1632mount_argb(struct mntarg *ma, int flag, const char *name)
1633{
1634
1635	KASSERT(name[0] == 'n' && name[1] == 'o',
1636	    ("mount_argb(...,%s): name must start with 'no'", name));
1637
1638	return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
1639}
1640
1641/*
1642 * Add an argument printf style
1643 */
1644struct mntarg *
1645mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
1646{
1647	va_list ap;
1648	struct mntaarg *maa;
1649	struct sbuf *sb;
1650	int len;
1651
1652	if (ma == NULL) {
1653		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
1654		SLIST_INIT(&ma->list);
1655	}
1656	if (ma->error)
1657		return (ma);
1658
1659	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
1660	    M_MOUNT, M_WAITOK);
1661	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
1662	ma->v[ma->len].iov_len = strlen(name) + 1;
1663	ma->len++;
1664
1665	sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
1666	va_start(ap, fmt);
1667	sbuf_vprintf(sb, fmt, ap);
1668	va_end(ap);
1669	sbuf_finish(sb);
1670	len = sbuf_len(sb) + 1;
1671	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
1672	SLIST_INSERT_HEAD(&ma->list, maa, next);
1673	bcopy(sbuf_data(sb), maa + 1, len);
1674	sbuf_delete(sb);
1675
1676	ma->v[ma->len].iov_base = maa + 1;
1677	ma->v[ma->len].iov_len = len;
1678	ma->len++;
1679
1680	return (ma);
1681}
1682
1683/*
1684 * Add an argument which is a userland string.
1685 */
1686struct mntarg *
1687mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
1688{
1689	struct mntaarg *maa;
1690	char *tbuf;
1691
1692	if (val == NULL)
1693		return (ma);
1694	if (ma == NULL) {
1695		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
1696		SLIST_INIT(&ma->list);
1697	}
1698	if (ma->error)
1699		return (ma);
1700	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
1701	SLIST_INSERT_HEAD(&ma->list, maa, next);
1702	tbuf = (void *)(maa + 1);
1703	ma->error = copyinstr(val, tbuf, len, NULL);
1704	return (mount_arg(ma, name, tbuf, -1));
1705}
1706
1707/*
1708 * Plain argument.
1709 *
1710 * If length is -1, use printf.
1711 */
1712struct mntarg *
1713mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
1714{
1715
1716	if (ma == NULL) {
1717		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
1718		SLIST_INIT(&ma->list);
1719	}
1720	if (ma->error)
1721		return (ma);
1722
1723	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
1724	    M_MOUNT, M_WAITOK);
1725	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
1726	ma->v[ma->len].iov_len = strlen(name) + 1;
1727	ma->len++;
1728
1729	ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
1730	if (len < 0)
1731		ma->v[ma->len].iov_len = strlen(val) + 1;
1732	else
1733		ma->v[ma->len].iov_len = len;
1734	ma->len++;
1735	return (ma);
1736}
1737
1738/*
1739 * Free a mntarg structure
1740 */
1741void
1742free_mntarg(struct mntarg *ma)
1743{
1744	struct mntaarg *maa;
1745
1746	while (!SLIST_EMPTY(&ma->list)) {
1747		maa = SLIST_FIRST(&ma->list);
1748		SLIST_REMOVE_HEAD(&ma->list, next);
1749		free(maa, M_MOUNT);
1750	}
1751	free(ma->v, M_MOUNT);
1752	free(ma, M_MOUNT);
1753}
1754
1755/*
1756 * Mount a filesystem
1757 */
1758int
1759kernel_mount(struct mntarg *ma, int flags)
1760{
1761	struct uio auio;
1762	int error;
1763
1764	KASSERT(ma != NULL, ("kernel_mount NULL ma"));
1765	KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
1766	KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
1767
1768	auio.uio_iov = ma->v;
1769	auio.uio_iovcnt = ma->len;
1770	auio.uio_segflg = UIO_SYSSPACE;
1771
1772	error = ma->error;
1773	if (!error)
1774		error = vfs_donmount(curthread, flags, &auio);
1775	free_mntarg(ma);
1776	return (error);
1777}
1778
1779/*
1780 * A printflike function to mount a filesystem.
1781 */
1782int
1783kernel_vmount(int flags, ...)
1784{
1785	struct mntarg *ma = NULL;
1786	va_list ap;
1787	const char *cp;
1788	const void *vp;
1789	int error;
1790
1791	va_start(ap, flags);
1792	for (;;) {
1793		cp = va_arg(ap, const char *);
1794		if (cp == NULL)
1795			break;
1796		vp = va_arg(ap, const void *);
1797		ma = mount_arg(ma, cp, vp, -1);
1798	}
1799	va_end(ap);
1800
1801	error = kernel_mount(ma, flags);
1802	return (error);
1803}
1804