2 * Mini init implementation for busybox
5 * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6 * Adjusted by so many folks, it's impossible to keep track.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #include <sys/types.h>
34 #include <sys/fcntl.h>
37 #include <sys/mount.h>
38 #include <sys/reboot.h>
39 #include <sys/kdaemon.h>
40 #include <sys/sysmacros.h>
41 #include <linux/serial.h> /* for serial_struct */
42 #include <sys/vt.h> /* for vt_stat */
43 #include <sys/ioctl.h>
45 #include <sys/syslog.h>
48 #if ! defined BB_FEATURE_USE_PROCFS
49 #error Sorry, I depend on the /proc filesystem right now.
53 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
54 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
55 #define VT_LOG "/dev/tty3" /* Virtual console */
56 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
57 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
58 #define GETTY "/sbin/getty" /* Default location of getty */
59 #define SHELL "/bin/sh" /* Default shell */
60 #define INITSCRIPT "/etc/init.d/rcS" /* Initscript. */
64 static char *console = _PATH_CONSOLE;
65 static char *second_console = VT_SECONDARY;
66 static char *log = VT_LOG;
67 static int kernel_version = 0;
70 /* try to open up the specified device */
71 int device_open(char *device, int mode)
75 m = mode | O_NONBLOCK;
77 /* Retry up to 5 times */
78 for (f = 0; f < 5; f++)
79 if ((fd = open(device, m)) >= 0)
83 /* Reset original flags. */
85 fcntl(fd, F_SETFL, mode);
89 /* print a message to the specified device:
90 * device may be bitwise-or'd from LOG | CONSOLE */
91 void message(int device, char *fmt, ...)
97 /* Log the message to syslogd */
100 va_start(arguments, fmt);
101 vsnprintf(msg, sizeof(msg), fmt, arguments);
103 syslog(LOG_DAEMON|LOG_NOTICE, msg);
107 static int log_fd=-1;
109 /* Take full control of the log tty, and never close it.
110 * It's mine, all mine! Muhahahaha! */
113 /* don't even try to log, because there is no such console */
115 /* log to main console instead */
118 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
120 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
125 if ( (device & LOG) && (log_fd >= 0) ) {
126 va_start(arguments, fmt);
127 vdprintf(log_fd, fmt, arguments);
132 if (device & CONSOLE) {
133 /* Always send console messages to /dev/console so people will see them. */
134 if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
135 va_start(arguments, fmt);
136 vdprintf(fd, fmt, arguments);
140 fprintf(stderr, "Bummer, can't print: ");
141 va_start(arguments, fmt);
142 vfprintf(stderr, fmt, arguments);
150 /* Set terminal settings to reasonable defaults */
151 void set_term( int fd)
154 static const char control_characters[] = {
155 '\003', '\034', '\177', '\025', '\004', '\0',
156 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
157 '\017', '\027', '\026', '\0'
162 /* set control chars */
163 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
165 /* use line dicipline 0 */
168 /* Make it be sane */
169 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
170 //tty.c_cflag |= HUPCL|CLOCAL;
173 tty.c_iflag = ICRNL|IXON|IXOFF;
176 tty.c_oflag = OPOST|ONLCR;
179 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
181 tcsetattr(fd, TCSANOW, &tty);
184 /* How much memory does this machine have? */
185 static int mem_total()
188 char *p = "/proc/meminfo";
190 const char pattern[] = "MemTotal:";
192 if ((f = fopen(p, "r")) < 0) {
193 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
196 while (NULL != fgets(s, 79, f)) {
197 p = strstr(s, pattern);
200 return (atoi(p + strlen(pattern)));
206 static void console_init()
209 int tried_devcons = 0;
210 int tried_vtprimary = 0;
211 struct serial_struct sr;
214 if ((s = getenv("CONSOLE")) != NULL) {
218 /* sparc kernel supports console=tty[ab] parameter which is also
219 * passed to init, so catch it here */
220 else if ((s = getenv("console")) != NULL) {
221 /* remap tty[ab] to /dev/ttyS[01] */
222 if (strcmp( s, "ttya" )==0)
223 console = SERIAL_CON0;
224 else if (strcmp( s, "ttyb" )==0)
225 console = SERIAL_CON1;
230 static char the_console[13];
232 console = the_console;
233 /* 2.2 kernels: identify the real console backend and try to use it */
234 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
235 /* this is a serial console */
236 snprintf( the_console, sizeof the_console, "/dev/ttyS%d", sr.line );
238 else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
239 /* this is linux virtual tty */
240 snprintf( the_console, sizeof the_console, "/dev/tty%d", vt.v_active );
242 console = _PATH_CONSOLE;
247 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
248 /* Can't open selected console -- try /dev/console */
249 if (!tried_devcons) {
251 console = _PATH_CONSOLE;
254 /* Can't open selected console -- try vt1 */
255 if (!tried_vtprimary) {
257 console = VT_PRIMARY;
263 /* Perhaps we should panic here? */
264 console = "/dev/null";
266 /* check for serial console and disable logging to tty3 & running a
268 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
269 message(LOG|CONSOLE, "serial console detected. Disabling 2nd virtual terminal.\r\n", console );
271 second_console = NULL;
275 message(LOG, "console=%s\n", console );
278 static int waitfor(int pid)
282 message(LOG, "Waiting for process %d.\n", pid);
283 while ((wpid = wait(&status)) != pid) {
285 message(LOG, "pid %d exited, status=0x%x.\n", wpid, status);
291 static pid_t run(const char * const* command,
292 char *terminal, int get_enter)
296 const char * const* cmd = command+1;
297 static const char press_enter[] =
298 "\nPlease press Enter to activate this console. ";
300 if ((pid = fork()) == 0) {
307 /* Reset signal handlers set for parent process */
308 signal(SIGUSR1, SIG_DFL);
309 signal(SIGUSR2, SIG_DFL);
310 signal(SIGINT, SIG_DFL);
311 signal(SIGTERM, SIG_DFL);
313 if ((fd = device_open(terminal, O_RDWR)) < 0) {
314 message(LOG, "Bummer, can't open %s\r\n", terminal);
319 tcsetpgrp(0, getpgrp());
322 if (get_enter==TRUE) {
324 * Save memory by not exec-ing anything large (like a shell)
325 * before the user wants it. This is critical if swap is not
326 * enabled and the system has low memory. Generally this will
327 * be run on the second virtual console, and the first will
328 * be allowed to start a shell or whatever an init script
332 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
333 *cmd, getpid(), terminal );
334 write(1, press_enter, sizeof(press_enter) - 1);
338 /* Log the process name and args */
339 message(LOG|CONSOLE, "Starting pid %d, console %s: '", getpid(), terminal);
340 while ( *cmd) message(LOG|CONSOLE, "%s ", *cmd++);
341 message(LOG|CONSOLE, "'\r\n");
343 /* Now run it. The new program will take over this PID,
344 * so nothing further in init.c should be run. */
345 execvp(*command, (char**)command+1);
347 message(LOG, "Bummer, could not run '%s'\n", command);
353 /* Make sure there is enough memory to do something useful. *
354 * Calls swapon if needed so be sure /proc is mounted. */
355 static void check_memory()
358 const char* const swap_on_cmd[] =
359 { "/bin/swapon", "swapon", "-a", 0};
361 if (mem_total() > 3500)
364 if (stat("/etc/fstab", &statbuf) == 0) {
365 /* Try to turn on swap */
366 waitfor(run(swap_on_cmd, log, FALSE));
367 if (mem_total() < 3500)
374 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
378 static void shutdown_system(void)
380 const char* const swap_off_cmd[] = { "swapoff", "swapoff", "-a", 0};
381 const char* const umount_cmd[] = { "umount", "umount", "-a", 0};
384 /* Allow Ctrl-Alt-Del to reboot system. */
385 reboot(RB_ENABLE_CAD);
387 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
389 /* Send signals to every process _except_ pid 1 */
390 message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
396 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
401 message(CONSOLE, "Disabling swap.\r\n");
402 waitfor(run( swap_off_cmd, console, FALSE));
403 message(CONSOLE, "Unmounting filesystems.\r\n");
404 waitfor(run( umount_cmd, console, FALSE));
406 if (kernel_version > 0 && kernel_version <= 2 * 65536 + 2 * 256 + 11) {
407 /* bdflush, kupdate not needed for kernels >2.2.11 */
408 message(CONSOLE, "Flushing buffers.\r\n");
414 static void halt_signal(int sig)
418 "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
422 reboot(RB_POWER_OFF);
424 reboot(RB_HALT_SYSTEM);
429 static void reboot_signal(int sig)
432 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
440 extern int init_main(int argc, char **argv)
444 int wait_for_enter_tty1 = TRUE;
445 int wait_for_enter_tty2 = TRUE;
451 const char* const rc_script_command[] = { INITSCRIPT, INITSCRIPT, 0};
452 const char* const getty1_command[] = { GETTY, GETTY, "38400", which_vt1, 0};
453 const char* const getty2_command[] = { GETTY, GETTY, "38400", which_vt2, 0};
454 const char* const shell_command[] = { SHELL, "-" SHELL, 0};
455 const char* const* tty1_command = shell_command;
456 const char* const* tty2_command = shell_command;
457 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
458 const char* const rc_exit_command[] = { "BB_INIT_CMD_IF_RC_SCRIPT_EXITS",
459 "BB_INIT_CMD_IF_RC_SCRIPT_EXITS", 0 };
463 char *hello_msg_format =
464 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n";
466 char *hello_msg_format =
467 "init started: BusyBox v%s (%s) multi-call binary\r\n";
472 /* Expect to be PID 1 iff we are run as init (not linuxrc) */
473 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
474 usage( "init\n\nInit is the parent of all processes.\n\n"
475 "This version of init is designed to be run only by the kernel\n");
479 /* Set up sig handlers -- be sure to
480 * clear all of these in run() */
481 signal(SIGUSR1, halt_signal);
482 signal(SIGUSR2, reboot_signal);
483 signal(SIGINT, reboot_signal);
484 signal(SIGTERM, reboot_signal);
486 /* Turn off rebooting via CTL-ALT-DEL -- we get a
487 * SIGINT on CAD so we can shut things down gracefully... */
489 reboot(RB_DISABLE_CAD);
492 /* Figure out where the default console should be */
495 /* Close whatever files are open, and reset the console. */
502 /* Make sure PATH is set to something sane */
503 putenv(_PATH_STDPATH);
508 message(CONSOLE|LOG, hello_msg_format, BB_VER, BB_BT);
510 message(CONSOLE|LOG, hello_msg_format, getpid(), BB_VER, BB_BT);
515 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
516 message(CONSOLE|LOG, "Mounting /proc: done.\n");
517 kernel_version = get_kernel_revision();
519 message(CONSOLE|LOG, "Mounting /proc: failed!\n");
521 /* Make sure there is enough memory to do something useful. */
524 /* Check if we are supposed to be in single user mode */
525 if ( argc > 1 && (!strcmp(argv[1], "single") ||
526 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
528 tty1_command = shell_command;
529 tty2_command = shell_command;
532 /* Make sure an init script exists before trying to run it */
533 if (single==FALSE && stat(INITSCRIPT, &statbuf)==0) {
535 wait_for_enter_tty1 = FALSE;
536 tty1_command = rc_script_command;
539 /* Make sure /sbin/getty exists before trying to run it */
540 if (stat(GETTY, &statbuf)==0) {
543 wait_for_enter_tty2 = FALSE;
544 where = strrchr( second_console, '/');
545 if ( where != NULL) {
547 strncpy( which_vt2, where, sizeof(which_vt2));
549 tty2_command = getty2_command;
551 /* Check on hooking a getty onto tty1 */
552 if (run_rc == FALSE && single==FALSE) {
553 wait_for_enter_tty1 = FALSE;
554 where = strrchr( console, '/');
555 if ( where != NULL) {
557 strncpy( which_vt1, where, sizeof(which_vt1));
559 tty1_command = getty1_command;
564 /* Ok, now launch the tty1_command and tty2_command */
569 if (pid1 == 0 && tty1_command) {
570 pid1 = run(tty1_command, console, wait_for_enter_tty1);
572 #ifdef BB_FEATURE_INIT_SECOND_CONSOLE
573 if (pid2 == 0 && tty2_command && second_console) {
574 pid2 = run(tty2_command, second_console, wait_for_enter_tty2);
577 wpid = wait(&status);
579 message(LOG, "pid %d exited, status=%x.\n", wpid, status);
581 /* Don't respawn init script if it exits */
583 if (run_rc == FALSE) {
586 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
590 wait_for_enter_tty1=TRUE;
591 tty1_command=rc_exit_command;
595 #ifdef BB_FEATURE_INIT_SECOND_CONSOLE