1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 Copyright © 2010 ProFUSION embedded systems
8 #include <linux/reboot.h>
12 #include <sys/mount.h>
13 #include <sys/reboot.h>
17 #include "sd-daemon.h"
19 #include "alloc-util.h"
21 #include "binfmt-util.h"
22 #include "cgroup-setup.h"
23 #include "cgroup-util.h"
24 #include "coredump-util.h"
25 #include "constants.h"
26 #include "errno-util.h"
27 #include "exec-util.h"
30 #include "getopt-defs.h"
31 #include "initrd-util.h"
34 #include "parse-util.h"
35 #include "process-util.h"
36 #include "reboot-util.h"
37 #include "rlimit-util.h"
38 #include "signal-util.h"
39 #include "string-util.h"
40 #include "switch-root.h"
41 #include "sysctl-util.h"
42 #include "terminal-util.h"
47 #define SYNC_PROGRESS_ATTEMPTS 3
48 #define SYNC_TIMEOUT_USEC (10*USEC_PER_SEC)
50 static char* arg_verb
;
51 static uint8_t arg_exit_code
;
52 static usec_t arg_timeout
= DEFAULT_TIMEOUT_USEC
;
54 static int parse_argv(int argc
, char *argv
[]) {
60 static const struct option options
[] = {
61 COMMON_GETOPT_OPTIONS
,
62 SHUTDOWN_GETOPT_OPTIONS
,
71 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
72 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
75 /* "-" prevents getopt from permuting argv[] and moving the verb away
76 * from argv[1]. Our interface to initrd promises it'll be there. */
77 while ((c
= getopt_long(argc
, argv
, "-", options
, NULL
)) >= 0)
81 r
= log_set_max_level_from_string(optarg
);
83 log_error_errno(r
, "Failed to parse log level %s, ignoring: %m", optarg
);
88 r
= log_set_target_from_string(optarg
);
90 log_error_errno(r
, "Failed to parse log target %s, ignoring: %m", optarg
);
97 r
= log_show_color_from_string(optarg
);
99 log_error_errno(r
, "Failed to parse log color setting %s, ignoring: %m", optarg
);
101 log_show_color(true);
105 case ARG_LOG_LOCATION
:
107 r
= log_show_location_from_string(optarg
);
109 log_error_errno(r
, "Failed to parse log location setting %s, ignoring: %m", optarg
);
111 log_show_location(true);
118 r
= log_show_time_from_string(optarg
);
120 log_error_errno(r
, "Failed to parse log time setting %s, ignoring: %m", optarg
);
127 r
= safe_atou8(optarg
, &arg_exit_code
);
129 log_error_errno(r
, "Failed to parse exit code %s, ignoring: %m", optarg
);
134 r
= parse_sec(optarg
, &arg_timeout
);
136 log_error_errno(r
, "Failed to parse shutdown timeout %s, ignoring: %m", optarg
);
144 log_error("Excess arguments, ignoring");
151 assert_not_reached();
155 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
156 "Verb argument missing.");
161 static int switch_root_initramfs(void) {
162 if (mount("/run/initramfs", "/run/initramfs", NULL
, MS_BIND
, NULL
) < 0)
163 return log_error_errno(errno
, "Failed to mount bind /run/initramfs on /run/initramfs: %m");
165 if (mount(NULL
, "/run/initramfs", NULL
, MS_PRIVATE
, NULL
) < 0)
166 return log_error_errno(errno
, "Failed to make /run/initramfs private mount: %m");
168 /* switch_root with MS_BIND, because there might still be processes lurking around, which have open file descriptors.
169 * /run/initramfs/shutdown will take care of these.
170 * Also do not detach the old root, because /run/initramfs/shutdown needs to access it.
173 /* new_root= */ "/run/initramfs",
174 /* old_root_after= */ "/oldroot",
176 /* destroy_old_root= */ false);
179 /* Read the following fields from /proc/meminfo:
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.
189 static int sync_making_progress(unsigned long long *prev_dirty
) {
190 _cleanup_fclose_
FILE *f
= NULL
;
191 unsigned long long val
= 0;
194 f
= fopen("/proc/meminfo", "re");
196 return log_warning_errno(errno
, "Failed to open /proc/meminfo: %m");
199 _cleanup_free_
char *line
= NULL
;
200 unsigned long long ull
= 0;
203 q
= read_line(f
, LONG_LINE_MAX
, &line
);
205 return log_warning_errno(q
, "Failed to parse /proc/meminfo: %m");
209 if (!first_word(line
, "NFS_Unstable:") && !first_word(line
, "Writeback:") && !first_word(line
, "Dirty:"))
213 if (sscanf(line
, "%*s %llu %*s", &ull
) != 1) {
215 log_warning_errno(errno
, "Failed to parse /proc/meminfo: %m");
217 log_warning("Failed to parse /proc/meminfo");
225 ret
= *prev_dirty
> val
;
230 static void sync_with_progress(void) {
231 unsigned long long dirty
= ULLONG_MAX
;
236 BLOCK_SIGNALS(SIGCHLD
);
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. */
241 r
= asynchronous_sync(&pid
);
243 log_error_errno(r
, "Failed to fork sync(): %m");
247 log_info("Syncing filesystems and block devices.");
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
);
255 /* Sync finished without error.
256 * (The sync itself does not return an error code) */
258 else if (r
== -ETIMEDOUT
) {
259 /* Reset the check counter if the "Dirty" value is
261 if (sync_making_progress(&dirty
) > 0)
264 log_error_errno(r
, "Failed to sync filesystems and block devices: %m");
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
);
275 static int read_current_sysctl_printk_log_level(void) {
276 _cleanup_free_
char *sysctl_printk_vals
= NULL
, *sysctl_printk_curr
= NULL
;
281 r
= sysctl_read("kernel/printk", &sysctl_printk_vals
);
283 return log_debug_errno(r
, "Cannot read sysctl kernel.printk: %m");
285 p
= sysctl_printk_vals
;
286 r
= extract_first_word(&p
, &sysctl_printk_curr
, NULL
, 0);
288 return log_debug_errno(r
, "Failed to split out kernel printk priority: %m");
290 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Short read while reading kernel.printk sysctl");
292 r
= safe_atoi(sysctl_printk_curr
, ¤t_lvl
);
294 return log_debug_errno(r
, "Failed to parse kernel.printk sysctl: %s", sysctl_printk_vals
);
299 static void bump_sysctl_printk_log_level(int min_level
) {
302 /* Set the logging level to be able to see messages with log level smaller or equal to min_level */
304 current_lvl
= read_current_sysctl_printk_log_level();
305 if (current_lvl
< 0 || current_lvl
>= min_level
+ 1)
308 r
= sysctl_writef("kernel/printk", "%i", min_level
+ 1);
310 log_debug_errno(r
, "Failed to bump kernel.printk to %i: %m", min_level
+ 1);
313 static void init_watchdog(void) {
317 s
= getenv("WATCHDOG_DEVICE");
319 r
= watchdog_set_device(s
);
321 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", s
);
324 s
= getenv("WATCHDOG_USEC");
328 r
= safe_atou64(s
, &usec
);
330 log_warning_errno(r
, "Failed to parse watchdog timeout '%s', ignoring: %m", s
);
332 (void) watchdog_setup(usec
);
336 int main(int argc
, char *argv
[]) {
337 static const char* const dirs
[] = {
338 SYSTEM_SHUTDOWN_PATH
,
341 _cleanup_free_
char *cgroup
= NULL
;
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);
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. */
355 log_set_target(LOG_TARGET_CONSOLE
);
356 log_set_prohibit_ipc(true);
357 log_parse_environment();
359 if (getpid_cached() == 1)
360 log_set_always_reopen_console(true);
362 r
= parse_argv(argc
, argv
);
370 if (getpid_cached() != 1) {
371 r
= log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Not executed by init (PID 1).");
375 if (streq(arg_verb
, "reboot"))
377 else if (streq(arg_verb
, "poweroff"))
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 */
386 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown action '%s'.", arg_verb
);
390 (void) cg_get_root_path(&cgroup
);
391 bool in_container
= detect_container() > 0;
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.
398 IN_SET(log_get_target(),
400 LOG_TARGET_JOURNAL_OR_KMSG
,
401 LOG_TARGET_SYSLOG_OR_KMSG
,
403 bump_sysctl_printk_log_level(LOG_WARNING
);
407 /* Lock us into memory */
408 (void) mlockall(MCL_CURRENT
|MCL_FUTURE
);
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");
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
420 sync_with_progress();
425 log_info("Sending SIGTERM to remaining processes...");
426 broadcast_signal(SIGTERM
, true, true, arg_timeout
);
428 log_info("Sending SIGKILL to remaining processes...");
429 broadcast_signal(SIGKILL
, true, false, arg_timeout
);
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;
435 /* Unmount all mountpoints, swaps, and loopback devices */
437 bool changed
= false;
439 (void) watchdog_ping();
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 */
444 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, cgroup
, false);
447 log_info("Unmounting file systems.");
448 r
= umount_all(&changed
, last_try
);
451 log_info("All filesystems unmounted.");
453 log_info("Not all file systems unmounted, %d left.", r
);
455 log_error_errno(r
, "Failed to unmount file systems: %m");
459 log_info("Deactivating swaps.");
460 r
= swapoff_all(&changed
);
462 need_swapoff
= false;
463 log_info("All swaps deactivated.");
465 log_info("Not all swaps deactivated, %d left.", r
);
467 log_error_errno(r
, "Failed to deactivate swaps: %m");
470 if (need_loop_detach
) {
471 log_info("Detaching loop devices.");
472 r
= loopback_detach_all(&changed
, last_try
);
474 need_loop_detach
= false;
475 log_info("All loop devices detached.");
477 log_info("Not all loop devices detached, %d left.", r
);
479 log_error_errno(r
, "Failed to detach loop devices: %m");
482 if (need_md_detach
) {
483 log_info("Stopping MD devices.");
484 r
= md_detach_all(&changed
, last_try
);
486 need_md_detach
= false;
487 log_info("All MD devices stopped.");
489 log_info("Not all MD devices stopped, %d left.", r
);
491 log_error_errno(r
, "Failed to stop MD devices: %m");
494 if (need_dm_detach
) {
495 log_info("Detaching DM devices.");
496 r
= dm_detach_all(&changed
, last_try
);
498 need_dm_detach
= false;
499 log_info("All DM devices detached.");
501 log_info("Not all DM devices detached, %d left.", r
);
503 log_error_errno(r
, "Failed to detach DM devices: %m");
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.");
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. */
522 /* If in this iteration we didn't manage to unmount/deactivate anything, we simply give up */
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," : "");
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," : "");
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();
545 arguments
[0] = NULL
; /* Filled in by execute_directories(), when needed */
546 arguments
[1] = arg_verb
;
548 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
550 (void) rlimit_nofile_safe();
553 r
= switch_root_initramfs();
555 argv
[0] = (char*) "/shutdown";
558 (void) make_console_stdio();
560 log_info("Successfully changed into root pivot.\n"
561 "Returning to initrd...");
563 execv("/shutdown", argv
);
564 log_error_errno(errno
, "Failed to execute shutdown binary: %m");
566 log_error_errno(r
, "Failed to switch root to \"/run/initramfs\": %m");
569 if (need_umount
|| need_swapoff
|| need_loop_detach
|| need_dm_detach
|| need_md_detach
)
570 log_error("Failed to finalize%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," : "");
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
583 sync_with_progress();
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
);
589 if (streq(arg_verb
, "exit")) {
591 log_info("Exiting container.");
592 return arg_exit_code
;
595 cmd
= RB_POWER_OFF
; /* We cannot exit() on the host, fallback on another method. */
600 case LINUX_REBOOT_CMD_KEXEC
:
603 /* We cheat and exec kexec to avoid doing all its work */
604 log_info("Rebooting with kexec.");
606 r
= safe_fork("(sd-kexec)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_LOG
|FORK_WAIT
, NULL
);
608 const char * const args
[] = {
614 execv(args
[0], (char * const *) args
);
615 log_debug_errno(errno
, "Failed to execute '" KEXEC
"' binary, proceeding with reboot(RB_KEXEC): %m");
617 /* execv failed (kexec binary missing?), so try simply reboot(RB_KEXEC) */
622 /* If we are still running, then the kexec can't have worked, let's fall through */
629 (void) reboot_with_parameter(REBOOT_LOG
);
630 log_info("Rebooting.");
634 log_info("Powering off.");
638 log_info("Halting system.");
642 assert_not_reached();
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.");
653 r
= log_error_errno(errno
, "Failed to invoke reboot(): %m");
656 log_emergency_errno(r
, "Critical error while doing system shutdown: %m");