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