chiark / gitweb /
Merge remote-tracking branch 'harald/master'
[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 <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/mount.h>
30 #include <sys/syscall.h>
31 #include <fcntl.h>
32 #include <dirent.h>
33 #include <errno.h>
34 #include <unistd.h>
35 #include <signal.h>
36 #include <stdbool.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include "missing.h"
41 #include "log.h"
42 #include "umount.h"
43 #include "util.h"
44
45 #define TIMEOUT_USEC (5 * USEC_PER_SEC)
46 #define FINALIZE_ATTEMPTS 50
47 #define pivot_root(new_root,put_old) syscall(SYS_pivot_root,new_root,put_old)
48
49 static bool ignore_proc(pid_t pid) {
50         if (pid == 1)
51                 return true;
52
53         /* TODO: add more ignore rules here: device-mapper, etc */
54
55         return false;
56 }
57
58 static bool is_kernel_thread(pid_t pid)
59 {
60         char buf[PATH_MAX];
61         FILE *f;
62         char c;
63         size_t count;
64
65         snprintf(buf, sizeof(buf), "/proc/%lu/cmdline", (unsigned long)pid);
66         f = fopen(buf, "re");
67         if (!f)
68                 return true; /* not really, but has the desired effect */
69
70         count = fread(&c, 1, 1, f);
71         fclose(f);
72         return count != 1;
73 }
74
75 static int killall(int sign) {
76         DIR *dir;
77         struct dirent *d;
78         unsigned int n_processes = 0;
79
80         if ((dir = opendir("/proc")) == NULL)
81                 return -errno;
82
83         while ((d = readdir(dir))) {
84                 pid_t pid;
85
86                 if (parse_pid(d->d_name, &pid) < 0)
87                         continue;
88
89                 if (is_kernel_thread(pid))
90                         continue;
91
92                 if (ignore_proc(pid))
93                         continue;
94
95                 if (kill(pid, sign) == 0)
96                         n_processes++;
97                 else
98                         log_warning("Could not kill %d: %m", pid);
99         }
100
101         closedir(dir);
102
103         return n_processes;
104 }
105
106 static void wait_for_children(int n_processes, sigset_t *mask) {
107         usec_t until;
108
109         assert(mask);
110
111         until = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
112         for (;;) {
113                 struct timespec ts;
114                 int k;
115                 usec_t n;
116
117                 for (;;) {
118                         pid_t pid = waitpid(-1, NULL, WNOHANG);
119
120                         if (pid == 0)
121                                 break;
122
123                         if (pid < 0 && errno == ECHILD)
124                                 return;
125
126                         if (n_processes > 0)
127                                 if (--n_processes == 0)
128                                         return;
129                 }
130
131                 n = now(CLOCK_MONOTONIC);
132                 if (n >= until)
133                         return;
134
135                 timespec_store(&ts, until - n);
136
137                 if ((k = sigtimedwait(mask, NULL, &ts)) != SIGCHLD) {
138
139                         if (k < 0 && errno != EAGAIN) {
140                                 log_error("sigtimedwait() failed: %m");
141                                 return;
142                         }
143
144                         if (k >= 0)
145                                 log_warning("sigtimedwait() returned unexpected signal.");
146                 }
147         }
148 }
149
150 static void send_signal(int sign) {
151         sigset_t mask, oldmask;
152         int n_processes;
153
154         assert_se(sigemptyset(&mask) == 0);
155         assert_se(sigaddset(&mask, SIGCHLD) == 0);
156         assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
157
158         if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
159                 log_warning("kill(-1, SIGSTOP) failed: %m");
160
161         n_processes = killall(sign);
162
163         if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
164                 log_warning("kill(-1, SIGCONT) failed: %m");
165
166         if (n_processes <= 0)
167                 goto finish;
168
169         wait_for_children(n_processes, &mask);
170
171 finish:
172         sigprocmask(SIG_SETMASK, &oldmask, NULL);
173 }
174
175 static void ultimate_send_signal(int sign) {
176         sigset_t mask, oldmask;
177         int r;
178
179         assert_se(sigemptyset(&mask) == 0);
180         assert_se(sigaddset(&mask, SIGCHLD) == 0);
181         assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
182
183         if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
184                 log_warning("kill(-1, SIGSTOP) failed: %m");
185
186         r = kill(-1, sign);
187         if (r < 0 && errno != ESRCH)
188                 log_warning("kill(-1, %s) failed: %m", signal_to_string(sign));
189
190         if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
191                 log_warning("kill(-1, SIGCONT) failed: %m");
192
193         if (r < 0)
194                 goto finish;
195
196         wait_for_children(0, &mask);
197
198 finish:
199         sigprocmask(SIG_SETMASK, &oldmask, NULL);
200 }
201
202 static bool prepare_new_root(void) {
203         int r = false;
204         const char *dirs[] = { "/run/initramfs/oldroot",
205                                "/run/initramfs/proc",
206                                "/run/initramfs/sys",
207                                "/run/initramfs/dev",
208                                "/run/initramfs/run",
209                                NULL };
210         const char **dir;
211         const char *msg;
212
213         msg = "Failed to mount bind /run/initramfs on /run/initramfs";
214         if (mount("/run/initramfs", "/run/initramfs", NULL, MS_BIND, NULL) != 0)
215                 goto out;
216
217         msg="Failed to make /run/initramfs private mount %m:";
218         if (mount(NULL, "/run/initramfs", NULL, MS_PRIVATE, NULL) != 0)
219                 goto out;
220
221         for (dir = &dirs[0]; *dir != NULL; dir++) {
222                 asprintf((char **) &msg, "mkdir %s: %%m", *dir);
223                 if (mkdir(*dir, 0755) != 0) {
224                         if (errno != EEXIST)
225                                 goto out;
226                 }
227                 free((char *) msg);
228         }
229
230         msg = "Failed to mount bind /sys on /run/initramfs/sys";
231         if (mount("/sys", "/run/initramfs/sys", NULL, MS_BIND, NULL) != 0)
232                 goto out;
233         msg = "Failed to mount bind /proc on /run/initramfs/proc";
234         if (mount("/proc", "/run/initramfs/proc", NULL, MS_BIND, NULL) != 0)
235                 goto out;
236         msg = "Failed to mount bind /dev on /run/initramfs/dev";
237         if (mount("/dev", "/run/initramfs/dev", NULL, MS_BIND, NULL) != 0)
238                 goto out;
239         msg = "Failed to mount bind /run on /run/initramfs/run";
240         if (mount("/run", "/run/initramfs/run", NULL, MS_BIND, NULL) != 0)
241                 goto out;
242
243         r = true;
244  out:
245         if (!r)
246                 log_error("%s: %m", msg);
247         return r;
248 }
249
250 static bool pivot_to_new_root(void) {
251         int fd;
252         int r = 0;
253         chdir("/run/initramfs");
254
255         /*
256           In case some evil process made "/" MS_SHARED
257           It works for pivot_root, but the ref count for the root device
258           is not decreasing :-/
259         */
260         if (mount(NULL, "/", NULL, MS_PRIVATE, NULL) != 0) {
261                 log_error("Failed to make \"/\" private mount %m: ");
262                 return false;
263         }
264
265         r = pivot_root(".", "oldroot");
266         if (r!=0) {
267                 log_error("pivot failed: %m");
268                 /* only chroot, if pivot root succeded */
269                 return false;
270         }
271         chroot(".");
272         log_info("pivot rooted");
273
274         fd = open("dev/console", O_RDONLY);
275         dup2(fd, STDIN_FILENO);
276         close_nointr_nofail(fd);
277         fd = open("dev/console", O_WRONLY);
278         dup2(fd, STDOUT_FILENO);
279         close_nointr_nofail(fd);
280         fd = open("dev/console", O_WRONLY);
281         dup2(fd, STDERR_FILENO);
282         close_nointr_nofail(fd);
283         return true;
284 }
285
286 int main(int argc, char *argv[]) {
287         int cmd, r;
288         unsigned retries;
289         bool need_umount = true, need_swapoff = true, need_loop_detach = true, need_dm_detach = true;
290         bool killed_everbody = false, in_container;
291
292         log_parse_environment();
293         log_set_target(LOG_TARGET_CONSOLE); /* syslog will die if not gone yet */
294         log_open();
295
296         if (getpid() != 1) {
297                 log_error("Not executed by init (pid 1).");
298                 r = -EPERM;
299                 goto error;
300         }
301
302         if (argc != 2) {
303                 log_error("Invalid number of arguments.");
304                 r = -EINVAL;
305                 goto error;
306         }
307
308         in_container = detect_container(NULL) > 0;
309
310         if (streq(argv[1], "reboot"))
311                 cmd = RB_AUTOBOOT;
312         else if (streq(argv[1], "poweroff"))
313                 cmd = RB_POWER_OFF;
314         else if (streq(argv[1], "halt"))
315                 cmd = RB_HALT_SYSTEM;
316         else if (streq(argv[1], "kexec"))
317                 cmd = LINUX_REBOOT_CMD_KEXEC;
318         else {
319                 log_error("Unknown action '%s'.", argv[1]);
320                 r = -EINVAL;
321                 goto error;
322         }
323
324         /* lock us into memory */
325         if (mlockall(MCL_CURRENT|MCL_FUTURE) != 0)
326                 log_warning("Cannot lock process memory: %m");
327
328         log_info("Sending SIGTERM to remaining processes...");
329         send_signal(SIGTERM);
330
331         log_info("Sending SIGKILL to remaining processes...");
332         send_signal(SIGKILL);
333
334         if (in_container)
335                 need_swapoff = false;
336
337         /* Unmount all mountpoints, swaps, and loopback devices */
338         for (retries = 0; retries < FINALIZE_ATTEMPTS; retries++) {
339                 bool changed = false;
340
341                 if (need_umount) {
342                         log_info("Unmounting file systems.");
343                         r = umount_all(&changed);
344                         if (r == 0)
345                                 need_umount = false;
346                         else if (r > 0)
347                                 log_info("Not all file systems unmounted, %d left.", r);
348                         else
349                                 log_error("Failed to unmount file systems: %s", strerror(-r));
350                 }
351
352                 if (need_swapoff) {
353                         log_info("Disabling swaps.");
354                         r = swapoff_all(&changed);
355                         if (r == 0)
356                                 need_swapoff = false;
357                         else if (r > 0)
358                                 log_info("Not all swaps are turned off, %d left.", r);
359                         else
360                                 log_error("Failed to turn off swaps: %s", strerror(-r));
361                 }
362
363                 if (need_loop_detach) {
364                         log_info("Detaching loop devices.");
365                         r = loopback_detach_all(&changed);
366                         if (r == 0)
367                                 need_loop_detach = false;
368                         else if (r > 0)
369                                 log_info("Not all loop devices detached, %d left.", r);
370                         else
371                                 log_error("Failed to detach loop devices: %s", strerror(-r));
372                 }
373
374                 if (need_dm_detach) {
375                         log_info("Detaching DM devices.");
376                         r = dm_detach_all(&changed);
377                         if (r == 0)
378                                 need_dm_detach = false;
379                         else if (r > 0)
380                                 log_warning("Not all DM devices detached, %d left.", r);
381                         else
382                                 log_error("Failed to detach DM devices: %s", strerror(-r));
383                 }
384
385                 if (!need_umount && !need_swapoff && !need_loop_detach && !need_dm_detach)
386                         /* Yay, done */
387                         break;
388
389                 /* If in this iteration we didn't manage to
390                  * unmount/deactivate anything, we either kill more
391                  * processes, or simply give up */
392                 if (!changed) {
393
394                         if (killed_everbody) {
395                                 /* Hmm, we already killed everybody,
396                                  * let's just give up */
397                                 log_error("Cannot finalize remaining file systems and devices, giving up.");
398                                 break;
399                         }
400
401                         log_warning("Cannot finalize remaining file systems and devices, trying to kill remaining processes.");
402                         ultimate_send_signal(SIGTERM);
403                         ultimate_send_signal(SIGKILL);
404                         killed_everbody = true;
405                 }
406
407                 log_debug("Couldn't finalize remaining file systems and devices after %u retries, trying again.", retries+1);
408         }
409
410         if (retries >= FINALIZE_ATTEMPTS)
411                 log_error("Too many iterations, giving up.");
412
413         execute_directory(SYSTEM_SHUTDOWN_PATH, NULL, NULL);
414
415         /* If we are in a container, just exit, this will kill our
416          * container for good. */
417         if (in_container) {
418                 log_error("Exiting container.");
419                 exit(0);
420         }
421
422         sync();
423
424         if (access("/run/initramfs/shutdown", X_OK) == 0) {
425                 char *new_argv[3];
426                 new_argv[0] = strdup(argv[0]);
427                 new_argv[1] = strdup(argv[1]);
428                 new_argv[2] = NULL;
429                 if (prepare_new_root() && pivot_to_new_root()) {
430                         execv("/shutdown", new_argv);
431                         log_error("Failed to execute shutdown binary: %m");
432                 }
433         }
434
435         if (cmd == LINUX_REBOOT_CMD_KEXEC) {
436                 /* We cheat and exec kexec to avoid doing all its work */
437                 pid_t pid = fork();
438
439                 if (pid < 0)
440                         log_error("Could not fork: %m. Falling back to normal reboot.");
441                 else if (pid > 0) {
442                         wait_for_terminate_and_warn("kexec", pid);
443                         log_warning("kexec failed. Falling back to normal reboot.");
444                 } else {
445                         /* Child */
446                         const char *args[3] = { "/sbin/kexec", "-e", NULL };
447                         execv(args[0], (char * const *) args);
448                         return EXIT_FAILURE;
449                 }
450
451                 cmd = RB_AUTOBOOT;
452         }
453
454         reboot(cmd);
455         log_error("Failed to invoke reboot(): %m");
456         r = -errno;
457
458   error:
459         log_error("Critical error while doing system shutdown: %s", strerror(-r));
460
461         freeze();
462         return EXIT_FAILURE;
463 }