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 #ifndef BB_INIT_SCRIPT
66 #define BB_INIT_SCRIPT "/etc/init.d/rcS" /* Initscript. */
71 static char *console = _PATH_CONSOLE;
72 static char *second_console = VT_SECONDARY;
73 static char *log = VT_LOG;
74 static int kernel_version = 0;
77 /* try to open up the specified device */
78 int device_open(char *device, int mode)
82 m = mode | O_NONBLOCK;
84 /* Retry up to 5 times */
85 for (f = 0; f < 5; f++)
86 if ((fd = open(device, m)) >= 0)
90 /* Reset original flags. */
92 fcntl(fd, F_SETFL, mode);
96 /* print a message to the specified device:
97 * device may be bitwise-or'd from LOG | CONSOLE */
98 void message(int device, char *fmt, ...)
104 /* Log the message to syslogd */
107 va_start(arguments, fmt);
108 vsnprintf(msg, sizeof(msg), fmt, arguments);
110 syslog(LOG_DAEMON|LOG_NOTICE, msg);
114 static int log_fd=-1;
116 /* Take full control of the log tty, and never close it.
117 * It's mine, all mine! Muhahahaha! */
120 /* don't even try to log, because there is no such console */
122 /* log to main console instead */
125 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
127 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
132 if ( (device & LOG) && (log_fd >= 0) ) {
133 va_start(arguments, fmt);
134 vdprintf(log_fd, fmt, arguments);
139 if (device & CONSOLE) {
140 /* Always send console messages to /dev/console so people will see them. */
141 if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
142 va_start(arguments, fmt);
143 vdprintf(fd, fmt, arguments);
147 fprintf(stderr, "Bummer, can't print: ");
148 va_start(arguments, fmt);
149 vfprintf(stderr, fmt, arguments);
157 /* Set terminal settings to reasonable defaults */
158 void set_term( int fd)
161 static const char control_characters[] = {
162 '\003', '\034', '\177', '\025', '\004', '\0',
163 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
164 '\017', '\027', '\026', '\0'
169 /* set control chars */
170 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
172 /* use line dicipline 0 */
175 /* Make it be sane */
176 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
177 //tty.c_cflag |= HUPCL|CLOCAL;
180 tty.c_iflag = ICRNL|IXON|IXOFF;
183 tty.c_oflag = OPOST|ONLCR;
186 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
188 tcsetattr(fd, TCSANOW, &tty);
191 /* How much memory does this machine have? */
192 static int mem_total()
195 char *p = "/proc/meminfo";
197 const char pattern[] = "MemTotal:";
199 if ((f = fopen(p, "r")) < 0) {
200 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
203 while (NULL != fgets(s, 79, f)) {
204 p = strstr(s, pattern);
207 return (atoi(p + strlen(pattern)));
213 static void console_init()
216 int tried_devcons = 0;
217 int tried_vtprimary = 0;
218 struct serial_struct sr;
221 if ((s = getenv("CONSOLE")) != NULL) {
225 /* sparc kernel supports console=tty[ab] parameter which is also
226 * passed to init, so catch it here */
227 else if ((s = getenv("console")) != NULL) {
228 /* remap tty[ab] to /dev/ttyS[01] */
229 if (strcmp( s, "ttya" )==0)
230 console = SERIAL_CON0;
231 else if (strcmp( s, "ttyb" )==0)
232 console = SERIAL_CON1;
237 static char the_console[13];
239 console = the_console;
240 /* 2.2 kernels: identify the real console backend and try to use it */
241 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
242 /* this is a serial console */
243 snprintf( the_console, sizeof the_console, "/dev/ttyS%d", sr.line );
245 else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
246 /* this is linux virtual tty */
247 snprintf( the_console, sizeof the_console, "/dev/tty%d", vt.v_active );
249 console = _PATH_CONSOLE;
254 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
255 /* Can't open selected console -- try /dev/console */
256 if (!tried_devcons) {
258 console = _PATH_CONSOLE;
261 /* Can't open selected console -- try vt1 */
262 if (!tried_vtprimary) {
264 console = VT_PRIMARY;
270 /* Perhaps we should panic here? */
271 console = "/dev/null";
273 /* check for serial console and disable logging to tty3 & running a
275 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
276 message(LOG|CONSOLE, "serial console detected. Disabling 2nd virtual terminal.\r\n", console );
278 second_console = NULL;
282 message(LOG, "console=%s\n", console );
285 static int waitfor(int pid)
289 message(LOG, "Waiting for process %d.\n", pid);
290 while ((wpid = wait(&status)) != pid) {
292 message(LOG, "pid %d exited, status=0x%x.\n", wpid, status);
298 static pid_t run(const char * const* command,
299 char *terminal, int get_enter)
303 const char * const* cmd = command+1;
304 static const char press_enter[] =
305 "\nPlease press Enter to activate this console. ";
307 if ((pid = fork()) == 0) {
314 /* Reset signal handlers set for parent process */
315 signal(SIGUSR1, SIG_DFL);
316 signal(SIGUSR2, SIG_DFL);
317 signal(SIGINT, SIG_DFL);
318 signal(SIGTERM, SIG_DFL);
320 if ((fd = device_open(terminal, O_RDWR)) < 0) {
321 message(LOG, "Bummer, can't open %s\r\n", terminal);
326 tcsetpgrp(0, getpgrp());
329 if (get_enter==TRUE) {
331 * Save memory by not exec-ing anything large (like a shell)
332 * before the user wants it. This is critical if swap is not
333 * enabled and the system has low memory. Generally this will
334 * be run on the second virtual console, and the first will
335 * be allowed to start a shell or whatever an init script
339 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
340 *cmd, getpid(), terminal );
341 write(1, press_enter, sizeof(press_enter) - 1);
345 /* Log the process name and args */
346 message(LOG|CONSOLE, "Starting pid %d, console %s: '", getpid(), terminal);
347 while ( *cmd) message(LOG|CONSOLE, "%s ", *cmd++);
348 message(LOG|CONSOLE, "'\r\n");
350 /* Now run it. The new program will take over this PID,
351 * so nothing further in init.c should be run. */
352 execvp(*command, (char**)command+1);
354 message(LOG, "Bummer, could not run '%s'\n", command);
360 /* Make sure there is enough memory to do something useful. *
361 * Calls swapon if needed so be sure /proc is mounted. */
362 static void check_memory()
365 const char* const swap_on_cmd[] =
366 { "/bin/swapon", "swapon", "-a", 0};
368 if (mem_total() > 3500)
371 if (stat("/etc/fstab", &statbuf) == 0) {
372 /* Try to turn on swap */
373 waitfor(run(swap_on_cmd, log, FALSE));
374 if (mem_total() < 3500)
381 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
385 static void shutdown_system(void)
387 const char* const swap_off_cmd[] = { "swapoff", "swapoff", "-a", 0};
388 const char* const umount_cmd[] = { "umount", "umount", "-a", 0};
391 /* Allow Ctrl-Alt-Del to reboot system. */
392 reboot(RB_ENABLE_CAD);
394 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
396 /* Send signals to every process _except_ pid 1 */
397 message(CONSOLE, "Sending SIGHUP to all processes.\r\n");
403 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
408 message(CONSOLE, "Disabling swap.\r\n");
409 waitfor(run( swap_off_cmd, console, FALSE));
410 message(CONSOLE, "Unmounting filesystems.\r\n");
411 waitfor(run( umount_cmd, console, FALSE));
413 if (kernel_version > 0 && kernel_version <= 2 * 65536 + 2 * 256 + 11) {
414 /* bdflush, kupdate not needed for kernels >2.2.11 */
415 message(CONSOLE, "Flushing buffers.\r\n");
421 static void halt_signal(int sig)
425 "The system is halted. Press CTRL-ALT-DEL or turn off power\r\n");
428 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
430 reboot(RB_POWER_OFF);
433 reboot(RB_HALT_SYSTEM);
438 static void reboot_signal(int sig)
441 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
449 extern int init_main(int argc, char **argv)
453 int wait_for_enter_tty1 = TRUE;
454 int wait_for_enter_tty2 = TRUE;
460 const char* const rc_script_command[] = { BB_INIT_SCRIPT, BB_INIT_SCRIPT, 0};
461 const char* const getty1_command[] = { GETTY, GETTY, "38400", which_vt1, 0};
462 const char* const getty2_command[] = { GETTY, GETTY, "38400", which_vt2, 0};
463 const char* const shell_command[] = { SHELL, "-" SHELL, 0};
464 const char* const* tty1_command = shell_command;
465 const char* const* tty2_command = shell_command;
466 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
467 const char* const rc_exit_command[] = { "BB_INIT_CMD_IF_RC_SCRIPT_EXITS",
468 "BB_INIT_CMD_IF_RC_SCRIPT_EXITS", 0 };
472 char *hello_msg_format =
473 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n";
475 char *hello_msg_format =
476 "init started: BusyBox v%s (%s) multi-call binary\r\n";
481 /* Expect to be PID 1 iff we are run as init (not linuxrc) */
482 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
483 usage( "init\n\nInit is the parent of all processes.\n\n"
484 "This version of init is designed to be run only by the kernel\n");
488 /* Set up sig handlers -- be sure to
489 * clear all of these in run() */
490 signal(SIGUSR1, halt_signal);
491 signal(SIGUSR2, reboot_signal);
492 signal(SIGINT, reboot_signal);
493 signal(SIGTERM, reboot_signal);
495 /* Turn off rebooting via CTL-ALT-DEL -- we get a
496 * SIGINT on CAD so we can shut things down gracefully... */
498 reboot(RB_DISABLE_CAD);
501 /* Figure out where the default console should be */
504 /* Close whatever files are open, and reset the console. */
511 /* Make sure PATH is set to something sane */
512 putenv(_PATH_STDPATH);
517 message(CONSOLE|LOG, hello_msg_format, BB_VER, BB_BT);
519 message(CONSOLE|LOG, hello_msg_format, getpid(), BB_VER, BB_BT);
524 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
525 message(CONSOLE|LOG, "Mounting /proc: done.\n");
526 kernel_version = get_kernel_revision();
528 message(CONSOLE|LOG, "Mounting /proc: failed!\n");
530 /* Make sure there is enough memory to do something useful. */
533 /* Check if we are supposed to be in single user mode */
534 if ( argc > 1 && (!strcmp(argv[1], "single") ||
535 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1"))) {
537 tty1_command = shell_command;
538 tty2_command = shell_command;
541 /* Make sure an init script exists before trying to run it */
542 if (single==FALSE && stat(BB_INIT_SCRIPT, &statbuf)==0) {
544 wait_for_enter_tty1 = FALSE;
545 tty1_command = rc_script_command;
548 /* Make sure /sbin/getty exists before trying to run it */
549 if (stat(GETTY, &statbuf)==0) {
552 wait_for_enter_tty2 = FALSE;
553 where = strrchr( second_console, '/');
554 if ( where != NULL) {
556 strncpy( which_vt2, where, sizeof(which_vt2));
558 tty2_command = getty2_command;
560 /* Check on hooking a getty onto tty1 */
561 if (run_rc == FALSE && single==FALSE) {
562 wait_for_enter_tty1 = FALSE;
563 where = strrchr( console, '/');
564 if ( where != NULL) {
566 strncpy( which_vt1, where, sizeof(which_vt1));
568 tty1_command = getty1_command;
573 /* Ok, now launch the tty1_command and tty2_command */
578 if (pid1 == 0 && tty1_command) {
579 pid1 = run(tty1_command, console, wait_for_enter_tty1);
581 #ifdef BB_FEATURE_INIT_SECOND_CONSOLE
582 if (pid2 == 0 && tty2_command && second_console) {
583 pid2 = run(tty2_command, second_console, wait_for_enter_tty2);
586 wpid = wait(&status);
588 message(LOG, "pid %d exited, status=%x.\n", wpid, status);
590 /* Don't respawn init script if it exits */
592 if (run_rc == FALSE) {
595 #ifdef BB_INIT_CMD_IF_RC_SCRIPT_EXITS
599 wait_for_enter_tty1=TRUE;
600 tty1_command=rc_exit_command;
604 #ifdef BB_FEATURE_INIT_SECOND_CONSOLE