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