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>
44 #include <linux/version.h>
46 #include <sys/syslog.h>
49 #if ! defined BB_FEATURE_USE_PROCFS
50 #error Sorry, I depend on the /proc filesystem right now.
53 #ifndef KERNEL_VERSION
54 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
58 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
59 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
60 #define VT_LOG "/dev/tty3" /* Virtual console */
61 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
62 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
63 #define GETTY "/sbin/getty" /* Default location of getty */
64 #define SHELL "/bin/sh" /* Default shell */
65 #define INITSCRIPT "/etc/init.d/rcS" /* Initscript. */
69 static char *console = _PATH_CONSOLE;
70 static char *second_console = VT_SECONDARY;
71 static char *log = VT_LOG;
72 static int kernel_version = 0;
75 /* try to open up the specified device */
76 int device_open(char *device, int mode)
80 m = mode | O_NONBLOCK;
82 /* Retry up to 5 times */
83 for (f = 0; f < 5; f++)
84 if ((fd = open(device, m)) >= 0)
88 /* Reset original flags. */
90 fcntl(fd, F_SETFL, mode);
94 /* print a message to the specified device:
95 * device may be bitwise-or'd from LOG | CONSOLE */
96 void message(int device, char *fmt, ...)
102 /* Log the message to syslogd */
105 va_start(arguments, fmt);
106 vsnprintf(msg, sizeof(msg), fmt, arguments);
108 syslog(LOG_DAEMON|LOG_NOTICE, msg);
112 static int log_fd=-1;
114 /* Take full control of the log tty, and never close it.
115 * It's mine, all mine! Muhahahaha! */
118 /* don't even try to log, because there is no such console */
120 /* log to main console instead */
123 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
125 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
130 if ( (device & LOG) && (log_fd >= 0) ) {
131 va_start(arguments, fmt);
132 vdprintf(log_fd, fmt, arguments);
137 if (device & CONSOLE) {
138 /* Always send console messages to /dev/console so people will see them. */
139 if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
140 va_start(arguments, fmt);
141 vdprintf(fd, fmt, arguments);
145 fprintf(stderr, "Bummer, can't print: ");
146 va_start(arguments, fmt);
147 vfprintf(stderr, fmt, arguments);
155 /* Set terminal settings to reasonable defaults */
156 void set_term( int fd)
159 static const char control_characters[] = {
160 '\003', '\034', '\177', '\025', '\004', '\0',
161 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
162 '\017', '\027', '\026', '\0'
167 /* set control chars */
168 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
170 /* use line dicipline 0 */
173 /* Make it be sane */
174 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
175 //tty.c_cflag |= HUPCL|CLOCAL;
178 tty.c_iflag = ICRNL|IXON|IXOFF;
181 tty.c_oflag = OPOST|ONLCR;
184 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
186 tcsetattr(fd, TCSANOW, &tty);
189 /* How much memory does this machine have? */
190 static int mem_total()
193 char *p = "/proc/meminfo";
195 const char pattern[] = "MemTotal:";
197 if ((f = fopen(p, "r")) < 0) {
198 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
201 while (NULL != fgets(s, 79, f)) {
202 p = strstr(s, pattern);
205 return (atoi(p + strlen(pattern)));
211 static void console_init()
214 int tried_devcons = 0;
215 int tried_vtprimary = 0;
216 struct serial_struct sr;
219 if ((s = getenv("CONSOLE")) != NULL) {
223 /* sparc kernel supports console=tty[ab] parameter which is also
224 * passed to init, so catch it here */
225 else if ((s = getenv("console")) != NULL) {
226 /* remap tty[ab] to /dev/ttyS[01] */
227 if (strcmp( s, "ttya" )==0)
228 console = SERIAL_CON0;
229 else if (strcmp( s, "ttyb" )==0)
230 console = SERIAL_CON1;
235 static char the_console[13];
237 console = the_console;
238 /* 2.2 kernels: identify the real console backend and try to use it */
239 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
240 /* this is a serial console */
241 snprintf( the_console, sizeof the_console, "/dev/ttyS%d", sr.line );
243 else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
244 /* this is linux virtual tty */
245 snprintf( the_console, sizeof the_console, "/dev/tty%d", vt.v_active );
247 console = _PATH_CONSOLE;
252 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
253 /* Can't open selected console -- try /dev/console */
254 if (!tried_devcons) {
256 console = _PATH_CONSOLE;
259 /* Can't open selected console -- try vt1 */
260 if (!tried_vtprimary) {
262 console = VT_PRIMARY;
268 /* Perhaps we should panic here? */
269 console = "/dev/null";
271 /* check for serial console and disable logging to tty3 & running a
273 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
274 message(LOG|CONSOLE, "serial console detected. Disabling 2nd virtual terminal.\r\n", console );
276 second_console = NULL;
280 message(LOG, "console=%s\n", console );
283 static int waitfor(int pid)
287 message(LOG, "Waiting for process %d.\n", pid);
288 while ((wpid = wait(&status)) != pid) {
290 message(LOG, "pid %d exited, status=0x%x.\n", wpid, status);
296 static pid_t run(const char * const* command,
297 char *terminal, int get_enter)
301 const char * const* cmd = command+1;
302 static const char press_enter[] =
303 "\nPlease press Enter to activate this console. ";
305 if ((pid = fork()) == 0) {
312 /* Reset signal handlers set for parent process */
313 signal(SIGUSR1, SIG_DFL);
314 signal(SIGUSR2, SIG_DFL);
315 signal(SIGINT, SIG_DFL);
316 signal(SIGTERM, SIG_DFL);
318 if ((fd = device_open(terminal, O_RDWR)) < 0) {
319 message(LOG, "Bummer, can't open %s\r\n", terminal);
324 tcsetpgrp(0, getpgrp());
327 if (get_enter==TRUE) {
329 * Save memory by not exec-ing anything large (like a shell)
330 * before the user wants it. This is critical if swap is not
331 * enabled and the system has low memory. Generally this will
332 * be run on the second virtual console, and the first will
333 * be allowed to start a shell or whatever an init script
337 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
338 *cmd, getpid(), terminal );
339 write(1, press_enter, sizeof(press_enter) - 1);
343 /* Log the process name and args */
344 message(LOG|CONSOLE, "Starting pid %d, console %s: '", getpid(), terminal);
345 while ( *cmd) message(LOG|CONSOLE, "%s ", *cmd++);
346 message(LOG|CONSOLE, "'\r\n");
348 /* Now run it. The new program will take over this PID,
349 * so nothing further in init.c should be run. */
350 execvp(*command, (char**)command+1);
352 message(LOG, "Bummer, could not run '%s'\n", command);
358 /* Make sure there is enough memory to do something useful. *
359 * Calls swapon if needed so be sure /proc is mounted. */
360 static void check_memory()
363 const char* const swap_on_cmd[] =
364 { "/bin/swapon", "swapon", "-a", 0};
366 if (mem_total() > 3500)
369 if (stat("/etc/fstab", &statbuf) == 0) {
370 /* Try to turn on swap */
371 waitfor(run(swap_on_cmd, log, FALSE));
372 if (mem_total() < 3500)
379 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
383 static void shutdown_system(void)
385 const char* const swap_off_cmd[] = { "swapoff", "swapoff", "-a", 0};
386 const char* const umount_cmd[] = { "umount", "umount", "-a", 0};
389 /* Allow Ctrl-Alt-Del to reboot system. */
390 reboot(RB_ENABLE_CAD);
392 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
394 /* Send signals to every process _except_ pid 1 */
395 message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
401 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
406 message(CONSOLE, "Disabling swap.\r\n");
407 waitfor(run( swap_off_cmd, console, FALSE));
408 message(CONSOLE, "Unmounting filesystems.\r\n");
409 waitfor(run( umount_cmd, console, FALSE));
411 if (kernel_version > 0 && kernel_version <= 2 * 65536 + 2 * 256 + 11) {
412 /* bdflush, kupdate not needed for kernels >2.2.11 */
413 message(CONSOLE, "Flushing buffers.\r\n");
419 static void halt_signal(int sig)
423 "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
426 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
428 reboot(RB_POWER_OFF);
431 reboot(RB_HALT_SYSTEM);
436 static void reboot_signal(int sig)
439 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
447 extern int init_main(int argc, char **argv)
451 int wait_for_enter_tty1 = TRUE;
452 int wait_for_enter_tty2 = TRUE;
458 const char* const rc_script_command[] = { INITSCRIPT, INITSCRIPT, 0};
459 const char* const getty1_command[] = { GETTY, GETTY, "38400", which_vt1, 0};
460 const char* const getty2_command[] = { GETTY, GETTY, "38400", which_vt2, 0};
461 const char* const shell_command[] = { SHELL, "-" SHELL, 0};
462 const char* const* tty1_command = shell_command;
463 const char* const* tty2_command = shell_command;
464 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
465 const char* const rc_exit_command[] = { "BB_INIT_CMD_IF_RC_SCRIPT_EXITS",
466 "BB_INIT_CMD_IF_RC_SCRIPT_EXITS", 0 };
470 char *hello_msg_format =
471 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n";
473 char *hello_msg_format =
474 "init started: BusyBox v%s (%s) multi-call binary\r\n";
479 /* Expect to be PID 1 iff we are run as init (not linuxrc) */
480 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
481 usage( "init\n\nInit is the parent of all processes.\n\n"
482 "This version of init is designed to be run only by the kernel\n");
486 /* Set up sig handlers -- be sure to
487 * clear all of these in run() */
488 signal(SIGUSR1, halt_signal);
489 signal(SIGUSR2, reboot_signal);
490 signal(SIGINT, reboot_signal);
491 signal(SIGTERM, reboot_signal);
493 /* Turn off rebooting via CTL-ALT-DEL -- we get a
494 * SIGINT on CAD so we can shut things down gracefully... */
496 reboot(RB_DISABLE_CAD);
499 /* Figure out where the default console should be */
502 /* Close whatever files are open, and reset the console. */
509 /* Make sure PATH is set to something sane */
510 putenv(_PATH_STDPATH);
515 message(CONSOLE|LOG, hello_msg_format, BB_VER, BB_BT);
517 message(CONSOLE|LOG, hello_msg_format, getpid(), BB_VER, BB_BT);
522 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
523 message(CONSOLE|LOG, "Mounting /proc: done.\n");
524 kernel_version = get_kernel_revision();
526 message(CONSOLE|LOG, "Mounting /proc: failed!\n");
528 /* Make sure there is enough memory to do something useful. */
531 /* Check if we are supposed to be in single user mode */
532 if ( argc > 1 && (!strcmp(argv[1], "single") ||
533 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
535 tty1_command = shell_command;
536 tty2_command = shell_command;
539 /* Make sure an init script exists before trying to run it */
540 if (single==FALSE && stat(INITSCRIPT, &statbuf)==0) {
542 wait_for_enter_tty1 = FALSE;
543 tty1_command = rc_script_command;
546 /* Make sure /sbin/getty exists before trying to run it */
547 if (stat(GETTY, &statbuf)==0) {
550 wait_for_enter_tty2 = FALSE;
551 where = strrchr( second_console, '/');
552 if ( where != NULL) {
554 strncpy( which_vt2, where, sizeof(which_vt2));
556 tty2_command = getty2_command;
558 /* Check on hooking a getty onto tty1 */
559 if (run_rc == FALSE && single==FALSE) {
560 wait_for_enter_tty1 = FALSE;
561 where = strrchr( console, '/');
562 if ( where != NULL) {
564 strncpy( which_vt1, where, sizeof(which_vt1));
566 tty1_command = getty1_command;
571 /* Ok, now launch the tty1_command and tty2_command */
576 if (pid1 == 0 && tty1_command) {
577 pid1 = run(tty1_command, console, wait_for_enter_tty1);
579 #ifdef BB_FEATURE_INIT_SECOND_CONSOLE
580 if (pid2 == 0 && tty2_command && second_console) {
581 pid2 = run(tty2_command, second_console, wait_for_enter_tty2);
584 wpid = wait(&status);
586 message(LOG, "pid %d exited, status=%x.\n", wpid, status);
588 /* Don't respawn init script if it exits */
590 if (run_rc == FALSE) {
593 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
597 wait_for_enter_tty1=TRUE;
598 tty1_command=rc_exit_command;
602 #ifdef BB_FEATURE_INIT_SECOND_CONSOLE