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 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
49 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
50 #define VT_LOG "/dev/tty3" /* Virtual console */
51 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
52 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
53 #define SHELL "/bin/sh" /* Default shell */
54 #define INITSCRIPT "/etc/init.d/rcS" /* Initscript. */
58 static char *console = _PATH_CONSOLE;
59 static char *second_console = VT_SECONDARY;
60 static char *log = VT_LOG;
61 static int kernel_version = 0;
64 /* try to open up the specified device */
65 int device_open(char *device, int mode)
69 m = mode | O_NONBLOCK;
71 /* Retry up to 5 times */
72 for (f = 0; f < 5; f++)
73 if ((fd = open(device, m)) >= 0)
77 /* Reset original flags. */
79 fcntl(fd, F_SETFL, mode);
83 /* print a message to the specified device:
84 * device may be bitwise-or'd from LOG | CONSOLE */
85 void message(int device, char *fmt, ...)
91 /* Log the message to syslogd */
94 va_start(arguments, fmt);
95 vsnprintf(msg, sizeof(msg), fmt, arguments);
97 syslog(LOG_DAEMON|LOG_NOTICE, msg);
101 static int log_fd=-1;
103 /* Take full control of the log tty, and never close it.
104 * It's mine, all mine! Muhahahaha! */
107 /* don't even try to log, because there is no such console */
109 /* log to main console instead */
112 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
114 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
119 if ( (device & LOG) && (log_fd >= 0) ) {
120 va_start(arguments, fmt);
121 vdprintf(log_fd, fmt, arguments);
126 if (device & CONSOLE) {
127 /* Always send console messages to /dev/console so people will see them. */
128 if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
129 va_start(arguments, fmt);
130 vdprintf(fd, fmt, arguments);
134 fprintf(stderr, "Bummer, can't print: ");
135 va_start(arguments, fmt);
136 vfprintf(stderr, fmt, arguments);
144 /* Set terminal settings to reasonable defaults */
145 void set_term( int fd)
149 static const char control_characters[] = {
150 '\003', '\034', '\177', '\030', '\004', '\0',
151 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
152 '\017', '\027', '\026', '\0'
155 static const char control_characters[] = {
156 '\003', '\034', '\177', '\025', '\004', '\0',
157 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
158 '\017', '\027', '\026', '\0'
164 /* set control chars */
165 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
167 /* use line dicipline 0 */
170 /* Make it be sane */
171 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
172 //tty.c_cflag |= HUPCL|CLOCAL;
175 tty.c_iflag = ICRNL|IXON|IXOFF;
178 tty.c_oflag = OPOST|ONLCR;
181 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
183 tcsetattr(fd, TCSANOW, &tty);
186 /* How much memory does this machine have? */
187 static int mem_total()
190 char *p = "/proc/meminfo";
192 const char pattern[] = "MemTotal:";
194 if ((f = fopen(p, "r")) < 0) {
195 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
198 while (NULL != fgets(s, 79, f)) {
199 p = strstr(s, pattern);
202 return (atoi(p + strlen(pattern)));
208 static void console_init()
211 int tried_devcons = 0;
212 int tried_vtprimary = 0;
213 struct serial_struct sr;
216 if ((s = getenv("CONSOLE")) != NULL) {
220 /* sparc kernel supports console=tty[ab] parameter which is also
221 * passed to init, so catch it here */
222 else if ((s = getenv("console")) != NULL) {
223 /* remap tty[ab] to /dev/ttyS[01] */
224 if (strcmp( s, "ttya" )==0)
225 console = SERIAL_CON0;
226 else if (strcmp( s, "ttyb" )==0)
227 console = SERIAL_CON1;
232 static char the_console[13];
234 console = the_console;
235 /* 2.2 kernels: identify the real console backend and try to use it */
236 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
237 /* this is a serial console */
238 snprintf( the_console, sizeof the_console, "/dev/ttyS%d", sr.line );
240 else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
241 /* this is linux virtual tty */
242 snprintf( the_console, sizeof the_console, "/dev/tty%d", vt.v_active );
244 console = _PATH_CONSOLE;
249 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
250 /* Can't open selected console -- try /dev/console */
251 if (!tried_devcons) {
253 console = _PATH_CONSOLE;
256 /* Can't open selected console -- try vt1 */
257 if (!tried_vtprimary) {
259 console = VT_PRIMARY;
265 /* Perhaps we should panic here? */
266 console = "/dev/null";
268 /* check for serial console and disable logging to tty3 & running a
270 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
271 message(LOG|CONSOLE, "serial console detected. Disabling 2nd virtual terminal.\r\n", console );
273 second_console = NULL;
277 message(LOG, "console=%s\n", console );
280 static int waitfor(int pid)
284 message(LOG, "Waiting for process %d.\n", pid);
285 while ((wpid = wait(&status)) != pid) {
287 message(LOG, "pid %d exited, status=0x%x.\n", wpid, status);
293 static pid_t run(const char * const* command,
294 char *terminal, int get_enter)
298 const char * const* cmd = command+1;
299 static const char press_enter[] =
300 "\nPlease press Enter to activate this console. ";
302 if ((pid = fork()) == 0) {
309 /* Reset signal handlers set for parent process */
310 signal(SIGUSR1, SIG_DFL);
311 signal(SIGUSR2, SIG_DFL);
312 signal(SIGINT, SIG_DFL);
313 signal(SIGTERM, SIG_DFL);
315 if ((fd = device_open(terminal, O_RDWR)) < 0) {
316 message(LOG, "Bummer, can't open %s\r\n", terminal);
321 tcsetpgrp(0, getpgrp());
324 if (get_enter==TRUE) {
326 * Save memory by not exec-ing anything large (like a shell)
327 * before the user wants it. This is critical if swap is not
328 * enabled and the system has low memory. Generally this will
329 * be run on the second virtual console, and the first will
330 * be allowed to start a shell or whatever an init script
334 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
335 *cmd, getpid(), terminal );
336 write(1, press_enter, sizeof(press_enter) - 1);
340 /* Log the process name and args */
341 message(LOG, "Starting pid %d, console %s: '", getpid(), terminal);
342 while ( *cmd) message(LOG, "%s ", *cmd++);
343 message(LOG, "'\r\n");
345 /* Now run it. The new program will take over this PID,
346 * so nothing further in init.c should be run. */
347 execvp(*command, (char**)command+1);
349 message(LOG, "Bummer, could not run '%s'\n", command);
355 /* Make sure there is enough memory to do something useful. *
356 * Calls swapon if needed so be sure /proc is mounted. */
357 static void check_memory()
360 const char* const swap_on_cmd[] =
361 { "/bin/swapon", "swapon", "-a", 0};
363 if (mem_total() > 3500)
366 if (stat("/etc/fstab", &statbuf) == 0) {
367 /* Try to turn on swap */
368 waitfor(run(swap_on_cmd, log, FALSE));
369 if (mem_total() < 3500)
376 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
380 static void shutdown_system(void)
382 const char* const swap_off_cmd[] = { "swapoff", "swapoff", "-a", 0};
383 const char* const umount_cmd[] = { "umount", "umount", "-a", "-n", 0};
386 /* Allow Ctrl-Alt-Del to reboot system. */
387 reboot(RB_ENABLE_CAD);
389 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
391 /* Send signals to every process _except_ pid 1 */
392 message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
398 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
403 message(CONSOLE, "Disabling swap.\r\n");
404 waitfor(run( swap_off_cmd, console, FALSE));
405 message(CONSOLE, "Unmounting filesystems.\r\n");
406 waitfor(run( umount_cmd, console, FALSE));
408 if (kernel_version > 0 && kernel_version <= 2 * 65536 + 2 * 256 + 11) {
409 /* bdflush, kupdate not needed for kernels >2.2.11 */
410 message(CONSOLE, "Flushing buffers.\r\n");
416 static void halt_signal(int sig)
420 "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
424 reboot(RB_HALT_SYSTEM);
425 //reboot(RB_POWER_OFF);
430 static void reboot_signal(int sig)
433 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
442 extern int init_main(int argc, char **argv)
445 int wait_for_enter = TRUE;
449 const char* const rc_script_command[] = { INITSCRIPT, INITSCRIPT, 0};
450 const char* const shell_command[] = { SHELL, "-" SHELL, 0};
451 const char* const* tty0_command = shell_command;
452 const char* const* tty1_command = shell_command;
453 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
454 const char* const rc_exit_command[] = { "BB_INIT_CMD_IF_RC_SCRIPT_EXITS",
455 "BB_INIT_CMD_IF_RC_SCRIPT_EXITS", 0 };
459 char *hello_msg_format =
460 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n";
462 char *hello_msg_format =
463 "init started: BusyBox v%s (%s) multi-call binary\r\n";
468 /* Expect to be PID 1 iff we are run as init (not linuxrc) */
469 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
470 usage( "init\n\nInit is the parent of all processes.\n\n"
471 "This version of init is designed to be run only by the kernel\n");
475 /* Check if we are supposed to be in single user mode */
476 if ( argc > 1 && (!strcmp(argv[1], "single") ||
477 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
482 /* Set up sig handlers -- be sure to
483 * clear all of these in run() */
484 signal(SIGUSR1, halt_signal);
485 signal(SIGUSR2, reboot_signal);
486 signal(SIGINT, reboot_signal);
487 signal(SIGTERM, reboot_signal);
489 /* Turn off rebooting via CTL-ALT-DEL -- we get a
490 * SIGINT on CAD so we can shut things down gracefully... */
492 reboot(RB_DISABLE_CAD);
495 /* Figure out where the default console should be */
498 /* Close whatever files are open, and reset the console. */
505 /* Make sure PATH is set to something sane */
506 putenv(_PATH_STDPATH);
511 message(CONSOLE|LOG, hello_msg_format, BB_VER, BB_BT);
513 message(CONSOLE|LOG, hello_msg_format, getpid(), BB_VER, BB_BT);
518 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
519 message(CONSOLE|LOG, "Mounting /proc: done.\n");
520 kernel_version = get_kernel_revision();
522 message(CONSOLE|LOG, "Mounting /proc: failed!\n");
524 /* Make sure there is enough memory to do something useful. */
528 /* Make sure an init script exists before trying to run it */
529 if (run_rc == TRUE && stat(INITSCRIPT, &statbuf)==0) {
530 wait_for_enter = FALSE;
531 tty0_command = rc_script_command;
535 /* Ok, now launch the rc script and/or prepare to
536 * start up some VTs if somebody hits enter...
542 if (pid1 == 0 && tty0_command) {
543 pid1 = run(tty0_command, console, wait_for_enter);
545 if (pid2 == 0 && tty1_command && second_console) {
546 pid2 = run(tty1_command, second_console, TRUE);
548 wpid = wait(&status);
550 message(LOG, "pid %d exited, status=%x.\n", wpid, status);
552 /* Don't respawn init script if it exits */
554 if (run_rc == FALSE) {
557 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
562 tty0_command=rc_exit_command;