]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shutdown/shutdown.c
man/systemd.mount: tmpfs automatically gains After=swap.target dep
[thirdparty/systemd.git] / src / shutdown / shutdown.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2010 ProFUSION embedded systems
4 ***/
5
6 #include <errno.h>
7 #include <getopt.h>
8 #include <linux/reboot.h>
9 #include <stdbool.h>
10 #include <stdlib.h>
11 #include <sys/mman.h>
12 #include <sys/mount.h>
13 #include <sys/reboot.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16
17 #include "sd-daemon.h"
18 #include "sd-messages.h"
19
20 #include "alloc-util.h"
21 #include "async.h"
22 #include "binfmt-util.h"
23 #include "cgroup-setup.h"
24 #include "cgroup-util.h"
25 #include "constants.h"
26 #include "coredump-util.h"
27 #include "detach-dm.h"
28 #include "detach-loopback.h"
29 #include "detach-md.h"
30 #include "detach-swap.h"
31 #include "errno-util.h"
32 #include "exec-util.h"
33 #include "fd-util.h"
34 #include "fileio.h"
35 #include "getopt-defs.h"
36 #include "initrd-util.h"
37 #include "killall.h"
38 #include "log.h"
39 #include "parse-util.h"
40 #include "process-util.h"
41 #include "reboot-util.h"
42 #include "rlimit-util.h"
43 #include "signal-util.h"
44 #include "string-util.h"
45 #include "switch-root.h"
46 #include "sysctl-util.h"
47 #include "terminal-util.h"
48 #include "umount.h"
49 #include "virt.h"
50 #include "watchdog.h"
51
52 #define SYNC_PROGRESS_ATTEMPTS 3
53 #define SYNC_TIMEOUT_USEC (10*USEC_PER_SEC)
54
55 static char* arg_verb;
56 static uint8_t arg_exit_code;
57 static usec_t arg_timeout = DEFAULT_TIMEOUT_USEC;
58
59 static int parse_argv(int argc, char *argv[]) {
60 enum {
61 COMMON_GETOPT_ARGS,
62 SHUTDOWN_GETOPT_ARGS,
63 };
64
65 static const struct option options[] = {
66 COMMON_GETOPT_OPTIONS,
67 SHUTDOWN_GETOPT_OPTIONS,
68 {}
69 };
70
71 int c, r;
72
73 assert(argc >= 1);
74 assert(argv);
75
76 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
77 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
78 optind = 0;
79
80 /* "-" prevents getopt from permuting argv[] and moving the verb away
81 * from argv[1]. Our interface to initrd promises it'll be there. */
82 while ((c = getopt_long(argc, argv, "-", options, NULL)) >= 0)
83 switch (c) {
84
85 case ARG_LOG_LEVEL:
86 r = log_set_max_level_from_string(optarg);
87 if (r < 0)
88 log_error_errno(r, "Failed to parse log level %s, ignoring: %m", optarg);
89
90 break;
91
92 case ARG_LOG_TARGET:
93 r = log_set_target_from_string(optarg);
94 if (r < 0)
95 log_error_errno(r, "Failed to parse log target %s, ignoring: %m", optarg);
96
97 break;
98
99 case ARG_LOG_COLOR:
100
101 if (optarg) {
102 r = log_show_color_from_string(optarg);
103 if (r < 0)
104 log_error_errno(r, "Failed to parse log color setting %s, ignoring: %m", optarg);
105 } else
106 log_show_color(true);
107
108 break;
109
110 case ARG_LOG_LOCATION:
111 if (optarg) {
112 r = log_show_location_from_string(optarg);
113 if (r < 0)
114 log_error_errno(r, "Failed to parse log location setting %s, ignoring: %m", optarg);
115 } else
116 log_show_location(true);
117
118 break;
119
120 case ARG_LOG_TIME:
121
122 if (optarg) {
123 r = log_show_time_from_string(optarg);
124 if (r < 0)
125 log_error_errno(r, "Failed to parse log time setting %s, ignoring: %m", optarg);
126 } else
127 log_show_time(true);
128
129 break;
130
131 case ARG_EXIT_CODE:
132 r = safe_atou8(optarg, &arg_exit_code);
133 if (r < 0)
134 log_error_errno(r, "Failed to parse exit code %s, ignoring: %m", optarg);
135
136 break;
137
138 case ARG_TIMEOUT:
139 r = parse_sec(optarg, &arg_timeout);
140 if (r < 0)
141 log_error_errno(r, "Failed to parse shutdown timeout %s, ignoring: %m", optarg);
142
143 break;
144
145 case '\001':
146 if (!arg_verb)
147 arg_verb = optarg;
148 else
149 log_error("Excess arguments, ignoring");
150 break;
151
152 case '?':
153 return -EINVAL;
154
155 default:
156 assert_not_reached();
157 }
158
159 if (!arg_verb)
160 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
161 "Verb argument missing.");
162
163 return 0;
164 }
165
166 static int switch_root_initramfs(void) {
167 /* Do not detach the old root, because /run/initramfs/shutdown needs to access it.
168 *
169 * Disable sync() during switch-root, we after all sync'ed here plenty, and a dumb sync (as opposed
170 * to the "smart" sync() we did here that looks at progress parameters) would defeat much of our
171 * efforts here. As the new root will be /run/initramfs/, it is not necessary to mount /run/
172 * recursively. */
173 return switch_root(
174 /* new_root= */ "/run/initramfs",
175 /* old_root_after= */ "/oldroot",
176 /* flags= */ SWITCH_ROOT_DONT_SYNC);
177 }
178
179 /* Read the following fields from /proc/meminfo:
180 *
181 * NFS_Unstable
182 * Writeback
183 * Dirty
184 *
185 * Return true if the sum of these fields is greater than the previous
186 * value input. For all other issues, report the failure and indicate that
187 * the sync is not making progress.
188 */
189 static int sync_making_progress(unsigned long long *prev_dirty) {
190 _cleanup_fclose_ FILE *f = NULL;
191 unsigned long long val = 0;
192 int ret;
193
194 f = fopen("/proc/meminfo", "re");
195 if (!f)
196 return log_warning_errno(errno, "Failed to open /proc/meminfo: %m");
197
198 for (;;) {
199 _cleanup_free_ char *line = NULL;
200 unsigned long long ull = 0;
201 int q;
202
203 q = read_line(f, LONG_LINE_MAX, &line);
204 if (q < 0)
205 return log_warning_errno(q, "Failed to parse /proc/meminfo: %m");
206 if (q == 0)
207 break;
208
209 if (!first_word(line, "NFS_Unstable:") && !first_word(line, "Writeback:") && !first_word(line, "Dirty:"))
210 continue;
211
212 errno = 0;
213 if (sscanf(line, "%*s %llu %*s", &ull) != 1) {
214 if (errno != 0)
215 log_warning_errno(errno, "Failed to parse /proc/meminfo: %m");
216 else
217 log_warning("Failed to parse /proc/meminfo");
218
219 return false;
220 }
221
222 val += ull;
223 }
224
225 ret = *prev_dirty > val;
226 *prev_dirty = val;
227 return ret;
228 }
229
230 static void sync_with_progress(void) {
231 unsigned long long dirty = ULLONG_MAX;
232 unsigned checks;
233 pid_t pid;
234 int r;
235
236 BLOCK_SIGNALS(SIGCHLD);
237
238 /* Due to the possibility of the sync operation hanging, we fork a child process and monitor
239 * the progress. If the timeout lapses, the assumption is that the particular sync stalled. */
240
241 r = asynchronous_sync(&pid);
242 if (r < 0) {
243 log_error_errno(r, "Failed to fork sync(): %m");
244 return;
245 }
246
247 log_info("Syncing filesystems and block devices.");
248
249 /* Start monitoring the sync operation. If more than
250 * SYNC_PROGRESS_ATTEMPTS lapse without progress being made,
251 * we assume that the sync is stalled */
252 for (checks = 0; checks < SYNC_PROGRESS_ATTEMPTS; checks++) {
253 r = wait_for_terminate_with_timeout(pid, SYNC_TIMEOUT_USEC);
254 if (r == 0)
255 /* Sync finished without error.
256 * (The sync itself does not return an error code) */
257 return;
258 else if (r == -ETIMEDOUT) {
259 /* Reset the check counter if the "Dirty" value is
260 * decreasing */
261 if (sync_making_progress(&dirty) > 0)
262 checks = 0;
263 } else {
264 log_error_errno(r, "Failed to sync filesystems and block devices: %m");
265 return;
266 }
267 }
268
269 /* Only reached in the event of a timeout. We should issue a kill
270 * to the stray process. */
271 log_error("Syncing filesystems and block devices - timed out, issuing SIGKILL to PID "PID_FMT".", pid);
272 (void) kill(pid, SIGKILL);
273 }
274
275 static int read_current_sysctl_printk_log_level(void) {
276 _cleanup_free_ char *sysctl_printk_vals = NULL, *sysctl_printk_curr = NULL;
277 int current_lvl;
278 const char *p;
279 int r;
280
281 r = sysctl_read("kernel/printk", &sysctl_printk_vals);
282 if (r < 0)
283 return log_debug_errno(r, "Cannot read sysctl kernel.printk: %m");
284
285 p = sysctl_printk_vals;
286 r = extract_first_word(&p, &sysctl_printk_curr, NULL, 0);
287 if (r < 0)
288 return log_debug_errno(r, "Failed to split out kernel printk priority: %m");
289 if (r == 0)
290 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Short read while reading kernel.printk sysctl");
291
292 r = safe_atoi(sysctl_printk_curr, &current_lvl);
293 if (r < 0)
294 return log_debug_errno(r, "Failed to parse kernel.printk sysctl: %s", sysctl_printk_vals);
295
296 return current_lvl;
297 }
298
299 static void bump_sysctl_printk_log_level(int min_level) {
300 int current_lvl, r;
301
302 /* Set the logging level to be able to see messages with log level smaller or equal to min_level */
303
304 current_lvl = read_current_sysctl_printk_log_level();
305 if (current_lvl < 0 || current_lvl >= min_level + 1)
306 return;
307
308 r = sysctl_writef("kernel/printk", "%i", min_level + 1);
309 if (r < 0)
310 log_debug_errno(r, "Failed to bump kernel.printk to %i: %m", min_level + 1);
311 }
312
313 static void init_watchdog(void) {
314 const char *s;
315 int r;
316
317 s = getenv("WATCHDOG_DEVICE");
318 if (s) {
319 r = watchdog_set_device(s);
320 if (r < 0)
321 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", s);
322 }
323
324 s = getenv("WATCHDOG_USEC");
325 if (s) {
326 usec_t usec;
327
328 r = safe_atou64(s, &usec);
329 if (r < 0)
330 log_warning_errno(r, "Failed to parse watchdog timeout '%s', ignoring: %m", s);
331 else
332 (void) watchdog_setup(usec);
333 }
334 }
335
336 int main(int argc, char *argv[]) {
337 static const char* const dirs[] = {
338 SYSTEM_SHUTDOWN_PATH,
339 NULL
340 };
341 _cleanup_free_ char *cgroup = NULL;
342 char *arguments[3];
343 int cmd, r;
344
345 /* Close random fds we might have get passed, just for paranoia, before we open any new fds, for
346 * example for logging. After all this tool's purpose is about detaching any pinned resources, and
347 * open file descriptors are the primary way to pin resources. Note that we don't really expect any
348 * fds to be passed here. */
349 (void) close_all_fds(NULL, 0);
350
351 /* The log target defaults to console, but the original systemd process will pass its log target in through a
352 * command line argument, which will override this default. Also, ensure we'll never log to the journal or
353 * syslog, as these logging daemons are either already dead or will die very soon. */
354
355 log_set_target(LOG_TARGET_CONSOLE);
356 log_set_prohibit_ipc(true);
357 log_parse_environment();
358
359 if (getpid_cached() == 1)
360 log_set_always_reopen_console(true);
361
362 r = parse_argv(argc, argv);
363 if (r < 0)
364 goto error;
365
366 log_open();
367
368 umask(0022);
369
370 if (getpid_cached() != 1) {
371 r = log_error_errno(SYNTHETIC_ERRNO(EPERM), "Not executed by init (PID 1).");
372 goto error;
373 }
374
375 if (streq(arg_verb, "reboot"))
376 cmd = RB_AUTOBOOT;
377 else if (streq(arg_verb, "poweroff"))
378 cmd = RB_POWER_OFF;
379 else if (streq(arg_verb, "halt"))
380 cmd = RB_HALT_SYSTEM;
381 else if (streq(arg_verb, "kexec"))
382 cmd = LINUX_REBOOT_CMD_KEXEC;
383 else if (streq(arg_verb, "exit"))
384 cmd = 0; /* ignored, just checking that arg_verb is valid */
385 else {
386 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown action '%s'.", arg_verb);
387 goto error;
388 }
389
390 (void) cg_get_root_path(&cgroup);
391 bool in_container = detect_container() > 0;
392
393 /* If the logging messages are going to KMSG, and if we are not running from a container, then try to
394 * update the sysctl kernel.printk current value in order to see "info" messages; This current log
395 * level is not updated if already big enough.
396 */
397 if (!in_container &&
398 IN_SET(log_get_target(),
399 LOG_TARGET_AUTO,
400 LOG_TARGET_JOURNAL_OR_KMSG,
401 LOG_TARGET_SYSLOG_OR_KMSG,
402 LOG_TARGET_KMSG))
403 bump_sysctl_printk_log_level(LOG_WARNING);
404
405 init_watchdog();
406
407 /* Lock us into memory */
408 (void) mlockall(MCL_CURRENT|MCL_FUTURE);
409
410 /* We need to make mounts private so that we can MS_MOVE in unmount_all(). Kernel does not allow
411 * MS_MOVE when parent mountpoints have shared propagation. */
412 if (mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL) < 0)
413 log_warning_errno(errno, "Failed to make mounts private, ignoring: %m");
414
415 /* Synchronize everything that is not written to disk yet at this point already. This is a good idea so that
416 * slow IO is processed here already and the final process killing spree is not impacted by processes
417 * desperately trying to sync IO to disk within their timeout. Do not remove this sync, data corruption will
418 * result. */
419 if (!in_container)
420 sync_with_progress();
421
422 disable_coredumps();
423 disable_binfmt();
424
425 log_info("Sending SIGTERM to remaining processes...");
426 broadcast_signal(SIGTERM, true, true, arg_timeout);
427
428 log_info("Sending SIGKILL to remaining processes...");
429 broadcast_signal(SIGKILL, true, false, arg_timeout);
430
431 bool need_umount = !in_container, need_swapoff = !in_container, need_loop_detach = !in_container,
432 need_dm_detach = !in_container, need_md_detach = !in_container, can_initrd, last_try = false;
433 can_initrd = !in_container && !in_initrd() && access("/run/initramfs/shutdown", X_OK) == 0;
434
435 /* Unmount all mountpoints, swaps, and loopback devices */
436 for (;;) {
437 bool changed = false;
438
439 (void) watchdog_ping();
440
441 /* Let's trim the cgroup tree on each iteration so that we leave an empty cgroup tree around,
442 * so that container managers get a nice notify event when we are down */
443 if (cgroup)
444 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, cgroup, false);
445
446 if (need_umount) {
447 log_info("Unmounting file systems.");
448 r = umount_all(&changed, last_try);
449 if (r == 0) {
450 need_umount = false;
451 log_info("All filesystems unmounted.");
452 } else if (r > 0)
453 log_info("Not all file systems unmounted, %d left.", r);
454 else
455 log_error_errno(r, "Unable to unmount file systems: %m");
456 }
457
458 if (need_swapoff) {
459 log_info("Deactivating swaps.");
460 r = swapoff_all(&changed);
461 if (r == 0) {
462 need_swapoff = false;
463 log_info("All swaps deactivated.");
464 } else if (r > 0)
465 log_info("Not all swaps deactivated, %d left.", r);
466 else
467 log_error_errno(r, "Unable to deactivate swaps: %m");
468 }
469
470 if (need_loop_detach) {
471 log_info("Detaching loop devices.");
472 r = loopback_detach_all(&changed, last_try);
473 if (r == 0) {
474 need_loop_detach = false;
475 log_info("All loop devices detached.");
476 } else if (r > 0)
477 log_info("Not all loop devices detached, %d left.", r);
478 else
479 log_error_errno(r, "Unable to detach loop devices: %m");
480 }
481
482 if (need_md_detach) {
483 log_info("Stopping MD devices.");
484 r = md_detach_all(&changed, last_try);
485 if (r == 0) {
486 need_md_detach = false;
487 log_info("All MD devices stopped.");
488 } else if (r > 0)
489 log_info("Not all MD devices stopped, %d left.", r);
490 else
491 log_error_errno(r, "Unable to stop MD devices: %m");
492 }
493
494 if (need_dm_detach) {
495 log_info("Detaching DM devices.");
496 r = dm_detach_all(&changed, last_try);
497 if (r == 0) {
498 need_dm_detach = false;
499 log_info("All DM devices detached.");
500 } else if (r > 0)
501 log_info("Not all DM devices detached, %d left.", r);
502 else
503 log_error_errno(r, "Unable to detach DM devices: %m");
504 }
505
506 if (!need_umount && !need_swapoff && !need_loop_detach && !need_dm_detach
507 && !need_md_detach) {
508 log_info("All filesystems, swaps, loop devices, MD devices and DM devices detached.");
509 /* Yay, done */
510 break;
511 }
512
513 if (!changed && !last_try && !can_initrd) {
514 /* There are things we cannot get rid of. Loop one more time in which we will log
515 * with higher priority to inform the user. Note that we don't need to do this if
516 * there is an initrd to switch to, because that one is likely to get rid of the
517 * remaining mounts. If not, it will log about them. */
518 last_try = true;
519 continue;
520 }
521
522 /* If in this iteration we didn't manage to unmount/deactivate anything, we simply give up */
523 if (!changed) {
524 log_info("Cannot finalize remaining%s%s%s%s%s continuing.",
525 need_umount ? " file systems," : "",
526 need_swapoff ? " swap devices," : "",
527 need_loop_detach ? " loop devices," : "",
528 need_dm_detach ? " DM devices," : "",
529 need_md_detach ? " MD devices," : "");
530 break;
531 }
532
533 log_debug("Couldn't finalize remaining %s%s%s%s%s trying again.",
534 need_umount ? " file systems," : "",
535 need_swapoff ? " swap devices," : "",
536 need_loop_detach ? " loop devices," : "",
537 need_dm_detach ? " DM devices," : "",
538 need_md_detach ? " MD devices," : "");
539 }
540
541 /* We're done with the watchdog. Note that the watchdog is explicitly not stopped here. It remains
542 * active to guard against any issues during the rest of the shutdown sequence. */
543 watchdog_free_device();
544
545 arguments[0] = NULL; /* Filled in by execute_directories(), when needed */
546 arguments[1] = arg_verb;
547 arguments[2] = NULL;
548 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
549
550 (void) rlimit_nofile_safe();
551
552 if (can_initrd) {
553 r = switch_root_initramfs();
554 if (r >= 0) {
555 argv[0] = (char*) "/shutdown";
556
557 (void) setsid();
558 (void) make_console_stdio();
559
560 log_info("Successfully changed into root pivot.\n"
561 "Returning to initrd...");
562
563 execv("/shutdown", argv);
564 log_error_errno(errno, "Failed to execute shutdown binary: %m");
565 } else
566 log_error_errno(r, "Failed to switch root to \"/run/initramfs\": %m");
567 }
568
569 if (need_umount || need_swapoff || need_loop_detach || need_dm_detach || need_md_detach)
570 log_error("Unable to finalize remaining%s%s%s%s%s ignoring.",
571 need_umount ? " file systems," : "",
572 need_swapoff ? " swap devices," : "",
573 need_loop_detach ? " loop devices," : "",
574 need_dm_detach ? " DM devices," : "",
575 need_md_detach ? " MD devices," : "");
576
577 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need
578 * to be sync'ed explicitly in advance. So let's do this here, but not needlessly slow down
579 * containers. Note that we sync'ed things already once above, but we did some more work since then
580 * which might have caused IO, hence let's do it once more. Do not remove this sync, data corruption
581 * will result. */
582 if (!in_container)
583 sync_with_progress();
584
585 /* This is primarily useful when running systemd in a VM, as it provides the user running the VM with
586 * a mechanism to pick up systemd's exit status in the VM. */
587 (void) sd_notifyf(0, "EXIT_STATUS=%i", arg_exit_code);
588
589 if (streq(arg_verb, "exit")) {
590 if (in_container) {
591 log_info("Exiting container.");
592 return arg_exit_code;
593 }
594
595 cmd = RB_POWER_OFF; /* We cannot exit() on the host, fallback on another method. */
596 }
597
598 switch (cmd) {
599
600 case LINUX_REBOOT_CMD_KEXEC:
601
602 if (!in_container) {
603 /* We cheat and exec kexec to avoid doing all its work */
604 log_info("Rebooting with kexec.");
605
606 r = safe_fork("(sd-kexec)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_LOG|FORK_WAIT, NULL);
607 if (r == 0) {
608 const char * const args[] = {
609 KEXEC, "-e", NULL
610 };
611
612 /* Child */
613
614 execv(args[0], (char * const *) args);
615 log_debug_errno(errno, "Failed to execute '" KEXEC "' binary, proceeding with reboot(RB_KEXEC): %m");
616
617 /* execv failed (kexec binary missing?), so try simply reboot(RB_KEXEC) */
618 (void) reboot(cmd);
619 _exit(EXIT_FAILURE);
620 }
621
622 /* If we are still running, then the kexec can't have worked, let's fall through */
623 }
624
625 cmd = RB_AUTOBOOT;
626 _fallthrough_;
627
628 case RB_AUTOBOOT:
629 (void) reboot_with_parameter(REBOOT_LOG);
630 log_info("Rebooting.");
631 break;
632
633 case RB_POWER_OFF:
634 log_info("Powering off.");
635 break;
636
637 case RB_HALT_SYSTEM:
638 log_info("Halting system.");
639 break;
640
641 default:
642 assert_not_reached();
643 }
644
645 (void) reboot(cmd);
646 if (ERRNO_IS_PRIVILEGE(errno) && in_container) {
647 /* If we are in a container, and we lacked CAP_SYS_BOOT just exit, this will kill our
648 * container for good. */
649 log_info("Exiting container.");
650 return EXIT_SUCCESS;
651 }
652
653 r = log_error_errno(errno, "Failed to invoke reboot(): %m");
654
655 error:
656 log_struct_errno(LOG_EMERG, r,
657 LOG_MESSAGE("Critical error while doing system shutdown: %m"),
658 "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_ERROR_STR);
659 freeze();
660 }