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