f83032ce9d4c2ad0c7080d7eea9392390409e5b1
[project/procd.git] / state.c
1 /*
2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4 *
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
8 *
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.
13 */
14
15 #include <sys/reboot.h>
16 #include <stdlib.h>
17 #include <unistd.h>
18
19 #include "procd.h"
20 #include "syslog.h"
21 #include "hotplug.h"
22 #include "watchdog.h"
23 #include "service.h"
24
25 enum {
26 STATE_NONE = 0,
27 STATE_EARLY,
28 STATE_INIT,
29 STATE_RUNNING,
30 STATE_SHUTDOWN,
31 STATE_HALT,
32 __STATE_MAX,
33 };
34
35 static int state = STATE_NONE;
36 static int reboot_event;
37
38 static void state_enter(void)
39 {
40
41 switch (state) {
42 case STATE_EARLY:
43 LOG("- early -\n");
44 watchdog_init(0);
45 hotplug("/etc/hotplug.json");
46 procd_coldplug();
47 break;
48
49 case STATE_INIT:
50 // try to reopen incase the wdt was not available before coldplug
51 watchdog_init(0);
52 LOG("- init -\n");
53 log_init();
54 procd_connect_ubus();
55 service_init();
56 procd_inittab();
57 procd_inittab_run("respawn");
58 procd_inittab_run("askconsole");
59 procd_inittab_run("askfirst");
60 procd_inittab_run("sysinit");
61 break;
62
63 case STATE_RUNNING:
64 LOG("- init complete -\n");
65 break;
66
67 case STATE_SHUTDOWN:
68 LOG("- shutdown -\n");
69 procd_inittab_run("shutdown");
70 sync();
71 break;
72
73 case STATE_HALT:
74 LOG("- reboot -\n");
75 reboot(reboot_event);
76 break;
77
78 default:
79 ERROR("Unhandled state %d\n", state);
80 return;
81 };
82 }
83
84 void procd_state_next(void)
85 {
86 DEBUG(2, "Change state %d -> %d\n", state, state + 1);
87 state++;
88 state_enter();
89 }
90
91 void procd_shutdown(int event)
92 {
93 DEBUG(1, "Shutting down system with event %x\n", event);
94 reboot_event = event;
95 state = STATE_SHUTDOWN;
96 state_enter();
97 }