2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
16 #include <sys/reboot.h>
20 #include <sys/types.h>
25 #include "plug/hotplug.h"
27 #include "service/service.h"
28 #include "utils/utils.h"
41 static int state = STATE_NONE;
42 static int reboot_event;
44 static void set_stdio(const char* tty)
47 !freopen(tty, "r", stdin) ||
48 !freopen(tty, "w", stdout) ||
49 !freopen(tty, "w", stderr) ||
51 ERROR("failed to set stdio\n");
53 fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
56 static void set_console(void)
61 const char* try[] = { "tty0", "console", NULL }; /* Try the most common outputs */
64 tty = get_cmdline_val("console",line,sizeof(line));
66 split = strchr(tty, ',');
76 ERROR("failed to change dir to /dev\n");
80 f = open(tty, O_RDONLY);
90 ERROR("failed to change dir to /\n");
96 static void state_enter(void)
98 char ubus_cmd[] = "/sbin/ubusd";
104 hotplug("/etc/hotplug.json");
109 // try to reopen incase the wdt was not available before coldplug
111 set_stdio("console");
113 procd_connect_ubus();
114 service_start_early("ubus", ubus_cmd);
120 procd_inittab_run("respawn");
121 procd_inittab_run("askconsole");
122 procd_inittab_run("askfirst");
123 procd_inittab_run("sysinit");
125 // switch to syslog log channel
126 ulog_open(ULOG_SYSLOG, LOG_DAEMON, "procd");
130 LOG("- init complete -\n");
131 procd_inittab_run("respawnlate");
132 procd_inittab_run("askconsolelate");
136 /* Redirect output to the console for the users' benefit */
138 LOG("- shutdown -\n");
139 procd_inittab_run("shutdown");
144 // To prevent killed processes from interrupting the sleep
145 signal(SIGCHLD, SIG_IGN);
146 LOG("- SIGTERM processes -\n");
150 LOG("- SIGKILL processes -\n");
155 if (reboot_event == RB_POWER_OFF)
156 LOG("- power down -\n");
160 /* Allow time for last message to reach serial console, etc */
163 /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
164 * in linux/kernel/sys.c, which can cause the machine to panic when
165 * the init process exits... */
166 if (!vfork( )) { /* child */
167 reboot(reboot_event);
178 ERROR("Unhandled state %d\n", state);
183 void procd_state_next(void)
185 DEBUG(4, "Change state %d -> %d\n", state, state + 1);
190 void procd_state_ubus_connect(void)
192 if (state == STATE_UBUS)
196 void procd_shutdown(int event)
198 if (state >= STATE_SHUTDOWN)
200 DEBUG(2, "Shutting down system with event %x\n", event);
201 reboot_event = event;
202 state = STATE_SHUTDOWN;