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