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