tar: support -T - and -X -
[oweals/busybox.git] / init / init.c
index 68e6242944ee8764197f2381e2fb7ed3dc0f77fc..586e34a18eb448d4b6cef4789e7614ee88138ce6 100644 (file)
  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  * Adjusted by so many folks, it's impossible to keep track.
  *
- * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
+ * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  */
 
+//applet:IF_INIT(APPLET(init, BB_DIR_SBIN, BB_SUID_DROP))
+//applet:IF_FEATURE_INITRD(APPLET_ODDNAME(linuxrc, init, BB_DIR_ROOT, BB_SUID_DROP, linuxrc))
+
+//kbuild:lib-$(CONFIG_INIT) += init.o
+
+//config:config INIT
+//config:      bool "init"
+//config:      default y
+//config:      select FEATURE_SYSLOG
+//config:      help
+//config:        init is the first program run when the system boots.
+//config:
+//config:config FEATURE_USE_INITTAB
+//config:      bool "Support reading an inittab file"
+//config:      default y
+//config:      depends on INIT
+//config:      help
+//config:        Allow init to read an inittab file when the system boot.
+//config:
+//config:config FEATURE_KILL_REMOVED
+//config:      bool "Support killing processes that have been removed from inittab"
+//config:      default n
+//config:      depends on FEATURE_USE_INITTAB
+//config:      help
+//config:        When respawn entries are removed from inittab and a SIGHUP is
+//config:        sent to init, this option will make init kill the processes
+//config:        that have been removed.
+//config:
+//config:config FEATURE_KILL_DELAY
+//config:      int "How long to wait between TERM and KILL (0 - send TERM only)" if FEATURE_KILL_REMOVED
+//config:      range 0 1024
+//config:      default 0
+//config:      depends on FEATURE_KILL_REMOVED
+//config:      help
+//config:        With nonzero setting, init sends TERM, forks, child waits N
+//config:        seconds, sends KILL and exits. Setting it too high is unwise
+//config:        (child will hang around for too long and could actually kill
+//config:        the wrong process!)
+//config:
+//config:config FEATURE_INIT_SCTTY
+//config:      bool "Run commands with leading dash with controlling tty"
+//config:      default y
+//config:      depends on INIT
+//config:      help
+//config:        If this option is enabled, init will try to give a controlling
+//config:        tty to any command which has leading hyphen (often it's "-/bin/sh").
+//config:        More precisely, init will do "ioctl(STDIN_FILENO, TIOCSCTTY, 0)".
+//config:        If device attached to STDIN_FILENO can be a ctty but is not yet
+//config:        a ctty for other session, it will become this process' ctty.
+//config:        This is not the traditional init behavour, but is often what you want
+//config:        in an embedded system where the console is only accessed during
+//config:        development or for maintenance.
+//config:        NB: using cttyhack applet may work better.
+//config:
+//config:config FEATURE_INIT_SYSLOG
+//config:      bool "Enable init to write to syslog"
+//config:      default y
+//config:      depends on INIT
+//config:
+//config:config FEATURE_EXTRA_QUIET
+//config:      bool "Be _extra_ quiet on boot"
+//config:      default y
+//config:      depends on INIT
+//config:      help
+//config:        Prevent init from logging some messages to the console during boot.
+//config:
+//config:config FEATURE_INIT_COREDUMPS
+//config:      bool "Support dumping core for child processes (debugging only)"
+//config:      default y
+//config:      depends on INIT
+//config:      help
+//config:        If this option is enabled and the file /.init_enable_core
+//config:        exists, then init will call setrlimit() to allow unlimited
+//config:        core file sizes. If this option is disabled, processes
+//config:        will not generate any core files.
+//config:
+//config:config FEATURE_INITRD
+//config:      bool "Support running init from within an initrd (not initramfs)"
+//config:      default y
+//config:      depends on INIT
+//config:      help
+//config:        Legacy support for running init under the old-style initrd. Allows
+//config:        the name linuxrc to act as init, and it doesn't assume init is PID 1.
+//config:
+//config:        This does not apply to initramfs, which runs /init as PID 1 and
+//config:        requires no special support.
+//config:
+//config:config INIT_TERMINAL_TYPE
+//config:      string "Initial terminal type"
+//config:      default "linux"
+//config:      depends on INIT
+//config:      help
+//config:        This is the initial value set by init for the TERM environment
+//config:        variable. This variable is used by programs which make use of
+//config:        extended terminal capabilities.
+//config:
+//config:        Note that on Linux, init attempts to detect serial terminal and
+//config:        sets TERM to "vt102" if one is found.
+
 #include "libbb.h"
 #include <syslog.h>
 #include <paths.h>
