vfs_mountroot.c revision 274476
1/*-
2 * Copyright (c) 2010 Marcel Moolenaar
3 * Copyright (c) 1999-2004 Poul-Henning Kamp
4 * Copyright (c) 1999 Michael Smith
5 * Copyright (c) 1989, 1993
6 *      The Regents of the University of California.  All rights reserved.
7 * (c) UNIX System Laboratories, Inc.
8 * All or some portions of this file are derived from material licensed
9 * to the University of California by American Telephone and Telegraph
10 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11 * the permission of UNIX System Laboratories, Inc.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 *    notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 *    notice, this list of conditions and the following disclaimer in the
20 *    documentation and/or other materials provided with the distribution.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38#include "opt_rootdevname.h"
39
40#include <sys/cdefs.h>
41__FBSDID("$FreeBSD: head/sys/kern/vfs_mountroot.c 274476 2014-11-13 18:01:51Z kib $");
42
43#include <sys/param.h>
44#include <sys/conf.h>
45#include <sys/cons.h>
46#include <sys/fcntl.h>
47#include <sys/jail.h>
48#include <sys/kernel.h>
49#include <sys/malloc.h>
50#include <sys/mdioctl.h>
51#include <sys/mount.h>
52#include <sys/mutex.h>
53#include <sys/namei.h>
54#include <sys/priv.h>
55#include <sys/proc.h>
56#include <sys/filedesc.h>
57#include <sys/reboot.h>
58#include <sys/sbuf.h>
59#include <sys/stat.h>
60#include <sys/syscallsubr.h>
61#include <sys/sysproto.h>
62#include <sys/sx.h>
63#include <sys/sysctl.h>
64#include <sys/sysent.h>
65#include <sys/systm.h>
66#include <sys/vnode.h>
67
68#include <geom/geom.h>
69
70/*
71 * The root filesystem is detailed in the kernel environment variable
72 * vfs.root.mountfrom, which is expected to be in the general format
73 *
74 * <vfsname>:[<path>][	<vfsname>:[<path>] ...]
75 * vfsname   := the name of a VFS known to the kernel and capable
76 *              of being mounted as root
77 * path      := disk device name or other data used by the filesystem
78 *              to locate its physical store
79 *
80 * If the environment variable vfs.root.mountfrom is a space separated list,
81 * each list element is tried in turn and the root filesystem will be mounted
82 * from the first one that suceeds.
83 *
84 * The environment variable vfs.root.mountfrom.options is a comma delimited
85 * set of string mount options.  These mount options must be parseable
86 * by nmount() in the kernel.
87 */
88
89static int parse_mount(char **);
90static struct mntarg *parse_mountroot_options(struct mntarg *, const char *);
91
92/*
93 * The vnode of the system's root (/ in the filesystem, without chroot
94 * active.)
95 */
96struct vnode *rootvnode;
97
98char *rootdevnames[2] = {NULL, NULL};
99
100struct mtx root_holds_mtx;
101MTX_SYSINIT(root_holds, &root_holds_mtx, "root_holds", MTX_DEF);
102
103struct root_hold_token {
104	const char			*who;
105	LIST_ENTRY(root_hold_token)	list;
106};
107
108static LIST_HEAD(, root_hold_token)	root_holds =
109    LIST_HEAD_INITIALIZER(root_holds);
110
111enum action {
112	A_CONTINUE,
113	A_PANIC,
114	A_REBOOT,
115	A_RETRY
116};
117
118static enum action root_mount_onfail = A_CONTINUE;
119
120static int root_mount_mddev;
121static int root_mount_complete;
122
123/* By default wait up to 3 seconds for devices to appear. */
124static int root_mount_timeout = 3;
125TUNABLE_INT("vfs.mountroot.timeout", &root_mount_timeout);
126
127struct root_hold_token *
128root_mount_hold(const char *identifier)
129{
130	struct root_hold_token *h;
131
132	if (root_mounted())
133		return (NULL);
134
135	h = malloc(sizeof *h, M_DEVBUF, M_ZERO | M_WAITOK);
136	h->who = identifier;
137	mtx_lock(&root_holds_mtx);
138	LIST_INSERT_HEAD(&root_holds, h, list);
139	mtx_unlock(&root_holds_mtx);
140	return (h);
141}
142
143void
144root_mount_rel(struct root_hold_token *h)
145{
146
147	if (h == NULL)
148		return;
149	mtx_lock(&root_holds_mtx);
150	LIST_REMOVE(h, list);
151	wakeup(&root_holds);
152	mtx_unlock(&root_holds_mtx);
153	free(h, M_DEVBUF);
154}
155
156int
157root_mounted(void)
158{
159
160	/* No mutex is acquired here because int stores are atomic. */
161	return (root_mount_complete);
162}
163
164void
165root_mount_wait(void)
166{
167
168	/*
169	 * Panic on an obvious deadlock - the function can't be called from
170	 * a thread which is doing the whole SYSINIT stuff.
171	 */
172	KASSERT(curthread->td_proc->p_pid != 0,
173	    ("root_mount_wait: cannot be called from the swapper thread"));
174	mtx_lock(&root_holds_mtx);
175	while (!root_mount_complete) {
176		msleep(&root_mount_complete, &root_holds_mtx, PZERO, "rootwait",
177		    hz);
178	}
179	mtx_unlock(&root_holds_mtx);
180}
181
182static void
183set_rootvnode(void)
184{
185	struct proc *p;
186
187	if (VFS_ROOT(TAILQ_FIRST(&mountlist), LK_EXCLUSIVE, &rootvnode))
188		panic("Cannot find root vnode");
189
190	VOP_UNLOCK(rootvnode, 0);
191
192	p = curthread->td_proc;
193	FILEDESC_XLOCK(p->p_fd);
194
195	if (p->p_fd->fd_cdir != NULL)
196		vrele(p->p_fd->fd_cdir);
197	p->p_fd->fd_cdir = rootvnode;
198	VREF(rootvnode);
199
200	if (p->p_fd->fd_rdir != NULL)
201		vrele(p->p_fd->fd_rdir);
202	p->p_fd->fd_rdir = rootvnode;
203	VREF(rootvnode);
204
205	FILEDESC_XUNLOCK(p->p_fd);
206}
207
208static int
209vfs_mountroot_devfs(struct thread *td, struct mount **mpp)
210{
211	struct vfsoptlist *opts;
212	struct vfsconf *vfsp;
213	struct mount *mp;
214	int error;
215
216	*mpp = NULL;
217
218	vfsp = vfs_byname("devfs");
219	KASSERT(vfsp != NULL, ("Could not find devfs by name"));
220	if (vfsp == NULL)
221		return (ENOENT);
222
223	mp = vfs_mount_alloc(NULLVP, vfsp, "/dev", td->td_ucred);
224
225	error = VFS_MOUNT(mp);
226	KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
227	if (error)
228		return (error);
229
230	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
231	TAILQ_INIT(opts);
232	mp->mnt_opt = opts;
233
234	mtx_lock(&mountlist_mtx);
235	TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
236	mtx_unlock(&mountlist_mtx);
237
238	*mpp = mp;
239	set_rootvnode();
240
241	error = kern_symlinkat(td, "/", AT_FDCWD, "dev", UIO_SYSSPACE);
242	if (error)
243		printf("kern_symlink /dev -> / returns %d\n", error);
244
245	return (error);
246}
247
248static int
249vfs_mountroot_shuffle(struct thread *td, struct mount *mpdevfs)
250{
251	struct nameidata nd;
252	struct mount *mporoot, *mpnroot;
253	struct vnode *vp, *vporoot, *vpdevfs;
254	char *fspath;
255	int error;
256
257	mpnroot = TAILQ_NEXT(mpdevfs, mnt_list);
258
259	/* Shuffle the mountlist. */
260	mtx_lock(&mountlist_mtx);
261	mporoot = TAILQ_FIRST(&mountlist);
262	TAILQ_REMOVE(&mountlist, mpdevfs, mnt_list);
263	if (mporoot != mpdevfs) {
264		TAILQ_REMOVE(&mountlist, mpnroot, mnt_list);
265		TAILQ_INSERT_HEAD(&mountlist, mpnroot, mnt_list);
266	}
267	TAILQ_INSERT_TAIL(&mountlist, mpdevfs, mnt_list);
268	mtx_unlock(&mountlist_mtx);
269
270	cache_purgevfs(mporoot);
271	if (mporoot != mpdevfs)
272		cache_purgevfs(mpdevfs);
273
274	VFS_ROOT(mporoot, LK_EXCLUSIVE, &vporoot);
275
276	VI_LOCK(vporoot);
277	vporoot->v_iflag &= ~VI_MOUNT;
278	VI_UNLOCK(vporoot);
279	vporoot->v_mountedhere = NULL;
280	mporoot->mnt_flag &= ~MNT_ROOTFS;
281	mporoot->mnt_vnodecovered = NULL;
282	vput(vporoot);
283
284	/* Set up the new rootvnode, and purge the cache */
285	mpnroot->mnt_vnodecovered = NULL;
286	set_rootvnode();
287	cache_purgevfs(rootvnode->v_mount);
288
289	if (mporoot != mpdevfs) {
290		/* Remount old root under /.mount or /mnt */
291		fspath = "/.mount";
292		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
293		    fspath, td);
294		error = namei(&nd);
295		if (error) {
296			NDFREE(&nd, NDF_ONLY_PNBUF);
297			fspath = "/mnt";
298			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
299			    fspath, td);
300			error = namei(&nd);
301		}
302		if (!error) {
303			vp = nd.ni_vp;
304			error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
305			if (!error)
306				error = vinvalbuf(vp, V_SAVE, 0, 0);
307			if (!error) {
308				cache_purge(vp);
309				mporoot->mnt_vnodecovered = vp;
310				vp->v_mountedhere = mporoot;
311				strlcpy(mporoot->mnt_stat.f_mntonname,
312				    fspath, MNAMELEN);
313				VOP_UNLOCK(vp, 0);
314			} else
315				vput(vp);
316		}
317		NDFREE(&nd, NDF_ONLY_PNBUF);
318
319		if (error && bootverbose)
320			printf("mountroot: unable to remount previous root "
321			    "under /.mount or /mnt (error %d).\n", error);
322	}
323
324	/* Remount devfs under /dev */
325	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
326	error = namei(&nd);
327	if (!error) {
328		vp = nd.ni_vp;
329		error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
330		if (!error)
331			error = vinvalbuf(vp, V_SAVE, 0, 0);
332		if (!error) {
333			vpdevfs = mpdevfs->mnt_vnodecovered;
334			if (vpdevfs != NULL) {
335				cache_purge(vpdevfs);
336				vpdevfs->v_mountedhere = NULL;
337				vrele(vpdevfs);
338			}
339			mpdevfs->mnt_vnodecovered = vp;
340			vp->v_mountedhere = mpdevfs;
341			VOP_UNLOCK(vp, 0);
342		} else
343			vput(vp);
344	}
345	if (error && bootverbose)
346		printf("mountroot: unable to remount devfs under /dev "
347		    "(error %d).\n", error);
348	NDFREE(&nd, NDF_ONLY_PNBUF);
349
350	if (mporoot == mpdevfs) {
351		vfs_unbusy(mpdevfs);
352		/* Unlink the no longer needed /dev/dev -> / symlink */
353		error = kern_unlinkat(td, AT_FDCWD, "/dev/dev",
354		    UIO_SYSSPACE, 0);
355		if (error && bootverbose)
356			printf("mountroot: unable to unlink /dev/dev "
357			    "(error %d)\n", error);
358	}
359
360	return (0);
361}
362
363/*
364 * Configuration parser.
365 */
366
367/* Parser character classes. */
368#define	CC_WHITESPACE		-1
369#define	CC_NONWHITESPACE	-2
370
371/* Parse errors. */
372#define	PE_EOF			-1
373#define	PE_EOL			-2
374
375static __inline int
376parse_peek(char **conf)
377{
378
379	return (**conf);
380}
381
382static __inline void
383parse_poke(char **conf, int c)
384{
385
386	**conf = c;
387}
388
389static __inline void
390parse_advance(char **conf)
391{
392
393	(*conf)++;
394}
395
396static int
397parse_skipto(char **conf, int mc)
398{
399	int c, match;
400
401	while (1) {
402		c = parse_peek(conf);
403		if (c == 0)
404			return (PE_EOF);
405		switch (mc) {
406		case CC_WHITESPACE:
407			match = (c == ' ' || c == '\t' || c == '\n') ? 1 : 0;
408			break;
409		case CC_NONWHITESPACE:
410			if (c == '\n')
411				return (PE_EOL);
412			match = (c != ' ' && c != '\t') ? 1 : 0;
413			break;
414		default:
415			match = (c == mc) ? 1 : 0;
416			break;
417		}
418		if (match)
419			break;
420		parse_advance(conf);
421	}
422	return (0);
423}
424
425static int
426parse_token(char **conf, char **tok)
427{
428	char *p;
429	size_t len;
430	int error;
431
432	*tok = NULL;
433	error = parse_skipto(conf, CC_NONWHITESPACE);
434	if (error)
435		return (error);
436	p = *conf;
437	error = parse_skipto(conf, CC_WHITESPACE);
438	len = *conf - p;
439	*tok = malloc(len + 1, M_TEMP, M_WAITOK | M_ZERO);
440	bcopy(p, *tok, len);
441	return (0);
442}
443
444static void
445parse_dir_ask_printenv(const char *var)
446{
447	char *val;
448
449	val = kern_getenv(var);
450	if (val != NULL) {
451		printf("  %s=%s\n", var, val);
452		freeenv(val);
453	}
454}
455
456static int
457parse_dir_ask(char **conf)
458{
459	char name[80];
460	char *mnt;
461	int error;
462
463	printf("\nLoader variables:\n");
464	parse_dir_ask_printenv("vfs.root.mountfrom");
465	parse_dir_ask_printenv("vfs.root.mountfrom.options");
466
467	printf("\nManual root filesystem specification:\n");
468	printf("  <fstype>:<device> [options]\n");
469	printf("      Mount <device> using filesystem <fstype>\n");
470	printf("      and with the specified (optional) option list.\n");
471	printf("\n");
472	printf("    eg. ufs:/dev/da0s1a\n");
473	printf("        zfs:tank\n");
474	printf("        cd9660:/dev/acd0 ro\n");
475	printf("          (which is equivalent to: ");
476	printf("mount -t cd9660 -o ro /dev/acd0 /)\n");
477	printf("\n");
478	printf("  ?               List valid disk boot devices\n");
479	printf("  .               Yield 1 second (for background tasks)\n");
480	printf("  <empty line>    Abort manual input\n");
481
482	do {
483		error = EINVAL;
484		printf("\nmountroot> ");
485		cngets(name, sizeof(name), GETS_ECHO);
486		if (name[0] == '\0')
487			break;
488		if (name[0] == '?' && name[1] == '\0') {
489			printf("\nList of GEOM managed disk devices:\n  ");
490			g_dev_print();
491			continue;
492		}
493		if (name[0] == '.' && name[1] == '\0') {
494			pause("rmask", hz);
495			continue;
496		}
497		mnt = name;
498		error = parse_mount(&mnt);
499		if (error == -1)
500			printf("Invalid file system specification.\n");
501	} while (error != 0);
502
503	return (error);
504}
505
506static int
507parse_dir_md(char **conf)
508{
509	struct stat sb;
510	struct thread *td;
511	struct md_ioctl *mdio;
512	char *path, *tok;
513	int error, fd, len;
514
515	td = curthread;
516
517	error = parse_token(conf, &tok);
518	if (error)
519		return (error);
520
521	len = strlen(tok);
522	mdio = malloc(sizeof(*mdio) + len + 1, M_TEMP, M_WAITOK | M_ZERO);
523	path = (void *)(mdio + 1);
524	bcopy(tok, path, len);
525	free(tok, M_TEMP);
526
527	/* Get file status. */
528	error = kern_statat(td, 0, AT_FDCWD, path, UIO_SYSSPACE, &sb, NULL);
529	if (error)
530		goto out;
531
532	/* Open /dev/mdctl so that we can attach/detach. */
533	error = kern_openat(td, AT_FDCWD, "/dev/" MDCTL_NAME, UIO_SYSSPACE,
534	    O_RDWR, 0);
535	if (error)
536		goto out;
537
538	fd = td->td_retval[0];
539	mdio->md_version = MDIOVERSION;
540	mdio->md_type = MD_VNODE;
541
542	if (root_mount_mddev != -1) {
543		mdio->md_unit = root_mount_mddev;
544		DROP_GIANT();
545		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
546		PICKUP_GIANT();
547		/* Ignore errors. We don't care. */
548		root_mount_mddev = -1;
549	}
550
551	mdio->md_file = (void *)(mdio + 1);
552	mdio->md_options = MD_AUTOUNIT | MD_READONLY;
553	mdio->md_mediasize = sb.st_size;
554	mdio->md_unit = 0;
555	DROP_GIANT();
556	error = kern_ioctl(td, fd, MDIOCATTACH, (void *)mdio);
557	PICKUP_GIANT();
558	if (error)
559		goto out;
560
561	if (mdio->md_unit > 9) {
562		printf("rootmount: too many md units\n");
563		mdio->md_file = NULL;
564		mdio->md_options = 0;
565		mdio->md_mediasize = 0;
566		DROP_GIANT();
567		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
568		PICKUP_GIANT();
569		/* Ignore errors. We don't care. */
570		error = ERANGE;
571		goto out;
572	}
573
574	root_mount_mddev = mdio->md_unit;
575	printf(MD_NAME "%u attached to %s\n", root_mount_mddev, mdio->md_file);
576
577	error = kern_close(td, fd);
578
579 out:
580	free(mdio, M_TEMP);
581	return (error);
582}
583
584static int
585parse_dir_onfail(char **conf)
586{
587	char *action;
588	int error;
589
590	error = parse_token(conf, &action);
591	if (error)
592		return (error);
593
594	if (!strcmp(action, "continue"))
595		root_mount_onfail = A_CONTINUE;
596	else if (!strcmp(action, "panic"))
597		root_mount_onfail = A_PANIC;
598	else if (!strcmp(action, "reboot"))
599		root_mount_onfail = A_REBOOT;
600	else if (!strcmp(action, "retry"))
601		root_mount_onfail = A_RETRY;
602	else {
603		printf("rootmount: %s: unknown action\n", action);
604		error = EINVAL;
605	}
606
607	free(action, M_TEMP);
608	return (0);
609}
610
611static int
612parse_dir_timeout(char **conf)
613{
614	char *tok, *endtok;
615	long secs;
616	int error;
617
618	error = parse_token(conf, &tok);
619	if (error)
620		return (error);
621
622	secs = strtol(tok, &endtok, 0);
623	error = (secs < 0 || *endtok != '\0') ? EINVAL : 0;
624	if (!error)
625		root_mount_timeout = secs;
626	free(tok, M_TEMP);
627	return (error);
628}
629
630static int
631parse_directive(char **conf)
632{
633	char *dir;
634	int error;
635
636	error = parse_token(conf, &dir);
637	if (error)
638		return (error);
639
640	if (strcmp(dir, ".ask") == 0)
641		error = parse_dir_ask(conf);
642	else if (strcmp(dir, ".md") == 0)
643		error = parse_dir_md(conf);
644	else if (strcmp(dir, ".onfail") == 0)
645		error = parse_dir_onfail(conf);
646	else if (strcmp(dir, ".timeout") == 0)
647		error = parse_dir_timeout(conf);
648	else {
649		printf("mountroot: invalid directive `%s'\n", dir);
650		/* Ignore the rest of the line. */
651		(void)parse_skipto(conf, '\n');
652		error = EINVAL;
653	}
654	free(dir, M_TEMP);
655	return (error);
656}
657
658static int
659parse_mount_dev_present(const char *dev)
660{
661	struct nameidata nd;
662	int error;
663
664	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, dev, curthread);
665	error = namei(&nd);
666	if (!error)
667		vput(nd.ni_vp);
668	NDFREE(&nd, NDF_ONLY_PNBUF);
669	return (error != 0) ? 0 : 1;
670}
671
672#define	ERRMSGL	255
673static int
674parse_mount(char **conf)
675{
676	char *errmsg;
677	struct mntarg *ma;
678	char *dev, *fs, *opts, *tok;
679	int delay, error, timeout;
680
681	error = parse_token(conf, &tok);
682	if (error)
683		return (error);
684	fs = tok;
685	error = parse_skipto(&tok, ':');
686	if (error) {
687		free(fs, M_TEMP);
688		return (error);
689	}
690	parse_poke(&tok, '\0');
691	parse_advance(&tok);
692	dev = tok;
693
694	if (root_mount_mddev != -1) {
695		/* Handle substitution for the md unit number. */
696		tok = strstr(dev, "md#");
697		if (tok != NULL)
698			tok[2] = '0' + root_mount_mddev;
699	}
700
701	/* Parse options. */
702	error = parse_token(conf, &tok);
703	opts = (error == 0) ? tok : NULL;
704
705	printf("Trying to mount root from %s:%s [%s]...\n", fs, dev,
706	    (opts != NULL) ? opts : "");
707
708	errmsg = malloc(ERRMSGL, M_TEMP, M_WAITOK | M_ZERO);
709
710	if (vfs_byname(fs) == NULL) {
711		strlcpy(errmsg, "unknown file system", ERRMSGL);
712		error = ENOENT;
713		goto out;
714	}
715
716	if (strcmp(fs, "zfs") != 0 && strstr(fs, "nfs") == NULL &&
717	    dev[0] != '\0' && !parse_mount_dev_present(dev)) {
718		printf("mountroot: waiting for device %s ...\n", dev);
719		delay = hz / 10;
720		timeout = root_mount_timeout * hz;
721		do {
722			pause("rmdev", delay);
723			timeout -= delay;
724		} while (timeout > 0 && !parse_mount_dev_present(dev));
725		if (timeout <= 0) {
726			error = ENODEV;
727			goto out;
728		}
729	}
730
731	ma = NULL;
732	ma = mount_arg(ma, "fstype", fs, -1);
733	ma = mount_arg(ma, "fspath", "/", -1);
734	ma = mount_arg(ma, "from", dev, -1);
735	ma = mount_arg(ma, "errmsg", errmsg, ERRMSGL);
736	ma = mount_arg(ma, "ro", NULL, 0);
737	ma = parse_mountroot_options(ma, opts);
738	error = kernel_mount(ma, MNT_ROOTFS);
739
740 out:
741	if (error) {
742		printf("Mounting from %s:%s failed with error %d",
743		    fs, dev, error);
744		if (errmsg[0] != '\0')
745			printf(": %s", errmsg);
746		printf(".\n");
747	}
748	free(fs, M_TEMP);
749	free(errmsg, M_TEMP);
750	if (opts != NULL)
751		free(opts, M_TEMP);
752	/* kernel_mount can return -1 on error. */
753	return ((error < 0) ? EDOOFUS : error);
754}
755#undef ERRMSGL
756
757static int
758vfs_mountroot_parse(struct sbuf *sb, struct mount *mpdevfs)
759{
760	struct mount *mp;
761	char *conf;
762	int error;
763
764	root_mount_mddev = -1;
765
766retry:
767	conf = sbuf_data(sb);
768	mp = TAILQ_NEXT(mpdevfs, mnt_list);
769	error = (mp == NULL) ? 0 : EDOOFUS;
770	root_mount_onfail = A_CONTINUE;
771	while (mp == NULL) {
772		error = parse_skipto(&conf, CC_NONWHITESPACE);
773		if (error == PE_EOL) {
774			parse_advance(&conf);
775			continue;
776		}
777		if (error < 0)
778			break;
779		switch (parse_peek(&conf)) {
780		case '#':
781			error = parse_skipto(&conf, '\n');
782			break;
783		case '.':
784			error = parse_directive(&conf);
785			break;
786		default:
787			error = parse_mount(&conf);
788			break;
789		}
790		if (error < 0)
791			break;
792		/* Ignore any trailing garbage on the line. */
793		if (parse_peek(&conf) != '\n') {
794			printf("mountroot: advancing to next directive...\n");
795			(void)parse_skipto(&conf, '\n');
796		}
797		mp = TAILQ_NEXT(mpdevfs, mnt_list);
798	}
799	if (mp != NULL)
800		return (0);
801
802	/*
803	 * We failed to mount (a new) root.
804	 */
805	switch (root_mount_onfail) {
806	case A_CONTINUE:
807		break;
808	case A_PANIC:
809		panic("mountroot: unable to (re-)mount root.");
810		/* NOTREACHED */
811	case A_RETRY:
812		goto retry;
813	case A_REBOOT:
814		kern_reboot(RB_NOSYNC);
815		/* NOTREACHED */
816	}
817
818	return (error);
819}
820
821static void
822vfs_mountroot_conf0(struct sbuf *sb)
823{
824	char *s, *tok, *mnt, *opt;
825	int error;
826
827	sbuf_printf(sb, ".onfail panic\n");
828	sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
829	if (boothowto & RB_ASKNAME)
830		sbuf_printf(sb, ".ask\n");
831#ifdef ROOTDEVNAME
832	if (boothowto & RB_DFLTROOT)
833		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
834#endif
835	if (boothowto & RB_CDROM) {
836		sbuf_printf(sb, "cd9660:/dev/cd0 ro\n");
837		sbuf_printf(sb, ".timeout 0\n");
838		sbuf_printf(sb, "cd9660:/dev/acd0 ro\n");
839		sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
840	}
841	s = kern_getenv("vfs.root.mountfrom");
842	if (s != NULL) {
843		opt = kern_getenv("vfs.root.mountfrom.options");
844		tok = s;
845		error = parse_token(&tok, &mnt);
846		while (!error) {
847			sbuf_printf(sb, "%s %s\n", mnt,
848			    (opt != NULL) ? opt : "");
849			free(mnt, M_TEMP);
850			error = parse_token(&tok, &mnt);
851		}
852		if (opt != NULL)
853			freeenv(opt);
854		freeenv(s);
855	}
856	if (rootdevnames[0] != NULL)
857		sbuf_printf(sb, "%s\n", rootdevnames[0]);
858	if (rootdevnames[1] != NULL)
859		sbuf_printf(sb, "%s\n", rootdevnames[1]);
860#ifdef ROOTDEVNAME
861	if (!(boothowto & RB_DFLTROOT))
862		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
863#endif
864	if (!(boothowto & RB_ASKNAME))
865		sbuf_printf(sb, ".ask\n");
866}
867
868static int
869vfs_mountroot_readconf(struct thread *td, struct sbuf *sb)
870{
871	static char buf[128];
872	struct nameidata nd;
873	off_t ofs;
874	ssize_t resid;
875	int error, flags, len;
876
877	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/.mount.conf", td);
878	flags = FREAD;
879	error = vn_open(&nd, &flags, 0, NULL);
880	if (error)
881		return (error);
882
883	NDFREE(&nd, NDF_ONLY_PNBUF);
884	ofs = 0;
885	len = sizeof(buf) - 1;
886	while (1) {
887		error = vn_rdwr(UIO_READ, nd.ni_vp, buf, len, ofs,
888		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
889		    NOCRED, &resid, td);
890		if (error)
891			break;
892		if (resid == len)
893			break;
894		buf[len - resid] = 0;
895		sbuf_printf(sb, "%s", buf);
896		ofs += len - resid;
897	}
898
899	VOP_UNLOCK(nd.ni_vp, 0);
900	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
901	return (error);
902}
903
904static void
905vfs_mountroot_wait(void)
906{
907	struct root_hold_token *h;
908	struct timeval lastfail;
909	int curfail;
910
911	curfail = 0;
912	while (1) {
913		DROP_GIANT();
914		g_waitidle();
915		PICKUP_GIANT();
916		mtx_lock(&root_holds_mtx);
917		if (LIST_EMPTY(&root_holds)) {
918			mtx_unlock(&root_holds_mtx);
919			break;
920		}
921		if (ppsratecheck(&lastfail, &curfail, 1)) {
922			printf("Root mount waiting for:");
923			LIST_FOREACH(h, &root_holds, list)
924				printf(" %s", h->who);
925			printf("\n");
926		}
927		msleep(&root_holds, &root_holds_mtx, PZERO | PDROP, "roothold",
928		    hz);
929	}
930}
931
932void
933vfs_mountroot(void)
934{
935	struct mount *mp;
936	struct sbuf *sb;
937	struct thread *td;
938	time_t timebase;
939	int error;
940
941	td = curthread;
942
943	vfs_mountroot_wait();
944
945	sb = sbuf_new_auto();
946	vfs_mountroot_conf0(sb);
947	sbuf_finish(sb);
948
949	error = vfs_mountroot_devfs(td, &mp);
950	while (!error) {
951		error = vfs_mountroot_parse(sb, mp);
952		if (!error) {
953			error = vfs_mountroot_shuffle(td, mp);
954			if (!error) {
955				sbuf_clear(sb);
956				error = vfs_mountroot_readconf(td, sb);
957				sbuf_finish(sb);
958			}
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