debloat and reorganize code
[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 "plug/hotplug.h"
22 #include "watchdog.h"
23 #include "service/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("- ubus -\n");
53 procd_connect_ubus();
54
55 LOG("- init -\n");
56 service_init();
57 service_start_early("ubus", "/sbin/ubusd");
58
59 procd_inittab();
60 procd_inittab_run("respawn");
61 procd_inittab_run("askconsole");
62 procd_inittab_run("askfirst");
63 procd_inittab_run("sysinit");
64 break;
65
66 case STATE_RUNNING:
67 LOG("- init complete -\n");
68 break;
69
70 case STATE_SHUTDOWN:
71 LOG("- shutdown -\n");
72 procd_inittab_run("shutdown");
73 sync();
74 break;
75
76 case STATE_HALT:
77 LOG("- reboot -\n");
78 reboot(reboot_event);
79 break;
80
81 default:
82 ERROR("Unhandled state %d\n", state);
83 return;
84 };
85 }
86
87 void procd_state_next(void)
88 {
89 DEBUG(4, "Change state %d -> %d\n", state, state + 1);
90 state++;
91 state_enter();
92 }
93
94 void procd_shutdown(int event)
95 {
96 DEBUG(2, "Shutting down system with event %x\n", event);
97 reboot_event = event;
98 state = STATE_SHUTDOWN;
99 state_enter();
100 }