-#include <sys/reboot.h>
 #include <sys/resource.h>
+#ifdef __linux__
+#include <linux/vt.h>
+#endif
+#include "reboot.h" /* reboot() constants */
 
+/* Used only for sanitizing purposes in set_sane_term() below. On systems where
+ * the baud rate is stored in a separate field, we can safely disable them. */
+#ifndef CBAUD
+# define CBAUD 0
+# define CBAUDEX 0
+#endif
 
 /* Was a CONFIG_xxx option. A lot of people were building
  * not fully functional init by switching it on! */
 #define ONCE        0x04
 /*
  * NB: while SYSINIT/WAIT/ONCE are being processed,
- * SIGHUP ("reread /etc/inittab") will be ignored.
- * Rationale: it would be ambiguous whether SYSINIT/WAIT/ONCE
- * need to be rerun or not.
+ * SIGHUP ("reread /etc/inittab") will be processed only after
+ * each group of actions. If new inittab adds, say, a SYSINIT action,
+ * it will not be run, since init is already "past SYSINIT stage".
  */
 /* Start these after ONCE are started, restart on exit */
 #define RESPAWN     0x08
@@ -85,14 +193,6 @@ static const char *log_console = VC_5;
 enum {
        L_LOG = 0x1,
        L_CONSOLE = 0x2,
-       MAYBE_CONSOLE = L_CONSOLE * !ENABLE_FEATURE_EXTRA_QUIET,
-#ifndef RB_HALT_SYSTEM
-       RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
-       RB_ENABLE_CAD = 0x89abcdef,
-       RB_DISABLE_CAD = 0,
-       RB_POWER_OFF = 0x4321fedc,
-       RB_AUTOBOOT = 0x01234567,
-#endif
 };
 
 /* Print a message to the specified device.
@@ -119,7 +219,7 @@ static void message(int where, const char *fmt, ...)
        msg[l] = '\0';
        if (where & L_LOG) {
                /* Log the message to syslogd */
-               openlog("init", 0, LOG_DAEMON);
+               openlog(applet_name, 0, LOG_DAEMON);
                /* don't print "\r" */
                syslog(LOG_INFO, "%s", msg + 1);
                closelog();
@@ -161,33 +261,11 @@ static void message(int where, const char *fmt, ...)
        }
 }
 
-/* From <linux/serial.h> */
-struct serial_struct {
-       int     type;
-       int     line;
-       unsigned int    port;
-       int     irq;
-       int     flags;
-       int     xmit_fifo_size;
-       int     custom_divisor;
-       int     baud_base;
-       unsigned short  close_delay;
-       char    io_type;
-       char    reserved_char[1];
-       int     hub6;
-       unsigned short  closing_wait; /* time to wait before closing */
-       unsigned short  closing_wait2; /* no longer used... */
-       unsigned char   *iomem_base;
-       unsigned short  iomem_reg_shift;
-       unsigned int    port_high;
-       unsigned long   iomap_base;     /* cookie passed into ioremap */
-       int     reserved[1];
-       /* Paranoia (imagine 64bit kernel overwriting 32bit userspace stack) */
-       uint32_t bbox_reserved[16];
-};
 static void console_init(void)
 {
-       struct serial_struct sr;
+#ifdef VT_OPENQRY
+       int vtno;
+#endif
        char *s;
 
        s = getenv("CONSOLE");
@@ -211,15 +289,19 @@ static void console_init(void)
        }
 
        s = getenv("TERM");
-       if (ioctl(STDIN_FILENO, TIOCGSERIAL, &sr) == 0) {
-               /* Force the TERM setting to vt102 for serial console
+#ifdef VT_OPENQRY
+       if (ioctl(STDIN_FILENO, VT_OPENQRY, &vtno) != 0) {
+               /* Not a linux terminal, probably serial console.
+                * Force the TERM setting to vt102
                 * if TERM is set to linux (the default) */
                if (!s || strcmp(s, "linux") == 0)
                        putenv((char*)"TERM=vt102");
                if (!ENABLE_FEATURE_INIT_SYSLOG)
                        log_console = NULL;
-       } else if (!s)
-               putenv((char*)"TERM=linux");
+       } else
+#endif
+       if (!s)
+               putenv((char*)"TERM=" CONFIG_INIT_TERMINAL_TYPE);
 }
 
 /* Set terminal settings to reasonable defaults.
@@ -240,11 +322,17 @@ static void set_sane_term(void)
        tty.c_cc[VSTOP] = 19;   /* C-s */
        tty.c_cc[VSUSP] = 26;   /* C-z */
 
