vfs_mountroot.c revision 253847
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 253847 2013-07-31 19:14:00Z ian $");
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 root_hold_token {
101	const char			*who;
102	LIST_ENTRY(root_hold_token)	list;
103};
104
105static LIST_HEAD(, root_hold_token)	root_holds =
106    LIST_HEAD_INITIALIZER(root_holds);
107
108enum action {
109	A_CONTINUE,
110	A_PANIC,
111	A_REBOOT,
112	A_RETRY
113};
114
115static enum action root_mount_onfail = A_CONTINUE;
116
117static int root_mount_mddev;
118static int root_mount_complete;
119
120/* By default wait up to 3 seconds for devices to appear. */
121static int root_mount_timeout = 3;
122
123struct root_hold_token *
124root_mount_hold(const char *identifier)
125{
126	struct root_hold_token *h;
127
128	if (root_mounted())
129		return (NULL);
130
131	h = malloc(sizeof *h, M_DEVBUF, M_ZERO | M_WAITOK);
132	h->who = identifier;
133	mtx_lock(&mountlist_mtx);
134	LIST_INSERT_HEAD(&root_holds, h, list);
135	mtx_unlock(&mountlist_mtx);
136	return (h);
137}
138
139void
140root_mount_rel(struct root_hold_token *h)
141{
142
143	if (h == NULL)
144		return;
145	mtx_lock(&mountlist_mtx);
146	LIST_REMOVE(h, list);
147	wakeup(&root_holds);
148	mtx_unlock(&mountlist_mtx);
149	free(h, M_DEVBUF);
150}
151
152int
153root_mounted(void)
154{
155
156	/* No mutex is acquired here because int stores are atomic. */
157	return (root_mount_complete);
158}
159
160void
161root_mount_wait(void)
162{
163
164	/*
165	 * Panic on an obvious deadlock - the function can't be called from
166	 * a thread which is doing the whole SYSINIT stuff.
167	 */
168	KASSERT(curthread->td_proc->p_pid != 0,
169	    ("root_mount_wait: cannot be called from the swapper thread"));
170	mtx_lock(&mountlist_mtx);
171	while (!root_mount_complete) {
172		msleep(&root_mount_complete, &mountlist_mtx, PZERO, "rootwait",
173		    hz);
174	}
175	mtx_unlock(&mountlist_mtx);
176}
177
178static void
179set_rootvnode(void)
180{
181	struct proc *p;
182
183	if (VFS_ROOT(TAILQ_FIRST(&mountlist), LK_EXCLUSIVE, &rootvnode))
184		panic("Cannot find root vnode");
185
186	VOP_UNLOCK(rootvnode, 0);
187
188	p = curthread->td_proc;
189	FILEDESC_XLOCK(p->p_fd);
190
191	if (p->p_fd->fd_cdir != NULL)
192		vrele(p->p_fd->fd_cdir);
193	p->p_fd->fd_cdir = rootvnode;
194	VREF(rootvnode);
195
196	if (p->p_fd->fd_rdir != NULL)
197		vrele(p->p_fd->fd_rdir);
198	p->p_fd->fd_rdir = rootvnode;
199	VREF(rootvnode);
200
201	FILEDESC_XUNLOCK(p->p_fd);
202}
203
204static int
205vfs_mountroot_devfs(struct thread *td, struct mount **mpp)
206{
207	struct vfsoptlist *opts;
208	struct vfsconf *vfsp;
209	struct mount *mp;
210	int error;
211
212	*mpp = NULL;
213
214	vfsp = vfs_byname("devfs");
215	KASSERT(vfsp != NULL, ("Could not find devfs by name"));
216	if (vfsp == NULL)
217		return (ENOENT);
218
219	mp = vfs_mount_alloc(NULLVP, vfsp, "/dev", td->td_ucred);
220
221	error = VFS_MOUNT(mp);
222	KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
223	if (error)
224		return (error);
225
226	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
227	TAILQ_INIT(opts);
228	mp->mnt_opt = opts;
229
230	mtx_lock(&mountlist_mtx);
231	TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
232	mtx_unlock(&mountlist_mtx);
233
234	*mpp = mp;
235	set_rootvnode();
236
237	error = kern_symlink(td, "/", "dev", UIO_SYSSPACE);
238	if (error)
239		printf("kern_symlink /dev -> / returns %d\n", error);
240
241	return (error);
242}
243
244static int
245vfs_mountroot_shuffle(struct thread *td, struct mount *mpdevfs)
246{
247	struct nameidata nd;
248	struct mount *mporoot, *mpnroot;
249	struct vnode *vp, *vporoot, *vpdevfs;
250	char *fspath;
251	int error;
252
253	mpnroot = TAILQ_NEXT(mpdevfs, mnt_list);
254
255	/* Shuffle the mountlist. */
256	mtx_lock(&mountlist_mtx);
257	mporoot = TAILQ_FIRST(&mountlist);
258	TAILQ_REMOVE(&mountlist, mpdevfs, mnt_list);
259	if (mporoot != mpdevfs) {
260		TAILQ_REMOVE(&mountlist, mpnroot, mnt_list);
261		TAILQ_INSERT_HEAD(&mountlist, mpnroot, mnt_list);
262	}
263	TAILQ_INSERT_TAIL(&mountlist, mpdevfs, mnt_list);
264	mtx_unlock(&mountlist_mtx);
265
266	cache_purgevfs(mporoot);
267	if (mporoot != mpdevfs)
268		cache_purgevfs(mpdevfs);
269
270	VFS_ROOT(mporoot, LK_EXCLUSIVE, &vporoot);
271
272	VI_LOCK(vporoot);
273	vporoot->v_iflag &= ~VI_MOUNT;
274	VI_UNLOCK(vporoot);
275	vporoot->v_mountedhere = NULL;
276	mporoot->mnt_flag &= ~MNT_ROOTFS;
277	mporoot->mnt_vnodecovered = NULL;
278	vput(vporoot);
279
280	/* Set up the new rootvnode, and purge the cache */
281	mpnroot->mnt_vnodecovered = NULL;
282	set_rootvnode();
283	cache_purgevfs(rootvnode->v_mount);
284
285	if (mporoot != mpdevfs) {
286		/* Remount old root under /.mount or /mnt */
287		fspath = "/.mount";
288		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
289		    fspath, td);
290		error = namei(&nd);
291		if (error) {
292			NDFREE(&nd, NDF_ONLY_PNBUF);
293			fspath = "/mnt";
294			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
295			    fspath, td);
296			error = namei(&nd);
297		}
298		if (!error) {
299			vp = nd.ni_vp;
300			error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
301			if (!error)
302				error = vinvalbuf(vp, V_SAVE, 0, 0);
303			if (!error) {
304				cache_purge(vp);
305				mporoot->mnt_vnodecovered = vp;
306				vp->v_mountedhere = mporoot;
307				strlcpy(mporoot->mnt_stat.f_mntonname,
308				    fspath, MNAMELEN);
309				VOP_UNLOCK(vp, 0);
310			} else
311				vput(vp);
312		}
313		NDFREE(&nd, NDF_ONLY_PNBUF);
314
315		if (error && bootverbose)
316			printf("mountroot: unable to remount previous root "
317			    "under /.mount or /mnt (error %d).\n", error);
318	}
319
320	/* Remount devfs under /dev */
321	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
322	error = namei(&nd);
323	if (!error) {
324		vp = nd.ni_vp;
325		error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
326		if (!error)
327			error = vinvalbuf(vp, V_SAVE, 0, 0);
328		if (!error) {
329			vpdevfs = mpdevfs->mnt_vnodecovered;
330			if (vpdevfs != NULL) {
331				cache_purge(vpdevfs);
332				vpdevfs->v_mountedhere = NULL;
333				vrele(vpdevfs);
334			}
335			mpdevfs->mnt_vnodecovered = vp;
336			vp->v_mountedhere = mpdevfs;
337			VOP_UNLOCK(vp, 0);
338		} else
339			vput(vp);
340	}
341	if (error && bootverbose)
342		printf("mountroot: unable to remount devfs under /dev "
343		    "(error %d).\n", error);
344	NDFREE(&nd, NDF_ONLY_PNBUF);
345
346	if (mporoot == mpdevfs) {
347		vfs_unbusy(mpdevfs);
348		/* Unlink the no longer needed /dev/dev -> / symlink */
349		error = kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
350		if (error && bootverbose)
351			printf("mountroot: unable to unlink /dev/dev "
352			    "(error %d)\n", error);
353	}
354
355	return (0);
356}
357
358/*
359 * Configuration parser.
360 */
361
362/* Parser character classes. */
363#define	CC_WHITESPACE		-1
364#define	CC_NONWHITESPACE	-2
365
366/* Parse errors. */
367#define	PE_EOF			-1
368#define	PE_EOL			-2
369
370static __inline int
371parse_peek(char **conf)
372{
373
374	return (**conf);
375}
376
377static __inline void
378parse_poke(char **conf, int c)
379{
380
381	**conf = c;
382}
383
384static __inline void
385parse_advance(char **conf)
386{
387
388	(*conf)++;
389}
390
391static __inline int
392parse_isspace(int c)
393{
394
395	return ((c == ' ' || c == '\t' || c == '\n') ? 1 : 0);
396}
397
398static int
399parse_skipto(char **conf, int mc)
400{
401	int c, match;
402
403	while (1) {
404		c = parse_peek(conf);
405		if (c == 0)
406			return (PE_EOF);
407		switch (mc) {
408		case CC_WHITESPACE:
409			match = (c == ' ' || c == '\t' || c == '\n') ? 1 : 0;
410			break;
411		case CC_NONWHITESPACE:
412			if (c == '\n')
413				return (PE_EOL);
414			match = (c != ' ' && c != '\t') ? 1 : 0;
415			break;
416		default:
417			match = (c == mc) ? 1 : 0;
418			break;
419		}
420		if (match)
421			break;
422		parse_advance(conf);
423	}
424	return (0);
425}
426
427static int
428parse_token(char **conf, char **tok)
429{
430	char *p;
431	size_t len;
432	int error;
433
434	*tok = NULL;
435	error = parse_skipto(conf, CC_NONWHITESPACE);
436	if (error)
437		return (error);
438	p = *conf;
439	error = parse_skipto(conf, CC_WHITESPACE);
440	len = *conf - p;
441	*tok = malloc(len + 1, M_TEMP, M_WAITOK | M_ZERO);
442	bcopy(p, *tok, len);
443	return (0);
444}
445
446static void
447parse_dir_ask_printenv(const char *var)
448{
449	char *val;
450
451	val = getenv(var);
452	if (val != NULL) {
453		printf("  %s=%s\n", var, val);
454		freeenv(val);
455	}
456}
457
458static int
459parse_dir_ask(char **conf)
460{
461	char name[80];
462	char *mnt;
463	int error;
464
465	printf("\nLoader variables:\n");
466	parse_dir_ask_printenv("vfs.root.mountfrom");
467	parse_dir_ask_printenv("vfs.root.mountfrom.options");
468
469	printf("\nManual root filesystem specification:\n");
470	printf("  <fstype>:<device> [options]\n");
471	printf("      Mount <device> using filesystem <fstype>\n");
472	printf("      and with the specified (optional) option list.\n");
473	printf("\n");
474	printf("    eg. ufs:/dev/da0s1a\n");
475	printf("        zfs:tank\n");
476	printf("        cd9660:/dev/acd0 ro\n");
477	printf("          (which is equivalent to: ");
478	printf("mount -t cd9660 -o ro /dev/acd0 /)\n");
479	printf("\n");
480	printf("  ?               List valid disk boot devices\n");
481	printf("  .               Yield 1 second (for background tasks)\n");
482	printf("  <empty line>    Abort manual input\n");
483
484	do {
485		error = EINVAL;
486		printf("\nmountroot> ");
487		cngets(name, sizeof(name), GETS_ECHO);
488		if (name[0] == '\0')
489			break;
490		if (name[0] == '?' && name[1] == '\0') {
491			printf("\nList of GEOM managed disk devices:\n  ");
492			g_dev_print();
493			continue;
494		}
495		if (name[0] == '.' && name[1] == '\0') {
496			pause("rmask", hz);
497			continue;
498		}
499		mnt = name;
500		error = parse_mount(&mnt);
501		if (error == -1)
502			printf("Invalid file system specification.\n");
503	} while (error != 0);
504
505	return (error);
506}
507
508static int
509parse_dir_md(char **conf)
510{
511	struct stat sb;
512	struct thread *td;
513	struct md_ioctl *mdio;
514	char *path, *tok;
515	int error, fd, len;
516
517	td = curthread;
518
519	error = parse_token(conf, &tok);
520	if (error)
521		return (error);
522
523	len = strlen(tok);
524	mdio = malloc(sizeof(*mdio) + len + 1, M_TEMP, M_WAITOK | M_ZERO);
525	path = (void *)(mdio + 1);
526	bcopy(tok, path, len);
527	free(tok, M_TEMP);
528
529	/* Get file status. */
530	error = kern_stat(td, path, UIO_SYSSPACE, &sb);
531	if (error)
532		goto out;
533
534	/* Open /dev/mdctl so that we can attach/detach. */
535	error = kern_open(td, "/dev/" MDCTL_NAME, UIO_SYSSPACE, O_RDWR, 0);
536	if (error)
537		goto out;
538
539	fd = td->td_retval[0];
540	mdio->md_version = MDIOVERSION;
541	mdio->md_type = MD_VNODE;
542
543	if (root_mount_mddev != -1) {
544		mdio->md_unit = root_mount_mddev;
545		DROP_GIANT();
546		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
547		PICKUP_GIANT();
548		/* Ignore errors. We don't care. */
549		root_mount_mddev = -1;
550	}
551
552	mdio->md_file = (void *)(mdio + 1);
553	mdio->md_options = MD_AUTOUNIT | MD_READONLY;
554	mdio->md_mediasize = sb.st_size;
555	mdio->md_unit = 0;
556	DROP_GIANT();
557	error = kern_ioctl(td, fd, MDIOCATTACH, (void *)mdio);
558	PICKUP_GIANT();
559	if (error)
560		goto out;
561
562	if (mdio->md_unit > 9) {
563		printf("rootmount: too many md units\n");
564		mdio->md_file = NULL;
565		mdio->md_options = 0;
566		mdio->md_mediasize = 0;
567		DROP_GIANT();
568		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
569		PICKUP_GIANT();
570		/* Ignore errors. We don't care. */
571		error = ERANGE;
572		goto out;
573	}
574
575	root_mount_mddev = mdio->md_unit;
576	printf(MD_NAME "%u attached to %s\n", root_mount_mddev, mdio->md_file);
577
578	error = kern_close(td, fd);
579
580 out:
581	free(mdio, M_TEMP);
582	return (error);
583}
584
585static int
586parse_dir_onfail(char **conf)
587{
588	char *action;
589	int error;
590
591	error = parse_token(conf, &action);
592	if (error)
593		return (error);
594
595	if (!strcmp(action, "continue"))
596		root_mount_onfail = A_CONTINUE;
597	else if (!strcmp(action, "panic"))
598		root_mount_onfail = A_PANIC;
599	else if (!strcmp(action, "reboot"))
600		root_mount_onfail = A_REBOOT;
601	else if (!strcmp(action, "retry"))
602		root_mount_onfail = A_RETRY;
603	else {
604		printf("rootmount: %s: unknown action\n", action);
605		error = EINVAL;
606	}
607
608	free(action, M_TEMP);
609	return (0);
610}
611
612static int
613parse_dir_timeout(char **conf)
614{
615	char *tok, *endtok;
616	long secs;
617	int error;
618
619	error = parse_token(conf, &tok);
620	if (error)
621		return (error);
622
623	secs = strtol(tok, &endtok, 0);
624	error = (secs < 0 || *endtok != '\0') ? EINVAL : 0;
625	if (!error)
626		root_mount_timeout = secs;
627	free(tok, M_TEMP);
628	return (error);
629}
630
631static int
632parse_directive(char **conf)
633{
634	char *dir;
635	int error;
636
637	error = parse_token(conf, &dir);
638	if (error)
639		return (error);
640
641	if (strcmp(dir, ".ask") == 0)
642		error = parse_dir_ask(conf);
643	else if (strcmp(dir, ".md") == 0)
644		error = parse_dir_md(conf);
645	else if (strcmp(dir, ".onfail") == 0)
646		error = parse_dir_onfail(conf);
647	else if (strcmp(dir, ".timeout") == 0)
648		error = parse_dir_timeout(conf);
649	else {
650		printf("mountroot: invalid directive `%s'\n", dir);
651		/* Ignore the rest of the line. */
652		(void)parse_skipto(conf, '\n');
653		error = EINVAL;
654	}
655	free(dir, M_TEMP);
656	return (error);
657}
658
659static int
660parse_mount_dev_present(const char *dev)
661{
662	struct nameidata nd;
663	int error;
664
665	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, dev, curthread);
666	error = namei(&nd);
667	if (!error)
668		vput(nd.ni_vp);
669	NDFREE(&nd, NDF_ONLY_PNBUF);
670	return (error != 0) ? 0 : 1;
671}
672
673#define	ERRMSGL	255
674static int
675parse_mount(char **conf)
676{
677	char *errmsg;
678	struct mntarg *ma;
679	char *dev, *fs, *opts, *tok;
680	int delay, error, timeout;
681
682	error = parse_token(conf, &tok);
683	if (error)
684		return (error);
685	fs = tok;
686	error = parse_skipto(&tok, ':');
687	if (error) {
688		free(fs, M_TEMP);
689		return (error);
690	}
691	parse_poke(&tok, '\0');
692	parse_advance(&tok);
693	dev = tok;
694
695	if (root_mount_mddev != -1) {
696		/* Handle substitution for the md unit number. */
697		tok = strstr(dev, "md#");
698		if (tok != NULL)
699			tok[2] = '0' + root_mount_mddev;
700	}
701
702	/* Parse options. */
703	error = parse_token(conf, &tok);
704	opts = (error == 0) ? tok : NULL;
705
706	printf("Trying to mount root from %s:%s [%s]...\n", fs, dev,
707	    (opts != NULL) ? opts : "");
708
709	errmsg = malloc(ERRMSGL, M_TEMP, M_WAITOK | M_ZERO);
710
711	if (vfs_byname(fs) == NULL) {
712		strlcpy(errmsg, "unknown file system", sizeof(errmsg));
713		error = ENOENT;
714		goto out;
715	}
716
717	if (strcmp(fs, "zfs") != 0 && strstr(fs, "nfs") == NULL &&
718	    dev[0] != '\0' && !parse_mount_dev_present(dev)) {
719		printf("mountroot: waiting for device %s ...\n", dev);
720		delay = hz / 10;
721		timeout = root_mount_timeout * hz;
722		do {
723			pause("rmdev", delay);
724			timeout -= delay;
725		} while (timeout > 0 && !parse_mount_dev_present(dev));
726		if (timeout <= 0) {
727			error = ENODEV;
728			goto out;
729		}
730	}
731
732	ma = NULL;
733	ma = mount_arg(ma, "fstype", fs, -1);
734	ma = mount_arg(ma, "fspath", "/", -1);
735	ma = mount_arg(ma, "from", dev, -1);
736	ma = mount_arg(ma, "errmsg", errmsg, ERRMSGL);
737	ma = mount_arg(ma, "ro", NULL, 0);
738	ma = parse_mountroot_options(ma, opts);
739	error = kernel_mount(ma, MNT_ROOTFS);
740
741 out:
742	if (error) {
743		printf("Mounting from %s:%s failed with error %d",
744		    fs, dev, error);
745		if (errmsg[0] != '\0')
746			printf(": %s", errmsg);
747		printf(".\n");
748	}
749	free(fs, M_TEMP);
750	free(errmsg, M_TEMP);
751	if (opts != NULL)
752		free(opts, M_TEMP);
753	/* kernel_mount can return -1 on error. */
754	return ((error < 0) ? EDOOFUS : error);
755}
756#undef ERRMSGL
757
758static int
759vfs_mountroot_parse(struct sbuf *sb, struct mount *mpdevfs)
760{
761	struct mount *mp;
762	char *conf;
763	int error;
764
765	root_mount_mddev = -1;
766
767retry:
768	conf = sbuf_data(sb);
769	mp = TAILQ_NEXT(mpdevfs, mnt_list);
770	error = (mp == NULL) ? 0 : EDOOFUS;
771	root_mount_onfail = A_CONTINUE;
772	while (mp == NULL) {
773		error = parse_skipto(&conf, CC_NONWHITESPACE);
774		if (error == PE_EOL) {
775			parse_advance(&conf);
776			continue;
777		}
778		if (error < 0)
779			break;
780		switch (parse_peek(&conf)) {
781		case '#':
782			error = parse_skipto(&conf, '\n');
783			break;
784		case '.':
785			error = parse_directive(&conf);
786			break;
787		default:
788			error = parse_mount(&conf);
789			break;
790		}
791		if (error < 0)
792			break;
793		/* Ignore any trailing garbage on the line. */
794		if (parse_peek(&conf) != '\n') {
795			printf("mountroot: advancing to next directive...\n");
796			(void)parse_skipto(&conf, '\n');
797		}
798		mp = TAILQ_NEXT(mpdevfs, mnt_list);
799	}
800	if (mp != NULL)
801		return (0);
802
803	/*
804	 * We failed to mount (a new) root.
805	 */
806	switch (root_mount_onfail) {
807	case A_CONTINUE:
808		break;
809	case A_PANIC:
810		panic("mountroot: unable to (re-)mount root.");
811		/* NOTREACHED */
812	case A_RETRY:
813		goto retry;
814	case A_REBOOT:
815		kern_reboot(RB_NOSYNC);
816		/* NOTREACHED */
817	}
818
819	return (error);
820}
821
822static void
823vfs_mountroot_conf0(struct sbuf *sb)
824{
825	char *s, *tok, *mnt, *opt;
826	int error;
827
828	sbuf_printf(sb, ".onfail panic\n");
829	sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
830	if (boothowto & RB_ASKNAME)
831		sbuf_printf(sb, ".ask\n");
832#ifdef ROOTDEVNAME
833	if (boothowto & RB_DFLTROOT)
834		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
835#endif
836	if (boothowto & RB_CDROM) {
837		sbuf_printf(sb, "cd9660:/dev/cd0 ro\n");
838		sbuf_printf(sb, ".timeout 0\n");
839		sbuf_printf(sb, "cd9660:/dev/acd0 ro\n");
840		sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
841	}
842	s = getenv("vfs.root.mountfrom");
843	if (s != NULL) {
844		opt = getenv("vfs.root.mountfrom.options");
845		tok = s;
846		error = parse_token(&tok, &mnt);
847		while (!error) {
848			sbuf_printf(sb, "%s %s\n", mnt,
849			    (opt != NULL) ? opt : "");
850			free(mnt, M_TEMP);
851			error = parse_token(&tok, &mnt);
852		}
853		if (opt != NULL)
854			freeenv(opt);
855		freeenv(s);
856	}
857	if (rootdevnames[0] != NULL)
858		sbuf_printf(sb, "%s\n", rootdevnames[0]);
859	if (rootdevnames[1] != NULL)
860		sbuf_printf(sb, "%s\n", rootdevnames[1]);
861#ifdef ROOTDEVNAME
862	if (!(boothowto & RB_DFLTROOT))
863		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
864#endif
865	if (!(boothowto & RB_ASKNAME))
866		sbuf_printf(sb, ".ask\n");
867}
868
869static int
870vfs_mountroot_readconf(struct thread *td, struct sbuf *sb)
871{
872	static char buf[128];
873	struct nameidata nd;
874	off_t ofs;
875	ssize_t resid;
876	int error, flags, len;
877
878	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/.mount.conf", td);
879	flags = FREAD;
880	error = vn_open(&nd, &flags, 0, NULL);
881	if (error)
882		return (error);
883
884	NDFREE(&nd, NDF_ONLY_PNBUF);
885	ofs = 0;
886	len = sizeof(buf) - 1;
887	while (1) {
888		error = vn_rdwr(UIO_READ, nd.ni_vp, buf, len, ofs,
889		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
890		    NOCRED, &resid, td);
891		if (error)
892			break;
893		if (resid == len)
894			break;
895		buf[len - resid] = 0;
896		sbuf_printf(sb, "%s", buf);
897		ofs += len - resid;
898	}
899
900	VOP_UNLOCK(nd.ni_vp, 0);
901	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
902	return (error);
903}
904
905static void
906vfs_mountroot_wait(void)
907{
908	struct root_hold_token *h;
909	struct timeval lastfail;
910	int curfail;
911
912	curfail = 0;
913	while (1) {
914		DROP_GIANT();
915		g_waitidle();
916		PICKUP_GIANT();
917		mtx_lock(&mountlist_mtx);
918		if (LIST_EMPTY(&root_holds)) {
919			mtx_unlock(&mountlist_mtx);
920			break;
921		}
922		if (ppsratecheck(&lastfail, &curfail, 1)) {
923			printf("Root mount waiting for:");
924			LIST_FOREACH(h, &root_holds, list)
925				printf(" %s", h->who);
926			printf("\n");
927		}
928		msleep(&root_holds, &mountlist_mtx, PZERO | PDROP, "roothold",
929		    hz);
930	}
931}
932
933void
934vfs_mountroot(void)
935{
936	struct mount *mp;
937	struct sbuf *sb;
938	struct thread *td;
939	time_t timebase;
940	int error;
941
942	td = curthread;
943
944	vfs_mountroot_wait();
945
946	sb = sbuf_new_auto();
947	vfs_mountroot_conf0(sb);
948	sbuf_finish(sb);
949
950	error = vfs_mountroot_devfs(td, &mp);
951	while (!error) {
952		error = vfs_mountroot_parse(sb, mp);
953		if (!error) {
954			error = vfs_mountroot_shuffle(td, mp);
955			if (!error) {
956				sbuf_clear(sb);
957				error = vfs_mountroot_readconf(td, sb);
958				sbuf_finish(sb);
959			}
960		}
961	}
962
963	sbuf_delete(sb);
964
965	/*
966	 * Iterate over all currently mounted file systems and use
967	 * the time stamp found to check and/or initialize the RTC.
968	 * Call inittodr() only once and pass it the largest of the
969	 * timestamps we encounter.
970	 */
971	timebase = 0;
972	mtx_lock(&mountlist_mtx);
973	mp = TAILQ_FIRST(&mountlist);
974	while (mp != NULL) {
975		if (mp->mnt_time > timebase)
976			timebase = mp->mnt_time;
977		mp = TAILQ_NEXT(mp, mnt_list);
978	}
979	mtx_unlock(&mountlist_mtx);
980	inittodr(timebase);
981
982	/* Keep prison0's root in sync with the global rootvnode. */
983	mtx_lock(&prison0.pr_mtx);
984	prison0.pr_root = rootvnode;
985	vref(prison0.pr_root);
986	mtx_unlock(&prison0.pr_mtx);
987
988	mtx_lock(&mountlist_mtx);
989	atomic_store_rel_int(&root_mount_complete, 1);
990	wakeup(&root_mount_complete);
991	mtx_unlock(&mountlist_mtx);
992
993	EVENTHANDLER_INVOKE(mountroot);
994}
995
996static struct mntarg *
997parse_mountroot_options(struct mntarg *ma, const char *options)
998{
999	char *p;
1000	char *name, *name_arg;
1001	char *val, *val_arg;
1002	char *opts;
1003
1004	if (options == NULL || options[0] == '\0')
1005		return (ma);
1006
1007	p = opts = strdup(options, M_MOUNT);
1008	if (opts == NULL) {
1009		return (ma);
1010	}
1011
1012	while((name = strsep(&p, ",")) != NULL) {
1013		if (name[0] == '\0')
1014			break;
1015
1016		val = strchr(name, '=');
1017		if (val != NULL) {
1018			*val = '\0';
1019			++val;
1020		}
1021		if( strcmp(name, "rw") == 0 ||
1022		    strcmp(name, "noro") == 0) {
1023			/*
1024			 * The first time we mount the root file system,
1025			 * we need to mount 'ro', so We need to ignore
1026			 * 'rw' and 'noro' mount options.
1027			 */
1028			continue;
1029		}
1030		name_arg = strdup(name, M_MOUNT);
1031		val_arg = NULL;
1032		if (val != NULL)
1033			val_arg = strdup(val, M_MOUNT);
1034
1035		ma = mount_arg(ma, name_arg, val_arg,
1036		    (val_arg != NULL ? -1 : 0));
1037	}
1038	free(opts, M_MOUNT);
1039	return (ma);
1040}
1041