vfs_mountroot.c revision 287964
189837Skris/*-
289837Skris * Copyright (c) 2010 Marcel Moolenaar
389837Skris * Copyright (c) 1999-2004 Poul-Henning Kamp
489837Skris * Copyright (c) 1999 Michael Smith
589837Skris * Copyright (c) 1989, 1993
689837Skris *      The Regents of the University of California.  All rights reserved.
789837Skris * (c) UNIX System Laboratories, Inc.
889837Skris * All or some portions of this file are derived from material licensed
989837Skris * to the University of California by American Telephone and Telegraph
1089837Skris * Co. or Unix System Laboratories, Inc. and are reproduced herein with
1189837Skris * the permission of UNIX System Laboratories, Inc.
1289837Skris *
1389837Skris * Redistribution and use in source and binary forms, with or without
1489837Skris * modification, are permitted provided that the following conditions
15269686Sjkim * are met:
1689837Skris * 1. Redistributions of source code must retain the above copyright
1789837Skris *    notice, this list of conditions and the following disclaimer.
1889837Skris * 2. Redistributions in binary form must reproduce the above copyright
1989837Skris *    notice, this list of conditions and the following disclaimer in the
2089837Skris *    documentation and/or other materials provided with the distribution.
2189837Skris * 4. Neither the name of the University nor the names of its contributors
2289837Skris *    may be used to endorse or promote products derived from this software
2389837Skris *    without specific prior written permission.
2489837Skris *
2589837Skris * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
2689837Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2789837Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2889837Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2989837Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3089837Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3189837Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3289837Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3389837Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3489837Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3589837Skris * SUCH DAMAGE.
3689837Skris */
3789837Skris
3889837Skris#include "opt_rootdevname.h"
3989837Skris
4089837Skris#include <sys/cdefs.h>
4189837Skris__FBSDID("$FreeBSD: head/sys/kern/vfs_mountroot.c 287964 2015-09-18 17:32:22Z trasz $");
4289837Skris
4389837Skris#include <sys/param.h>
4489837Skris#include <sys/conf.h>
4589837Skris#include <sys/cons.h>
4689837Skris#include <sys/fcntl.h>
4789837Skris#include <sys/jail.h>
4889837Skris#include <sys/kernel.h>
4989837Skris#include <sys/malloc.h>
5089837Skris#include <sys/mdioctl.h>
51295016Sjkim#include <sys/mount.h>
52295016Sjkim#include <sys/mutex.h>
5389837Skris#include <sys/namei.h>
5489837Skris#include <sys/priv.h>
5589837Skris#include <sys/proc.h>
5689837Skris#include <sys/filedesc.h>
5789837Skris#include <sys/reboot.h>
5889837Skris#include <sys/sbuf.h>
5989837Skris#include <sys/stat.h>
60284285Sjkim#include <sys/syscallsubr.h>
61284285Sjkim#include <sys/sysproto.h>
6289837Skris#include <sys/sx.h>
63284285Sjkim#include <sys/sysctl.h>
6489837Skris#include <sys/sysent.h>
6589837Skris#include <sys/systm.h>
6689837Skris#include <sys/vnode.h>
67284285Sjkim
68284285Sjkim#include <geom/geom.h>
69284285Sjkim
70284285Sjkim/*
71284285Sjkim * The root filesystem is detailed in the kernel environment variable
7289837Skris * vfs.root.mountfrom, which is expected to be in the general format
7389837Skris *
74284285Sjkim * <vfsname>:[<path>][	<vfsname>:[<path>] ...]
7589837Skris * vfsname   := the name of a VFS known to the kernel and capable
76284285Sjkim *              of being mounted as root
77284285Sjkim * path      := disk device name or other data used by the filesystem
78284285Sjkim *              to locate its physical store
79295016Sjkim *
80295016Sjkim * If the environment variable vfs.root.mountfrom is a space separated list,
81295016Sjkim * each list element is tried in turn and the root filesystem will be mounted
8289837Skris * from the first one that suceeds.
8389837Skris *
8489837Skris * The environment variable vfs.root.mountfrom.options is a comma delimited
85284285Sjkim * set of string mount options.  These mount options must be parseable
8689837Skris * by nmount() in the kernel.
8789837Skris */
88284285Sjkim
89284285Sjkimstatic int parse_mount(char **);
90284285Sjkimstatic struct mntarg *parse_mountroot_options(struct mntarg *, const char *);
91284285Sjkim
92284285Sjkim/*
9389837Skris * The vnode of the system's root (/ in the filesystem, without chroot
94284285Sjkim * active.)
95284285Sjkim */
96284285Sjkimstruct vnode *rootvnode;
97284285Sjkim
98284285Sjkim/*
9989837Skris * Mount of the system's /dev.
100284285Sjkim */
10189837Skrisstruct mount *rootdevmp;
102284285Sjkim
10389837Skrischar *rootdevnames[2] = {NULL, NULL};
104284285Sjkim
105284285Sjkimstruct mtx root_holds_mtx;
10689837SkrisMTX_SYSINIT(root_holds, &root_holds_mtx, "root_holds", MTX_DEF);
107284285Sjkim
108284285Sjkimstruct root_hold_token {
10989837Skris	const char			*who;
110284285Sjkim	LIST_ENTRY(root_hold_token)	list;
111284285Sjkim};
112284285Sjkim
11389837Skrisstatic LIST_HEAD(, root_hold_token)	root_holds =
11489837Skris    LIST_HEAD_INITIALIZER(root_holds);
11589837Skris
11689837Skrisenum action {
11789837Skris	A_CONTINUE,
11889837Skris	A_PANIC,
11989837Skris	A_REBOOT,
12089837Skris	A_RETRY
12189837Skris};
12289837Skris
12389837Skrisstatic enum action root_mount_onfail = A_CONTINUE;
12489837Skris
12589837Skrisstatic int root_mount_mddev;
12689837Skrisstatic int root_mount_complete;
12789837Skris
12889837Skris/* By default wait up to 3 seconds for devices to appear. */
12989837Skrisstatic int root_mount_timeout = 3;
13089837SkrisTUNABLE_INT("vfs.mountroot.timeout", &root_mount_timeout);
131
132struct root_hold_token *
133root_mount_hold(const char *identifier)
134{
135	struct root_hold_token *h;
136
137	if (root_mounted())
138		return (NULL);
139
140	h = malloc(sizeof *h, M_DEVBUF, M_ZERO | M_WAITOK);
141	h->who = identifier;
142	mtx_lock(&root_holds_mtx);
143	LIST_INSERT_HEAD(&root_holds, h, list);
144	mtx_unlock(&root_holds_mtx);
145	return (h);
146}
147
148void
149root_mount_rel(struct root_hold_token *h)
150{
151
152	if (h == NULL)
153		return;
154	mtx_lock(&root_holds_mtx);
155	LIST_REMOVE(h, list);
156	wakeup(&root_holds);
157	mtx_unlock(&root_holds_mtx);
158	free(h, M_DEVBUF);
159}
160
161int
162root_mounted(void)
163{
164
165	/* No mutex is acquired here because int stores are atomic. */
166	return (root_mount_complete);
167}
168
169void
170root_mount_wait(void)
171{
172
173	/*
174	 * Panic on an obvious deadlock - the function can't be called from
175	 * a thread which is doing the whole SYSINIT stuff.
176	 */
177	KASSERT(curthread->td_proc->p_pid != 0,
178	    ("root_mount_wait: cannot be called from the swapper thread"));
179	mtx_lock(&root_holds_mtx);
180	while (!root_mount_complete) {
181		msleep(&root_mount_complete, &root_holds_mtx, PZERO, "rootwait",
182		    hz);
183	}
184	mtx_unlock(&root_holds_mtx);
185}
186
187static void
188set_rootvnode(void)
189{
190	struct proc *p;
191
192	if (VFS_ROOT(TAILQ_FIRST(&mountlist), LK_EXCLUSIVE, &rootvnode))
193		panic("Cannot find root vnode");
194
195	VOP_UNLOCK(rootvnode, 0);
196
197	p = curthread->td_proc;
198	FILEDESC_XLOCK(p->p_fd);
199
200	if (p->p_fd->fd_cdir != NULL)
201		vrele(p->p_fd->fd_cdir);
202	p->p_fd->fd_cdir = rootvnode;
203	VREF(rootvnode);
204
205	if (p->p_fd->fd_rdir != NULL)
206		vrele(p->p_fd->fd_rdir);
207	p->p_fd->fd_rdir = rootvnode;
208	VREF(rootvnode);
209
210	FILEDESC_XUNLOCK(p->p_fd);
211}
212
213static int
214vfs_mountroot_devfs(struct thread *td, struct mount **mpp)
215{
216	struct vfsoptlist *opts;
217	struct vfsconf *vfsp;
218	struct mount *mp;
219	int error;
220
221	*mpp = NULL;
222
223	if (rootdevmp != NULL) {
224		/*
225		 * Already have /dev; this happens during rerooting.
226		 */
227		error = vfs_busy(rootdevmp, 0);
228		if (error != 0)
229			return (error);
230		*mpp = rootdevmp;
231	} else {
232		vfsp = vfs_byname("devfs");
233		KASSERT(vfsp != NULL, ("Could not find devfs by name"));
234		if (vfsp == NULL)
235			return (ENOENT);
236
237		mp = vfs_mount_alloc(NULLVP, vfsp, "/dev", td->td_ucred);
238
239		error = VFS_MOUNT(mp);
240		KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
241		if (error)
242			return (error);
243
244		opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
245		TAILQ_INIT(opts);
246		mp->mnt_opt = opts;
247
248		mtx_lock(&mountlist_mtx);
249		TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
250		mtx_unlock(&mountlist_mtx);
251
252		*mpp = mp;
253		rootdevmp = mp;
254	}
255
256	set_rootvnode();
257
258	error = kern_symlinkat(td, "/", AT_FDCWD, "dev", UIO_SYSSPACE);
259	if (error)
260		printf("kern_symlink /dev -> / returns %d\n", error);
261
262	return (error);
263}
264
265static int
266vfs_mountroot_shuffle(struct thread *td, struct mount *mpdevfs)
267{
268	struct nameidata nd;
269	struct mount *mporoot, *mpnroot;
270	struct vnode *vp, *vporoot, *vpdevfs;
271	char *fspath;
272	int error;
273
274	mpnroot = TAILQ_NEXT(mpdevfs, mnt_list);
275
276	/* Shuffle the mountlist. */
277	mtx_lock(&mountlist_mtx);
278	mporoot = TAILQ_FIRST(&mountlist);
279	TAILQ_REMOVE(&mountlist, mpdevfs, mnt_list);
280	if (mporoot != mpdevfs) {
281		TAILQ_REMOVE(&mountlist, mpnroot, mnt_list);
282		TAILQ_INSERT_HEAD(&mountlist, mpnroot, mnt_list);
283	}
284	TAILQ_INSERT_TAIL(&mountlist, mpdevfs, mnt_list);
285	mtx_unlock(&mountlist_mtx);
286
287	cache_purgevfs(mporoot);
288	if (mporoot != mpdevfs)
289		cache_purgevfs(mpdevfs);
290
291	VFS_ROOT(mporoot, LK_EXCLUSIVE, &vporoot);
292
293	VI_LOCK(vporoot);
294	vporoot->v_iflag &= ~VI_MOUNT;
295	VI_UNLOCK(vporoot);
296	vporoot->v_mountedhere = NULL;
297	mporoot->mnt_flag &= ~MNT_ROOTFS;
298	mporoot->mnt_vnodecovered = NULL;
299	vput(vporoot);
300
301	/* Set up the new rootvnode, and purge the cache */
302	mpnroot->mnt_vnodecovered = NULL;
303	set_rootvnode();
304	cache_purgevfs(rootvnode->v_mount);
305
306	if (mporoot != mpdevfs) {
307		/* Remount old root under /.mount or /mnt */
308		fspath = "/.mount";
309		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
310		    fspath, td);
311		error = namei(&nd);
312		if (error) {
313			NDFREE(&nd, NDF_ONLY_PNBUF);
314			fspath = "/mnt";
315			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
316			    fspath, td);
317			error = namei(&nd);
318		}
319		if (!error) {
320			vp = nd.ni_vp;
321			error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
322			if (!error)
323				error = vinvalbuf(vp, V_SAVE, 0, 0);
324			if (!error) {
325				cache_purge(vp);
326				mporoot->mnt_vnodecovered = vp;
327				vp->v_mountedhere = mporoot;
328				strlcpy(mporoot->mnt_stat.f_mntonname,
329				    fspath, MNAMELEN);
330				VOP_UNLOCK(vp, 0);
331			} else
332				vput(vp);
333		}
334		NDFREE(&nd, NDF_ONLY_PNBUF);
335
336		if (error && bootverbose)
337			printf("mountroot: unable to remount previous root "
338			    "under /.mount or /mnt (error %d).\n", error);
339	}
340
341	/* Remount devfs under /dev */
342	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
343	error = namei(&nd);
344	if (!error) {
345		vp = nd.ni_vp;
346		error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
347		if (!error)
348			error = vinvalbuf(vp, V_SAVE, 0, 0);
349		if (!error) {
350			vpdevfs = mpdevfs->mnt_vnodecovered;
351			if (vpdevfs != NULL) {
352				cache_purge(vpdevfs);
353				vpdevfs->v_mountedhere = NULL;
354				vrele(vpdevfs);
355			}
356			mpdevfs->mnt_vnodecovered = vp;
357			vp->v_mountedhere = mpdevfs;
358			VOP_UNLOCK(vp, 0);
359		} else
360			vput(vp);
361	}
362	if (error && bootverbose)
363		printf("mountroot: unable to remount devfs under /dev "
364		    "(error %d).\n", error);
365	NDFREE(&nd, NDF_ONLY_PNBUF);
366
367	if (mporoot == mpdevfs) {
368		vfs_unbusy(mpdevfs);
369		/* Unlink the no longer needed /dev/dev -> / symlink */
370		error = kern_unlinkat(td, AT_FDCWD, "/dev/dev",
371		    UIO_SYSSPACE, 0);
372		if (error && bootverbose)
373			printf("mountroot: unable to unlink /dev/dev "
374			    "(error %d)\n", error);
375	}
376
377	return (0);
378}
379
380/*
381 * Configuration parser.
382 */
383
384/* Parser character classes. */
385#define	CC_WHITESPACE		-1
386#define	CC_NONWHITESPACE	-2
387
388/* Parse errors. */
389#define	PE_EOF			-1
390#define	PE_EOL			-2
391
392static __inline int
393parse_peek(char **conf)
394{
395
396	return (**conf);
397}
398
399static __inline void
400parse_poke(char **conf, int c)
401{
402
403	**conf = c;
404}
405
406static __inline void
407parse_advance(char **conf)
408{
409
410	(*conf)++;
411}
412
413static int
414parse_skipto(char **conf, int mc)
415{
416	int c, match;
417
418	while (1) {
419		c = parse_peek(conf);
420		if (c == 0)
421			return (PE_EOF);
422		switch (mc) {
423		case CC_WHITESPACE:
424			match = (c == ' ' || c == '\t' || c == '\n') ? 1 : 0;
425			break;
426		case CC_NONWHITESPACE:
427			if (c == '\n')
428				return (PE_EOL);
429			match = (c != ' ' && c != '\t') ? 1 : 0;
430			break;
431		default:
432			match = (c == mc) ? 1 : 0;
433			break;
434		}
435		if (match)
436			break;
437		parse_advance(conf);
438	}
439	return (0);
440}
441
442static int
443parse_token(char **conf, char **tok)
444{
445	char *p;
446	size_t len;
447	int error;
448
449	*tok = NULL;
450	error = parse_skipto(conf, CC_NONWHITESPACE);
451	if (error)
452		return (error);
453	p = *conf;
454	error = parse_skipto(conf, CC_WHITESPACE);
455	len = *conf - p;
456	*tok = malloc(len + 1, M_TEMP, M_WAITOK | M_ZERO);
457	bcopy(p, *tok, len);
458	return (0);
459}
460
461static void
462parse_dir_ask_printenv(const char *var)
463{
464	char *val;
465
466	val = kern_getenv(var);
467	if (val != NULL) {
468		printf("  %s=%s\n", var, val);
469		freeenv(val);
470	}
471}
472
473static int
474parse_dir_ask(char **conf)
475{
476	char name[80];
477	char *mnt;
478	int error;
479
480	printf("\nLoader variables:\n");
481	parse_dir_ask_printenv("vfs.root.mountfrom");
482	parse_dir_ask_printenv("vfs.root.mountfrom.options");
483
484	printf("\nManual root filesystem specification:\n");
485	printf("  <fstype>:<device> [options]\n");
486	printf("      Mount <device> using filesystem <fstype>\n");
487	printf("      and with the specified (optional) option list.\n");
488	printf("\n");
489	printf("    eg. ufs:/dev/da0s1a\n");
490	printf("        zfs:tank\n");
491	printf("        cd9660:/dev/acd0 ro\n");
492	printf("          (which is equivalent to: ");
493	printf("mount -t cd9660 -o ro /dev/acd0 /)\n");
494	printf("\n");
495	printf("  ?               List valid disk boot devices\n");
496	printf("  .               Yield 1 second (for background tasks)\n");
497	printf("  <empty line>    Abort manual input\n");
498
499	do {
500		error = EINVAL;
501		printf("\nmountroot> ");
502		cngets(name, sizeof(name), GETS_ECHO);
503		if (name[0] == '\0')
504			break;
505		if (name[0] == '?' && name[1] == '\0') {
506			printf("\nList of GEOM managed disk devices:\n  ");
507			g_dev_print();
508			continue;
509		}
510		if (name[0] == '.' && name[1] == '\0') {
511			pause("rmask", hz);
512			continue;
513		}
514		mnt = name;
515		error = parse_mount(&mnt);
516		if (error == -1)
517			printf("Invalid file system specification.\n");
518	} while (error != 0);
519
520	return (error);
521}
522
523static int
524parse_dir_md(char **conf)
525{
526	struct stat sb;
527	struct thread *td;
528	struct md_ioctl *mdio;
529	char *path, *tok;
530	int error, fd, len;
531
532	td = curthread;
533
534	error = parse_token(conf, &tok);
535	if (error)
536		return (error);
537
538	len = strlen(tok);
539	mdio = malloc(sizeof(*mdio) + len + 1, M_TEMP, M_WAITOK | M_ZERO);
540	path = (void *)(mdio + 1);
541	bcopy(tok, path, len);
542	free(tok, M_TEMP);
543
544	/* Get file status. */
545	error = kern_statat(td, 0, AT_FDCWD, path, UIO_SYSSPACE, &sb, NULL);
546	if (error)
547		goto out;
548
549	/* Open /dev/mdctl so that we can attach/detach. */
550	error = kern_openat(td, AT_FDCWD, "/dev/" MDCTL_NAME, UIO_SYSSPACE,
551	    O_RDWR, 0);
552	if (error)
553		goto out;
554
555	fd = td->td_retval[0];
556	mdio->md_version = MDIOVERSION;
557	mdio->md_type = MD_VNODE;
558
559	if (root_mount_mddev != -1) {
560		mdio->md_unit = root_mount_mddev;
561		DROP_GIANT();
562		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
563		PICKUP_GIANT();
564		/* Ignore errors. We don't care. */
565		root_mount_mddev = -1;
566	}
567
568	mdio->md_file = (void *)(mdio + 1);
569	mdio->md_options = MD_AUTOUNIT | MD_READONLY;
570	mdio->md_mediasize = sb.st_size;
571	mdio->md_unit = 0;
572	DROP_GIANT();
573	error = kern_ioctl(td, fd, MDIOCATTACH, (void *)mdio);
574	PICKUP_GIANT();
575	if (error)
576		goto out;
577
578	if (mdio->md_unit > 9) {
579		printf("rootmount: too many md units\n");
580		mdio->md_file = NULL;
581		mdio->md_options = 0;
582		mdio->md_mediasize = 0;
583		DROP_GIANT();
584		error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
585		PICKUP_GIANT();
586		/* Ignore errors. We don't care. */
587		error = ERANGE;
588		goto out;
589	}
590
591	root_mount_mddev = mdio->md_unit;
592	printf(MD_NAME "%u attached to %s\n", root_mount_mddev, mdio->md_file);
593
594	error = kern_close(td, fd);
595
596 out:
597	free(mdio, M_TEMP);
598	return (error);
599}
600
601static int
602parse_dir_onfail(char **conf)
603{
604	char *action;
605	int error;
606
607	error = parse_token(conf, &action);
608	if (error)
609		return (error);
610
611	if (!strcmp(action, "continue"))
612		root_mount_onfail = A_CONTINUE;
613	else if (!strcmp(action, "panic"))
614		root_mount_onfail = A_PANIC;
615	else if (!strcmp(action, "reboot"))
616		root_mount_onfail = A_REBOOT;
617	else if (!strcmp(action, "retry"))
618		root_mount_onfail = A_RETRY;
619	else {
620		printf("rootmount: %s: unknown action\n", action);
621		error = EINVAL;
622	}
623
624	free(action, M_TEMP);
625	return (0);
626}
627
628static int
629parse_dir_timeout(char **conf)
630{
631	char *tok, *endtok;
632	long secs;
633	int error;
634
635	error = parse_token(conf, &tok);
636	if (error)
637		return (error);
638
639	secs = strtol(tok, &endtok, 0);
640	error = (secs < 0 || *endtok != '\0') ? EINVAL : 0;
641	if (!error)
642		root_mount_timeout = secs;
643	free(tok, M_TEMP);
644	return (error);
645}
646
647static int
648parse_directive(char **conf)
649{
650	char *dir;
651	int error;
652
653	error = parse_token(conf, &dir);
654	if (error)
655		return (error);
656
657	if (strcmp(dir, ".ask") == 0)
658		error = parse_dir_ask(conf);
659	else if (strcmp(dir, ".md") == 0)
660		error = parse_dir_md(conf);
661	else if (strcmp(dir, ".onfail") == 0)
662		error = parse_dir_onfail(conf);
663	else if (strcmp(dir, ".timeout") == 0)
664		error = parse_dir_timeout(conf);
665	else {
666		printf("mountroot: invalid directive `%s'\n", dir);
667		/* Ignore the rest of the line. */
668		(void)parse_skipto(conf, '\n');
669		error = EINVAL;
670	}
671	free(dir, M_TEMP);
672	return (error);
673}
674
675static int
676parse_mount_dev_present(const char *dev)
677{
678	struct nameidata nd;
679	int error;
680
681	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, dev, curthread);
682	error = namei(&nd);
683	if (!error)
684		vput(nd.ni_vp);
685	NDFREE(&nd, NDF_ONLY_PNBUF);
686	return (error != 0) ? 0 : 1;
687}
688
689#define	ERRMSGL	255
690static int
691parse_mount(char **conf)
692{
693	char *errmsg;
694	struct mntarg *ma;
695	char *dev, *fs, *opts, *tok;
696	int delay, error, timeout;
697
698	error = parse_token(conf, &tok);
699	if (error)
700		return (error);
701	fs = tok;
702	error = parse_skipto(&tok, ':');
703	if (error) {
704		free(fs, M_TEMP);
705		return (error);
706	}
707	parse_poke(&tok, '\0');
708	parse_advance(&tok);
709	dev = tok;
710
711	if (root_mount_mddev != -1) {
712		/* Handle substitution for the md unit number. */
713		tok = strstr(dev, "md#");
714		if (tok != NULL)
715			tok[2] = '0' + root_mount_mddev;
716	}
717
718	/* Parse options. */
719	error = parse_token(conf, &tok);
720	opts = (error == 0) ? tok : NULL;
721
722	printf("Trying to mount root from %s:%s [%s]...\n", fs, dev,
723	    (opts != NULL) ? opts : "");
724
725	errmsg = malloc(ERRMSGL, M_TEMP, M_WAITOK | M_ZERO);
726
727	if (vfs_byname(fs) == NULL) {
728		strlcpy(errmsg, "unknown file system", ERRMSGL);
729		error = ENOENT;
730		goto out;
731	}
732
733	if (strcmp(fs, "zfs") != 0 && strstr(fs, "nfs") == NULL &&
734	    dev[0] != '\0' && !parse_mount_dev_present(dev)) {
735		printf("mountroot: waiting for device %s ...\n", dev);
736		delay = hz / 10;
737		timeout = root_mount_timeout * hz;
738		do {
739			pause("rmdev", delay);
740			timeout -= delay;
741		} while (timeout > 0 && !parse_mount_dev_present(dev));
742		if (timeout <= 0) {
743			error = ENODEV;
744			goto out;
745		}
746	}
747
748	ma = NULL;
749	ma = mount_arg(ma, "fstype", fs, -1);
750	ma = mount_arg(ma, "fspath", "/", -1);
751	ma = mount_arg(ma, "from", dev, -1);
752	ma = mount_arg(ma, "errmsg", errmsg, ERRMSGL);
753	ma = mount_arg(ma, "ro", NULL, 0);
754	ma = parse_mountroot_options(ma, opts);
755	error = kernel_mount(ma, MNT_ROOTFS);
756
757 out:
758	if (error) {
759		printf("Mounting from %s:%s failed with error %d",
760		    fs, dev, error);
761		if (errmsg[0] != '\0')
762			printf(": %s", errmsg);
763		printf(".\n");
764	}
765	free(fs, M_TEMP);
766	free(errmsg, M_TEMP);
767	if (opts != NULL)
768		free(opts, M_TEMP);
769	/* kernel_mount can return -1 on error. */
770	return ((error < 0) ? EDOOFUS : error);
771}
772#undef ERRMSGL
773
774static int
775vfs_mountroot_parse(struct sbuf *sb, struct mount *mpdevfs)
776{
777	struct mount *mp;
778	char *conf;
779	int error;
780
781	root_mount_mddev = -1;
782
783retry:
784	conf = sbuf_data(sb);
785	mp = TAILQ_NEXT(mpdevfs, mnt_list);
786	error = (mp == NULL) ? 0 : EDOOFUS;
787	root_mount_onfail = A_CONTINUE;
788	while (mp == NULL) {
789		error = parse_skipto(&conf, CC_NONWHITESPACE);
790		if (error == PE_EOL) {
791			parse_advance(&conf);
792			continue;
793		}
794		if (error < 0)
795			break;
796		switch (parse_peek(&conf)) {
797		case '#':
798			error = parse_skipto(&conf, '\n');
799			break;
800		case '.':
801			error = parse_directive(&conf);
802			break;
803		default:
804			error = parse_mount(&conf);
805			if (error == -1) {
806				printf("mountroot: invalid file system "
807				    "specification.\n");
808				error = 0;
809			}
810			break;
811		}
812		if (error < 0)
813			break;
814		/* Ignore any trailing garbage on the line. */
815		if (parse_peek(&conf) != '\n') {
816			printf("mountroot: advancing to next directive...\n");
817			(void)parse_skipto(&conf, '\n');
818		}
819		mp = TAILQ_NEXT(mpdevfs, mnt_list);
820	}
821	if (mp != NULL)
822		return (0);
823
824	/*
825	 * We failed to mount (a new) root.
826	 */
827	switch (root_mount_onfail) {
828	case A_CONTINUE:
829		break;
830	case A_PANIC:
831		panic("mountroot: unable to (re-)mount root.");
832		/* NOTREACHED */
833	case A_RETRY:
834		goto retry;
835	case A_REBOOT:
836		kern_reboot(RB_NOSYNC);
837		/* NOTREACHED */
838	}
839
840	return (error);
841}
842
843static void
844vfs_mountroot_conf0(struct sbuf *sb)
845{
846	char *s, *tok, *mnt, *opt;
847	int error;
848
849	sbuf_printf(sb, ".onfail panic\n");
850	sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
851	if (boothowto & RB_ASKNAME)
852		sbuf_printf(sb, ".ask\n");
853#ifdef ROOTDEVNAME
854	if (boothowto & RB_DFLTROOT)
855		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
856#endif
857	if (boothowto & RB_CDROM) {
858		sbuf_printf(sb, "cd9660:/dev/cd0 ro\n");
859		sbuf_printf(sb, ".timeout 0\n");
860		sbuf_printf(sb, "cd9660:/dev/acd0 ro\n");
861		sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
862	}
863	s = kern_getenv("vfs.root.mountfrom");
864	if (s != NULL) {
865		opt = kern_getenv("vfs.root.mountfrom.options");
866		tok = s;
867		error = parse_token(&tok, &mnt);
868		while (!error) {
869			sbuf_printf(sb, "%s %s\n", mnt,
870			    (opt != NULL) ? opt : "");
871			free(mnt, M_TEMP);
872			error = parse_token(&tok, &mnt);
873		}
874		if (opt != NULL)
875			freeenv(opt);
876		freeenv(s);
877	}
878	if (rootdevnames[0] != NULL)
879		sbuf_printf(sb, "%s\n", rootdevnames[0]);
880	if (rootdevnames[1] != NULL)
881		sbuf_printf(sb, "%s\n", rootdevnames[1]);
882#ifdef ROOTDEVNAME
883	if (!(boothowto & RB_DFLTROOT))
884		sbuf_printf(sb, "%s\n", ROOTDEVNAME);
885#endif
886	if (!(boothowto & RB_ASKNAME))
887		sbuf_printf(sb, ".ask\n");
888}
889
890static int
891vfs_mountroot_readconf(struct thread *td, struct sbuf *sb)
892{
893	static char buf[128];
894	struct nameidata nd;
895	off_t ofs;
896	ssize_t resid;
897	int error, flags, len;
898
899	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/.mount.conf", td);
900	flags = FREAD;
901	error = vn_open(&nd, &flags, 0, NULL);
902	if (error)
903		return (error);
904
905	NDFREE(&nd, NDF_ONLY_PNBUF);
906	ofs = 0;
907	len = sizeof(buf) - 1;
908	while (1) {
909		error = vn_rdwr(UIO_READ, nd.ni_vp, buf, len, ofs,
910		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
911		    NOCRED, &resid, td);
912		if (error)
913			break;
914		if (resid == len)
915			break;
916		buf[len - resid] = 0;
917		sbuf_printf(sb, "%s", buf);
918		ofs += len - resid;
919	}
920
921	VOP_UNLOCK(nd.ni_vp, 0);
922	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
923	return (error);
924}
925
926static void
927vfs_mountroot_wait(void)
928{
929	struct root_hold_token *h;
930	struct timeval lastfail;
931	int curfail;
932
933	curfail = 0;
934	while (1) {
935		DROP_GIANT();
936		g_waitidle();
937		PICKUP_GIANT();
938		mtx_lock(&root_holds_mtx);
939		if (LIST_EMPTY(&root_holds)) {
940			mtx_unlock(&root_holds_mtx);
941			break;
942		}
943		if (ppsratecheck(&lastfail, &curfail, 1)) {
944			printf("Root mount waiting for:");
945			LIST_FOREACH(h, &root_holds, list)
946				printf(" %s", h->who);
947			printf("\n");
948		}
949		msleep(&root_holds, &root_holds_mtx, PZERO | PDROP, "roothold",
950		    hz);
951	}
952}
953
954void
955vfs_mountroot(void)
956{
957	struct mount *mp;
958	struct sbuf *sb;
959	struct thread *td;
960	time_t timebase;
961	int error;
962
963	td = curthread;
964
965	vfs_mountroot_wait();
966
967	sb = sbuf_new_auto();
968	vfs_mountroot_conf0(sb);
969	sbuf_finish(sb);
970
971	error = vfs_mountroot_devfs(td, &mp);
972	while (!error) {
973		error = vfs_mountroot_parse(sb, mp);
974		if (!error) {
975			error = vfs_mountroot_shuffle(td, mp);
976			if (!error) {
977				sbuf_clear(sb);
978				error = vfs_mountroot_readconf(td, sb);
979				sbuf_finish(sb);
980			}
981		}
982	}
983
984	sbuf_delete(sb);
985
986	/*
987	 * Iterate over all currently mounted file systems and use
988	 * the time stamp found to check and/or initialize the RTC.
989	 * Call inittodr() only once and pass it the largest of the
990	 * timestamps we encounter.
991	 */
992	timebase = 0;
993	mtx_lock(&mountlist_mtx);
994	mp = TAILQ_FIRST(&mountlist);
995	while (mp != NULL) {
996		if (mp->mnt_time > timebase)
997			timebase = mp->mnt_time;
998		mp = TAILQ_NEXT(mp, mnt_list);
999	}
1000	mtx_unlock(&mountlist_mtx);
1001	inittodr(timebase);
1002
1003	/* Keep prison0's root in sync with the global rootvnode. */
1004	mtx_lock(&prison0.pr_mtx);
1005	prison0.pr_root = rootvnode;
1006	vref(prison0.pr_root);
1007	mtx_unlock(&prison0.pr_mtx);
1008
1009	mtx_lock(&root_holds_mtx);
1010	atomic_store_rel_int(&root_mount_complete, 1);
1011	wakeup(&root_mount_complete);
1012	mtx_unlock(&root_holds_mtx);
1013
1014	EVENTHANDLER_INVOKE(mountroot);
1015}
1016
1017static struct mntarg *
1018parse_mountroot_options(struct mntarg *ma, const char *options)
1019{
1020	char *p;
1021	char *name, *name_arg;
1022	char *val, *val_arg;
1023	char *opts;
1024
1025	if (options == NULL || options[0] == '\0')
1026		return (ma);
1027
1028	p = opts = strdup(options, M_MOUNT);
1029	if (opts == NULL) {
1030		return (ma);
1031	}
1032
1033	while((name = strsep(&p, ",")) != NULL) {
1034		if (name[0] == '\0')
1035			break;
1036
1037		val = strchr(name, '=');
1038		if (val != NULL) {
1039			*val = '\0';
1040			++val;
1041		}
1042		if( strcmp(name, "rw") == 0 ||
1043		    strcmp(name, "noro") == 0) {
1044			/*
1045			 * The first time we mount the root file system,
1046			 * we need to mount 'ro', so We need to ignore
1047			 * 'rw' and 'noro' mount options.
1048			 */
1049			continue;
1050		}
1051		name_arg = strdup(name, M_MOUNT);
1052		val_arg = NULL;
1053		if (val != NULL)
1054			val_arg = strdup(val, M_MOUNT);
1055
1056		ma = mount_arg(ma, name_arg, val_arg,
1057		    (val_arg != NULL ? -1 : 0));
1058	}
1059	free(opts, M_MOUNT);
1060	return (ma);
1061}
1062