chiark / gitweb /
023648c4cf9d5e5c32b1405b1b56a0140e953ce7
[elogind.git] / src / shutdown.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 ProFUSION embedded systems
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/mman.h>
23 #include <sys/types.h>
24 #include <sys/reboot.h>
25 #include <linux/reboot.h>
26 #include <sys/wait.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <signal.h>
31 #include <stdbool.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "log.h"
36 #include "umount.h"
37 #include "util.h"
38
39 #define TIMEOUT_USEC    (5 * USEC_PER_SEC)
40 #define FINALIZE_ATTEMPTS 50
41 #define FINALIZE_CRITICAL_ATTEMPTS 10
42
43 _noreturn_ static void freeze(void) {
44         for (;;)
45                 pause();
46 }
47
48 static bool ignore_proc(pid_t pid) {
49         if (pid == 1)
50                 return true;
51
52         /* TODO: add more ignore rules here: device-mapper, etc */
53
54         return false;
55 }
56
57 static bool is_kernel_thread(pid_t pid)
58 {
59         char buf[PATH_MAX];
60         FILE *f;
61         char c;
62         size_t count;
63
64         snprintf(buf, sizeof(buf), "/proc/%lu/cmdline", (unsigned long)pid);
65         f = fopen(buf, "re");
66         if (!f)
67                 return true; /* not really, but has the desired effect */
68
69         count = fread(&c, 1, 1, f);
70         fclose(f);
71         return count != 1;
72 }
73
74 static int killall(int sign) {
75         DIR *dir;
76         struct dirent *d;
77         unsigned int processes = 0;
78
79         if ((dir = opendir("/proc")) == NULL)
80                 return -errno;
81
82         while ((d = readdir(dir))) {
83                 pid_t pid;
84
85                 if (parse_pid(d->d_name, &pid) < 0)
86                         continue;
87
88                 if (is_kernel_thread(pid))
89                         continue;
90
91                 if (ignore_proc(pid))
92                         continue;
93
94                 if (kill(pid, sign) == 0)
95                         processes++;
96                 else
97                         log_warning("Could not kill %d: %m", pid);
98         }
99
100         closedir(dir);
101
102         return processes;
103 }
104
105 static int send_signal(int sign) {
106         sigset_t mask, oldmask;
107         usec_t until;
108         int processes;
109         struct timespec ts;
110
111         assert_se(sigemptyset(&mask) == 0);
112         assert_se(sigaddset(&mask, SIGCHLD) == 0);
113         if (sigprocmask(SIG_BLOCK, &mask, &oldmask) != 0)
114                 return -errno;
115
116         if (kill(-1, SIGSTOP) < 0)
117                 log_warning("Failed kill(-1, SIGSTOP): %m");
118
119         processes = killall(sign);
120
121         if (kill(-1, SIGCONT) < 0)
122                 log_warning("Failed kill(-1, SIGCONT): %m");
123
124         if (processes <= 0)
125                 goto finish;
126
127         until = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
128         for (;;) {
129                 usec_t n = now(CLOCK_MONOTONIC);
130                 for (;;) {
131                         pid_t pid = waitpid(-1, NULL, WNOHANG);
132                         if (pid == 0)
133                                 break;
134                         else if (pid < 0 && errno == ECHILD) {
135                                 processes = 0;
136                                 goto finish;
137                         }
138
139                         if (--processes == 0)
140                                 goto finish;
141                 }
142
143                 if (n >= until)
144                         goto finish;
145
146                 timespec_store(&ts, until - n);
147                 if (sigtimedwait(&mask, NULL, &ts) != SIGCHLD)
148                         log_warning("Failed: sigtimedwait did not return SIGCHLD: %m");
149         }
150
151 finish:
152         sigprocmask(SIG_SETMASK, &oldmask, NULL);
153
154         return processes;
155 }
156
157 static int rescue_send_signal(int sign) {
158         sigset_t mask, oldmask;
159         usec_t until;
160         struct timespec ts;
161         int r;
162
163         sigemptyset(&mask);
164         sigaddset(&mask, SIGCHLD);
165         if (sigprocmask(SIG_BLOCK, &mask, &oldmask) != 0)
166                 return -errno;
167
168         if (kill(-1, SIGSTOP) < 0)
169                 log_warning("Failed kill(-1, SIGSTOP): %m");
170
171         r = kill(-1, sign);
172         if (r < 0)
173                 log_warning("Failed kill(-1, %d): %m", sign);
174
175         if (kill(-1, SIGCONT) < 0)
176                 log_warning("Failed kill(-1, SIGCONT): %m");
177
178         if (r < 0)
179                 goto finish;
180
181         until = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
182         for (;;) {
183                 usec_t n = now(CLOCK_MONOTONIC);
184                 for (;;) {
185                         pid_t pid = waitpid(-1, NULL, WNOHANG);
186                         if (pid == 0)
187                                 break;
188                         else if (pid < 0 && errno == ECHILD)
189                                 goto finish;
190                 }
191
192                 if (n >= until)
193                         goto finish;
194
195                 timespec_store(&ts, until - n);
196                 if (sigtimedwait(&mask, NULL, &ts) != SIGCHLD)
197                         log_warning("Failed: sigtimedwait did not return SIGCHLD: %m");
198         }
199
200 finish:
201         sigprocmask(SIG_SETMASK, &oldmask, NULL);
202
203         return r;
204 }
205
206
207 int main(int argc, char *argv[]) {
208         int cmd, r, retries;
209         bool need_umount = true, need_swapoff = true, need_loop_detach = true;
210
211         log_parse_environment();
212         log_set_target(LOG_TARGET_KMSG); /* syslog will die if not gone yet */
213         log_open();
214
215         if (getpid() != 1) {
216                 log_error("Not executed by init (pid-1).");
217                 r = -EPERM;
218                 goto error;
219         }
220
221         if (argc != 2) {
222                 log_error("Invalid number of arguments.");
223                 r = -EINVAL;
224                 goto error;
225         }
226
227         if (streq(argv[1], "reboot"))
228                 cmd = RB_AUTOBOOT;
229         else if (streq(argv[1], "poweroff"))
230                 cmd = RB_POWER_OFF;
231         else if (streq(argv[1], "halt"))
232                 cmd = RB_HALT_SYSTEM;
233         else if (streq(argv[1], "kexec"))
234                 cmd = LINUX_REBOOT_CMD_KEXEC;
235         else {
236                 log_error("Unknown action '%s'.", argv[1]);
237                 r = -EINVAL;
238                 goto error;
239         }
240
241         /* lock us into memory */
242         if (mlockall(MCL_CURRENT|MCL_FUTURE) != 0)
243                 log_warning("Cannot lock process memory: %m");
244
245         log_info("Sending SIGTERM to processes");
246         r = send_signal(SIGTERM);
247         if (r < 0)
248                 log_warning("Cannot send SIGTERM to all process: %s", strerror(r));
249
250         log_info("Sending SIGKILL to processes");
251         r = send_signal(SIGKILL);
252         if (r < 0)
253                 log_warning("Cannot send SIGKILL to all process: %s", strerror(r));
254
255
256         /* preventing that we won't block umounts */
257         if (chdir("/") != 0)
258                 log_warning("Cannot chdir(\"/\"): %m. Unmounts likely to fail.");
259
260         /* umount all mountpoints, swaps, and loopback devices */
261         retries = FINALIZE_ATTEMPTS;
262         while (need_umount || need_swapoff || need_loop_detach) {
263                 if (need_umount) {
264                         log_info("Unmounting filesystems.");
265                         r = umount_all();
266                         if (r == 0)
267                                 need_umount = false;
268                         else if (r > 0)
269                                 log_warning("Not all filesystems unmounted, %d left.", r);
270                         else
271                                 log_error("Error unmounting filesystems: %s", strerror(-r));
272                 }
273
274                 if (need_swapoff) {
275                         log_info("Disabling swaps.");
276                         r = swapoff_all();
277                         if (r == 0)
278                                 need_swapoff = false;
279                         else if (r > 0)
280                                 log_warning("Not all swaps are off, %d left.", r);
281                         else
282                                 log_error("Error turning off swaps: %s", strerror(-r));
283                 }
284
285                 if (need_loop_detach) {
286                         log_info("Detaching loop devices.");
287                         r = loopback_detach_all();
288                         if (r == 0)
289                                 need_loop_detach = false;
290                         else if (r > 0)
291                                 log_warning("Not all loop devices detached, %d left.", r);
292                         else
293                                 log_error("Error detaching loop devices: %s", strerror(-r));
294
295                 }
296
297                 if (need_umount || need_swapoff || need_loop_detach) {
298                         retries--;
299
300                         if (retries <= FINALIZE_CRITICAL_ATTEMPTS) {
301                                 log_warning("Approaching critical level to finalize filesystem and devices, try to kill all processes.");
302                                 rescue_send_signal(SIGTERM);
303                                 rescue_send_signal(SIGKILL);
304                         }
305
306                         if (retries > 0)
307                                 log_info("Action still required, %d tries left", retries);
308                         else {
309                                 log_error("Tried enough but still action required need_umount=%d, need_swapoff=%d, need_loop_detach=%d", need_umount, need_swapoff, need_loop_detach);
310                                 r = -EBUSY;
311                                 goto error;
312                         }
313                 }
314         }
315
316         sync();
317
318         if (cmd == LINUX_REBOOT_CMD_KEXEC) {
319                 /* we cheat and exec kexec to avoid doing all its work */
320                 pid_t pid = fork();
321                 if (pid < 0) {
322                         log_error("Could not fork: %m. Falling back to reboot.");
323                         cmd = RB_AUTOBOOT;
324                 } else if (pid > 0) {
325                         waitpid(pid, NULL, 0);
326                         log_warning("Failed %s -e -x -f. Falling back to reboot", KEXEC_BINARY_PATH);
327                         cmd = RB_AUTOBOOT;
328                 } else {
329                         const char *args[5] = {KEXEC_BINARY_PATH, "-e", "-f", "-x", NULL};
330                         execv(args[0], (char * const *) args);
331                         return EXIT_FAILURE;
332                 }
333         }
334
335         reboot(cmd);
336         r = errno;
337
338   error:
339         sync();
340         if (r < 0)
341                 r = -r;
342         log_error("Critical error while doing system shutdown: %s", strerror(r));
343         freeze();
344         return 0;
345 }