+#ifdef __linux__
        /* use line discipline 0 */
        tty.c_line = 0;
+#endif
 
        /* Make it be sane */
-       tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
+#ifndef CRTSCTS
+# define CRTSCTS 0
+#endif
+       /* added CRTSCTS to fix Debian bug 528560 */
+       tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD | CRTSCTS;
        tty.c_cflag |= CREAD | HUPCL | CLOCAL;
 
        /* input modes */
@@ -254,8 +342,7 @@ static void set_sane_term(void)
        tty.c_oflag = OPOST | ONLCR;
 
        /* local modes */
-       tty.c_lflag =
-               ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
+       tty.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
 
        tcsetattr_stdin_TCSANOW(&tty);
 }
@@ -283,6 +370,21 @@ static int open_stdio_to_tty(const char* tty_name)
        return 1; /* success */
 }
 
+static void reset_sighandlers_and_unblock_sigs(void)
+{
+       bb_signals(0
+               + (1 << SIGUSR1)
+               + (1 << SIGUSR2)
+               + (1 << SIGTERM)
+               + (1 << SIGQUIT)
+               + (1 << SIGINT)
+               + (1 << SIGHUP)
+               + (1 << SIGTSTP)
+               + (1 << SIGSTOP)
+               , SIG_DFL);
+       sigprocmask_allsigs(SIG_UNBLOCK);
+}
+
 /* Wrapper around exec:
  * Takes string (max COMMAND_SIZE chars).
  * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
@@ -296,20 +398,22 @@ static void init_exec(const char *command)
        char buf[COMMAND_SIZE + 6];  /* COMMAND_SIZE+strlen("exec ")+1 */
        int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
 
+       command += dash;
+
        /* See if any special /bin/sh requiring characters are present */
        if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
-               strcpy(buf, "exec ");
-               strcpy(buf + 5, command + dash); /* excluding "-" */
+               sprintf(buf, "exec %s", command); /* excluding "-" */
                /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
                cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
                cmd[1] = (char*)"-c";
                cmd[2] = buf;
                cmd[3] = NULL;
+               command = LIBBB_DEFAULT_LOGIN_SHELL + 1;
        } else {
                /* Convert command (char*) into cmd (char**, one word per string) */
                char *word, *next;
                int i = 0;
-               next = strcpy(buf, command); /* including "-" */
+               next = strcpy(buf, command - dash); /* command including "-" */
                while ((word = strsep(&next, " \t")) != NULL) {
                        if (*word != '\0') { /* not two spaces/tabs together? */
                                cmd[i] = word;
@@ -320,14 +424,14 @@ static void init_exec(const char *command)
        }
        /* If we saw leading "-", it is interactive shell.
         * Try harder to give it a controlling tty.
-        * And skip "-" in actual exec call. */
-       if (dash) {
+        */
+       if (ENABLE_FEATURE_INIT_SCTTY && dash) {
                /* _Attempt_ to make stdin a controlling tty. */
-               if (ENABLE_FEATURE_INIT_SCTTY)
-                       ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
+               ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
        }
-       BB_EXECVP(cmd[0] + dash, cmd);
-       message(L_LOG | L_CONSOLE, "cannot run '%s': %s", cmd[0], strerror(errno));
+       /* Here command never contains the dash, cmd[0] might */
+       BB_EXECVP(command, cmd);
+       message(L_LOG | L_CONSOLE, "can't run '%s': %s", command, strerror(errno));
        /* returns if execvp fails */
 }
 
@@ -336,29 +440,23 @@ static pid_t run(const struct init_action *a)
 {
        pid_t pid;
 
+       /* Careful: don't be affected by a signal in vforked child */
+       sigprocmask_allsigs(SIG_BLOCK);
        if (BB_MMU && (a->action_type & ASKFIRST))
                pid = fork();
        else
                pid = vfork();
        if (pid < 0)
                message(L_LOG | L_CONSOLE, "can't fork");
-       if (pid)
+       if (pid) {
+               sigprocmask_allsigs(SIG_UNBLOCK);
                return pid; /* Parent or error */
+       }
 
        /* Child */
 
        /* Reset signal handlers that were set by the parent process */
-//TODO: block signals across fork(), prevent them to affect child before
-//signals are reset?
-       bb_signals(0
-               + (1 << SIGUSR1)
-               + (1 << SIGUSR2)
-               + (1 << SIGTERM)
-               + (1 << SIGQUIT)
-               + (1 << SIGINT)
-               + (1 << SIGHUP)
-               + (1 << SIGTSTP)
-               , SIG_DFL);
+       reset_sighandlers_and_unblock_sigs();
 
        /* Create a new session and make ourself the process group leader */
        setsid();
@@ -429,6 +527,9 @@ static struct init_action *mark_terminated(pid_t pid)
                                return a;
                        }
                }
+               update_utmp(pid, DEAD_PROCESS, /*tty_name:*/ NULL,
+                               /*username:*/ NULL,
+                               /*hostname:*/ NULL);
        }
        return NULL;
 }
