xref: /freebsd/sys/kern/vfs_mount.c (revision ceaec73d406831b1251babb61675df0a1aa54a31)
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$");
39 
40 #include <sys/param.h>
41 #include <sys/conf.h>
42 #include <sys/jail.h>
43 #include <sys/kernel.h>
44 #include <sys/libkern.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 
76 static int	vfs_domount(struct thread *td, const char *fstype,
77 		    char *fspath, int fsflags, void *fsdata);
78 static int	vfs_mount_alloc(struct vnode *dvp, struct vfsconf *vfsp,
79 		    const char *fspath, struct thread *td, struct mount **mpp);
80 static int	vfs_mountroot_ask(void);
81 static int	vfs_mountroot_try(const char *mountfrom);
82 static int	vfs_donmount(struct thread *td, int fsflags,
83 		    struct uio *fsoptions);
84 static void	free_mntarg(struct mntarg *ma);
85 static void	vfs_mount_destroy(struct mount *, struct thread *);
86 
87 static int	usermount = 0;
88 SYSCTL_INT(_vfs, OID_AUTO, usermount, CTLFLAG_RW, &usermount, 0,
89     "Unprivileged users may mount and unmount file systems");
90 
91 MALLOC_DEFINE(M_MOUNT, "mount", "vfs mount structure");
92 
93 /* List of mounted filesystems. */
94 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
95 
96 /* For any iteration/modification of mountlist */
97 struct mtx mountlist_mtx;
98 
99 TAILQ_HEAD(vfsoptlist, vfsopt);
100 struct 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  */
111 struct 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  */
127 static 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  */
139 static char *cdrom_rootdevnames[] = {
140 	"cd9660:cd0",
141 	"cd9660:acd0",
142 	NULL
143 };
144 
145 /* legacy find-root code */
146 char		*rootdevnames[2] = {NULL, NULL};
147 #ifndef ROOTDEVNAME
148 #  define ROOTDEVNAME NULL
149 #endif
150 static const char	*ctrootdevname = ROOTDEVNAME;
151 
152 /*
153  * ---------------------------------------------------------------------
154  * Functions for building and sanitizing the mount options
155  */
156 
157 /* Remove one mount option. */
158 static void
159 vfs_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. */
175 static void
176 vfs_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  */
190 static int
191 vfs_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  */
211 static void
212 vfs_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  */
233 static int
234 vfs_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);
302 bad:
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  */
311 static void
312 vfs_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);
344 next:
345 		continue;
346 	}
347 }
348 
349 /*
350  * ---------------------------------------------------------------------
351  * Mount a filesystem
352  */
353 int
354 nmount(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  */
404 static int
405 vfs_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, 0);
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 	arc4rand(&mp->mnt_hashseed, sizeof mp->mnt_hashseed, 0);
432 	*mpp = mp;
433 	return (0);
434 }
435 
436 /*
437  * Destroy the mount struct previously allocated by vfs_mount_alloc().
438  */
439 static void
440 vfs_mount_destroy(struct mount *mp, struct thread *td)
441 {
442 
443 	mp->mnt_vfc->vfc_refcount--;
444 	if (!TAILQ_EMPTY(&mp->mnt_nvnodelist))
445 		panic("unmount: dangling vnode");
446 	vfs_unbusy(mp,td);
447 	lockdestroy(&mp->mnt_lock);
448 	MNT_ILOCK(mp);
449 	if (mp->mnt_kern_flag & MNTK_MWAIT)
450 		wakeup(mp);
451 	MNT_IUNLOCK(mp);
452 	mtx_destroy(&mp->mnt_mtx);
453 #ifdef MAC
454 	mac_destroy_mount(mp);
455 #endif
456 	if (mp->mnt_opt != NULL)
457 		vfs_freeopts(mp->mnt_opt);
458 	crfree(mp->mnt_cred);
459 	free(mp, M_MOUNT);
460 }
461 
462 static int
463 vfs_donmount(struct thread *td, int fsflags, struct uio *fsoptions)
464 {
465 	struct vfsoptlist *optlist;
466 	char *fstype, *fspath;
467 	int error, fstypelen, fspathlen;
468 
469 	error = vfs_buildopts(fsoptions, &optlist);
470 	if (error)
471 		return (error);
472 
473 	/*
474 	 * We need these two options before the others,
475 	 * and they are mandatory for any filesystem.
476 	 * Ensure they are NUL terminated as well.
477 	 */
478 	fstypelen = 0;
479 	error = vfs_getopt(optlist, "fstype", (void **)&fstype, &fstypelen);
480 	if (error || fstype[fstypelen - 1] != '\0') {
481 		error = EINVAL;
482 		goto bail;
483 	}
484 	fspathlen = 0;
485 	error = vfs_getopt(optlist, "fspath", (void **)&fspath, &fspathlen);
486 	if (error || fspath[fspathlen - 1] != '\0') {
487 		error = EINVAL;
488 		goto bail;
489 	}
490 
491 	/*
492 	 * Be ultra-paranoid about making sure the type and fspath
493 	 * variables will fit in our mp buffers, including the
494 	 * terminating NUL.
495 	 */
496 	if (fstypelen >= MFSNAMELEN - 1 || fspathlen >= MNAMELEN - 1) {
497 		error = ENAMETOOLONG;
498 		goto bail;
499 	}
500 
501 	mtx_lock(&Giant);
502 	error = vfs_domount(td, fstype, fspath, fsflags, optlist);
503 	mtx_unlock(&Giant);
504 bail:
505 	if (error)
506 		vfs_freeopts(optlist);
507 	return (error);
508 }
509 
510 /*
511  * ---------------------------------------------------------------------
512  * Old mount API.
513  */
514 #ifndef _SYS_SYSPROTO_H_
515 struct mount_args {
516 	char	*type;
517 	char	*path;
518 	int	flags;
519 	caddr_t	data;
520 };
521 #endif
522 /* ARGSUSED */
523 int
524 mount(td, uap)
525 	struct thread *td;
526 	struct mount_args /* {
527 		char *type;
528 		char *path;
529 		int flags;
530 		caddr_t data;
531 	} */ *uap;
532 {
533 	char *fstype;
534 	struct vfsconf *vfsp = NULL;
535 	struct mntarg *ma = NULL;
536 	int error;
537 
538 	/* Kick out MNT_ROOTFS early as it is legal internally */
539 	uap->flags &= ~MNT_ROOTFS;
540 
541 	if (uap->data == NULL)
542 		return (EINVAL);
543 
544 	fstype = malloc(MFSNAMELEN, M_TEMP, M_WAITOK);
545 	error = copyinstr(uap->type, fstype, MFSNAMELEN, NULL);
546 	if (!error) {
547 		mtx_lock(&Giant);	/* XXX ? */
548 		vfsp = vfs_byname_kld(fstype, td, &error);
549 		mtx_unlock(&Giant);
550 	}
551 	free(fstype, M_TEMP);
552 	if (error)
553 		return (error);
554 	if (vfsp == NULL)
555 		return (ENOENT);
556 	if (vfsp->vfc_vfsops->vfs_cmount == NULL)
557 		return (EOPNOTSUPP);
558 
559 	ma = mount_argsu(ma, "fstype", uap->type, MNAMELEN);
560 	ma = mount_argsu(ma, "fspath", uap->path, MNAMELEN);
561 	ma = mount_argb(ma, uap->flags & MNT_RDONLY, "noro");
562 	ma = mount_argb(ma, !(uap->flags & MNT_NOSUID), "nosuid");
563 	ma = mount_argb(ma, !(uap->flags & MNT_NOEXEC), "noexec");
564 
565 	error = vfsp->vfc_vfsops->vfs_cmount(ma, uap->data, uap->flags, td);
566 	return (error);
567 }
568 
569 
570 /*
571  * vfs_domount(): actually attempt a filesystem mount.
572  */
573 static int
574 vfs_domount(
575 	struct thread *td,	/* Flags common to all filesystems. */
576 	const char *fstype,	/* Filesystem type. */
577 	char *fspath,		/* Mount path. */
578 	int fsflags,		/* Flags common to all filesystems. */
579 	void *fsdata		/* Options local to the filesystem. */
580 	)
581 {
582 	struct vnode *vp;
583 	struct mount *mp;
584 	struct vfsconf *vfsp;
585 	int error, flag = 0, kern_flag = 0;
586 	struct vattr va;
587 	struct nameidata nd;
588 
589 	mtx_assert(&Giant, MA_OWNED);
590 
591 	/*
592 	 * Be ultra-paranoid about making sure the type and fspath
593 	 * variables will fit in our mp buffers, including the
594 	 * terminating NUL.
595 	 */
596 	if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
597 		return (ENAMETOOLONG);
598 
599 	if (jailed(td->td_ucred))
600 		return (EPERM);
601 	if (usermount == 0) {
602 		if ((error = suser(td)) != 0)
603 			return (error);
604 	}
605 
606 	/*
607 	 * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
608 	 */
609 	if (fsflags & (MNT_EXPORTED | MNT_SUIDDIR)) {
610 		if ((error = suser(td)) != 0)
611 			return (error);
612 	}
613 	/*
614 	 * Silently enforce MNT_NOSUID and MNT_USER for
615 	 * unprivileged users.
616 	 */
617 	if (suser(td) != 0)
618 		fsflags |= MNT_NOSUID | MNT_USER;
619 	/*
620 	 * Get vnode to be covered
621 	 */
622 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, fspath, td);
623 	if ((error = namei(&nd)) != 0)
624 		return (error);
625 	NDFREE(&nd, NDF_ONLY_PNBUF);
626 	vp = nd.ni_vp;
627 	if (fsflags & MNT_UPDATE) {
628 		if ((vp->v_vflag & VV_ROOT) == 0) {
629 			vput(vp);
630 			return (EINVAL);
631 		}
632 		mp = vp->v_mount;
633 		flag = mp->mnt_flag;
634 		kern_flag = mp->mnt_kern_flag;
635 		/*
636 		 * We only allow the filesystem to be reloaded if it
637 		 * is currently mounted read-only.
638 		 */
639 		if ((fsflags & MNT_RELOAD) &&
640 		    ((mp->mnt_flag & MNT_RDONLY) == 0)) {
641 			vput(vp);
642 			return (EOPNOTSUPP);	/* Needs translation */
643 		}
644 		/*
645 		 * Only privileged root, or (if MNT_USER is set) the user that
646 		 * did the original mount is permitted to update it.
647 		 */
648 		error = vfs_suser(mp, td);
649 		if (error) {
650 			vput(vp);
651 			return (error);
652 		}
653 		if (vfs_busy(mp, LK_NOWAIT, 0, td)) {
654 			vput(vp);
655 			return (EBUSY);
656 		}
657 		VI_LOCK(vp);
658 		if ((vp->v_iflag & VI_MOUNT) != 0 ||
659 		    vp->v_mountedhere != NULL) {
660 			VI_UNLOCK(vp);
661 			vfs_unbusy(mp, td);
662 			vput(vp);
663 			return (EBUSY);
664 		}
665 		vp->v_iflag |= VI_MOUNT;
666 		VI_UNLOCK(vp);
667 		mp->mnt_flag |= fsflags &
668 		    (MNT_RELOAD | MNT_FORCE | MNT_UPDATE | MNT_SNAPSHOT | MNT_ROOTFS);
669 		VOP_UNLOCK(vp, 0, td);
670 		mp->mnt_optnew = fsdata;
671 		vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
672 	} else {
673 		/*
674 		 * If the user is not root, ensure that they own the directory
675 		 * onto which we are attempting to mount.
676 		 */
677 		error = VOP_GETATTR(vp, &va, td->td_ucred, td);
678 		if (error) {
679 			vput(vp);
680 			return (error);
681 		}
682 		if (va.va_uid != td->td_ucred->cr_uid) {
683 			if ((error = suser(td)) != 0) {
684 				vput(vp);
685 				return (error);
686 			}
687 		}
688 		error = vinvalbuf(vp, V_SAVE, td, 0, 0);
689 		if (error != 0) {
690 			vput(vp);
691 			return (error);
692 		}
693 		if (vp->v_type != VDIR) {
694 			vput(vp);
695 			return (ENOTDIR);
696 		}
697 		vfsp = vfs_byname_kld(fstype, td, &error);
698 		if (vfsp == NULL) {
699 			vput(vp);
700 			return (error);
701 		}
702 		VI_LOCK(vp);
703 		if ((vp->v_iflag & VI_MOUNT) != 0 ||
704 		    vp->v_mountedhere != NULL) {
705 			VI_UNLOCK(vp);
706 			vput(vp);
707 			return (EBUSY);
708 		}
709 		vp->v_iflag |= VI_MOUNT;
710 		VI_UNLOCK(vp);
711 
712 		/*
713 		 * Allocate and initialize the filesystem.
714 		 */
715 		error = vfs_mount_alloc(vp, vfsp, fspath, td, &mp);
716 		if (error) {
717 			vput(vp);
718 			return (error);
719 		}
720 		VOP_UNLOCK(vp, 0, td);
721 
722 		/* XXXMAC: pass to vfs_mount_alloc? */
723 		mp->mnt_optnew = fsdata;
724 	}
725 
726 	/*
727 	 * Set the mount level flags.
728 	 */
729 	if (fsflags & MNT_RDONLY)
730 		mp->mnt_flag |= MNT_RDONLY;
731 	mp->mnt_flag &=~ MNT_UPDATEMASK;
732 	mp->mnt_flag |= fsflags & (MNT_UPDATEMASK | MNT_FORCE | MNT_ROOTFS);
733 	/*
734 	 * Mount the filesystem.
735 	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
736 	 * get.  No freeing of cn_pnbuf.
737 	 */
738         error = VFS_MOUNT(mp, td);
739 	if (!error) {
740 		if (mp->mnt_opt != NULL)
741 			vfs_freeopts(mp->mnt_opt);
742 		mp->mnt_opt = mp->mnt_optnew;
743 		VFS_STATFS(mp, &mp->mnt_stat, td);
744 	}
745 	/*
746 	 * Prevent external consumers of mount options from reading
747 	 * mnt_optnew.
748 	*/
749 	mp->mnt_optnew = NULL;
750 	if (mp->mnt_flag & MNT_UPDATE) {
751 		mp->mnt_flag &=
752 		    ~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE | MNT_SNAPSHOT);
753 		if (error) {
754 			mp->mnt_flag = flag;
755 			mp->mnt_kern_flag = kern_flag;
756 		}
757 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
758 			if (mp->mnt_syncer == NULL)
759 				error = vfs_allocate_syncvnode(mp);
760 		} else {
761 			if (mp->mnt_syncer != NULL)
762 				vrele(mp->mnt_syncer);
763 			mp->mnt_syncer = NULL;
764 		}
765 		vfs_unbusy(mp, td);
766 		VI_LOCK(vp);
767 		vp->v_iflag &= ~VI_MOUNT;
768 		VI_UNLOCK(vp);
769 		vrele(vp);
770 		return (error);
771 	}
772 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
773 	/*
774 	 * Put the new filesystem on the mount list after root.
775 	 */
776 	cache_purge(vp);
777 	if (!error) {
778 		struct vnode *newdp;
779 
780 		VI_LOCK(vp);
781 		vp->v_iflag &= ~VI_MOUNT;
782 		VI_UNLOCK(vp);
783 		vp->v_mountedhere = mp;
784 		mtx_lock(&mountlist_mtx);
785 		TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
786 		mtx_unlock(&mountlist_mtx);
787 		vfs_event_signal(NULL, VQ_MOUNT, 0);
788 		if (VFS_ROOT(mp, LK_EXCLUSIVE, &newdp, td))
789 			panic("mount: lost mount");
790 		mountcheckdirs(vp, newdp);
791 		vput(newdp);
792 		VOP_UNLOCK(vp, 0, td);
793 		if ((mp->mnt_flag & MNT_RDONLY) == 0)
794 			error = vfs_allocate_syncvnode(mp);
795 		vfs_unbusy(mp, td);
796 		if (error)
797 			vrele(vp);
798 	} else {
799 		VI_LOCK(vp);
800 		vp->v_iflag &= ~VI_MOUNT;
801 		VI_UNLOCK(vp);
802 		vfs_mount_destroy(mp, td);
803 		vput(vp);
804 	}
805 	return (error);
806 }
807 
808 /*
809  * ---------------------------------------------------------------------
810  * Unmount a filesystem.
811  *
812  * Note: unmount takes a path to the vnode mounted on as argument,
813  * not special file (as before).
814  */
815 #ifndef _SYS_SYSPROTO_H_
816 struct unmount_args {
817 	char	*path;
818 	int	flags;
819 };
820 #endif
821 /* ARGSUSED */
822 int
823 unmount(td, uap)
824 	struct thread *td;
825 	register struct unmount_args /* {
826 		char *path;
827 		int flags;
828 	} */ *uap;
829 {
830 	struct mount *mp;
831 	char *pathbuf;
832 	int error, id0, id1;
833 
834 	if (jailed(td->td_ucred))
835 		return (EPERM);
836 	if (usermount == 0) {
837 		if ((error = suser(td)) != 0)
838 			return (error);
839 	}
840 
841 	pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
842 	error = copyinstr(uap->path, pathbuf, MNAMELEN, NULL);
843 	if (error) {
844 		free(pathbuf, M_TEMP);
845 		return (error);
846 	}
847 	if (uap->flags & MNT_BYFSID) {
848 		/* Decode the filesystem ID. */
849 		if (sscanf(pathbuf, "FSID:%d:%d", &id0, &id1) != 2) {
850 			free(pathbuf, M_TEMP);
851 			return (EINVAL);
852 		}
853 
854 		mtx_lock(&mountlist_mtx);
855 		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
856 			if (mp->mnt_stat.f_fsid.val[0] == id0 &&
857 			    mp->mnt_stat.f_fsid.val[1] == id1)
858 				break;
859 		}
860 		mtx_unlock(&mountlist_mtx);
861 	} else {
862 		mtx_lock(&mountlist_mtx);
863 		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
864 			if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0)
865 				break;
866 		}
867 		mtx_unlock(&mountlist_mtx);
868 	}
869 	free(pathbuf, M_TEMP);
870 	if (mp == NULL) {
871 		/*
872 		 * Previously we returned ENOENT for a nonexistent path and
873 		 * EINVAL for a non-mountpoint.  We cannot tell these apart
874 		 * now, so in the !MNT_BYFSID case return the more likely
875 		 * EINVAL for compatibility.
876 		 */
877 		return ((uap->flags & MNT_BYFSID) ? ENOENT : EINVAL);
878 	}
879 
880 	/*
881 	 * Only privileged root, or (if MNT_USER is set) the user that did the
882 	 * original mount is permitted to unmount this filesystem.
883 	 */
884 	error = vfs_suser(mp, td);
885 	if (error)
886 		return (error);
887 
888 	/*
889 	 * Don't allow unmounting the root filesystem.
890 	 */
891 	if (mp->mnt_flag & MNT_ROOTFS)
892 		return (EINVAL);
893 	mtx_lock(&Giant);
894 	error = dounmount(mp, uap->flags, td);
895 	mtx_unlock(&Giant);
896 	return (error);
897 }
898 
899 /*
900  * Do the actual filesystem unmount.
901  */
902 int
903 dounmount(mp, flags, td)
904 	struct mount *mp;
905 	int flags;
906 	struct thread *td;
907 {
908 	struct vnode *coveredvp, *fsrootvp;
909 	int error;
910 	int async_flag;
911 
912 	mtx_assert(&Giant, MA_OWNED);
913 
914 	MNT_ILOCK(mp);
915 	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
916 		MNT_IUNLOCK(mp);
917 		return (EBUSY);
918 	}
919 	mp->mnt_kern_flag |= MNTK_UNMOUNT;
920 	/* Allow filesystems to detect that a forced unmount is in progress. */
921 	if (flags & MNT_FORCE)
922 		mp->mnt_kern_flag |= MNTK_UNMOUNTF;
923 	error = lockmgr(&mp->mnt_lock, LK_DRAIN | LK_INTERLOCK |
924 	    ((flags & MNT_FORCE) ? 0 : LK_NOWAIT), MNT_MTX(mp), td);
925 	if (error) {
926 		MNT_ILOCK(mp);
927 		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
928 		if (mp->mnt_kern_flag & MNTK_MWAIT)
929 			wakeup(mp);
930 		MNT_IUNLOCK(mp);
931 		return (error);
932 	}
933 	vn_start_write(NULL, &mp, V_WAIT);
934 
935 	if (mp->mnt_flag & MNT_EXPUBLIC)
936 		vfs_setpublicfs(NULL, NULL, NULL);
937 
938 	vfs_msync(mp, MNT_WAIT);
939 	async_flag = mp->mnt_flag & MNT_ASYNC;
940 	mp->mnt_flag &= ~MNT_ASYNC;
941 	cache_purgevfs(mp);	/* remove cache entries for this file sys */
942 	if (mp->mnt_syncer != NULL)
943 		vrele(mp->mnt_syncer);
944 	/*
945 	 * For forced unmounts, move process cdir/rdir refs on the fs root
946 	 * vnode to the covered vnode.  For non-forced unmounts we want
947 	 * such references to cause an EBUSY error.
948 	 */
949 	if ((flags & MNT_FORCE) &&
950 	    VFS_ROOT(mp, LK_EXCLUSIVE, &fsrootvp, td) == 0) {
951 		if (mp->mnt_vnodecovered != NULL)
952 			mountcheckdirs(fsrootvp, mp->mnt_vnodecovered);
953 		if (fsrootvp == rootvnode) {
954 			vrele(rootvnode);
955 			rootvnode = NULL;
956 		}
957 		vput(fsrootvp);
958 	}
959 	if (((mp->mnt_flag & MNT_RDONLY) ||
960 	     (error = VFS_SYNC(mp, MNT_WAIT, td)) == 0) ||
961 	    (flags & MNT_FORCE)) {
962 		error = VFS_UNMOUNT(mp, flags, td);
963 	}
964 	vn_finished_write(mp);
965 	if (error) {
966 		/* Undo cdir/rdir and rootvnode changes made above. */
967 		if ((flags & MNT_FORCE) &&
968 		    VFS_ROOT(mp, LK_EXCLUSIVE, &fsrootvp, td) == 0) {
969 			if (mp->mnt_vnodecovered != NULL)
970 				mountcheckdirs(mp->mnt_vnodecovered, fsrootvp);
971 			if (rootvnode == NULL) {
972 				rootvnode = fsrootvp;
973 				vref(rootvnode);
974 			}
975 			vput(fsrootvp);
976 		}
977 		if ((mp->mnt_flag & MNT_RDONLY) == 0 && mp->mnt_syncer == NULL)
978 			(void) vfs_allocate_syncvnode(mp);
979 		MNT_ILOCK(mp);
980 		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
981 		mp->mnt_flag |= async_flag;
982 		lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
983 		if (mp->mnt_kern_flag & MNTK_MWAIT)
984 			wakeup(mp);
985 		MNT_IUNLOCK(mp);
986 		return (error);
987 	}
988 	mtx_lock(&mountlist_mtx);
989 	TAILQ_REMOVE(&mountlist, mp, mnt_list);
990 	if ((coveredvp = mp->mnt_vnodecovered) != NULL)
991 		coveredvp->v_mountedhere = NULL;
992 	mtx_unlock(&mountlist_mtx);
993 	vfs_event_signal(NULL, VQ_UNMOUNT, 0);
994 	vfs_mount_destroy(mp, td);
995 	if (coveredvp != NULL)
996 		vrele(coveredvp);
997 	return (0);
998 }
999 
1000 /*
1001  * ---------------------------------------------------------------------
1002  * Mounting of root filesystem
1003  *
1004  */
1005 
1006 static void
1007 set_rootvnode(struct thread *td)
1008 {
1009 	struct proc *p;
1010 
1011 	if (VFS_ROOT(TAILQ_FIRST(&mountlist), LK_EXCLUSIVE, &rootvnode, td))
1012 		panic("Cannot find root vnode");
1013 
1014 	p = td->td_proc;
1015 	FILEDESC_LOCK(p->p_fd);
1016 
1017 	if (p->p_fd->fd_cdir != NULL)
1018 		vrele(p->p_fd->fd_cdir);
1019 	p->p_fd->fd_cdir = rootvnode;
1020 	VREF(rootvnode);
1021 
1022 	if (p->p_fd->fd_rdir != NULL)
1023 		vrele(p->p_fd->fd_rdir);
1024 	p->p_fd->fd_rdir = rootvnode;
1025 	VREF(rootvnode);
1026 
1027 	FILEDESC_UNLOCK(p->p_fd);
1028 
1029 	VOP_UNLOCK(rootvnode, 0, td);
1030 }
1031 
1032 /*
1033  * Mount /devfs as our root filesystem, but do not put it on the mountlist
1034  * yet.  Create a /dev -> / symlink so that absolute pathnames will lookup.
1035  */
1036 
1037 static struct mount *
1038 devfs_first(void)
1039 {
1040 	struct thread *td = curthread;
1041 	struct vfsconf *vfsp;
1042 	struct mount *mp = NULL;
1043 	int error;
1044 
1045 	vfsp = vfs_byname("devfs");
1046 	KASSERT(vfsp != NULL, ("Could not find devfs by name"));
1047 	if (vfsp == NULL)
1048 		return(NULL);
1049 
1050 	error = vfs_mount_alloc(NULLVP, vfsp, "/dev", td, &mp);
1051 	KASSERT(error == 0, ("vfs_mount_alloc failed %d", error));
1052 	if (error)
1053 		return (NULL);
1054 
1055 	error = VFS_MOUNT(mp, curthread);
1056 	KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
1057 	if (error)
1058 		return (NULL);
1059 
1060 	mtx_lock(&mountlist_mtx);
1061 	TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
1062 	mtx_unlock(&mountlist_mtx);
1063 
1064 	set_rootvnode(td);
1065 
1066 	error = kern_symlink(td, "/", "dev", UIO_SYSSPACE);
1067 	if (error)
1068 		printf("kern_symlink /dev -> / returns %d\n", error);
1069 
1070 	return (mp);
1071 }
1072 
1073 /*
1074  * Surgically move our devfs to be mounted on /dev.
1075  */
1076 
1077 static void
1078 devfs_fixup(struct thread *td)
1079 {
1080 	struct nameidata nd;
1081 	int error;
1082 	struct vnode *vp, *dvp;
1083 	struct mount *mp;
1084 
1085 	/* Remove our devfs mount from the mountlist and purge the cache */
1086 	mtx_lock(&mountlist_mtx);
1087 	mp = TAILQ_FIRST(&mountlist);
1088 	TAILQ_REMOVE(&mountlist, mp, mnt_list);
1089 	mtx_unlock(&mountlist_mtx);
1090 	cache_purgevfs(mp);
1091 
1092 	VFS_ROOT(mp, LK_EXCLUSIVE, &dvp, td);
1093 	VI_LOCK(dvp);
1094 	dvp->v_iflag &= ~VI_MOUNT;
1095 	dvp->v_mountedhere = NULL;
1096 	VI_UNLOCK(dvp);
1097 
1098 	/* Set up the real rootvnode, and purge the cache */
1099 	TAILQ_FIRST(&mountlist)->mnt_vnodecovered = NULL;
1100 	set_rootvnode(td);
1101 	cache_purgevfs(rootvnode->v_mount);
1102 
1103 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
1104 	error = namei(&nd);
1105 	if (error) {
1106 		printf("Lookup of /dev for devfs, error: %d\n", error);
1107 		return;
1108 	}
1109 	NDFREE(&nd, NDF_ONLY_PNBUF);
1110 	vp = nd.ni_vp;
1111 	if (vp->v_type != VDIR) {
1112 		vput(vp);
1113 	}
1114 	error = vinvalbuf(vp, V_SAVE, td, 0, 0);
1115 	if (error) {
1116 		vput(vp);
1117 	}
1118 	cache_purge(vp);
1119 	mp->mnt_vnodecovered = vp;
1120 	vp->v_mountedhere = mp;
1121 	mtx_lock(&mountlist_mtx);
1122 	TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1123 	mtx_unlock(&mountlist_mtx);
1124 	VOP_UNLOCK(vp, 0, td);
1125 	vfs_unbusy(mp, td);
1126 	vput(dvp);
1127 
1128 	/* Unlink the no longer needed /dev/dev -> / symlink */
1129 	kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
1130 }
1131 
1132 /*
1133  * Find and mount the root filesystem
1134  */
1135 void
1136 vfs_mountroot(void)
1137 {
1138 	char *cp;
1139 	int error, i, asked = 0;
1140 	struct mount *mp;
1141 
1142 	/*
1143 	 * Wait for GEOM to settle down
1144 	 */
1145 	DROP_GIANT();
1146 	g_waitidle();
1147 	PICKUP_GIANT();
1148 
1149 	mp = devfs_first();
1150 
1151 	/*
1152 	 * We are booted with instructions to prompt for the root filesystem.
1153 	 */
1154 	if (boothowto & RB_ASKNAME) {
1155 		if (!vfs_mountroot_ask())
1156 			return;
1157 		asked = 1;
1158 	}
1159 
1160 	/*
1161 	 * The root filesystem information is compiled in, and we are
1162 	 * booted with instructions to use it.
1163 	 */
1164 	if (ctrootdevname != NULL && (boothowto & RB_DFLTROOT)) {
1165 		if (!vfs_mountroot_try(ctrootdevname))
1166 			return;
1167 		ctrootdevname = NULL;
1168 	}
1169 
1170 	/*
1171 	 * We've been given the generic "use CDROM as root" flag.  This is
1172 	 * necessary because one media may be used in many different
1173 	 * devices, so we need to search for them.
1174 	 */
1175 	if (boothowto & RB_CDROM) {
1176 		for (i = 0; cdrom_rootdevnames[i] != NULL; i++) {
1177 			if (!vfs_mountroot_try(cdrom_rootdevnames[i]))
1178 				return;
1179 		}
1180 	}
1181 
1182 	/*
1183 	 * Try to use the value read by the loader from /etc/fstab, or
1184 	 * supplied via some other means.  This is the preferred
1185 	 * mechanism.
1186 	 */
1187 	cp = getenv("vfs.root.mountfrom");
1188 	if (cp != NULL) {
1189 		error = vfs_mountroot_try(cp);
1190 		freeenv(cp);
1191 		if (!error)
1192 			return;
1193 	}
1194 
1195 	/*
1196 	 * Try values that may have been computed by code during boot
1197 	 */
1198 	if (!vfs_mountroot_try(rootdevnames[0]))
1199 		return;
1200 	if (!vfs_mountroot_try(rootdevnames[1]))
1201 		return;
1202 
1203 	/*
1204 	 * If we (still) have a compiled-in default, try it.
1205 	 */
1206 	if (ctrootdevname != NULL)
1207 		if (!vfs_mountroot_try(ctrootdevname))
1208 			return;
1209 	/*
1210 	 * Everything so far has failed, prompt on the console if we haven't
1211 	 * already tried that.
1212 	 */
1213 	if (!asked)
1214 		if (!vfs_mountroot_ask())
1215 			return;
1216 
1217 	panic("Root mount failed, startup aborted.");
1218 }
1219 
1220 /*
1221  * Mount (mountfrom) as the root filesystem.
1222  */
1223 static int
1224 vfs_mountroot_try(const char *mountfrom)
1225 {
1226         struct mount	*mp;
1227 	char		*vfsname, *path;
1228 	int		error;
1229 	char		patt[32];
1230 	int		s;
1231 
1232 	vfsname = NULL;
1233 	path    = NULL;
1234 	mp      = NULL;
1235 	error   = EINVAL;
1236 
1237 	if (mountfrom == NULL)
1238 		return (error);		/* don't complain */
1239 
1240 	s = splcam();			/* Overkill, but annoying without it */
1241 	printf("Trying to mount root from %s\n", mountfrom);
1242 	splx(s);
1243 
1244 	/* parse vfs name and path */
1245 	vfsname = malloc(MFSNAMELEN, M_MOUNT, M_WAITOK);
1246 	path = malloc(MNAMELEN, M_MOUNT, M_WAITOK);
1247 	vfsname[0] = path[0] = 0;
1248 	sprintf(patt, "%%%d[a-z0-9]:%%%ds", MFSNAMELEN, MNAMELEN);
1249 	if (sscanf(mountfrom, patt, vfsname, path) < 1) {
1250 		free(path, M_MOUNT);
1251 		free(vfsname, M_MOUNT);
1252 		return (error);
1253 	}
1254 
1255 	if (path[0] == '\0')
1256 		strcpy(path, ROOTNAME);
1257 
1258 	error = kernel_vmount(
1259 	    MNT_RDONLY | MNT_ROOTFS,
1260 	    "fstype", vfsname,
1261 	    "fspath", "/",
1262 	    "from", path,
1263 	    NULL);
1264 	if (error == 0) {
1265 		/*
1266 		 * We mount devfs prior to mounting the / FS, so the first
1267 		 * entry will typically be devfs.
1268 		 */
1269 		mp = TAILQ_FIRST(&mountlist);
1270 		KASSERT(mp != NULL, ("%s: mountlist is empty", __func__));
1271 		vfs_unbusy(mp, curthread);
1272 
1273 		/*
1274 		 * Iterate over all currently mounted file systems and use
1275 		 * the time stamp found to check and/or initialize the RTC.
1276 		 * Typically devfs has no time stamp and the only other FS
1277 		 * is the actual / FS.
1278 		 */
1279 		do {
1280 			if (mp->mnt_time != 0)
1281 				inittodr(mp->mnt_time);
1282 			mp = TAILQ_NEXT(mp, mnt_list);
1283 		} while (mp != NULL);
1284 
1285 		devfs_fixup(curthread);
1286 	}
1287 	return (error);
1288 }
1289 
1290 /*
1291  * ---------------------------------------------------------------------
1292  * Interactive root filesystem selection code.
1293  */
1294 
1295 static int
1296 vfs_mountroot_ask(void)
1297 {
1298 	char name[128];
1299 
1300 	for(;;) {
1301 		printf("\nManual root filesystem specification:\n");
1302 		printf("  <fstype>:<device>  Mount <device> using filesystem <fstype>\n");
1303 #if defined(__i386__) || defined(__ia64__)
1304 		printf("                       eg. ufs:da0s1a\n");
1305 #else
1306 		printf("                       eg. ufs:/dev/da0a\n");
1307 #endif
1308 		printf("  ?                  List valid disk boot devices\n");
1309 		printf("  <empty line>       Abort manual input\n");
1310 		printf("\nmountroot> ");
1311 		gets(name, sizeof(name), 1);
1312 		if (name[0] == '\0')
1313 			return (1);
1314 		if (name[0] == '?') {
1315 			printf("\nList of GEOM managed disk devices:\n  ");
1316 			g_dev_print();
1317 			continue;
1318 		}
1319 		if (!vfs_mountroot_try(name))
1320 			return (0);
1321 	}
1322 }
1323 
1324 /*
1325  * ---------------------------------------------------------------------
1326  * Functions for querying mount options/arguments from filesystems.
1327  */
1328 
1329 /*
1330  * Check that no unknown options are given
1331  */
1332 int
1333 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
1334 {
1335 	struct vfsopt *opt;
1336 	const char **t, *p;
1337 
1338 
1339 	TAILQ_FOREACH(opt, opts, link) {
1340 		p = opt->name;
1341 		if (p[0] == 'n' && p[1] == 'o')
1342 			p += 2;
1343 		for(t = global_opts; *t != NULL; t++)
1344 			if (!strcmp(*t, p))
1345 				break;
1346 		if (*t != NULL)
1347 			continue;
1348 		for(t = legal; *t != NULL; t++)
1349 			if (!strcmp(*t, p))
1350 				break;
1351 		if (*t != NULL)
1352 			continue;
1353 		printf("mount option <%s> is unknown\n", p);
1354 		return (EINVAL);
1355 	}
1356 	return (0);
1357 }
1358 
1359 /*
1360  * Get a mount option by its name.
1361  *
1362  * Return 0 if the option was found, ENOENT otherwise.
1363  * If len is non-NULL it will be filled with the length
1364  * of the option. If buf is non-NULL, it will be filled
1365  * with the address of the option.
1366  */
1367 int
1368 vfs_getopt(opts, name, buf, len)
1369 	struct vfsoptlist *opts;
1370 	const char *name;
1371 	void **buf;
1372 	int *len;
1373 {
1374 	struct vfsopt *opt;
1375 
1376 	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1377 
1378 	TAILQ_FOREACH(opt, opts, link) {
1379 		if (strcmp(name, opt->name) == 0) {
1380 			if (len != NULL)
1381 				*len = opt->len;
1382 			if (buf != NULL)
1383 				*buf = opt->value;
1384 			return (0);
1385 		}
1386 	}
1387 	return (ENOENT);
1388 }
1389 
1390 char *
1391 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
1392 {
1393 	struct vfsopt *opt;
1394 
1395 	*error = 0;
1396 	TAILQ_FOREACH(opt, opts, link) {
1397 		if (strcmp(name, opt->name) != 0)
1398 			continue;
1399 		if (((char *)opt->value)[opt->len - 1] != '\0') {
1400 			*error = EINVAL;
1401 			return (NULL);
1402 		}
1403 		return (opt->value);
1404 	}
1405 	return (NULL);
1406 }
1407 
1408 int
1409 vfs_flagopt(struct vfsoptlist *opts, const char *name, u_int *w, u_int val)
1410 {
1411 	struct vfsopt *opt;
1412 
1413 	TAILQ_FOREACH(opt, opts, link) {
1414 		if (strcmp(name, opt->name) == 0) {
1415 			if (w != NULL)
1416 				*w |= val;
1417 			return (1);
1418 		}
1419 	}
1420 	if (w != NULL)
1421 		*w &= ~val;
1422 	return (0);
1423 }
1424 
1425 int
1426 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
1427 {
1428 	va_list ap;
1429 	struct vfsopt *opt;
1430 	int ret;
1431 
1432 	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
1433 
1434 	TAILQ_FOREACH(opt, opts, link) {
1435 		if (strcmp(name, opt->name) != 0)
1436 			continue;
1437 		if (((char *)opt->value)[opt->len - 1] != '\0')
1438 			return (0);
1439 		va_start(ap, fmt);
1440 		ret = vsscanf(opt->value, fmt, ap);
1441 		va_end(ap);
1442 		return (ret);
1443 	}
1444 	return (0);
1445 }
1446 
1447 /*
1448  * Find and copy a mount option.
1449  *
1450  * The size of the buffer has to be specified
1451  * in len, if it is not the same length as the
1452  * mount option, EINVAL is returned.
1453  * Returns ENOENT if the option is not found.
1454  */
1455 int
1456 vfs_copyopt(opts, name, dest, len)
1457 	struct vfsoptlist *opts;
1458 	const char *name;
1459 	void *dest;
1460 	int len;
1461 {
1462 	struct vfsopt *opt;
1463 
1464 	KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
1465 
1466 	TAILQ_FOREACH(opt, opts, link) {
1467 		if (strcmp(name, opt->name) == 0) {
1468 			if (len != opt->len)
1469 				return (EINVAL);
1470 			bcopy(opt->value, dest, opt->len);
1471 			return (0);
1472 		}
1473 	}
1474 	return (ENOENT);
1475 }
1476 
1477 /*
1478  * This is a helper function for filesystems to traverse their
1479  * vnodes.  See MNT_VNODE_FOREACH() in sys/mount.h
1480  */
1481 
1482 struct vnode *
1483 __mnt_vnode_next(struct vnode **nvp, struct mount *mp)
1484 {
1485 	struct vnode *vp;
1486 
1487 	mtx_assert(&mp->mnt_mtx, MA_OWNED);
1488 
1489 	vp = *nvp;
1490 	/* Check if we are done */
1491 	if (vp == NULL)
1492 		return (NULL);
1493 	/* If our next vnode is no longer ours, start over */
1494 	if (vp->v_mount != mp)
1495 		vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
1496 	/* Save pointer to next vnode in list */
1497 	if (vp != NULL)
1498 		*nvp = TAILQ_NEXT(vp, v_nmntvnodes);
1499 	else
1500 		*nvp = NULL;
1501 	return (vp);
1502 }
1503 
1504 int
1505 __vfs_statfs(struct mount *mp, struct statfs *sbp, struct thread *td)
1506 {
1507 	int error;
1508 
1509 	error = mp->mnt_op->vfs_statfs(mp, &mp->mnt_stat, td);
1510 	if (sbp != &mp->mnt_stat)
1511 		*sbp = mp->mnt_stat;
1512 	return (error);
1513 }
1514 
1515 void
1516 vfs_mountedfrom(struct mount *mp, const char *from)
1517 {
1518 
1519 	bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
1520 	strlcpy(mp->mnt_stat.f_mntfromname, from,
1521 	    sizeof mp->mnt_stat.f_mntfromname);
1522 }
1523 
1524 /*
1525  * ---------------------------------------------------------------------
1526  * This is the api for building mount args and mounting filesystems from
1527  * inside the kernel.
1528  *
1529  * The API works by accumulation of individual args.  First error is
1530  * latched.
1531  *
1532  * XXX: should be documented in new manpage kernel_mount(9)
1533  */
1534 
1535 /* A memory allocation which must be freed when we are done */
1536 struct mntaarg {
1537 	SLIST_ENTRY(mntaarg)	next;
1538 };
1539 
1540 /* The header for the mount arguments */
1541 struct mntarg {
1542 	struct iovec *v;
1543 	int len;
1544 	int error;
1545 	SLIST_HEAD(, mntaarg)	list;
1546 };
1547 
1548 /*
1549  * Add a boolean argument.
1550  *
1551  * flag is the boolean value.
1552  * name must start with "no".
1553  */
1554 struct mntarg *
1555 mount_argb(struct mntarg *ma, int flag, const char *name)
1556 {
1557 
1558 	KASSERT(name[0] == 'n' && name[1] == 'o',
1559 	    ("mount_argb(...,%s): name must start with 'no'", name));
1560 
1561 	return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
1562 }
1563 
1564 /*
1565  * Add an argument printf style
1566  */
1567 struct mntarg *
1568 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
1569 {
1570 	va_list ap;
1571 	struct mntaarg *maa;
1572 	struct sbuf *sb;
1573 	int len;
1574 
1575 	if (ma == NULL) {
1576 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
1577 		SLIST_INIT(&ma->list);
1578 	}
1579 	if (ma->error)
1580 		return (ma);
1581 
1582 	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
1583 	    M_MOUNT, M_WAITOK);
1584 	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
1585 	ma->v[ma->len].iov_len = strlen(name) + 1;
1586 	ma->len++;
1587 
1588 	sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
1589 	va_start(ap, fmt);
1590 	sbuf_vprintf(sb, fmt, ap);
1591 	va_end(ap);
1592 	sbuf_finish(sb);
1593 	len = sbuf_len(sb) + 1;
1594 	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
1595 	SLIST_INSERT_HEAD(&ma->list, maa, next);
1596 	bcopy(sbuf_data(sb), maa + 1, len);
1597 	sbuf_delete(sb);
1598 
1599 	ma->v[ma->len].iov_base = maa + 1;
1600 	ma->v[ma->len].iov_len = len;
1601 	ma->len++;
1602 
1603 	return (ma);
1604 }
1605 
1606 /*
1607  * Add an argument which is a userland string.
1608  */
1609 struct mntarg *
1610 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
1611 {
1612 	struct mntaarg *maa;
1613 	char *tbuf;
1614 
1615 	if (val == NULL)
1616 		return (ma);
1617 	if (ma == NULL) {
1618 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
1619 		SLIST_INIT(&ma->list);
1620 	}
1621 	if (ma->error)
1622 		return (ma);
1623 	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
1624 	SLIST_INSERT_HEAD(&ma->list, maa, next);
1625 	tbuf = (void *)(maa + 1);
1626 	ma->error = copyinstr(val, tbuf, len, NULL);
1627 	return (mount_arg(ma, name, tbuf, -1));
1628 }
1629 
1630 /*
1631  * Plain argument.
1632  *
1633  * If length is -1, use printf.
1634  */
1635 struct mntarg *
1636 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
1637 {
1638 
1639 	if (ma == NULL) {
1640 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
1641 		SLIST_INIT(&ma->list);
1642 	}
1643 	if (ma->error)
1644 		return (ma);
1645 
1646 	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
1647 	    M_MOUNT, M_WAITOK);
1648 	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
1649 	ma->v[ma->len].iov_len = strlen(name) + 1;
1650 	ma->len++;
1651 
1652 	ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
1653 	if (len < 0)
1654 		ma->v[ma->len].iov_len = strlen(val) + 1;
1655 	else
1656 		ma->v[ma->len].iov_len = len;
1657 	ma->len++;
1658 	return (ma);
1659 }
1660 
1661 /*
1662  * Free a mntarg structure
1663  */
1664 static void
1665 free_mntarg(struct mntarg *ma)
1666 {
1667 	struct mntaarg *maa;
1668 
1669 	while (!SLIST_EMPTY(&ma->list)) {
1670 		maa = SLIST_FIRST(&ma->list);
1671 		SLIST_REMOVE_HEAD(&ma->list, next);
1672 		free(maa, M_MOUNT);
1673 	}
1674 	free(ma->v, M_MOUNT);
1675 	free(ma, M_MOUNT);
1676 }
1677 
1678 /*
1679  * Mount a filesystem
1680  */
1681 int
1682 kernel_mount(struct mntarg *ma, int flags)
1683 {
1684 	struct uio auio;
1685 	int error;
1686 
1687 	KASSERT(ma != NULL, ("kernel_mount NULL ma"));
1688 	KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
1689 	KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
1690 
1691 	auio.uio_iov = ma->v;
1692 	auio.uio_iovcnt = ma->len;
1693 	auio.uio_segflg = UIO_SYSSPACE;
1694 
1695 	error = ma->error;
1696 	if (!error)
1697 		error = vfs_donmount(curthread, flags, &auio);
1698 	free_mntarg(ma);
1699 	return (error);
1700 }
1701 
1702 /*
1703  * A printflike function to mount a filesystem.
1704  */
1705 int
1706 kernel_vmount(int flags, ...)
1707 {
1708 	struct mntarg *ma = NULL;
1709 	va_list ap;
1710 	const char *cp;
1711 	const void *vp;
1712 	int error;
1713 
1714 	va_start(ap, flags);
1715 	for (;;) {
1716 		cp = va_arg(ap, const char *);
1717 		if (cp == NULL)
1718 			break;
1719 		vp = va_arg(ap, const void *);
1720 		ma = mount_arg(ma, cp, vp, -1);
1721 	}
1722 	va_end(ap);
1723 
1724 	error = kernel_mount(ma, flags);
1725 	return (error);
1726 }
1727