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