1 /* vi: set sw=4 ts=4: */
3 * Mini init implementation for busybox
6 * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
7 * Adjusted by so many folks, it's impossible to keep track.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 #include <sys/types.h>
36 #include <sys/fcntl.h>
39 #include <sys/mount.h>
40 #include <sys/reboot.h>
41 #include <sys/kdaemon.h>
42 #include <sys/sysmacros.h>
43 #include <asm/types.h>
44 #include <linux/serial.h> /* for serial_struct */
45 #include <sys/vt.h> /* for vt_stat */
46 #include <sys/ioctl.h>
47 #include <linux/version.h>
49 #include <sys/syslog.h>
52 #if ! defined BB_FEATURE_USE_PROCFS
53 #error Sorry, I depend on the /proc filesystem right now.
56 #ifndef KERNEL_VERSION
57 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
61 #define VT_PRIMARY "/dev/tty1" /* Primary virtual console */
62 #define VT_SECONDARY "/dev/tty2" /* Virtual console */
63 #define VT_LOG "/dev/tty3" /* Virtual console */
64 #define SERIAL_CON0 "/dev/ttyS0" /* Primary serial console */
65 #define SERIAL_CON1 "/dev/ttyS1" /* Serial console */
66 #define SHELL "/bin/sh" /* Default shell */
67 #define INITTAB "/etc/inittab" /* inittab file location */
69 #define INIT_SCRIPT "/etc/init.d/rcS" /* Default sysinit script. */
75 /* Allowed init action types */
84 /* And now a list of the actions we support in the version of init */
85 typedef struct initActionType{
87 initActionEnum action;
90 static const struct initActionType actions[] = {
93 {"askfirst", ASKFIRST},
99 /* Set up a linked list of initactions, to be read from inittab */
100 typedef struct initActionTag initAction;
101 struct initActionTag {
106 initActionEnum action;
108 initAction* initActionList = NULL;
111 static char *secondConsole = VT_SECONDARY;
112 static char *log = VT_LOG;
113 static int kernelVersion = 0;
114 static char termType[32] = "TERM=ansi";
115 static char console[32] = _PATH_CONSOLE;
118 /* print a message to the specified device:
119 * device may be bitwise-or'd from LOG | CONSOLE */
120 void message(int device, char *fmt, ...)
127 /* Log the message to syslogd */
130 va_start(arguments, fmt);
131 vsnprintf(msg, sizeof(msg), fmt, arguments);
133 openlog( "init", 0, LOG_DAEMON);
134 syslog(LOG_DAEMON|LOG_NOTICE, msg);
139 static int log_fd = -1;
141 /* Take full control of the log tty, and never close it.
142 * It's mine, all mine! Muhahahaha! */
145 /* don't even try to log, because there is no such console */
147 /* log to main console instead */
150 else if ((log_fd = device_open(log, O_RDWR|O_NDELAY)) < 0) {
152 fprintf(stderr, "Bummer, can't write to log on %s!\r\n", log);
157 if ( (device & LOG) && (log_fd >= 0) ) {
158 va_start(arguments, fmt);
159 vdprintf(log_fd, fmt, arguments);
164 if (device & CONSOLE) {
165 /* Always send console messages to /dev/console so people will see them. */
166 if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NDELAY)) >= 0) {
167 va_start(arguments, fmt);
168 vdprintf(fd, fmt, arguments);
172 fprintf(stderr, "Bummer, can't print: ");
173 va_start(arguments, fmt);
174 vfprintf(stderr, fmt, arguments);
182 /* Set terminal settings to reasonable defaults */
183 void set_term( int fd)
186 static const char control_characters[] = {
187 '\003', '\034', '\177', '\025', '\004', '\0',
188 '\1', '\0', '\021', '\023', '\032', '\0', '\022',
189 '\017', '\027', '\026', '\0'
194 /* set control chars */
195 memcpy(tty.c_cc, control_characters, sizeof(control_characters));
197 /* use line dicipline 0 */
200 /* Make it be sane */
201 //tty.c_cflag &= CBAUD|CBAUDEX|CSIZE|CSTOPB|PARENB|PARODD;
202 //tty.c_cflag |= HUPCL|CLOCAL;
205 tty.c_iflag = ICRNL|IXON|IXOFF;
208 tty.c_oflag = OPOST|ONLCR;
211 tty.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
213 tcsetattr(fd, TCSANOW, &tty);
216 /* How much memory does this machine have? */
217 static int mem_total()
220 char *p = "/proc/meminfo";
222 const char pattern[] = "MemTotal:";
224 if ((f = fopen(p, "r")) < 0) {
225 message(LOG, "Error opening %s: %s\n", p, strerror( errno));
228 while (NULL != fgets(s, 79, f)) {
229 p = strstr(s, pattern);
232 return (atoi(p + strlen(pattern)));
238 static void console_init()
241 int tried_devcons = 0;
242 int tried_vtprimary = 0;
243 struct serial_struct sr;
246 if ((s = getenv("TERM")) != NULL) {
247 snprintf(termType,sizeof(termType)-1,"TERM=%s",s);
250 if ((s = getenv("CONSOLE")) != NULL) {
251 snprintf(console, sizeof(console)-1, "%s",s);
254 /* sparc kernel supports console=tty[ab] parameter which is also
255 * passed to init, so catch it here */
256 else if ((s = getenv("console")) != NULL) {
257 /* remap tty[ab] to /dev/ttyS[01] */
258 if (strcmp( s, "ttya" )==0)
259 snprintf(console, sizeof(console)-1, "%s", SERIAL_CON0);
260 else if (strcmp( s, "ttyb" )==0)
261 snprintf(console, sizeof(console)-1, "%s", SERIAL_CON1);
267 /* 2.2 kernels: identify the real console backend and try to use it */
268 if (ioctl(0, TIOCGSERIAL, &sr) == 0) {
269 /* this is a serial console */
270 snprintf(console, sizeof(console)-1, "/dev/ttyS%d", sr.line);
272 else if (ioctl(0, VT_GETSTATE, &vt) == 0) {
273 /* this is linux virtual tty */
274 snprintf(console, sizeof(console)-1, "/dev/tty%d", vt.v_active);
276 snprintf(console, sizeof(console)-1, "%s", _PATH_CONSOLE);
281 while ((fd = open(console, O_RDONLY | O_NONBLOCK)) < 0) {
282 /* Can't open selected console -- try /dev/console */
283 if (!tried_devcons) {
285 snprintf(console, sizeof(console)-1, "%s", _PATH_CONSOLE);
288 /* Can't open selected console -- try vt1 */
289 if (!tried_vtprimary) {
291 snprintf(console, sizeof(console)-1, "%s", VT_PRIMARY);
297 /* Perhaps we should panic here? */
298 snprintf(console, sizeof(console)-1, "/dev/null");
300 /* check for serial console and disable logging to tty3 & running a
302 if (ioctl(0,TIOCGSERIAL,&sr) == 0) {
303 message(LOG|CONSOLE, "serial console detected. Disabling virtual terminals.\r\n" );
305 secondConsole = NULL;
309 message(LOG, "console=%s\n", console );
312 static pid_t run(char* command,
313 char *terminal, int get_enter)
319 static const char press_enter[] =
320 "\nPlease press Enter to activate this console. ";
321 char* environment[] = {
323 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
331 if ((pid = fork()) == 0) {
332 pid_t shell_pgid = getpid ();
340 /* Reset signal handlers set for parent process */
341 signal(SIGUSR1, SIG_DFL);
342 signal(SIGUSR2, SIG_DFL);
343 signal(SIGINT, SIG_DFL);
344 signal(SIGTERM, SIG_DFL);
345 signal(SIGHUP, SIG_DFL);
347 if ((fd = device_open(terminal, O_RDWR)) < 0) {
348 message(LOG|CONSOLE, "Bummer, can't open %s\r\n", terminal);
354 tcsetpgrp (0, getpgrp());
357 if (get_enter==TRUE) {
359 * Save memory by not exec-ing anything large (like a shell)
360 * before the user wants it. This is critical if swap is not
361 * enabled and the system has low memory. Generally this will
362 * be run on the second virtual console, and the first will
363 * be allowed to start a shell or whatever an init script
367 message(LOG, "Waiting for enter to start '%s' (pid %d, console %s)\r\n",
368 command, shell_pgid, terminal );
369 write(fileno(stdout), press_enter, sizeof(press_enter) - 1);
370 read(fileno(stdin), &c, 1);
373 /* Log the process name and args */
374 message(LOG, "Starting pid %d, console %s: '",
375 shell_pgid, terminal, command);
377 /* Convert command (char*) into cmd (char**, one word per string) */
378 for (tmpCmd=command, i=0; (tmpCmd=strsep(&command, " \t")) != NULL;) {
379 if (*tmpCmd != '\0') {
381 message(LOG, "%s ", tmpCmd);
387 message(LOG, "'\r\n");
389 /* Now run it. The new program will take over this PID,
390 * so nothing further in init.c should be run. */
391 execve(cmd[0], cmd, environment);
393 /* We're still here? Some error happened. */
394 message(LOG|CONSOLE, "Bummer, could not run '%s': %s\n", cmd[0],
401 static int waitfor(char* command,
402 char *terminal, int get_enter)
405 int pid = run( command, terminal, get_enter);
408 wpid = wait(&status);
410 message(LOG, "Process '%s' (pid %d) exited.\n",
420 /* Make sure there is enough memory to do something useful. *
421 * Calls swapon if needed so be sure /proc is mounted. */
422 static void check_memory()
426 if (mem_total() > 3500)
429 if (stat("/etc/fstab", &statBuf) == 0) {
430 /* Try to turn on swap */
431 waitfor("/bin/swapon swapon -a", log, FALSE);
432 if (mem_total() < 3500)
439 message(CONSOLE, "Sorry, your computer does not have enough memory.\r\n");
444 static void shutdown_system(void)
446 /* first disable our SIGHUP signal */
447 signal(SIGHUP, SIG_DFL);
449 /* Allow Ctrl-Alt-Del to reboot system. */
450 reboot(RB_ENABLE_CAD);
451 message(CONSOLE, "\r\nThe system is going down NOW !!\r\n");
454 /* Send signals to every process _except_ pid 1 */
455 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
460 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
464 message(CONSOLE, "Disabling swap.\r\n");
465 waitfor( "swapoff -a", console, FALSE);
466 message(CONSOLE, "Unmounting filesystems.\r\n");
467 waitfor("umount -a -r", console, FALSE);
469 if (kernelVersion > 0 && kernelVersion <= 2 * 65536 + 2 * 256 + 11) {
470 /* bdflush, kupdate not needed for kernels >2.2.11 */
476 static void halt_signal(int sig)
479 message(CONSOLE, "The system is halted. Press %s or turn off power\r\n",
480 (secondConsole == NULL) /* serial console */
481 ? "Reset" : "CTRL-ALT-DEL");
484 /* allow time for last message to reach serial console */
487 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
489 reboot(RB_POWER_OFF);
492 reboot(RB_HALT_SYSTEM);
496 static void reboot_signal(int sig)
499 message(CONSOLE, "Please stand by while rebooting the system.\r\n");
502 /* allow time for last message to reach serial console */
509 #if defined BB_FEATURE_INIT_CHROOT
510 static void check_chroot(int sig)
512 char *argv_init[2] = { "init", NULL, };
513 char *envp_init[3] = { "HOME=/", "TERM=linux", NULL, };
514 char rootpath[256], *tc;
517 if ((fd = open("/proc/sys/kernel/init-chroot", O_RDONLY)) == -1) {
518 message(CONSOLE, "SIGHUP recived, but could not open proc file\r\n");
522 if (read(fd, rootpath, sizeof(rootpath)) == -1) {
523 message(CONSOLE, "SIGHUP recived, but could not read proc file\r\n");
529 if (rootpath[0] == '\0') {
530 message(CONSOLE, "SIGHUP recived, but new root is not valid: %s\r\n",
536 tc = strrchr(rootpath, '\n');
539 /* Ok, making it this far means we commit */
540 message(CONSOLE, "Please stand by, changing root to `%s'.\r\n", rootpath);
542 /* kill all other programs first */
543 message(CONSOLE, "Sending SIGTERM to all processes.\r\n");
548 message(CONSOLE, "Sending SIGKILL to all processes.\r\n");
553 /* ok, we don't need /proc anymore. we also assume that the signaling
554 * process left the rest of the filesystems alone for us */
557 /* Ok, now we chroot. Hopefully we only have two things mounted, the
558 * new chroot'd mount point, and the old "/" mount. s,
559 * we go ahead and unmount the old "/". This should trigger the kernel
560 * to set things up the Right Way(tm). */
562 if (!chroot(rootpath))
565 /* If the chroot fails, we are already too far to turn back, so we
566 * continue and hope that executing init below will revive the system */
568 /* close all of our descriptors and open new ones */
572 open("/dev/console", O_RDWR, 0);
576 message(CONSOLE, "Executing real init...\r\n");
577 /* execute init in the (hopefully) new root */
578 execve("/sbin/init",argv_init,envp_init);
580 message(CONSOLE, "ERROR: Could not exec new init. Press %s to reboot.\r\n",
581 (secondConsole == NULL) /* serial console */
582 ? "Reset" : "CTRL-ALT-DEL");
585 #endif /* BB_FEATURE_INIT_CHROOT */
587 #endif /* ! DEBUG_INIT */
589 void new_initAction (initActionEnum action,
590 char* process, char* cons)
592 initAction* newAction;
597 /* If BusyBox detects that a serial console is in use,
598 * then entries not refering to the console or null devices will _not_ be run.
599 * The exception to this rule is the null device.
601 if (secondConsole == NULL && strcmp(cons, console) && strcmp(cons, "/dev/null"))
604 newAction = calloc ((size_t)(1), sizeof(initAction));
606 message(LOG|CONSOLE,"Memory allocation failure\n");
609 newAction->nextPtr = initActionList;
610 initActionList = newAction;
611 strncpy( newAction->process, process, 255);
612 newAction->action = action;
613 strncpy(newAction->console, cons, 255);
615 // message(LOG|CONSOLE, "process='%s' action='%d' console='%s'\n",
616 // newAction->process, newAction->action, newAction->console);
619 void delete_initAction (initAction *action)
621 initAction *a, *b=NULL;
622 for( a=initActionList ; a ; b=a, a=a->nextPtr) {
625 initActionList=a->nextPtr;
627 b->nextPtr=a->nextPtr;
635 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
636 * then parse_inittab() simply adds in some default
637 * actions(i.e runs INIT_SCRIPT and then starts a pair
638 * of "askfirst" shells). If BB_FEATURE_USE_INITTAB
639 * _is_ defined, but /etc/inittab is missing, this
640 * results in the same set of default behaviors.
642 void parse_inittab(void)
644 #ifdef BB_FEATURE_USE_INITTAB
646 char buf[256], lineAsRead[256], tmpConsole[256];
648 const struct initActionType *a = actions;
652 file = fopen(INITTAB, "r");
654 /* No inittab file -- set up some default behavior */
656 /* Askfirst shell on tty1 */
657 new_initAction( ASKFIRST, SHELL, console );
658 /* Askfirst shell on tty2 */
659 if (secondConsole != NULL)
660 new_initAction( ASKFIRST, SHELL, secondConsole );
662 new_initAction( SYSINIT, INIT_SCRIPT, console );
665 #ifdef BB_FEATURE_USE_INITTAB
668 while ( fgets(buf, 255, file) != NULL) {
670 for(p = buf; *p == ' ' || *p == '\t'; p++);
671 if (*p == '#' || *p == '\n') continue;
673 /* Trim the trailing \n */
674 q = strrchr( p, '\n');
678 /* Keep a copy around for posterity's sake (and error msgs) */
679 strcpy(lineAsRead, buf);
681 /* Grab the ID field */
684 if ( p != NULL || *(p+1) != '\0' ) {
689 /* Now peal off the process field from the end
691 q = strrchr( p, ':');
692 if ( q == NULL || *(q+1) == '\0' ) {
693 message(LOG|CONSOLE,"Bad inittab entry: %s\n", lineAsRead);
700 /* Now peal off the action field */
701 r = strrchr( p, ':');
702 if ( r == NULL || *(r+1) == '\0') {
703 message(LOG|CONSOLE,"Bad inittab entry: %s\n", lineAsRead);
709 /* Ok, now process it */
711 while (a->name != 0) {
712 if (strcmp(a->name, r) == 0) {
715 strcpy(tmpConsole, "/dev/");
716 strncat(tmpConsole, s, 200);
717 if (stat(tmpConsole, &statBuf) != 0) {
718 message(LOG|CONSOLE, "device '%s' does not exist. Did you read the directions?\n", tmpConsole);
723 new_initAction( a->action, q, s);
731 /* Choke on an unknown action */
732 message(LOG|CONSOLE, "Bad inittab entry: %s\n", lineAsRead);
739 extern int init_main(int argc, char **argv)
746 /* Expect to be PID 1 if we are run as init (not linuxrc) */
747 if (getpid() != 1 && strstr(argv[0], "init")!=NULL ) {
748 usage( "init\n\nInit is the parent of all processes.\n\n"
749 "This version of init is designed to be run only by the kernel\n");
751 /* Fix up argv[0] to be certain we claim to be init */
752 strncpy(argv[0], "init", strlen(argv[0]));
754 /* Set up sig handlers -- be sure to
755 * clear all of these in run() */
756 signal(SIGUSR1, halt_signal);
757 signal(SIGUSR2, reboot_signal);
758 signal(SIGINT, reboot_signal);
759 signal(SIGTERM, reboot_signal);
760 #if defined BB_FEATURE_INIT_CHROOT
761 signal(SIGHUP, check_chroot);
764 /* Turn off rebooting via CTL-ALT-DEL -- we get a
765 * SIGINT on CAD so we can shut things down gracefully... */
766 reboot(RB_DISABLE_CAD);
769 /* Figure out where the default console should be */
772 /* Close whatever files are open, and reset the console. */
779 /* Make sure PATH is set to something sane */
780 putenv(_PATH_STDPATH);
785 "init started: BusyBox v%s (%s) multi-call binary\r\n",
789 "init(%d) started: BusyBox v%s (%s) multi-call binary\r\n",
790 getpid(), BB_VER, BB_BT);
795 if (mount ("proc", "/proc", "proc", 0, 0) == 0) {
796 message(LOG|CONSOLE, "Mounting /proc: done.\n");
797 kernelVersion = get_kernel_revision();
799 message(LOG|CONSOLE, "Mounting /proc: failed!\n");
801 /* Make sure there is enough memory to do something useful. */
804 /* Check if we are supposed to be in single user mode */
805 if ( argc > 1 && (!strcmp(argv[1], "single") ||
806 !strcmp(argv[1], "-s") || !strcmp(argv[1], "1")))
808 /* Ask first then start a shell on tty2 */
809 if (secondConsole != NULL)
810 new_initAction( ASKFIRST, SHELL, secondConsole);
811 /* Start a shell on tty1 */
812 new_initAction( RESPAWN, SHELL, console);
814 /* Not in single user mode -- see what inittab says */
816 /* NOTE that if BB_FEATURE_USE_INITTAB is NOT defined,
817 * then parse_inittab() simply adds in some default
818 * actions(i.e runs INIT_SCRIPT and then starts a pair
819 * of "askfirst" shells */
823 /* Now run everything that needs to be run */
825 /* First run the sysinit command */
826 for( a=initActionList ; a; a=a->nextPtr) {
827 if (a->action == SYSINIT) {
828 waitfor(a->process, a->console, FALSE);
829 /* Now remove the "sysinit" entry from the list */
830 delete_initAction( a);
833 /* Next run anything that wants to block */
834 for( a=initActionList ; a; a=a->nextPtr) {
835 if (a->action == WAIT) {
836 waitfor(a->process, a->console, FALSE);
837 /* Now remove the "wait" entry from the list */
838 delete_initAction( a);
841 /* Next run anything to be run only once */
842 for( a=initActionList ; a; a=a->nextPtr) {
843 if (a->action == ONCE) {
844 run(a->process, a->console, FALSE);
845 /* Now remove the "once" entry from the list */
846 delete_initAction( a);
849 /* If there is nothing else to do, stop */
850 if (initActionList == NULL) {
851 message(LOG|CONSOLE, "No more tasks for init -- sleeping forever.\n");
855 /* Now run the looping stuff for the rest of forever */
857 for( a=initActionList ; a; a=a->nextPtr) {
858 /* Only run stuff with pid==0. If they have
859 * a pid, that means they are still running */
863 /* run the respawn stuff */
864 a->pid = run(a->process, a->console, FALSE);
867 /* run the askfirst stuff */
868 a->pid = run(a->process, a->console, TRUE);
870 /* silence the compiler's incessant whining */
876 /* Wait for a child process to exit */
877 wpid = wait(&status);
879 /* Find out who died and clean up their corpse */
880 for( a=initActionList ; a; a=a->nextPtr) {
883 message(LOG, "Process '%s' (pid %d) exited. Scheduling it for restart.\n",