Home | History | Annotate | Line # | Download | only in init
init.c revision 1.63
      1 /*	$NetBSD: init.c,v 1.63 2003/10/03 13:31:32 dsl Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Donn Seeley at Berkeley Software Design, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 __COPYRIGHT("@(#) Copyright (c) 1991, 1993\n"
     38 "	The Regents of the University of California.  All rights reserved.\n");
     39 #endif /* not lint */
     40 
     41 #ifndef lint
     42 #if 0
     43 static char sccsid[] = "@(#)init.c	8.2 (Berkeley) 4/28/95";
     44 #else
     45 __RCSID("$NetBSD: init.c,v 1.63 2003/10/03 13:31:32 dsl Exp $");
     46 #endif
     47 #endif /* not lint */
     48 
     49 #include <sys/param.h>
     50 #include <sys/sysctl.h>
     51 #include <sys/wait.h>
     52 #include <sys/mman.h>
     53 #include <sys/stat.h>
     54 #include <sys/mount.h>
     55 #include <sys/sysctl.h>
     56 #include <machine/cpu.h>
     57 
     58 #include <db.h>
     59 #include <errno.h>
     60 #include <fcntl.h>
     61 #include <signal.h>
     62 #include <stdio.h>
     63 #include <stdlib.h>
     64 #include <string.h>
     65 #include <syslog.h>
     66 #include <time.h>
     67 #include <ttyent.h>
     68 #include <unistd.h>
     69 #include <util.h>
     70 #include <paths.h>
     71 #include <err.h>
     72 
     73 #include <stdarg.h>
     74 
     75 #ifdef SECURE
     76 #include <pwd.h>
     77 #endif
     78 
     79 #include "pathnames.h"
     80 
     81 #define XSTR(x) #x
     82 #define STR(x) XSTR(x)
     83 
     84 /*
     85  * Sleep times; used to prevent thrashing.
     86  */
     87 #define	GETTY_SPACING		 5	/* N secs minimum getty spacing */
     88 #define	GETTY_SLEEP		30	/* sleep N secs after spacing problem */
     89 #define	WINDOW_WAIT		 3	/* wait N secs after starting window */
     90 #define	STALL_TIMEOUT		30	/* wait N secs after warning */
     91 #define	DEATH_WATCH		10	/* wait N secs for procs to die */
     92 
     93 
     94 #if defined(RESCUEDIR)
     95 #define	INIT_BSHELL	RESCUEDIR "/sh"
     96 #define	INIT_MOUNT_MFS	RESCUEDIR "/mount_mfs"
     97 #define	INIT_PATH	RESCUEDIR ":" _PATH_STDPATH
     98 #else
     99 #define	INIT_BSHELL	_PATH_BSHELL
    100 #define	INIT_MOUNT_MFS	"/sbin/mount_mfs"
    101 #define	INIT_PATH	_PATH_STDPATH
    102 #endif
    103 
    104 int main(int, char *[]);
    105 
    106 void handle(sig_t, ...);
    107 void delset(sigset_t *, ...);
    108 
    109 void stall(const char *, ...)
    110     __attribute__((__format__(__printf__,1,2)));
    111 void warning(const char *, ...)
    112     __attribute__((__format__(__printf__,1,2)));
    113 void emergency(const char *, ...)
    114     __attribute__((__format__(__printf__,1,2)));
    115 void disaster(int);
    116 void badsys(int);
    117 
    118 /*
    119  * We really need a recursive typedef...
    120  * The following at least guarantees that the return type of (*state_t)()
    121  * is sufficiently wide to hold a function pointer.
    122  */
    123 typedef long (*state_func_t)(void);
    124 typedef state_func_t (*state_t)(void);
    125 
    126 state_func_t single_user(void);
    127 state_func_t runcom(void);
    128 state_func_t read_ttys(void);
    129 state_func_t multi_user(void);
    130 state_func_t clean_ttys(void);
    131 state_func_t catatonia(void);
    132 state_func_t death(void);
    133 
    134 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
    135 
    136 void transition(state_t);
    137 #ifndef LETS_GET_SMALL
    138 state_t requested_transition = runcom;
    139 #else /* LETS_GET_SMALL */
    140 state_t requested_transition = single_user;
    141 #endif /* LETS_GET_SMALL */
    142 
    143 void setctty(const char *);
    144 
    145 typedef struct init_session {
    146 	int	se_index;		/* index of entry in ttys file */
    147 	pid_t	se_process;		/* controlling process */
    148 	time_t	se_started;		/* used to avoid thrashing */
    149 	int	se_flags;		/* status of session */
    150 #define	SE_SHUTDOWN	0x1		/* session won't be restarted */
    151 #define	SE_PRESENT	0x2		/* session is in /etc/ttys */
    152 	char	*se_device;		/* filename of port */
    153 	char	*se_getty;		/* what to run on that port */
    154 	char	**se_getty_argv;	/* pre-parsed argument array */
    155 	char	*se_window;		/* window system (started only once) */
    156 	char	**se_window_argv;	/* pre-parsed argument array */
    157 	struct	init_session *se_prev;
    158 	struct	init_session *se_next;
    159 } session_t;
    160 
    161 void free_session(session_t *);
    162 session_t *new_session(session_t *, int, struct ttyent *);
    163 session_t *sessions;
    164 
    165 char **construct_argv(char *);
    166 void start_window_system(session_t *);
    167 void collect_child(pid_t, int);
    168 pid_t start_getty(session_t *);
    169 void transition_handler(int);
    170 void alrm_handler(int);
    171 void setsecuritylevel(int);
    172 int getsecuritylevel(void);
    173 int setupargv(session_t *, struct ttyent *);
    174 int clang;
    175 
    176 void clear_session_logs(session_t *, int);
    177 
    178 int start_session_db(void);
    179 void add_session(session_t *);
    180 void del_session(session_t *);
    181 session_t *find_session(pid_t);
    182 DB *session_db;
    183 
    184 #ifdef MFS_DEV_IF_NO_CONSOLE
    185 
    186 #define NINODE 896
    187 #define FSSIZE ((8192		/* boot area */				\
    188 	+ 2 * 8192		/* two copies of superblock */		\
    189 	+ 4096			/* cylinder group info */		\
    190 	+ NINODE * (128 + 18)	/* inode and directory entry */		\
    191 	+ mfile[0].len		/* size of MAKEDEV file */		\
    192 	+ 2 * 4096) / 512)	/* some slack */
    193 
    194 struct mappedfile {
    195 	const char *path;
    196 	char	*buf;
    197 	int	len;
    198 } mfile[] = {
    199 	{ "/dev/MAKEDEV",	NULL,	0 },
    200 	{ "/dev/MAKEDEV.local",	NULL,	0 }
    201 };
    202 
    203 static int mfs_dev(void);
    204 static void mapfile(struct mappedfile *);
    205 static void writefile(struct mappedfile *);
    206 
    207 #endif
    208 
    209 /*
    210  * The mother of all processes.
    211  */
    212 int
    213 main(int argc, char **argv)
    214 {
    215 	struct sigaction sa;
    216 	sigset_t mask;
    217 #ifndef LETS_GET_SMALL
    218 	int c;
    219 
    220 	/* Dispose of random users. */
    221 	if (getuid() != 0) {
    222 		errno = EPERM;
    223 		err(1, NULL);
    224 	}
    225 
    226 	/* System V users like to reexec init. */
    227 	if (getpid() != 1)
    228 		errx(1, "already running");
    229 #endif
    230 
    231 	/*
    232 	 * Create an initial session.
    233 	 */
    234 	if (setsid() < 0)
    235 		warn("initial setsid() failed");
    236 
    237 	/*
    238 	 * Establish an initial user so that programs running
    239 	 * single user do not freak out and die (like passwd).
    240 	 */
    241 	if (setlogin("root") < 0)
    242 		warn("setlogin() failed");
    243 
    244 
    245 #ifdef MFS_DEV_IF_NO_CONSOLE
    246 	if (mfs_dev() == -1)
    247 		requested_transition = single_user;
    248 #endif
    249 
    250 #ifndef LETS_GET_SMALL
    251 	/*
    252 	 * Note that this does NOT open a file...
    253 	 * Does 'init' deserve its own facility number?
    254 	 */
    255 	openlog("init", LOG_CONS, LOG_AUTH);
    256 #endif /* LETS_GET_SMALL */
    257 
    258 
    259 #ifndef LETS_GET_SMALL
    260 	/*
    261 	 * This code assumes that we always get arguments through flags,
    262 	 * never through bits set in some random machine register.
    263 	 */
    264 	while ((c = getopt(argc, argv, "sf")) != -1)
    265 		switch (c) {
    266 		case 's':
    267 			requested_transition = single_user;
    268 			break;
    269 		case 'f':
    270 			runcom_mode = FASTBOOT;
    271 			break;
    272 		default:
    273 			warning("unrecognized flag '-%c'", c);
    274 			break;
    275 		}
    276 
    277 	if (optind != argc)
    278 		warning("ignoring excess arguments");
    279 #else /* LETS_GET_SMALL */
    280 	requested_transition = single_user;
    281 #endif /* LETS_GET_SMALL */
    282 
    283 	/*
    284 	 * We catch or block signals rather than ignore them,
    285 	 * so that they get reset on exec.
    286 	 */
    287 	handle(badsys, SIGSYS, 0);
    288 	handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
    289 	       SIGBUS, SIGXCPU, SIGXFSZ, 0);
    290 	handle(transition_handler, SIGHUP, SIGTERM, SIGTSTP, 0);
    291 	handle(alrm_handler, SIGALRM, 0);
    292 	(void)sigfillset(&mask);
    293 	delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
    294 	    SIGXCPU, SIGXFSZ, SIGHUP, SIGTERM, SIGTSTP, SIGALRM, 0);
    295 	(void)sigprocmask(SIG_SETMASK, &mask, NULL);
    296 	(void)sigemptyset(&sa.sa_mask);
    297 	sa.sa_flags = 0;
    298 	sa.sa_handler = SIG_IGN;
    299 	(void)sigaction(SIGTTIN, &sa, NULL);
    300 	(void)sigaction(SIGTTOU, &sa, NULL);
    301 
    302 	/*
    303 	 * Paranoia.
    304 	 */
    305 	(void)close(0);
    306 	(void)close(1);
    307 	(void)close(2);
    308 
    309 	/*
    310 	 * Start the state machine.
    311 	 */
    312 	transition(requested_transition);
    313 
    314 	/*
    315 	 * Should never reach here.
    316 	 */
    317 	return 1;
    318 }
    319 
    320 /*
    321  * Associate a function with a signal handler.
    322  */
    323 void
    324 handle(sig_t handler, ...)
    325 {
    326 	int sig;
    327 	struct sigaction sa;
    328 	sigset_t mask_everything;
    329 	va_list ap;
    330 
    331 	va_start(ap, handler);
    332 
    333 	sa.sa_handler = handler;
    334 	(void)sigfillset(&mask_everything);
    335 
    336 	while ((sig = va_arg(ap, int)) != 0) {
    337 		sa.sa_mask = mask_everything;
    338 		/* XXX SA_RESTART? */
    339 		sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
    340 		(void)sigaction(sig, &sa, NULL);
    341 	}
    342 	va_end(ap);
    343 }
    344 
    345 /*
    346  * Delete a set of signals from a mask.
    347  */
    348 void
    349 delset(sigset_t *maskp, ...)
    350 {
    351 	int sig;
    352 	va_list ap;
    353 
    354 	va_start(ap, maskp);
    355 
    356 	while ((sig = va_arg(ap, int)) != 0)
    357 		(void)sigdelset(maskp, sig);
    358 	va_end(ap);
    359 }
    360 
    361 /*
    362  * Log a message and sleep for a while (to give someone an opportunity
    363  * to read it and to save log or hardcopy output if the problem is chronic).
    364  * NB: should send a message to the session logger to avoid blocking.
    365  */
    366 void
    367 stall(const char *message, ...)
    368 {
    369 	va_list ap;
    370 
    371 	va_start(ap, message);
    372 	vsyslog(LOG_ALERT, message, ap);
    373 	va_end(ap);
    374 	closelog();
    375 	(void)sleep(STALL_TIMEOUT);
    376 }
    377 
    378 /*
    379  * Like stall(), but doesn't sleep.
    380  * If cpp had variadic macros, the two functions could be #defines for another.
    381  * NB: should send a message to the session logger to avoid blocking.
    382  */
    383 void
    384 warning(const char *message, ...)
    385 {
    386 	va_list ap;
    387 
    388 	va_start(ap, message);
    389 	vsyslog(LOG_ALERT, message, ap);
    390 	va_end(ap);
    391 	closelog();
    392 }
    393 
    394 /*
    395  * Log an emergency message.
    396  * NB: should send a message to the session logger to avoid blocking.
    397  */
    398 void
    399 emergency(const char *message, ...)
    400 {
    401 	va_list ap;
    402 
    403 	va_start(ap, message);
    404 	vsyslog(LOG_EMERG, message, ap);
    405 	va_end(ap);
    406 	closelog();
    407 }
    408 
    409 /*
    410  * Catch a SIGSYS signal.
    411  *
    412  * These may arise if a system does not support sysctl.
    413  * We tolerate up to 25 of these, then throw in the towel.
    414  */
    415 void
    416 badsys(int sig)
    417 {
    418 	static int badcount = 0;
    419 
    420 	if (badcount++ < 25)
    421 		return;
    422 	disaster(sig);
    423 }
    424 
    425 /*
    426  * Catch an unexpected signal.
    427  */
    428 void
    429 disaster(int sig)
    430 {
    431 
    432 	emergency("fatal signal: %s", strsignal(sig));
    433 	(void)sleep(STALL_TIMEOUT);
    434 	_exit(sig);		/* reboot */
    435 }
    436 
    437 /*
    438  * Get the security level of the kernel.
    439  */
    440 int
    441 getsecuritylevel(void)
    442 {
    443 #ifdef KERN_SECURELVL
    444 	int name[2], curlevel;
    445 	size_t len;
    446 
    447 	name[0] = CTL_KERN;
    448 	name[1] = KERN_SECURELVL;
    449 	len = sizeof curlevel;
    450 	if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
    451 		emergency("cannot get kernel security level: %m");
    452 		return (-1);
    453 	}
    454 	return (curlevel);
    455 #else
    456 	return (-1);
    457 #endif
    458 }
    459 
    460 /*
    461  * Set the security level of the kernel.
    462  */
    463 void
    464 setsecuritylevel(int newlevel)
    465 {
    466 #ifdef KERN_SECURELVL
    467 	int name[2], curlevel;
    468 
    469 	curlevel = getsecuritylevel();
    470 	if (newlevel == curlevel)
    471 		return;
    472 	name[0] = CTL_KERN;
    473 	name[1] = KERN_SECURELVL;
    474 	if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
    475 		emergency( "cannot change kernel security level from"
    476 		    " %d to %d: %m", curlevel, newlevel);
    477 		return;
    478 	}
    479 #ifdef SECURE
    480 	warning("kernel security level changed from %d to %d",
    481 	    curlevel, newlevel);
    482 #endif
    483 #endif
    484 }
    485 
    486 /*
    487  * Change states in the finite state machine.
    488  * The initial state is passed as an argument.
    489  */
    490 void
    491 transition(state_t s)
    492 {
    493 
    494 	if (s == NULL)
    495 		return;
    496 	for (;;)
    497 		s = (state_t)(*s)();
    498 }
    499 
    500 /*
    501  * Close out the accounting files for a login session.
    502  * NB: should send a message to the session logger to avoid blocking.
    503  */
    504 void
    505 clear_session_logs(session_t *sp, int status)
    506 {
    507 	char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
    508 
    509 #ifdef SUPPORT_UTMPX
    510 	if (logoutx(line, status, DEAD_PROCESS))
    511 		logwtmpx(line, "", "", status, DEAD_PROCESS);
    512 #endif
    513 #ifdef SUPPORT_UTMP
    514 	if (logout(line))
    515 		logwtmp(line, "", "");
    516 #endif
    517 }
    518 
    519 /*
    520  * Start a session and allocate a controlling terminal.
    521  * Only called by children of init after forking.
    522  */
    523 void
    524 setctty(const char *name)
    525 {
    526 	int fd;
    527 
    528 	(void) revoke(name);
    529 	sleep(2);			/* leave DTR low */
    530 	if ((fd = open(name, O_RDWR)) == -1) {
    531 		stall("can't open %s: %m", name);
    532 		_exit(1);
    533 	}
    534 	if (login_tty(fd) == -1) {
    535 		stall("can't get %s for controlling terminal: %m", name);
    536 		_exit(1);
    537 	}
    538 }
    539 
    540 /*
    541  * Bring the system up single user.
    542  */
    543 state_func_t
    544 single_user(void)
    545 {
    546 	pid_t pid, wpid;
    547 	int status;
    548 	int from_securitylevel;
    549 	sigset_t mask;
    550 	struct sigaction sa, satstp, sahup;
    551 #ifdef ALTSHELL
    552 	const char *shell = INIT_BSHELL;
    553 #endif
    554 	char *argv[2];
    555 #ifdef SECURE
    556 	struct ttyent *typ;
    557 	struct passwd *pp;
    558 	char *clear, *password;
    559 #endif
    560 #ifdef ALTSHELL
    561 	char altshell[128];
    562 #endif /* ALTSHELL */
    563 
    564 	/*
    565 	 * If the kernel is in secure mode, downgrade it to insecure mode.
    566 	 */
    567 	from_securitylevel = getsecuritylevel();
    568 	if (from_securitylevel > 0)
    569 		setsecuritylevel(0);
    570 
    571 	(void)sigemptyset(&sa.sa_mask);
    572 	sa.sa_flags = 0;
    573 	sa.sa_handler = SIG_IGN;
    574 	(void)sigaction(SIGTSTP, &sa, &satstp);
    575 	(void)sigaction(SIGHUP, &sa, &sahup);
    576 	if ((pid = fork()) == 0) {
    577 		/*
    578 		 * Start the single user session.
    579 		 */
    580 		if (access(_PATH_CONSTTY, F_OK) == 0)
    581 			setctty(_PATH_CONSTTY);
    582 		else
    583 			setctty(_PATH_CONSOLE);
    584 
    585 #ifdef SECURE
    586 		/*
    587 		 * Check the root password.
    588 		 * We don't care if the console is 'on' by default;
    589 		 * it's the only tty that can be 'off' and 'secure'.
    590 		 */
    591 		typ = getttynam("console");
    592 		pp = getpwnam("root");
    593 		if (typ && (from_securitylevel >=2 || (typ->ty_status
    594 		    & TTY_SECURE) == 0) && pp && *pp->pw_passwd != '\0') {
    595 			(void)fprintf(stderr,
    596 			    "Enter root password, or ^D to go multi-user\n");
    597 			for (;;) {
    598 				clear = getpass("Password:");
    599 				if (clear == 0 || *clear == '\0')
    600 					_exit(0);
    601 				password = crypt(clear, pp->pw_passwd);
    602 				(void)memset(clear, 0, _PASSWORD_LEN);
    603 				if (strcmp(password, pp->pw_passwd) == 0)
    604 					break;
    605 				warning("single-user login failed\n");
    606 			}
    607 		}
    608 		endttyent();
    609 		endpwent();
    610 #endif /* SECURE */
    611 
    612 #ifdef ALTSHELL
    613 		(void)fprintf(stderr,
    614 		    "Enter pathname of shell or RETURN for %s: ", shell);
    615 		if (fgets(altshell, sizeof(altshell), stdin) == NULL) {
    616 			altshell[0] = '\0';
    617 		} else {
    618 			/* nuke \n */
    619 			char *p;
    620 
    621 			if ((p = strchr(altshell, '\n')) != NULL)
    622 				*p = '\0';
    623 		}
    624 
    625 		if (altshell[0])
    626 			shell = altshell;
    627 #endif /* ALTSHELL */
    628 
    629 		/*
    630 		 * Unblock signals.
    631 		 * We catch all the interesting ones,
    632 		 * and those are reset to SIG_DFL on exec.
    633 		 */
    634 		(void)sigemptyset(&mask);
    635 		(void)sigprocmask(SIG_SETMASK, &mask, NULL);
    636 
    637 		/*
    638 		 * Fire off a shell.
    639 		 * If the default one doesn't work, try the Bourne shell.
    640 		 */
    641 		argv[0] = "-sh";
    642 		argv[1] = 0;
    643 		setenv("PATH", INIT_PATH, 1);
    644 #ifdef ALTSHELL
    645 		if (altshell[0])
    646 			argv[0] = altshell;
    647 		(void)execv(shell, argv);
    648 		emergency("can't exec %s for single user: %m", shell);
    649 		argv[0] = "-sh";
    650 #endif /* ALTSHELL */
    651 		(void)execv(INIT_BSHELL, argv);
    652 		emergency("can't exec %s for single user: %m", INIT_BSHELL);
    653 		(void)sleep(STALL_TIMEOUT);
    654 		_exit(1);
    655 	}
    656 
    657 	if (pid == -1) {
    658 		/*
    659 		 * We are seriously hosed.  Do our best.
    660 		 */
    661 		emergency("can't fork single-user shell, trying again");
    662 		while (waitpid(-1, NULL, WNOHANG) > 0)
    663 			continue;
    664 		(void)sigaction(SIGTSTP, &satstp, NULL);
    665 		(void)sigaction(SIGHUP, &sahup, NULL);
    666 		return (state_func_t) single_user;
    667 	}
    668 
    669 	requested_transition = 0;
    670 	do {
    671 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
    672 			collect_child(wpid, status);
    673 		if (wpid == -1) {
    674 			if (errno == EINTR)
    675 				continue;
    676 			warning("wait for single-user shell failed: %m; "
    677 			    "restarting");
    678 			return (state_func_t)single_user;
    679 		}
    680 		if (wpid == pid && WIFSTOPPED(status)) {
    681 			warning("init: shell stopped, restarting\n");
    682 			kill(pid, SIGCONT);
    683 			wpid = -1;
    684 		}
    685 	} while (wpid != pid && !requested_transition);
    686 
    687 	if (requested_transition) {
    688 		(void)sigaction(SIGTSTP, &satstp, NULL);
    689 		(void)sigaction(SIGHUP, &sahup, NULL);
    690 		return (state_func_t)requested_transition;
    691 	}
    692 
    693 	if (WIFSIGNALED(status)) {
    694 		if (WTERMSIG(status) == SIGKILL) {
    695 			/* executed /sbin/reboot; wait for the end quietly */
    696 			sigset_t s;
    697 
    698 			(void)sigfillset(&s);
    699 			for (;;)
    700 				(void)sigsuspend(&s);
    701 		} else {
    702 			warning("single user shell terminated, restarting");
    703 			(void)sigaction(SIGTSTP, &satstp, NULL);
    704 			(void)sigaction(SIGHUP, &sahup, NULL);
    705 			return (state_func_t) single_user;
    706 		}
    707 	}
    708 
    709 	runcom_mode = FASTBOOT;
    710 	(void)sigaction(SIGTSTP, &satstp, NULL);
    711 	(void)sigaction(SIGHUP, &sahup, NULL);
    712 #ifndef LETS_GET_SMALL
    713 	return (state_func_t) runcom;
    714 #else /* LETS_GET_SMALL */
    715 	return (state_func_t) single_user;
    716 #endif /* LETS_GET_SMALL */
    717 }
    718 
    719 #ifndef LETS_GET_SMALL
    720 /*
    721  * Run the system startup script.
    722  */
    723 state_func_t
    724 runcom(void)
    725 {
    726 	pid_t pid, wpid;
    727 	int status;
    728 	char *argv[4];
    729 	struct sigaction sa;
    730 
    731 	switch ((pid = fork())) {
    732 	case 0:
    733 		(void)sigemptyset(&sa.sa_mask);
    734 		sa.sa_flags = 0;
    735 		sa.sa_handler = SIG_IGN;
    736 		(void)sigaction(SIGTSTP, &sa, NULL);
    737 		(void)sigaction(SIGHUP, &sa, NULL);
    738 
    739 		setctty(_PATH_CONSOLE);
    740 
    741 		argv[0] = "sh";
    742 		argv[1] = _PATH_RUNCOM;
    743 		argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
    744 		argv[3] = 0;
    745 
    746 		(void)sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
    747 
    748 		(void)execv(INIT_BSHELL, argv);
    749 		stall("can't exec %s for %s: %m", INIT_BSHELL, _PATH_RUNCOM);
    750 		_exit(1);	/* force single user mode */
    751 		/*NOTREACHED*/
    752 	case -1:
    753 		emergency("can't fork for %s on %s: %m", INIT_BSHELL,
    754 		    _PATH_RUNCOM);
    755 		while (waitpid(-1, NULL, WNOHANG) > 0)
    756 			continue;
    757 		(void)sleep(STALL_TIMEOUT);
    758 		return (state_func_t)single_user;
    759 	default:
    760 		break;
    761 	}
    762 
    763 	/*
    764 	 * Copied from single_user().  This is a bit paranoid.
    765 	 */
    766 	do {
    767 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
    768 			collect_child(wpid, status);
    769 		if (wpid == -1) {
    770 			if (errno == EINTR)
    771 				continue;
    772 			warning("wait for %s on %s failed: %m; going to "
    773 			    "single user mode", INIT_BSHELL, _PATH_RUNCOM);
    774 			return (state_func_t)single_user;
    775 		}
    776 		if (wpid == pid && WIFSTOPPED(status)) {
    777 			warning("init: %s on %s stopped, restarting\n",
    778 			    INIT_BSHELL, _PATH_RUNCOM);
    779 			(void)kill(pid, SIGCONT);
    780 			wpid = -1;
    781 		}
    782 	} while (wpid != pid);
    783 
    784 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
    785 	    requested_transition == catatonia) {
    786 		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
    787 		sigset_t s;
    788 
    789 		(void)sigfillset(&s);
    790 		for (;;)
    791 			(void)sigsuspend(&s);
    792 	}
    793 
    794 	if (!WIFEXITED(status)) {
    795 		warning("%s on %s terminated abnormally, going to "
    796 		    "single user mode", INIT_BSHELL, _PATH_RUNCOM);
    797 		return (state_func_t)single_user;
    798 	}
    799 
    800 	if (WEXITSTATUS(status))
    801 		return (state_func_t)single_user;
    802 
    803 	runcom_mode = AUTOBOOT;		/* the default */
    804 	/* NB: should send a message to the session logger to avoid blocking. */
    805 #ifdef SUPPORT_UTMPX
    806 	logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
    807 #endif
    808 #ifdef SUPPORT_UTMP
    809 	logwtmp("~", "reboot", "");
    810 #endif
    811 	return (state_func_t) read_ttys;
    812 }
    813 
    814 /*
    815  * Open the session database.
    816  *
    817  * NB: We could pass in the size here; is it necessary?
    818  */
    819 int
    820 start_session_db(void)
    821 {
    822 
    823 	if (session_db && (*session_db->close)(session_db))
    824 		emergency("session database close: %m");
    825 	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
    826 		emergency("session database open: %m");
    827 		return (1);
    828 	}
    829 	return (0);
    830 
    831 }
    832 
    833 /*
    834  * Add a new login session.
    835  */
    836 void
    837 add_session(session_t *sp)
    838 {
    839 	DBT key;
    840 	DBT data;
    841 
    842 	if (session_db == NULL)
    843 		return;
    844 
    845 	key.data = &sp->se_process;
    846 	key.size = sizeof sp->se_process;
    847 	data.data = &sp;
    848 	data.size = sizeof sp;
    849 
    850 	if ((*session_db->put)(session_db, &key, &data, 0))
    851 		emergency("insert %d: %m", sp->se_process);
    852 }
    853 
    854 /*
    855  * Delete an old login session.
    856  */
    857 void
    858 del_session(session_t *sp)
    859 {
    860 	DBT key;
    861 
    862 	key.data = &sp->se_process;
    863 	key.size = sizeof sp->se_process;
    864 
    865 	if ((*session_db->del)(session_db, &key, 0))
    866 		emergency("delete %d: %m", sp->se_process);
    867 }
    868 
    869 /*
    870  * Look up a login session by pid.
    871  */
    872 session_t *
    873 find_session(pid_t pid)
    874 {
    875 	DBT key;
    876 	DBT data;
    877 	session_t *ret;
    878 
    879 	if (session_db == NULL)
    880 		return NULL;
    881 
    882 	key.data = &pid;
    883 	key.size = sizeof pid;
    884 	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
    885 		return 0;
    886 	(void)memmove(&ret, data.data, sizeof(ret));
    887 	return ret;
    888 }
    889 
    890 /*
    891  * Construct an argument vector from a command line.
    892  */
    893 char **
    894 construct_argv(char *command)
    895 {
    896 	int argc = 0;
    897 	char **argv = malloc(((strlen(command) + 1) / 2 + 1) * sizeof (char *));
    898 	static const char separators[] = " \t";
    899 
    900 	if ((argv[argc++] = strtok(command, separators)) == 0)
    901 		return (NULL);
    902 	while ((argv[argc++] = strtok(NULL, separators)) != NULL)
    903 		continue;
    904 	return (argv);
    905 }
    906 
    907 /*
    908  * Deallocate a session descriptor.
    909  */
    910 void
    911 free_session(session_t *sp)
    912 {
    913 
    914 	free(sp->se_device);
    915 	if (sp->se_getty) {
    916 		free(sp->se_getty);
    917 		free(sp->se_getty_argv);
    918 	}
    919 	if (sp->se_window) {
    920 		free(sp->se_window);
    921 		free(sp->se_window_argv);
    922 	}
    923 	free(sp);
    924 }
    925 
    926 /*
    927  * Allocate a new session descriptor.
    928  */
    929 session_t *
    930 new_session(session_t *sprev, int session_index, struct ttyent *typ)
    931 {
    932 	session_t *sp;
    933 
    934 	if ((typ->ty_status & TTY_ON) == 0 || typ->ty_name == NULL ||
    935 	    typ->ty_getty == NULL)
    936 		return (NULL);
    937 
    938 	sp = malloc(sizeof (session_t));
    939 	if (sp == NULL)
    940 		return NULL;
    941 	memset(sp, 0, sizeof *sp);
    942 
    943 	sp->se_flags = SE_PRESENT;
    944 	sp->se_index = session_index;
    945 
    946 	(void)asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
    947 	if (!sp->se_device)
    948 		return NULL;
    949 
    950 	if (setupargv(sp, typ) == 0) {
    951 		free_session(sp);
    952 		return (NULL);
    953 	}
    954 
    955 	sp->se_next = NULL;
    956 	if (sprev == NULL) {
    957 		sessions = sp;
    958 		sp->se_prev = NULL;
    959 	} else {
    960 		sprev->se_next = sp;
    961 		sp->se_prev = sprev;
    962 	}
    963 
    964 	return (sp);
    965 }
    966 
    967 /*
    968  * Calculate getty and if useful window argv vectors.
    969  */
    970 int
    971 setupargv(session_t *sp, struct ttyent *typ)
    972 {
    973 
    974 	if (sp->se_getty) {
    975 		free(sp->se_getty);
    976 		free(sp->se_getty_argv);
    977 	}
    978 	(void)asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
    979 	if (!sp->se_getty)
    980 		return (0);
    981 	sp->se_getty_argv = construct_argv(sp->se_getty);
    982 	if (sp->se_getty_argv == NULL) {
    983 		warning("can't parse getty for port %s", sp->se_device);
    984 		free(sp->se_getty);
    985 		sp->se_getty = NULL;
    986 		return (0);
    987 	}
    988 	if (typ->ty_window) {
    989 		if (sp->se_window)
    990 			free(sp->se_window);
    991 		sp->se_window = strdup(typ->ty_window);
    992 		sp->se_window_argv = construct_argv(sp->se_window);
    993 		if (sp->se_window_argv == NULL) {
    994 			warning("can't parse window for port %s",
    995 			    sp->se_device);
    996 			free(sp->se_window);
    997 			sp->se_window = NULL;
    998 			return (0);
    999 		}
   1000 	}
   1001 	return (1);
   1002 }
   1003 
   1004 /*
   1005  * Walk the list of ttys and create sessions for each active line.
   1006  */
   1007 state_func_t
   1008 read_ttys(void)
   1009 {
   1010 	int session_index = 0;
   1011 	session_t *sp, *snext;
   1012 	struct ttyent *typ;
   1013 
   1014 	/*
   1015 	 * Destroy any previous session state.
   1016 	 * There shouldn't be any, but just in case...
   1017 	 */
   1018 	for (sp = sessions; sp; sp = snext) {
   1019 		if (sp->se_process)
   1020 			clear_session_logs(sp, 0);
   1021 		snext = sp->se_next;
   1022 		free_session(sp);
   1023 	}
   1024 	sessions = NULL;
   1025 	if (start_session_db())
   1026 		return (state_func_t)single_user;
   1027 
   1028 	/*
   1029 	 * Allocate a session entry for each active port.
   1030 	 * Note that sp starts at 0.
   1031 	 */
   1032 	while ((typ = getttyent()) != NULL)
   1033 		if ((snext = new_session(sp, ++session_index, typ)) != NULL)
   1034 			sp = snext;
   1035 
   1036 	endttyent();
   1037 
   1038 	return (state_func_t)multi_user;
   1039 }
   1040 
   1041 /*
   1042  * Start a window system running.
   1043  */
   1044 void
   1045 start_window_system(session_t *sp)
   1046 {
   1047 	pid_t pid;
   1048 	sigset_t mask;
   1049 
   1050 	if ((pid = fork()) == -1) {
   1051 		emergency("can't fork for window system on port %s: %m",
   1052 		    sp->se_device);
   1053 		/* hope that getty fails and we can try again */
   1054 		return;
   1055 	}
   1056 
   1057 	if (pid)
   1058 		return;
   1059 
   1060 	sigemptyset(&mask);
   1061 	sigprocmask(SIG_SETMASK, &mask, NULL);
   1062 
   1063 	if (setsid() < 0)
   1064 		emergency("setsid failed (window) %m");
   1065 
   1066 	(void)execv(sp->se_window_argv[0], sp->se_window_argv);
   1067 	stall("can't exec window system '%s' for port %s: %m",
   1068 	    sp->se_window_argv[0], sp->se_device);
   1069 	_exit(1);
   1070 }
   1071 
   1072 /*
   1073  * Start a login session running.
   1074  */
   1075 pid_t
   1076 start_getty(session_t *sp)
   1077 {
   1078 	pid_t pid;
   1079 	sigset_t mask;
   1080 	time_t current_time = time(NULL);
   1081 
   1082 	/*
   1083 	 * fork(), not vfork() -- we can't afford to block.
   1084 	 */
   1085 	if ((pid = fork()) == -1) {
   1086 		emergency("can't fork for getty on port %s: %m", sp->se_device);
   1087 		return -1;
   1088 	}
   1089 
   1090 	if (pid)
   1091 		return pid;
   1092 
   1093 	if (current_time > sp->se_started &&
   1094 	    current_time - sp->se_started < GETTY_SPACING) {
   1095 		warning("getty repeating too quickly on port %s, sleeping",
   1096 		    sp->se_device);
   1097 		(void)sleep(GETTY_SLEEP);
   1098 	}
   1099 
   1100 	if (sp->se_window) {
   1101 		start_window_system(sp);
   1102 		(void)sleep(WINDOW_WAIT);
   1103 	}
   1104 
   1105 	(void)sigemptyset(&mask);
   1106 	(void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
   1107 
   1108 	(void)execv(sp->se_getty_argv[0], sp->se_getty_argv);
   1109 	stall("can't exec getty '%s' for port %s: %m",
   1110 	    sp->se_getty_argv[0], sp->se_device);
   1111 	_exit(1);
   1112 	/*NOTREACHED*/
   1113 }
   1114 #endif /* LETS_GET_SMALL */
   1115 
   1116 /*
   1117  * Collect exit status for a child.
   1118  * If an exiting login, start a new login running.
   1119  */
   1120 void
   1121 collect_child(pid_t pid, int status)
   1122 {
   1123 #ifndef LETS_GET_SMALL
   1124 	session_t *sp, *sprev, *snext;
   1125 
   1126 	if (! sessions)
   1127 		return;
   1128 
   1129 	if ((sp = find_session(pid)) == NULL)
   1130 		return;
   1131 
   1132 	clear_session_logs(sp, status);
   1133 	del_session(sp);
   1134 	sp->se_process = 0;
   1135 
   1136 	if (sp->se_flags & SE_SHUTDOWN) {
   1137 		if ((sprev = sp->se_prev) != NULL)
   1138 			sprev->se_next = sp->se_next;
   1139 		else
   1140 			sessions = sp->se_next;
   1141 		if ((snext = sp->se_next) != NULL)
   1142 			snext->se_prev = sp->se_prev;
   1143 		free_session(sp);
   1144 		return;
   1145 	}
   1146 
   1147 	if ((pid = start_getty(sp)) == -1) {
   1148 		/* serious trouble */
   1149 		requested_transition = clean_ttys;
   1150 		return;
   1151 	}
   1152 
   1153 	sp->se_process = pid;
   1154 	sp->se_started = time(NULL);
   1155 	add_session(sp);
   1156 #endif /* LETS_GET_SMALL */
   1157 }
   1158 
   1159 /*
   1160  * Catch a signal and request a state transition.
   1161  */
   1162 void
   1163 transition_handler(int sig)
   1164 {
   1165 
   1166 	switch (sig) {
   1167 #ifndef LETS_GET_SMALL
   1168 	case SIGHUP:
   1169 		requested_transition = clean_ttys;
   1170 		break;
   1171 	case SIGTERM:
   1172 		requested_transition = death;
   1173 		break;
   1174 	case SIGTSTP:
   1175 		requested_transition = catatonia;
   1176 		break;
   1177 #endif /* LETS_GET_SMALL */
   1178 	default:
   1179 		requested_transition = 0;
   1180 		break;
   1181 	}
   1182 }
   1183 
   1184 #ifndef LETS_GET_SMALL
   1185 /*
   1186  * Take the system multiuser.
   1187  */
   1188 state_func_t
   1189 multi_user(void)
   1190 {
   1191 	pid_t pid;
   1192 	int status;
   1193 	session_t *sp;
   1194 
   1195 	requested_transition = 0;
   1196 
   1197 	/*
   1198 	 * If the administrator has not set the security level to -1
   1199 	 * to indicate that the kernel should not run multiuser in secure
   1200 	 * mode, and the run script has not set a higher level of security
   1201 	 * than level 1, then put the kernel into secure mode.
   1202 	 */
   1203 	if (getsecuritylevel() == 0)
   1204 		setsecuritylevel(1);
   1205 
   1206 	for (sp = sessions; sp; sp = sp->se_next) {
   1207 		if (sp->se_process)
   1208 			continue;
   1209 		if ((pid = start_getty(sp)) == -1) {
   1210 			/* serious trouble */
   1211 			requested_transition = clean_ttys;
   1212 			break;
   1213 		}
   1214 		sp->se_process = pid;
   1215 		sp->se_started = time(NULL);
   1216 		add_session(sp);
   1217 	}
   1218 
   1219 	while (!requested_transition)
   1220 		if ((pid = waitpid(-1, &status, 0)) != -1)
   1221 			collect_child(pid, status);
   1222 
   1223 	return (state_func_t)requested_transition;
   1224 }
   1225 
   1226 /*
   1227  * This is an n-squared algorithm.  We hope it isn't run often...
   1228  */
   1229 state_func_t
   1230 clean_ttys(void)
   1231 {
   1232 	session_t *sp, *sprev;
   1233 	struct ttyent *typ;
   1234 	int session_index = 0;
   1235 	int devlen;
   1236 
   1237 	for (sp = sessions; sp; sp = sp->se_next)
   1238 		sp->se_flags &= ~SE_PRESENT;
   1239 
   1240 	devlen = sizeof(_PATH_DEV) - 1;
   1241 	while ((typ = getttyent()) != NULL) {
   1242 		++session_index;
   1243 
   1244 		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
   1245 			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
   1246 				break;
   1247 
   1248 		if (sp) {
   1249 			sp->se_flags |= SE_PRESENT;
   1250 			if (sp->se_index != session_index) {
   1251 				warning("port %s changed utmp index from "
   1252 				    "%d to %d", sp->se_device, sp->se_index,
   1253 				    session_index);
   1254 				sp->se_index = session_index;
   1255 			}
   1256 			if ((typ->ty_status & TTY_ON) == 0 ||
   1257 			    typ->ty_getty == 0) {
   1258 				sp->se_flags |= SE_SHUTDOWN;
   1259 				if (sp->se_process != 0)
   1260 					(void)kill(sp->se_process, SIGHUP);
   1261 				continue;
   1262 			}
   1263 			sp->se_flags &= ~SE_SHUTDOWN;
   1264 			if (setupargv(sp, typ) == 0) {
   1265 				warning("can't parse getty for port %s",
   1266 				    sp->se_device);
   1267 				sp->se_flags |= SE_SHUTDOWN;
   1268 				if (sp->se_process != 0)
   1269 					(void)kill(sp->se_process, SIGHUP);
   1270 			}
   1271 			continue;
   1272 		}
   1273 
   1274 		new_session(sprev, session_index, typ);
   1275 	}
   1276 
   1277 	endttyent();
   1278 
   1279 	for (sp = sessions; sp; sp = sp->se_next)
   1280 		if ((sp->se_flags & SE_PRESENT) == 0) {
   1281 			sp->se_flags |= SE_SHUTDOWN;
   1282 			if (sp->se_process != 0)
   1283 				(void)kill(sp->se_process, SIGHUP);
   1284 		}
   1285 
   1286 	return (state_func_t)multi_user;
   1287 }
   1288 
   1289 /*
   1290  * Block further logins.
   1291  */
   1292 state_func_t
   1293 catatonia(void)
   1294 {
   1295 	session_t *sp;
   1296 
   1297 	for (sp = sessions; sp; sp = sp->se_next)
   1298 		sp->se_flags |= SE_SHUTDOWN;
   1299 
   1300 	return (state_func_t)multi_user;
   1301 }
   1302 #endif /* LETS_GET_SMALL */
   1303 
   1304 /*
   1305  * Note SIGALRM.
   1306  */
   1307 void
   1308 /*ARGSUSED*/
   1309 alrm_handler(int sig)
   1310 {
   1311 
   1312 	clang = 1;
   1313 }
   1314 
   1315 #ifndef LETS_GET_SMALL
   1316 /*
   1317  * Bring the system down to single user.
   1318  */
   1319 state_func_t
   1320 death(void)
   1321 {
   1322 	session_t *sp;
   1323 	int i, status;
   1324 	pid_t pid;
   1325 	static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
   1326 
   1327 	for (sp = sessions; sp; sp = sp->se_next)
   1328 		sp->se_flags |= SE_SHUTDOWN;
   1329 
   1330 	/* NB: should send a message to the session logger to avoid blocking. */
   1331 #ifdef SUPPORT_UTMPX
   1332 	logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
   1333 #endif
   1334 #ifdef SUPPORT_UTMP
   1335 	logwtmp("~", "shutdown", "");
   1336 #endif
   1337 
   1338 	for (i = 0; i < 3; ++i) {
   1339 		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
   1340 			return (state_func_t)single_user;
   1341 
   1342 		clang = 0;
   1343 		alarm(DEATH_WATCH);
   1344 		do
   1345 			if ((pid = waitpid(-1, &status, 0)) != -1)
   1346 				collect_child(pid, status);
   1347 		while (clang == 0 && errno != ECHILD);
   1348 
   1349 		if (errno == ECHILD)
   1350 			return (state_func_t)single_user;
   1351 	}
   1352 
   1353 	warning("some processes would not die; ps axl advised");
   1354 
   1355 	return (state_func_t)single_user;
   1356 }
   1357 #endif /* LETS_GET_SMALL */
   1358 
   1359 #ifdef MFS_DEV_IF_NO_CONSOLE
   1360 
   1361 static void
   1362 mapfile(struct mappedfile *mf)
   1363 {
   1364 	int fd;
   1365 	struct stat st;
   1366 
   1367 	if (lstat(mf->path, &st) == -1)
   1368 		return;
   1369 
   1370 	if ((st.st_mode & S_IFMT) == S_IFLNK) {
   1371 		mf->buf = malloc(st.st_size + 1);
   1372 		mf->buf[st.st_size] = 0;
   1373 		if (readlink(mf->path, mf->buf, st.st_size) != st.st_size)
   1374 			return;
   1375 		mf->len = -1;
   1376 		return;
   1377 	}
   1378 
   1379 	if ((fd = open(mf->path, O_RDONLY)) == -1)
   1380 		return;
   1381 	mf->buf = mmap(0, (size_t)st.st_size, PROT_READ,
   1382 			MAP_FILE|MAP_SHARED, fd, (off_t)0);
   1383 	(void)close(fd);
   1384 	if (mf->buf == MAP_FAILED)
   1385 		return;
   1386 	mf->len = st.st_size;
   1387 }
   1388 
   1389 static void
   1390 writefile(struct mappedfile *mf)
   1391 {
   1392 	int fd;
   1393 
   1394 	if (mf->len == -1) {
   1395 		symlink(mf->buf, mf->path);
   1396 		free(mf->buf);
   1397 		return;
   1398 	}
   1399 
   1400 	if (mf->len == 0)
   1401 		return;
   1402 	fd = open(mf->path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
   1403 	if (fd == -1)
   1404 		return;
   1405 	(void)write(fd, mf->buf, mf->len);
   1406 	(void)munmap(mf->buf, mf->len);
   1407 	(void)close(fd);
   1408 }
   1409 
   1410 static int
   1411 mfs_dev(void)
   1412 {
   1413 	/*
   1414 	 * We cannot print errors so we bail out silently...
   1415 	 */
   1416 	pid_t pid;
   1417 	int status;
   1418 	dev_t dev;
   1419 	char *fs_size;
   1420 #ifdef CPU_CONSDEV
   1421 	static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
   1422 	size_t olen;
   1423 #endif
   1424 
   1425 	/* If we have /dev/console, assume all is OK  */
   1426 	if (access(_PATH_CONSOLE, F_OK) != -1)
   1427 		return(0);
   1428 
   1429 	/* Grab the contents of MAKEDEV */
   1430 	mapfile(&mfile[0]);
   1431 
   1432 	/* Grab the contents of MAKEDEV.local */
   1433 	mapfile(&mfile[1]);
   1434 
   1435 	/* Mount an mfs over /dev so we can create devices */
   1436 	switch ((pid = fork())) {
   1437 	case 0:
   1438 		asprintf(&fs_size, "%d", FSSIZE);
   1439 		(void)execl(INIT_MOUNT_MFS, "mount_mfs",
   1440 		    "-b", "4096", "-f", "512",
   1441 		    "-s", fs_size, "-n", STR(NINODE),
   1442 		    "swap", "/dev", NULL);
   1443 		_exit(1);
   1444 		/*NOTREACHED*/
   1445 
   1446 	case -1:
   1447 		return(-1);
   1448 
   1449 	default:
   1450 		if (waitpid(pid, &status, 0) == -1)
   1451 			return(-1);
   1452 		if (status != 0)
   1453 			return(-1);
   1454 		break;
   1455 	}
   1456 
   1457 #ifdef CPU_CONSDEV
   1458 	olen = sizeof(dev);
   1459 	if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &olen,
   1460 	    NULL, 0) == -1)
   1461 #endif
   1462 		dev = makedev(0, 0);
   1463 
   1464 	/* Make a console for us, so we can see things happening */
   1465 	if (mknod(_PATH_CONSOLE, 0666 | S_IFCHR, dev) == -1)
   1466 		return(-1);
   1467 
   1468 	(void)freopen(_PATH_CONSOLE, "a", stderr);
   1469 
   1470 	warnx("Creating mfs /dev (%d blocks, %d inodes)", FSSIZE, NINODE);
   1471 
   1472 	/* Create a MAKEDEV script in the mfs /dev */
   1473 	writefile(&mfile[0]);
   1474 
   1475 	/* Create a MAKEDEV.local script in the mfs /dev */
   1476 	writefile(&mfile[1]);
   1477 
   1478 	/* Run the makedev script to create devices */
   1479 	switch ((pid = fork())) {
   1480 	case 0:
   1481 		dup2(2, 1);	/* Give the script stdout */
   1482 		if (chdir("/dev") == 0)
   1483 			(void)execl(INIT_BSHELL, "sh",
   1484 			    mfile[0].len ? "./MAKEDEV" : "/etc/MAKEDEV",
   1485 			    "init", NULL);
   1486 		_exit(1);
   1487 
   1488 	case -1:
   1489 		break;
   1490 
   1491 	default:
   1492 		if (waitpid(pid, &status, 0) == -1)
   1493 			break;
   1494 		if (status != 0) {
   1495 			errno = EINVAL;
   1496 			break;
   1497 		}
   1498 		return 0;
   1499 	}
   1500 	warn("Unable to run MAKEDEV");
   1501 	return (-1);
   1502 }
   1503 #endif
   1504