vfs_mountroot.c revision 293742
160786Sps/*-
260786Sps * Copyright (c) 2010 Marcel Moolenaar
360786Sps * Copyright (c) 1999-2004 Poul-Henning Kamp
460786Sps * Copyright (c) 1999 Michael Smith
560786Sps * Copyright (c) 1989, 1993
660786Sps *      The Regents of the University of California.  All rights reserved.
760786Sps * (c) UNIX System Laboratories, Inc.
860786Sps * All or some portions of this file are derived from material licensed
960786Sps * to the University of California by American Telephone and Telegraph
1060786Sps * Co. or Unix System Laboratories, Inc. and are reproduced herein with
1160786Sps * the permission of UNIX System Laboratories, Inc.
1260786Sps *
1360786Sps * Redistribution and use in source and binary forms, with or without
1460786Sps * modification, are permitted provided that the following conditions
1560786Sps * are met:
1660786Sps * 1. Redistributions of source code must retain the above copyright
1760786Sps *    notice, this list of conditions and the following disclaimer.
1860786Sps * 2. Redistributions in binary form must reproduce the above copyright
1960786Sps *    notice, this list of conditions and the following disclaimer in the
2060786Sps *    documentation and/or other materials provided with the distribution.
2160786Sps * 4. Neither the name of the University nor the names of its contributors
2260786Sps *    may be used to endorse or promote products derived from this software
2360786Sps *    without specific prior written permission.
2460786Sps *
25128345Stjr * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26128345Stjr * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2760786Sps * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2860786Sps * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2960786Sps * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3060786Sps * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3160786Sps * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3260786Sps * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3360786Sps * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3460786Sps * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3560786Sps * SUCH DAMAGE.
3660786Sps */
3760786Sps
3860786Sps#include "opt_rootdevname.h"
3960786Sps
4060786Sps#include <sys/cdefs.h>
4160786Sps__FBSDID("$FreeBSD: stable/10/sys/kern/vfs_mountroot.c 293742 2016-01-12 10:09:03Z trasz $");
4260786Sps
4360786Sps#include <sys/param.h>
4460786Sps#include <sys/conf.h>
4560786Sps#include <sys/cons.h>
4660786Sps#include <sys/fcntl.h>
4760786Sps#include <sys/jail.h>
4860786Sps#include <sys/kernel.h>
4960786Sps#include <sys/malloc.h>
5060786Sps#include <sys/mdioctl.h>
5160786Sps#include <sys/mount.h>
5260786Sps#include <sys/mutex.h>
5360786Sps#include <sys/namei.h>
5460786Sps#include <sys/priv.h>
5560786Sps#include <sys/proc.h>
5660786Sps#include <sys/filedesc.h>
5760786Sps#include <sys/reboot.h>
5889019Sps#include <sys/sbuf.h>
5989019Sps#include <sys/stat.h>
6060786Sps#include <sys/syscallsubr.h>
6160786Sps#include <sys/sysproto.h>
6260786Sps#include <sys/sx.h>
6360786Sps#include <sys/sysctl.h>
6460786Sps#include <sys/sysent.h>
6560786Sps#include <sys/systm.h>
6660786Sps#include <sys/vnode.h>
6760786Sps
6860786Sps#include <geom/geom.h>
6960786Sps
7060786Sps/*
7160786Sps * The root filesystem is detailed in the kernel environment variable
7260786Sps * vfs.root.mountfrom, which is expected to be in the general format
7360786Sps *
7460786Sps * <vfsname>:[<path>][	<vfsname>:[<path>] ...]
7560786Sps * vfsname   := the name of a VFS known to the kernel and capable
7660786Sps *              of being mounted as root
7760786Sps * path      := disk device name or other data used by the filesystem
7860786Sps *              to locate its physical store
7960786Sps *
8060786Sps * If the environment variable vfs.root.mountfrom is a space separated list,
8160786Sps * each list element is tried in turn and the root filesystem will be mounted
8260786Sps * from the first one that suceeds.
8360786Sps *
8460786Sps * The environment variable vfs.root.mountfrom.options is a comma delimited
8560786Sps * set of string mount options.  These mount options must be parseable
8660786Sps * by nmount() in the kernel.
8760786Sps */
8860786Sps
8960786Spsstatic int parse_mount(char **);
9060786Spsstatic struct mntarg *parse_mountroot_options(struct mntarg *, const char *);
9160786Sps
9260786Sps/*
9360786Sps * The vnode of the system's root (/ in the filesystem, without chroot
9460786Sps * active.)
9560786Sps */
9660786Spsstruct vnode *rootvnode;
9760786Sps
9860786Sps/*
9960786Sps * Mount of the system's /dev.
10060786Sps */
10160786Spsstruct mount *rootdevmp;
10260786Sps
10360786Spschar *rootdevnames[2] = {NULL, NULL};
10460786Sps
10560786Spsstruct mtx root_holds_mtx;
10660786SpsMTX_SYSINIT(root_holds, &root_holds_mtx, "root_holds", MTX_DEF);
10760786Sps
10860786Spsstruct root_hold_token {
10960786Sps	const char			*who;
11060786Sps	LIST_ENTRY(root_hold_token)	list;
11160786Sps};
11260786Sps
11360786Spsstatic LIST_HEAD(, root_hold_token)	root_holds =
11460786Sps    LIST_HEAD_INITIALIZER(root_holds);
11560786Sps
11660786Spsenum action {
11760786Sps	A_CONTINUE,
11860786Sps	A_PANIC,
11960786Sps	A_REBOOT,
12060786Sps	A_RETRY
121170256Sdelphij};
122170256Sdelphij
12360786Spsstatic enum action root_mount_onfail = A_CONTINUE;
12460786Sps
12560786Spsstatic int root_mount_mddev;
12660786Spsstatic int root_mount_complete;
12760786Sps
12860786Sps/* By default wait up to 3 seconds for devices to appear. */
12960786Spsstatic int root_mount_timeout = 3;
13060786SpsTUNABLE_INT("vfs.mountroot.timeout", &root_mount_timeout);
13160786Sps
13260786Spsstruct root_hold_token *
13360786Spsroot_mount_hold(const char *identifier)
13460786Sps{
13560786Sps	struct root_hold_token *h;
13660786Sps
13760786Sps	if (root_mounted())
13860786Sps		return (NULL);
13960786Sps
14060786Sps	h = malloc(sizeof *h, M_DEVBUF, M_ZERO | M_WAITOK);
14160786Sps	h->who = identifier;
14260786Sps	mtx_lock(&root_holds_mtx);
14360786Sps	LIST_INSERT_HEAD(&root_holds, h, list);
14460786Sps	mtx_unlock(&root_holds_mtx);
14563128Sps	return (h);
14663128Sps}
14760786Sps
14860786Spsvoid
149128345Stjrroot_mount_rel(struct root_hold_token *h)
150128345Stjr{
15160786Sps
15260786Sps	if (h == NULL)
15360786Sps		return;
154170256Sdelphij	mtx_lock(&root_holds_mtx);
15560786Sps	LIST_REMOVE(h, list);
15660786Sps	wakeup(&root_holds);
15760786Sps	mtx_unlock(&root_holds_mtx);
15860786Sps	free(h, M_DEVBUF);
15960786Sps}
16060786Sps
16160786Spsint
16260786Spsroot_mounted(void)
16360786Sps{
16460786Sps
16560786Sps	/* No mutex is acquired here because int stores are atomic. */
16660786Sps	return (root_mount_complete);
16760786Sps}
16860786Sps
16960786Spsvoid
17060786Spsroot_mount_wait(void)
17160786Sps{
17260786Sps
17360786Sps	/*
17460786Sps	 * Panic on an obvious deadlock - the function can't be called from
17560786Sps	 * a thread which is doing the whole SYSINIT stuff.
17660786Sps	 */
17760786Sps	KASSERT(curthread->td_proc->p_pid != 0,
17860786Sps	    ("root_mount_wait: cannot be called from the swapper thread"));
17960786Sps	mtx_lock(&root_holds_mtx);
18060786Sps	while (!root_mount_complete) {
18160786Sps		msleep(&root_mount_complete, &root_holds_mtx, PZERO, "rootwait",
18260786Sps		    hz);
18389019Sps	}
18460786Sps	mtx_unlock(&root_holds_mtx);
18560786Sps}
18660786Sps
18789019Spsstatic void
18889019Spsset_rootvnode(void)
18960786Sps{
19060786Sps	struct proc *p;
19160786Sps
19260786Sps	if (VFS_ROOT(TAILQ_FIRST(&mountlist), LK_EXCLUSIVE, &rootvnode))
19360786Sps		panic("Cannot find root vnode");
19460786Sps
19560786Sps	VOP_UNLOCK(rootvnode, 0);
19660786Sps
19763128Sps	p = curthread->td_proc;
19863128Sps	FILEDESC_XLOCK(p->p_fd);
19963128Sps
20060786Sps	if (p->p_fd->fd_cdir != NULL)
20160786Sps		vrele(p->p_fd->fd_cdir);
20260786Sps	p->p_fd->fd_cdir = rootvnode;
20360786Sps	VREF(rootvnode);
20460786Sps
20560786Sps	if (p->p_fd->fd_rdir != NULL)
20660786Sps		vrele(p->p_fd->fd_rdir);
20760786Sps	p->p_fd->fd_rdir = rootvnode;
20860786Sps	VREF(rootvnode);
20960786Sps
21060786Sps	FILEDESC_XUNLOCK(p->p_fd);
21160786Sps}
21260786Sps
21360786Spsstatic int
21460786Spsvfs_mountroot_devfs(struct thread *td, struct mount **mpp)
21560786Sps{
21660786Sps	struct vfsoptlist *opts;
21760786Sps	struct vfsconf *vfsp;
21860786Sps	struct mount *mp;
21960786Sps	int error;
22060786Sps
22160786Sps	*mpp = NULL;
22260786Sps
22360786Sps	vfsp = vfs_byname("devfs");
224170256Sdelphij	KASSERT(vfsp != NULL, ("Could not find devfs by name"));
22560786Sps	if (vfsp == NULL)
22660786Sps		return (ENOENT);
227
228	mp = vfs_mount_alloc(NULLVP, vfsp, "/dev", td->td_ucred);
229
230	error = VFS_MOUNT(mp);
231	KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
232	if (error)
233		return (error);
234
235	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
236	TAILQ_INIT(opts);
237	mp->mnt_opt = opts;
238
239	mtx_lock(&mountlist_mtx);
240	TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
241	mtx_unlock(&mountlist_mtx);
242
243	*mpp = mp;
244	rootdevmp = mp;
245	set_rootvnode();
246
247	error = kern_symlink(td, "/", "dev", UIO_SYSSPACE);
248	if (error)
249		printf("kern_symlink /dev -> / returns %d\n", error);
250
251	return (error);
252}
253
254static void
255vfs_mountroot_shuffle(struct thread *td, struct mount *mpdevfs)
256{
257	struct nameidata nd;
258	struct mount *mporoot, *mpnroot;
259	struct vnode *vp, *vporoot, *vpdevfs;
260	char *fspath;
261	int error;
262
263	mpnroot = TAILQ_NEXT(mpdevfs, mnt_list);
264
265	/* Shuffle the mountlist. */
266	mtx_lock(&mountlist_mtx);
267	mporoot = TAILQ_FIRST(&mountlist);
268	TAILQ_REMOVE(&mountlist, mpdevfs, mnt_list);
269	if (mporoot != mpdevfs) {
270		TAILQ_REMOVE(&mountlist, mpnroot, mnt_list);
271		TAILQ_INSERT_HEAD(&mountlist, mpnroot, mnt_list);
272	}
273	TAILQ_INSERT_TAIL(&mountlist, mpdevfs, mnt_list);
274	mtx_unlock(&mountlist_mtx);
275
276	cache_purgevfs(mporoot);
277	if (mporoot != mpdevfs)
278		cache_purgevfs(mpdevfs);
279
280	VFS_ROOT(mporoot, LK_EXCLUSIVE, &vporoot);
281
282	VI_LOCK(vporoot);
283	vporoot->v_iflag &= ~VI_MOUNT;
284	VI_UNLOCK(vporoot);
285	vporoot->v_mountedhere = NULL;
286	mporoot->mnt_flag &= ~MNT_ROOTFS;
287	mporoot->mnt_vnodecovered = NULL;
288	vput(vporoot);
289
290	/* Set up the new rootvnode, and purge the cache */
291	mpnroot->mnt_vnodecovered = NULL;
292	set_rootvnode();
293	cache_purgevfs(rootvnode->v_mount);
294
295	if (mporoot != mpdevfs) {
296		/* Remount old root under /.mount or /mnt */
297		fspath = "/.mount";
298		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
299		    fspath, td);
300		error = namei(&nd);
301		if (error) {
302			NDFREE(&nd, NDF_ONLY_PNBUF);
303			fspath = "/mnt";
304			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
305			    fspath, td);
306			error = namei(&nd);
307		}
308		if (!error) {
309			vp = nd.ni_vp;
310			error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
311			if (!error)
312				error = vinvalbuf(vp, V_SAVE, 0, 0);
313			if (!error) {
314				cache_purge(vp);
315				mporoot->mnt_vnodecovered = vp;
316				vp->v_mountedhere = mporoot;
317				strlcpy(mporoot->mnt_stat.f_mntonname,
318				    fspath, MNAMELEN);
319				VOP_UNLOCK(vp, 0);
320			} else
321				vput(vp);
322		}
323		NDFREE(&nd, NDF_ONLY_PNBUF);
324
325		if (error && bootverbose)
326			printf("mountroot: unable to remount previous root "
327			    "under /.mount or /mnt (error %d).\n", error);
328	}
329
330	/* Remount devfs under /dev */
331	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
332	error = namei(&nd);
333	if (!error) {
334		vp = nd.ni_vp;
335		error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
336		if (!error)
337			error = vinvalbuf(vp, V_SAVE, 0, 0);
338		if (!error) {
339			vpdevfs = mpdevfs->mnt_vnodecovered;
340			if (vpdevfs != NULL) {
341				cache_purge(vpdevfs);
342				vpdevfs->v_mountedhere = NULL;
343				vrele(vpdevfs);
344			}
345			mpdevfs->mnt_vnodecovered = vp;
346			vp->v_mountedhere = mpdevfs;
347			VOP_UNLOCK(vp, 0);
348		} else
349			vput(vp);
350	}
351	if (error && bootverbose)
352		printf("mountroot: unable to remount devfs under /dev "
353		    "(error %d).\n", error);
354	NDFREE(&nd, NDF_ONLY_PNBUF);
355
356	if (mporoot == mpdevfs) {
357		vfs_unbusy(mpdevfs);
358		/* Unlink the no longer needed /dev/dev -> / symlink */
359		error = kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
360		if (error && bootverbose)
361			printf("mountroot: unable to unlink /dev/dev "
362			    "(error %d)\n", error);
363	}
364}
365
366/*
367 * Configuration parser.
368 */
369
370/* Parser character classes. */
371#define	CC_WHITESPACE		-1
372#define	CC_NONWHITESPACE	-2
373
374/* Parse errors. */
375#define	PE_EOF			-1
376#define	PE_EOL			-2
377
378static __inline int
379parse_peek(char **conf)
380{
381
382	return (**conf);
383}
384
385static __inline void
386parse_poke(char **conf, int c)
387{
388
389	**conf = c;
390}
391
392static __inline void
393parse_advance(char **conf)
394{
395
396	(*conf)++;
397}
398
399static int
400parse_skipto(char **conf, int mc)
401{
402	int c, match;
403
404	while (1) {
405		c = parse_peek(conf);
406		if (c == 0)
407			return (PE_EOF);
408		switch (mc) {
409		case CC_WHITESPACE:
410			match = (c == ' ' || c == '\t' || c == '\n') ? 1 : 0;
411			break;
412		case CC_NONWHITESPACE:
413			if (c == '\n')
414				return (PE_EOL);
415			match = (c != ' ' && c != '\t') ? 1 : 0;
416			break;
417		default:
418			match = (c == mc) ? 1 : 0;
419			break;
420		}
421		if (match)
422			break;
423		parse_advance(conf);
424	}
425	return (0);
426}
427
428static int
429parse_token(char **conf, char **tok)
430{
431	char *p;
432	size_t len;
433	int error;
434
435	*tok = NULL;
436	error = parse_skipto(conf, CC_NONWHITESPACE);
437	if (error)
438		return (error);
439	p = *conf;
440	error = parse_skipto(conf, CC_WHITESPACE);
441	len = *conf - p;
442	*tok = malloc(len + 1, M_TEMP, M_WAITOK | M_ZERO);
443	bcopy(p, *tok, len);
444	return (0);
445}
446
447static void
448parse_dir_ask_printenv(const char *var)
449{
450	char *val;
451
452	val = getenv(var);
453	if (val != NULL) {
454		printf("  %s=%s\n", var, val);
455		freeenv(val);
456	}
457}
458
459static int
460parse_dir_ask(char **conf)
461{
462	char name[80];
463	char *mnt;
464	int error;
465
466	printf("\nLoader variables:\n");
467	parse_dir_ask_printenv("vfs.root.mountfrom");
468	parse_dir_ask_printenv("vfs.root.mountfrom.options");
469
470	printf("\nManual root filesystem specification:\n");
471	printf("  <fstype>:<device> [options]\n");
472	printf("      Mount <device> using filesystem <fstype>\n");
473	printf("      and with the specified (optional) option list.\n");
474	printf("\n");
475	printf("    eg. ufs:/dev/da0s1a\n");
476	printf("        zfs:tank\n");
477	printf("        cd9660:/dev/acd0 ro\n");
478	printf("          (which is equivalent to: ");
479	printf("mount -t cd9660 -o ro /dev/acd0 /)\n");
480	printf("\n");
481	printf("  ?               List valid disk boot devices\n");
482	printf("  .               Yield 1 second (for background tasks)\n");
483	printf("  <empty line>    Abort manual input\n");
484
485	do {
486		error = EINVAL;
487		printf("\nmountroot> ");
488		cngets(name, sizeof(name), GETS_ECHO);
489		if (name[0] == '\0')
490			break;
491		if (name[0] == '?' && name[1] == '\0') {
492			printf("\nList of GEOM managed disk devices:\n  ");
493			g_dev_print();
494			continue;
495		}
496		if (name[0] == '.' && name[1] == '\0') {
497			pause("rmask", hz);
498			continue;
499		}
500		mnt = name;
501		error = parse_mount(&mnt);
502		if (error == -1)
503			printf("Invalid file system specification.\n");
504	} while (error != 0);
505
506	return (error);
507}
508
509static int
510parse_dir_md(char **conf)
511{
512	struct stat sb;
513	struct thread *td;
514	struct md_ioctl *mdio;
515	char *path, *tok;
516	int error, fd, len;
517
518	td = curthread;
519
520	error = parse_token(conf, &tok);
521	if (error)
522		return (error);
523
524	len = strlen(tok);
525	mdio = malloc(sizeof(*mdio) + len + 1, M_TEMP, M_WAITOK | M_ZERO);
526	path = (void *)(mdio + 1);
527	bcopy(tok, path, len);
528	free(tok, M_TEMP);
529
530	/* Get file status. */
531	error = kern_stat(td, path, UIO_SYSSPACE, &sb);
532	if (error)
533		goto out;
534
535	/* Open /dev/mdctl so that we can attach/detach. */
536	error = kern_open(td, "/dev/" MDCTL_NAME, UIO_SYSSPACE, O_RDWR, 0);
537	if (error)
538		goto out;
539
540	fd = td->td_retval[0];
541	mdio->md_version = MDIOVERSION;
542	mdio->md_type = MD_VNODE;
543
544	if (root_mount_mddev != -1) {
545		mdio->md_unit = root_mount_mddev;
546		DROP_GIANT();
547		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
548		PICKUP_GIANT();
549		/* Ignore errors. We don't care. */
550		root_mount_mddev = -1;
551	}
552
553	mdio->md_file = (void *)(mdio + 1);
554	mdio->md_options = MD_AUTOUNIT | MD_READONLY;
555	mdio->md_mediasize = sb.st_size;
556	mdio->md_unit = 0;
557	DROP_GIANT();
558	error = kern_ioctl(td, fd, MDIOCATTACH, (void *)mdio);
559	PICKUP_GIANT();
560	if (error)
561		goto out;
562
563	if (mdio->md_unit > 9) {
564		printf("rootmount: too many md units\n");
565		mdio->md_file = NULL;
566		mdio->md_options = 0;
567		mdio->md_mediasize = 0;
568		DROP_GIANT();
569		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
570		PICKUP_GIANT();
571		/* Ignore errors. We don't care. */
572		error = ERANGE;
573		goto out;
574	}
575
576	root_mount_mddev = mdio->md_unit;
577	printf(MD_NAME "%u attached to %s\n", root_mount_mddev, mdio->md_file);
578
579	error = kern_close(td, fd);
580
581 out:
582	free(mdio, M_TEMP);
583	return (error);
584}
585
586static int
587parse_dir_onfail(char **conf)
588{
589	char *action;
590	int error;
591
592	error = parse_token(conf, &action);
593	if (error)
594		return (error);
595
596	if (!strcmp(action, "continue"))
597		root_mount_onfail = A_CONTINUE;
598	else if (!strcmp(action, "panic"))
599		root_mount_onfail = A_PANIC;
600	else if (!strcmp(action, "reboot"))
601		root_mount_onfail = A_REBOOT;
602	else if (!strcmp(action, "retry"))
603		root_mount_onfail = A_RETRY;
604	else {
605		printf("rootmount: %s: unknown action\n", action);
606		error = EINVAL;
607	}
608
609	free(action, M_TEMP);
610	return (0);
611}
612
613static int
614parse_dir_timeout(char **conf)
615{
616	char *tok, *endtok;
617	long secs;
618	int error;
619
620	error = parse_token(conf, &tok);
621	if (error)
622		return (error);
623
624	secs = strtol(tok, &endtok, 0);
625	error = (secs < 0 || *endtok != '\0') ? EINVAL : 0;
626	if (!error)
627		root_mount_timeout = secs;
628	free(tok, M_TEMP);
629	return (error);
630}
631
632static int
633parse_directive(char **conf)
634{
635	char *dir;
636	int error;
637
638	error = parse_token(conf, &dir);
639	if (error)
640		return (error);
641
642	if (strcmp(dir, ".ask") == 0)
643		error = parse_dir_ask(conf);
644	else if (strcmp(dir, ".md") == 0)
645		error = parse_dir_md(conf);
646	else if (strcmp(dir, ".onfail") == 0)
647		error = parse_dir_onfail(conf);
648	else if (strcmp(dir, ".timeout") == 0)
649		error = parse_dir_timeout(conf);
650	else {
651		printf("mountroot: invalid directive `%s'\n", dir);
652		/* Ignore the rest of the line. */
653		(void)parse_skipto(conf, '\n');
654		error = EINVAL;
655	}
656	free(dir, M_TEMP);
657	return (error);
658}
659
660static int
661parse_mount_dev_present(const char *dev)
662{
663	struct nameidata nd;
664	int error;
665
666	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, dev, curthread);
667	error = namei(&nd);
668	if (!error)
669		vput(nd.ni_vp);
670	NDFREE(&nd, NDF_ONLY_PNBUF);
671	return (error != 0) ? 0 : 1;
672}
673
674#define	ERRMSGL	255
675static int
676parse_mount(char **conf)
677{
678	char *errmsg;
679	struct mntarg *ma;
680	char *dev, *fs, *opts, *tok;
681	int delay, error, timeout;
682
683	error = parse_token(conf, &tok);
684	if (error)
685		return (error);
686	fs = tok;
687	error = parse_skipto(&tok, ':');
688	if (error) {
689		free(fs, M_TEMP);
690		return (error);
691	}
692	parse_poke(&tok, '\0');
693	parse_advance(&tok);
694	dev = tok;
695
696	if (root_mount_mddev != -1) {
697		/* Handle substitution for the md unit number. */
698		tok = strstr(dev, "md#");
699		if (tok != NULL)
700			tok[2] = '0' + root_mount_mddev;
701	}
702
703	/* Parse options. */
704	error = parse_token(conf, &tok);
705	opts = (error == 0) ? tok : NULL;
706
707	printf("Trying to mount root from %s:%s [%s]...\n", fs, dev,
708	    (opts != NULL) ? opts : "");
709
710	errmsg = malloc(ERRMSGL, M_TEMP, M_WAITOK | M_ZERO);
711
712	if (vfs_byname(fs) == NULL) {
713		strlcpy(errmsg, "unknown file system", ERRMSGL);
714		error = ENOENT;
715		goto out;
716	}
717
718	if (strcmp(fs, "zfs") != 0 && strstr(fs, "nfs") == NULL &&
719	    dev[0] != '\0' && !parse_mount_dev_present(dev)) {
720		printf("mountroot: waiting for device %s ...\n", dev);
721		delay = hz / 10;
722		timeout = root_mount_timeout * hz;
723		do {
724			pause("rmdev", delay);
725			timeout -= delay;
726		} while (timeout > 0 && !parse_mount_dev_present(dev));
727		if (timeout <= 0) {
728			error = ENODEV;
729			goto out;
730		}
731	}
732
733	ma = NULL;
734	ma = mount_arg(ma, "fstype", fs, -1);
735	ma = mount_arg(ma, "fspath", "/", -1);
736	ma = mount_arg(ma, "from", dev, -1);
737	ma = mount_arg(ma, "errmsg", errmsg, ERRMSGL);
738	ma = mount_arg(ma, "ro", NULL, 0);
739	ma = parse_mountroot_options(ma, opts);
740	error = kernel_mount(ma, MNT_ROOTFS);
741
742 out:
743	if (error) {
744		printf("Mounting from %s:%s failed with error %d",
745		    fs, dev, error);
746		if (errmsg[0] != '\0')
747			printf(": %s", errmsg);
748		printf(".\n");
749	}
750	free(fs, M_TEMP);
751	free(errmsg, M_TEMP);
752	if (opts != NULL)
753		free(opts, M_TEMP);
754	/* kernel_mount can return -1 on error. */
755	return ((error < 0) ? EDOOFUS : error);
756}
757#undef ERRMSGL
758
759static int
760vfs_mountroot_parse(struct sbuf *sb, struct mount *mpdevfs)
761{
762	struct mount *mp;
763	char *conf;
764	int error;
765
766	root_mount_mddev = -1;
767
768retry:
769	conf = sbuf_data(sb);
770	mp = TAILQ_NEXT(mpdevfs, mnt_list);
771	error = (mp == NULL) ? 0 : EDOOFUS;
772	root_mount_onfail = A_CONTINUE;
773	while (mp == NULL) {
774		error = parse_skipto(&conf, CC_NONWHITESPACE);
775		if (error == PE_EOL) {
776			parse_advance(&conf);
777			continue;
778		}
779		if (error < 0)
780			break;
781		switch (parse_peek(&conf)) {
782		case '#':
783			error = parse_skipto(&conf, '\n');
784			break;
785		case '.':
786			error = parse_directive(&conf);
787			break;
788		default:
789			error = parse_mount(&conf);
790			break;
791		}
792		if (error < 0)
793			break;
794		/* Ignore any trailing garbage on the line. */
795		if (parse_peek(&conf) != '\n') {
796			printf("mountroot: advancing to next directive...\n");
797			(void)parse_skipto(&conf, '\n');
798		}
799		mp = TAILQ_NEXT(mpdevfs, mnt_list);
800	}
801	if (mp != NULL)
802		return (0);
803
804	/*
805	 * We failed to mount (a new) root.
806	 */
807	switch (root_mount_onfail) {
808	case A_CONTINUE:
809		break;
810	case A_PANIC:
811		panic("mountroot: unable to (re-)mount root.");
812		/* NOTREACHED */
813	case A_RETRY:
814		goto retry;
815	case A_REBOOT:
816		kern_reboot(RB_NOSYNC);
817		/* NOTREACHED */
818	}
819
820	return (error);
821}
822
823static void
824vfs_mountroot_conf0(struct sbuf *sb)
825{
826	char *s, *tok, *mnt, *opt;
827	int error;
828
829	sbuf_printf(sb, ".onfail panic\n");
830	sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
831	if (boothowto & RB_ASKNAME)
832		sbuf_printf(sb, ".ask\n");
833#ifdef ROOTDEVNAME
834	if (boothowto & RB_DFLTROOT)
835		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
836#endif
837	if (boothowto & RB_CDROM) {
838		sbuf_printf(sb, "cd9660:/dev/cd0 ro\n");
839		sbuf_printf(sb, ".timeout 0\n");
840		sbuf_printf(sb, "cd9660:/dev/acd0 ro\n");
841		sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
842	}
843	s = getenv("vfs.root.mountfrom");
844	if (s != NULL) {
845		opt = getenv("vfs.root.mountfrom.options");
846		tok = s;
847		error = parse_token(&tok, &mnt);
848		while (!error) {
849			sbuf_printf(sb, "%s %s\n", mnt,
850			    (opt != NULL) ? opt : "");
851			free(mnt, M_TEMP);
852			error = parse_token(&tok, &mnt);
853		}
854		if (opt != NULL)
855			freeenv(opt);
856		freeenv(s);
857	}
858	if (rootdevnames[0] != NULL)
859		sbuf_printf(sb, "%s\n", rootdevnames[0]);
860	if (rootdevnames[1] != NULL)
861		sbuf_printf(sb, "%s\n", rootdevnames[1]);
862#ifdef ROOTDEVNAME
863	if (!(boothowto & RB_DFLTROOT))
864		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
865#endif
866	if (!(boothowto & RB_ASKNAME))
867		sbuf_printf(sb, ".ask\n");
868}
869
870static int
871vfs_mountroot_readconf(struct thread *td, struct sbuf *sb)
872{
873	static char buf[128];
874	struct nameidata nd;
875	off_t ofs;
876	ssize_t resid;
877	int error, flags, len;
878
879	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/.mount.conf", td);
880	flags = FREAD;
881	error = vn_open(&nd, &flags, 0, NULL);
882	if (error)
883		return (error);
884
885	NDFREE(&nd, NDF_ONLY_PNBUF);
886	ofs = 0;
887	len = sizeof(buf) - 1;
888	while (1) {
889		error = vn_rdwr(UIO_READ, nd.ni_vp, buf, len, ofs,
890		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
891		    NOCRED, &resid, td);
892		if (error)
893			break;
894		if (resid == len)
895			break;
896		buf[len - resid] = 0;
897		sbuf_printf(sb, "%s", buf);
898		ofs += len - resid;
899	}
900
901	VOP_UNLOCK(nd.ni_vp, 0);
902	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
903	return (error);
904}
905
906static void
907vfs_mountroot_wait(void)
908{
909	struct root_hold_token *h;
910	struct timeval lastfail;
911	int curfail;
912
913	curfail = 0;
914	while (1) {
915		DROP_GIANT();
916		g_waitidle();
917		PICKUP_GIANT();
918		mtx_lock(&root_holds_mtx);
919		if (LIST_EMPTY(&root_holds)) {
920			mtx_unlock(&root_holds_mtx);
921			break;
922		}
923		if (ppsratecheck(&lastfail, &curfail, 1)) {
924			printf("Root mount waiting for:");
925			LIST_FOREACH(h, &root_holds, list)
926				printf(" %s", h->who);
927			printf("\n");
928		}
929		msleep(&root_holds, &root_holds_mtx, PZERO | PDROP, "roothold",
930		    hz);
931	}
932}
933
934void
935vfs_mountroot(void)
936{
937	struct mount *mp;
938	struct sbuf *sb;
939	struct thread *td;
940	time_t timebase;
941	int error;
942
943	td = curthread;
944
945	vfs_mountroot_wait();
946
947	sb = sbuf_new_auto();
948	vfs_mountroot_conf0(sb);
949	sbuf_finish(sb);
950
951	error = vfs_mountroot_devfs(td, &mp);
952	while (!error) {
953		error = vfs_mountroot_parse(sb, mp);
954		if (!error) {
955			vfs_mountroot_shuffle(td, mp);
956			sbuf_clear(sb);
957			error = vfs_mountroot_readconf(td, sb);
958			sbuf_finish(sb);
959		}
960	}
961
962	sbuf_delete(sb);
963
964	/*
965	 * Iterate over all currently mounted file systems and use
966	 * the time stamp found to check and/or initialize the RTC.
967	 * Call inittodr() only once and pass it the largest of the
968	 * timestamps we encounter.
969	 */
970	timebase = 0;
971	mtx_lock(&mountlist_mtx);
972	mp = TAILQ_FIRST(&mountlist);
973	while (mp != NULL) {
974		if (mp->mnt_time > timebase)
975			timebase = mp->mnt_time;
976		mp = TAILQ_NEXT(mp, mnt_list);
977	}
978	mtx_unlock(&mountlist_mtx);
979	inittodr(timebase);
980
981	/* Keep prison0's root in sync with the global rootvnode. */
982	mtx_lock(&prison0.pr_mtx);
983	prison0.pr_root = rootvnode;
984	vref(prison0.pr_root);
985	mtx_unlock(&prison0.pr_mtx);
986
987	mtx_lock(&root_holds_mtx);
988	atomic_store_rel_int(&root_mount_complete, 1);
989	wakeup(&root_mount_complete);
990	mtx_unlock(&root_holds_mtx);
991
992	EVENTHANDLER_INVOKE(mountroot);
993}
994
995static struct mntarg *
996parse_mountroot_options(struct mntarg *ma, const char *options)
997{
998	char *p;
999	char *name, *name_arg;
1000	char *val, *val_arg;
1001	char *opts;
1002
1003	if (options == NULL || options[0] == '\0')
1004		return (ma);
1005
1006	p = opts = strdup(options, M_MOUNT);
1007	if (opts == NULL) {
1008		return (ma);
1009	}
1010
1011	while((name = strsep(&p, ",")) != NULL) {
1012		if (name[0] == '\0')
1013			break;
1014
1015		val = strchr(name, '=');
1016		if (val != NULL) {
1017			*val = '\0';
1018			++val;
1019		}
1020		if( strcmp(name, "rw") == 0 ||
1021		    strcmp(name, "noro") == 0) {
1022			/*
1023			 * The first time we mount the root file system,
1024			 * we need to mount 'ro', so We need to ignore
1025			 * 'rw' and 'noro' mount options.
1026			 */
1027			continue;
1028		}
1029		name_arg = strdup(name, M_MOUNT);
1030		val_arg = NULL;
1031		if (val != NULL)
1032			val_arg = strdup(val, M_MOUNT);
1033
1034		ma = mount_arg(ma, name_arg, val_arg,
1035		    (val_arg != NULL ? -1 : 0));
1036	}
1037	free(opts, M_MOUNT);
1038	return (ma);
1039}
1040