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