@@ -496,8 +597,8 @@ static void new_init_action(uint8_t action_type, const char *command, const char
                /* Don't enter action if it's already in the list,
                 * This prevents losing running RESPAWNs.
                 */
-               if ((strcmp(a->command, command) == 0)
-                && (strcmp(a->terminal, cons) == 0)
+               if (strcmp(a->command, command) == 0
+                && strcmp(a->terminal, cons) == 0
                ) {
                        /* Remove from list */
                        *nextp = a->next;
@@ -578,9 +679,7 @@ static void parse_inittab(void)
                        goto bad_entry;
                /* turn .*TTY -> /dev/TTY */
                if (tty[0]) {
-                       if (strncmp(tty, "/dev/", 5) == 0)
-                               tty += 5;
-                       tty = concat_path_file("/dev/", tty);
+                       tty = concat_path_file("/dev/", skip_dev_pfx(tty));
                }
                new_init_action(1 << action, token[3], tty);
                if (tty[0])
@@ -668,15 +767,24 @@ static void run_shutdown_and_kill_processes(void)
  * it to happen even somewhere inside "sysinit" would be a bit awkward.
  *
  * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
- * and only one will be remebered and acted upon.
+ * and only one will be remembered and acted upon.
  */
 
+/* The SIGUSR[12]/SIGTERM handler */
 static void halt_reboot_pwoff(int sig) NORETURN;
 static void halt_reboot_pwoff(int sig)
 {
        const char *m;
        unsigned rb;
 
+       /* We may call run() and it unmasks signals,
+        * including the one masked inside this signal handler.
+        * Testcase which would start multiple reboot scripts:
+        *  while true; do reboot; done
+        * Preventing it:
+        */
+       reset_sighandlers_and_unblock_sigs();
+
        run_shutdown_and_kill_processes();
 
        m = "halt";
@@ -693,38 +801,6 @@ static void halt_reboot_pwoff(int sig)
        /* not reached */
 }
 
-/* The SIGSTOP/SIGTSTP handler
- * NB: inside it, all signals except SIGCONT are masked
- * via appropriate setup in sigaction().
- */
-static void stop_handler(int sig UNUSED_PARAM)
-{
-       smallint saved_bb_got_signal;
-       int saved_errno;
-
-       saved_bb_got_signal = bb_got_signal;
-       saved_errno = errno;
-       signal(SIGCONT, record_signo);
-
-       while (1) {
-               pid_t wpid;
-
-               if (bb_got_signal == SIGCONT)
-                       break;
-               /* NB: this can accidentally wait() for a process
-                * which we waitfor() elsewhere! waitfor() must have
-                * code which is resilient against this.
-                */
-               wpid = wait_any_nohang(NULL);
-               mark_terminated(wpid);
-               sleep(1);
-       }
-
-       signal(SIGCONT, SIG_DFL);
-       errno = saved_errno;
-       bb_got_signal = saved_bb_got_signal;
-}
-
 /* Handler for QUIT - exec "restart" action,
  * else (no such action defined) do nothing */
 static void restart_handler(int sig UNUSED_PARAM)
@@ -739,12 +815,17 @@ static void restart_handler(int sig UNUSED_PARAM)
                 * Thus don't need to worry about preserving errno
                 * and such.
                 */
+
+               reset_sighandlers_and_unblock_sigs();
+
                run_shutdown_and_kill_processes();
 
+#ifdef RB_ENABLE_CAD
                /* Allow Ctrl-Alt-Del to reboot the system.
                 * This is how kernel sets it up for init, we follow suit.
                 */
                reboot(RB_ENABLE_CAD); /* misnomer */
+#endif
 
                if (open_stdio_to_tty(a->terminal)) {
                        dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
@@ -764,6 +845,38 @@ static void restart_handler(int sig UNUSED_PARAM)
        }
 }
 
+/* The SIGSTOP/SIGTSTP handler
+ * NB: inside it, all signals except SIGCONT are masked
+ * via appropriate setup in sigaction().
+ */
+static void stop_handler(int sig UNUSED_PARAM)
+{
+       smallint saved_bb_got_signal;
+       int saved_errno;
+
+       saved_bb_got_signal = bb_got_signal;
+       saved_errno = errno;
+       signal(SIGCONT, record_signo);
+
+       while (1) {
+               pid_t wpid;
+
+               if (bb_got_signal == SIGCONT)
+                       break;
+               /* NB: this can accidentally wait() for a process
+                * which we waitfor() elsewhere! waitfor() must have
+                * code which is resilient against this.
+                */
+               wpid = wait_any_nohang(NULL);
+               mark_terminated(wpid);
+               sleep(1);
+       }
+
+       signal(SIGCONT, SIG_DFL);
+       errno = saved_errno;
+       bb_got_signal = saved_bb_got_signal;
+}
+
 #if ENABLE_FEATURE_USE_INITTAB
 static void reload_inittab(void)
 {
@@ -773,37 +886,39 @@ static void reload_inittab(void)
 
        /* Disable old entries */
        for (a = init_action_list; a; a = a->next)
-               a->action_type = ONCE;
+               a->action_type = 0;
 
        /* Append new entries, or modify existing entries
-        * (set a->action_type) if cmd and device name
+        * (incl. setting a->action_type) if cmd and device name
         * match new ones. End result: only entries with
-        * a->action_type == ONCE are stale.
+        * a->action_type == 0 are stale.
         */
        parse_inittab();
 
-       if (ENABLE_FEATURE_KILL_REMOVED) {
-               /* Kill stale entries */
-               /* Be nice and send SIGTERM first */
-               for (a = init_action_list; a; a = a->next)
-                       if (a->action_type == ONCE && a->pid != 0)
-                               kill(a->pid, SIGTERM);
-               if (CONFIG_FEATURE_KILL_DELAY) {
-                       /* NB: parent will wait in NOMMU case */
-                       if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
-                               sleep(CONFIG_FEATURE_KILL_DELAY);
-                               for (a = init_action_list; a; a = a->next)
-                                       if (a->action_type == ONCE && a->pid != 0)
-                                               kill(a->pid, SIGKILL);
-                               _exit(EXIT_SUCCESS);
-                       }
+#if ENABLE_FEATURE_KILL_REMOVED
+       /* Kill stale entries */
+       /* Be nice and send SIGTERM first */
+       for (a = init_action_list; a; a = a->next)
+               if (a->action_type == 0 && a->pid != 0)
+                       kill(a->pid, SIGTERM);
+       if (CONFIG_FEATURE_KILL_DELAY) {
+               /* NB: parent will wait in NOMMU case */
+               if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
+                       sleep(CONFIG_FEATURE_KILL_DELAY);
+                       for (a = init_action_list; a; a = a->next)
+                               if (a->action_type == 0 && a->pid != 0)
+                                       kill(a->pid, SIGKILL);
+                       _exit(EXIT_SUCCESS);
                }
        }
+#endif
 
-       /* Remove stale (ONCE) and not useful (SYSINIT,WAIT) entries */
+       /* Remove stale entries and SYSINIT entries.
+        * We never rerun SYSINIT entries anyway,
+        * removing them too saves a few bytes */
        nextp = &init_action_list;
        while ((a = *nextp) != NULL) {
-               if (a->action_type & (ONCE | SYSINIT | WAIT)) {
+               if ((a->action_type & ~SYSINIT) == 0) {
                        *nextp = a->next;
                        free(a);
                } else {
@@ -840,24 +955,33 @@ static int check_delayed_sigs(void)
 int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 int init_main(int argc UNUSED_PARAM, char **argv)
 {
-       die_sleep = 30 * 24*60*60; /* if xmalloc would ever die... */
-
-       if (argv[1] && !strcmp(argv[1], "-q")) {
+       if (argv[1] && strcmp(argv[1], "-q") == 0) {
                return kill(1, SIGHUP);
        }
 
        if (!DEBUG_INIT) {
                /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
                if (getpid() != 1
-                && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
+                && (!ENABLE_FEATURE_INITRD || applet_name[0] != 'l') /* not linuxrc? */
                ) {
-                       bb_show_usage();
+                       bb_error_msg_and_die("must be run as PID 1");
                }
+#ifdef RB_DISABLE_CAD
                /* Turn off rebooting via CTL-ALT-DEL - we get a
                 * SIGINT on CAD so we can shut things down gracefully... */
                reboot(RB_DISABLE_CAD); /* misnomer */
+#endif
        }
 
+       /* If, say, xmalloc would ever die, we don't want to oops kernel
+        * by exiting.
+        * NB: we set die_sleep *after* PID 1 check and bb_show_usage.
+        * Otherwise, for example, "init u" ("please rexec yourself"
+        * command for sysvinit) will show help text (which isn't too bad),
+        * *and sleep forever* (which is bad!)
+        */
+       die_sleep = 30 * 24*60*60;
+
        /* Figure out where the default console should be */
        console_init();
        set_sane_term();
@@ -873,15 +997,19 @@ int init_main(int argc UNUSED_PARAM, char **argv)
        if (argv[1])
                xsetenv("RUNLEVEL", argv[1]);
 
+#if !ENABLE_FEATURE_EXTRA_QUIET
        /* Hello world */
-       message(MAYBE_CONSOLE | L_LOG, "init started: %s", bb_banner);
+       message(L_CONSOLE | L_LOG, "init started: %s", bb_banner);
+#endif
 
+/* struct sysinfo is linux-specific */
+#ifdef __linux__
        /* Make sure there is enough memory to do something useful. */
        if (ENABLE_SWAPONOFF) {
                struct sysinfo info;
 
                if (sysinfo(&info) == 0
-                && (info.mem_unit ? : 1) * (long long)info.totalram < 1024*1024
+                && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024
                ) {
                        message(L_CONSOLE, "Low memory, forcing swapon");
                        /* swapon -a requires /proc typically */
@@ -891,10 +1019,11 @@ int init_main(int argc UNUSED_PARAM, char **argv)
                        run_actions(SYSINIT);   /* wait and removing */
                }
        }
+#endif
 
        /* Check if we are supposed to be in single user mode */
        if (argv[1]
-        && (!strcmp(argv[1], "single") || !strcmp(argv[1], "-s") || LONE_CHAR(argv[1], '1'))
+        && (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "-s") == 0 || LONE_CHAR(argv[1], '1'))
        ) {
                /* ??? shouldn't we set RUNLEVEL="b" here? */
                /* Start a shell on console */
@@ -918,9 +1047,9 @@ int init_main(int argc UNUSED_PARAM, char **argv)
                        BB_EXECVP(argv[0], argv);
                } else if (enforce > 0) {
                        /* SELinux in enforcing mode but load_policy failed */
-                       message(L_CONSOLE, "cannot load SELinux Policy. "
+                       message(L_CONSOLE, "can't load SELinux Policy. "
                                "Machine is in enforcing mode. Halting now.");
-                       exit(EXIT_FAILURE);
+                       return EXIT_FAILURE;
                }
        }
 #endif
@@ -962,6 +1091,12 @@ int init_main(int argc UNUSED_PARAM, char **argv)
                bb_signals_recursive_norestart((1 << SIGINT), record_signo);
        }
 
+       /* Set up "reread /etc/inittab" handler.
+        * Handler is set up without SA_RESTART, it will interrupt syscalls.
+        */
+       if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
+               bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
+
        /* Now run everything that needs to be run */
        /* First run the sysinit command */
        run_actions(SYSINIT);
@@ -972,50 +1107,184 @@ int init_main(int argc UNUSED_PARAM, char **argv)
        /* Next run anything to be run only once */
        run_actions(ONCE);
 
-       /* Set up "reread /etc/inittab" handler.
-        * Handler is set up without SA_RESTART, it will interrupt syscalls.
-        */
-       if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
-               bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
-
        /* Now run the looping stuff for the rest of forever.
-        * NB: if delayed signal happened, avoid blocking in wait().
         */
        while (1) {
-               pid_t wpid;
-               int got_sigs;
+               int maybe_WNOHANG;
 
-               got_sigs = check_delayed_sigs();
+               maybe_WNOHANG = check_delayed_sigs();
 
                /* (Re)run the respawn/askfirst stuff */
                run_actions(RESPAWN | ASKFIRST);
-
-               got_sigs |= check_delayed_sigs();
+               maybe_WNOHANG |= check_delayed_sigs();
 
                /* Don't consume all CPU time - sleep a bit */
                sleep(1);
-
-               got_sigs |= check_delayed_sigs();
-
-               if (got_sigs)
-                       goto dont_block;
-               /* Wait for any child process to exit.
-                * NB: "delayed" signals will also interrupt this wait(),
-                * bb_signals_recursive_norestart() set them up for that.
-                * This guarantees we won't be stuck here
-                * till next orphan dies.
+               maybe_WNOHANG |= check_delayed_sigs();
+
+               /* Wait for any child process(es) to exit.
+                *
+                * If check_delayed_sigs above reported that a signal
+                * was caught, wait will be nonblocking. This ensures
+                * that if SIGHUP has reloaded inittab, respawn and askfirst
+                * actions will not be delayed until next child death.
                 */
-               wpid = wait(NULL);
-               while (wpid > 0) {
-                       struct init_action *a = mark_terminated(wpid);
+               if (maybe_WNOHANG)
+                       maybe_WNOHANG = WNOHANG;
+               while (1) {
+                       pid_t wpid;
+                       struct init_action *a;
+
+                       /* If signals happen _in_ the wait, they interrupt it,
+                        * bb_signals_recursive_norestart set them up that way
+                        */
+                       wpid = waitpid(-1, NULL, maybe_WNOHANG);
+                       if (wpid <= 0)
+                               break;
+
+                       a = mark_terminated(wpid);
                        if (a) {
                                message(L_LOG, "process '%s' (pid %d) exited. "
                                                "Scheduling for restart.",
                                                a->command, wpid);
                        }
                        /* See if anyone else is waiting to be reaped */
- dont_block:
-                       wpid = wait_any_nohang(NULL);
+                       maybe_WNOHANG = WNOHANG;
                }
        } /* while (1) */
 }
+
+//usage:#define linuxrc_trivial_usage NOUSAGE_STR
+//usage:#define linuxrc_full_usage ""
+
+//usage:#define init_trivial_usage
+//usage:       ""
+//usage:#define init_full_usage "\n\n"
+//usage:       "Init is the parent of all processes"
+//usage:
+//usage:#define init_notes_usage
+//usage:       "This version of init is designed to be run only by the kernel.\n"
+//usage:       "\n"
+//usage:       "BusyBox init doesn't support multiple runlevels. The runlevels field of\n"
+//usage:       "the /etc/inittab file is completely ignored by BusyBox init. If you want\n"
+//usage:       "runlevels, use sysvinit.\n"
+//usage:       "\n"
+//usage:       "BusyBox init works just fine without an inittab. If no inittab is found,\n"
+//usage:       "it has the following default behavior:\n"
+//usage:       "\n"
+//usage:       "       ::sysinit:/etc/init.d/rcS\n"
+//usage:       "       ::askfirst:/bin/sh\n"
+//usage:       "       ::ctrlaltdel:/sbin/reboot\n"
+//usage:       "       ::shutdown:/sbin/swapoff -a\n"
+//usage:       "       ::shutdown:/bin/umount -a -r\n"
+//usage:       "       ::restart:/sbin/init\n"
+//usage:       "\n"
+//usage:       "if it detects that /dev/console is _not_ a serial console, it will also run:\n"
+//usage:       "\n"
+//usage:       "       tty2::askfirst:/bin/sh\n"
+//usage:       "       tty3::askfirst:/bin/sh\n"
+//usage:       "       tty4::askfirst:/bin/sh\n"
+//usage:       "\n"
+//usage:       "If you choose to use an /etc/inittab file, the inittab entry format is as follows:\n"
+//usage:       "\n"
+//usage:       "       <id>:<runlevels>:<action>:<process>\n"
+//usage:       "\n"
+//usage:       "       <id>:\n"
+//usage:       "\n"
+//usage:       "               WARNING: This field has a non-traditional meaning for BusyBox init!\n"
+//usage:       "               The id field is used by BusyBox init to specify the controlling tty for\n"
+//usage:       "               the specified process to run on. The contents of this field are\n"
+//usage:       "               appended to \"/dev/\" and used as-is. There is no need for this field to\n"
+//usage:       "               be unique, although if it isn't you may have strange results. If this\n"
+//usage:       "               field is left blank, the controlling tty is set to the console. Also\n"
+//usage:       "               note that if BusyBox detects that a serial console is in use, then only\n"
+//usage:       "               entries whose controlling tty is either the serial console or /dev/null\n"
+//usage:       "               will be run. BusyBox init does nothing with utmp. We don't need no\n"
+//usage:       "               stinkin' utmp.\n"
+//usage:       "\n"
+//usage:       "       <runlevels>:\n"
+//usage:       "\n"
+//usage:       "               The runlevels field is completely ignored.\n"
+//usage:       "\n"
+//usage:       "       <action>:\n"
+//usage:       "\n"
+//usage:       "               Valid actions include: sysinit, respawn, askfirst, wait,\n"
+//usage:       "               once, restart, ctrlaltdel, and shutdown.\n"
+//usage:       "\n"
+//usage:       "               The available actions can be classified into two groups: actions\n"
+//usage:       "               that are run only once, and actions that are re-run when the specified\n"
+//usage:       "               process exits.\n"
+//usage:       "\n"
+//usage:       "               Run only-once actions:\n"
+//usage:       "\n"
+//usage:       "                       'sysinit' is the first item run on boot. init waits until all\n"
+//usage:       "                       sysinit actions are completed before continuing. Following the\n"
+//usage:       "                       completion of all sysinit actions, all 'wait' actions are run.\n"
+//usage:       "                       'wait' actions, like 'sysinit' actions, cause init to wait until\n"
+//usage:       "                       the specified task completes. 'once' actions are asynchronous,\n"
+//usage:       "                       therefore, init does not wait for them to complete. 'restart' is\n"
+//usage:       "                       the action taken to restart the init process. By default this should\n"
+//usage:       "                       simply run /sbin/init, but can be a script which runs pivot_root or it\n"
+//usage:       "                       can do all sorts of other interesting things. The 'ctrlaltdel' init\n"
+//usage:       "                       actions are run when the system detects that someone on the system\n"
+//usage:       "                       console has pressed the CTRL-ALT-DEL key combination. Typically one\n"
+//usage:       "                       wants to run 'reboot' at this point to cause the system to reboot.\n"
+//usage:       "                       Finally the 'shutdown' action specifies the actions to taken when\n"
+//usage:       "                       init is told to reboot. Unmounting filesystems and disabling swap\n"
+//usage:       "                       is a very good here.\n"
+//usage:       "\n"
+//usage:       "               Run repeatedly actions:\n"
+//usage:       "\n"
+//usage:       "                       'respawn' actions are run after the 'once' actions. When a process\n"
+//usage:       "                       started with a 'respawn' action exits, init automatically restarts\n"
+//usage:       "                       it. Unlike sysvinit, BusyBox init does not stop processes from\n"
+//usage:       "                       respawning out of control. The 'askfirst' actions acts just like\n"
+//usage:       "                       respawn, except that before running the specified process it\n"
+//usage:       "                       displays the line \"Please press Enter to activate this console.\"\n"
+//usage:       "                       and then waits for the user to press enter before starting the\n"
+//usage:       "                       specified process.\n"
+//usage:       "\n"
+//usage:       "               Unrecognized actions (like initdefault) will cause init to emit an\n"
+//usage:       "               error message, and then go along with its business. All actions are\n"
+//usage:       "               run in the order they appear in /etc/inittab.\n"
+//usage:       "\n"
+//usage:       "       <process>:\n"
+//usage:       "\n"
+//usage:       "               Specifies the process to be executed and its command line.\n"
+//usage:       "\n"
+//usage:       "Example /etc/inittab file:\n"
+//usage:       "\n"
+//usage:       "       # This is run first except when booting in single-user mode\n"
+//usage:       "       #\n"
+//usage:       "       ::sysinit:/etc/init.d/rcS\n"
+//usage:       "       \n"
+//usage:       "       # /bin/sh invocations on selected ttys\n"
+//usage:       "       #\n"
+//usage:       "       # Start an \"askfirst\" shell on the console (whatever that may be)\n"
+//usage:       "       ::askfirst:-/bin/sh\n"
+//usage:       "       # Start an \"askfirst\" shell on /dev/tty2-4\n"
+//usage:       "       tty2::askfirst:-/bin/sh\n"
+//usage:       "       tty3::askfirst:-/bin/sh\n"
+//usage:       "       tty4::askfirst:-/bin/sh\n"
+//usage:       "       \n"
+//usage:       "       # /sbin/getty invocations for selected ttys\n"
+//usage:       "       #\n"
+//usage:       "       tty4::respawn:/sbin/getty 38400 tty4\n"
+//usage:       "       tty5::respawn:/sbin/getty 38400 tty5\n"
+//usage:       "       \n"
+//usage:       "       \n"
+//usage:       "       # Example of how to put a getty on a serial line (for a terminal)\n"
+//usage:       "       #\n"
+//usage:       "       #::respawn:/sbin/getty -L ttyS0 9600 vt100\n"
+//usage:       "       #::respawn:/sbin/getty -L ttyS1 9600 vt100\n"
+//usage:       "       #\n"
+//usage:       "       # Example how to put a getty on a modem line\n"
+//usage:       "       #::respawn:/sbin/getty 57600 ttyS2\n"
+//usage:       "       \n"
+//usage:       "       # Stuff to do when restarting the init process\n"
+//usage:       "       ::restart:/sbin/init\n"
+//usage:       "       \n"
+//usage:       "       # Stuff to do before rebooting\n"
+//usage:       "       ::ctrlaltdel:/sbin/reboot\n"
+//usage:       "       ::shutdown:/bin/umount -a -r\n"
+//usage:       "       ::shutdown:/sbin/swapoff -a\n"