1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2010 ProFUSION embedded systems
8 #include <linux/reboot.h>
13 #include <sys/mount.h>
14 #include <sys/reboot.h>
18 #include "alloc-util.h"
20 #include "cgroup-util.h"
22 #include "exec-util.h"
28 #include "parse-util.h"
29 #include "process-util.h"
30 #include "reboot-util.h"
31 #include "rlimit-util.h"
32 #include "signal-util.h"
33 #include "string-util.h"
34 #include "switch-root.h"
35 #include "sysctl-util.h"
36 #include "terminal-util.h"
42 #define SYNC_PROGRESS_ATTEMPTS 3
43 #define SYNC_TIMEOUT_USEC (10*USEC_PER_SEC)
45 static char* arg_verb
;
46 static uint8_t arg_exit_code
;
47 static usec_t arg_timeout
= DEFAULT_TIMEOUT_USEC
;
49 static int parse_argv(int argc
, char *argv
[]) {
51 ARG_LOG_LEVEL
= 0x100,
59 static const struct option options
[] = {
60 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
61 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
62 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
63 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
64 { "exit-code", required_argument
, NULL
, ARG_EXIT_CODE
},
65 { "timeout", required_argument
, NULL
, ARG_TIMEOUT
},
74 /* "-" prevents getopt from permuting argv[] and moving the verb away
75 * from argv[1]. Our interface to initrd promises it'll be there. */
76 while ((c
= getopt_long(argc
, argv
, "-", options
, NULL
)) >= 0)
80 r
= log_set_max_level_from_string(optarg
);
82 log_error_errno(r
, "Failed to parse log level %s, ignoring: %m", optarg
);
87 r
= log_set_target_from_string(optarg
);
89 log_error_errno(r
, "Failed to parse log target %s, ignoring: %m", optarg
);
96 r
= log_show_color_from_string(optarg
);
98 log_error_errno(r
, "Failed to parse log color setting %s, ignoring: %m", optarg
);
100 log_show_color(true);
104 case ARG_LOG_LOCATION
:
106 r
= log_show_location_from_string(optarg
);
108 log_error_errno(r
, "Failed to parse log location setting %s, ignoring: %m", optarg
);
110 log_show_location(true);
115 r
= safe_atou8(optarg
, &arg_exit_code
);
117 log_error_errno(r
, "Failed to parse exit code %s, ignoring: %m", optarg
);
122 r
= parse_sec(optarg
, &arg_timeout
);
124 log_error_errno(r
, "Failed to parse shutdown timeout %s, ignoring: %m", optarg
);
132 log_error("Excess arguments, ignoring");
139 assert_not_reached("Unhandled option code.");
143 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
144 "Verb argument missing.");
149 static int switch_root_initramfs(void) {
150 if (mount("/run/initramfs", "/run/initramfs", NULL
, MS_BIND
, NULL
) < 0)
151 return log_error_errno(errno
, "Failed to mount bind /run/initramfs on /run/initramfs: %m");
153 if (mount(NULL
, "/run/initramfs", NULL
, MS_PRIVATE
, NULL
) < 0)
154 return log_error_errno(errno
, "Failed to make /run/initramfs private mount: %m");
156 /* switch_root with MS_BIND, because there might still be processes lurking around, which have open file descriptors.
157 * /run/initramfs/shutdown will take care of these.
158 * Also do not detach the old root, because /run/initramfs/shutdown needs to access it.
160 return switch_root("/run/initramfs", "/oldroot", false, MS_BIND
);
163 /* Read the following fields from /proc/meminfo:
169 * Return true if the sum of these fields is greater than the previous
170 * value input. For all other issues, report the failure and indicate that
171 * the sync is not making progress.
173 static int sync_making_progress(unsigned long long *prev_dirty
) {
174 _cleanup_fclose_
FILE *f
= NULL
;
175 unsigned long long val
= 0;
178 f
= fopen("/proc/meminfo", "re");
180 return log_warning_errno(errno
, "Failed to open /proc/meminfo: %m");
183 _cleanup_free_
char *line
= NULL
;
184 unsigned long long ull
= 0;
187 q
= read_line(f
, LONG_LINE_MAX
, &line
);
189 return log_warning_errno(q
, "Failed to parse /proc/meminfo: %m");
193 if (!first_word(line
, "NFS_Unstable:") && !first_word(line
, "Writeback:") && !first_word(line
, "Dirty:"))
197 if (sscanf(line
, "%*s %llu %*s", &ull
) != 1) {
199 log_warning_errno(errno
, "Failed to parse /proc/meminfo: %m");
201 log_warning("Failed to parse /proc/meminfo");
209 ret
= *prev_dirty
> val
;
214 static void sync_with_progress(void) {
215 unsigned long long dirty
= ULLONG_MAX
;
220 BLOCK_SIGNALS(SIGCHLD
);
222 /* Due to the possibility of the sync operation hanging, we fork a child process and monitor the progress. If
223 * the timeout lapses, the assumption is that that particular sync stalled. */
225 r
= asynchronous_sync(&pid
);
227 log_error_errno(r
, "Failed to fork sync(): %m");
231 log_info("Syncing filesystems and block devices.");
233 /* Start monitoring the sync operation. If more than
234 * SYNC_PROGRESS_ATTEMPTS lapse without progress being made,
235 * we assume that the sync is stalled */
236 for (checks
= 0; checks
< SYNC_PROGRESS_ATTEMPTS
; checks
++) {
237 r
= wait_for_terminate_with_timeout(pid
, SYNC_TIMEOUT_USEC
);
239 /* Sync finished without error.
240 * (The sync itself does not return an error code) */
242 else if (r
== -ETIMEDOUT
) {
243 /* Reset the check counter if the "Dirty" value is
245 if (sync_making_progress(&dirty
) > 0)
248 log_error_errno(r
, "Failed to sync filesystems and block devices: %m");
253 /* Only reached in the event of a timeout. We should issue a kill
254 * to the stray process. */
255 log_error("Syncing filesystems and block devices - timed out, issuing SIGKILL to PID "PID_FMT
".", pid
);
256 (void) kill(pid
, SIGKILL
);
259 static int read_current_sysctl_printk_log_level(void) {
260 _cleanup_free_
char *sysctl_printk_vals
= NULL
, *sysctl_printk_curr
= NULL
;
261 unsigned current_lvl
= 0;
265 r
= sysctl_read("kernel/printk", &sysctl_printk_vals
);
267 return log_debug_errno(r
, "Cannot read sysctl kernel.printk: %m");
269 p
= sysctl_printk_vals
;
270 r
= extract_first_word(&p
, &sysctl_printk_curr
, NULL
, 0);
272 r
= safe_atou(sysctl_printk_curr
, ¤t_lvl
);
277 return log_debug_errno(r
, "Unexpected sysctl kernel.printk content: %s", sysctl_printk_vals
);
282 static void bump_sysctl_printk_log_level(int min_level
) {
283 /* Set the logging level to be able to see messages with log level smaller or equal to min_level */
285 int current_lvl
= read_current_sysctl_printk_log_level();
286 if (current_lvl
>= 0 && current_lvl
<= min_level
) {
287 char buf
[DECIMAL_STR_MAX(int)];
288 xsprintf(buf
, "%d", min_level
+ 1);
289 int r
= sysctl_write("kernel/printk", buf
);
291 log_debug_errno(r
, "Failed to bump kernel.printk to %s: %m", buf
);
295 int main(int argc
, char *argv
[]) {
296 bool need_umount
, need_swapoff
, need_loop_detach
, need_dm_detach
;
297 bool in_container
, use_watchdog
= false, can_initrd
;
298 _cleanup_free_
char *cgroup
= NULL
;
300 int cmd
, r
, umount_log_level
= LOG_INFO
;
301 static const char* const dirs
[] = {SYSTEM_SHUTDOWN_PATH
, NULL
};
302 char *watchdog_device
;
304 /* The log target defaults to console, but the original systemd process will pass its log target in through a
305 * command line argument, which will override this default. Also, ensure we'll never log to the journal or
306 * syslog, as these logging daemons are either already dead or will die very soon. */
308 log_set_target(LOG_TARGET_CONSOLE
);
309 log_set_prohibit_ipc(true);
310 log_parse_environment();
312 r
= parse_argv(argc
, argv
);
320 if (getpid_cached() != 1) {
321 log_error("Not executed by init (PID 1).");
326 if (streq(arg_verb
, "reboot"))
328 else if (streq(arg_verb
, "poweroff"))
330 else if (streq(arg_verb
, "halt"))
331 cmd
= RB_HALT_SYSTEM
;
332 else if (streq(arg_verb
, "kexec"))
333 cmd
= LINUX_REBOOT_CMD_KEXEC
;
334 else if (streq(arg_verb
, "exit"))
335 cmd
= 0; /* ignored, just checking that arg_verb is valid */
337 log_error("Unknown action '%s'.", arg_verb
);
342 (void) cg_get_root_path(&cgroup
);
343 in_container
= detect_container() > 0;
345 /* If the logging messages are going to KMSG, and if we are not running from a container,
346 * then try to update the sysctl kernel.printk current value in order to see "info" messages;
347 * This current log level is not updated if already big enough.
349 if (!in_container
&& IN_SET(log_get_target(), LOG_TARGET_AUTO
,
350 LOG_TARGET_JOURNAL_OR_KMSG
,
351 LOG_TARGET_SYSLOG_OR_KMSG
,
353 bump_sysctl_printk_log_level(LOG_INFO
);
355 use_watchdog
= getenv("WATCHDOG_USEC");
356 watchdog_device
= getenv("WATCHDOG_DEVICE");
357 if (watchdog_device
) {
358 r
= watchdog_set_device(watchdog_device
);
360 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m",
364 /* Lock us into memory */
365 (void) mlockall(MCL_CURRENT
|MCL_FUTURE
);
367 /* Synchronize everything that is not written to disk yet at this point already. This is a good idea so that
368 * slow IO is processed here already and the final process killing spree is not impacted by processes
369 * desperately trying to sync IO to disk within their timeout. Do not remove this sync, data corruption will
372 sync_with_progress();
376 log_info("Sending SIGTERM to remaining processes...");
377 broadcast_signal(SIGTERM
, true, true, arg_timeout
);
379 log_info("Sending SIGKILL to remaining processes...");
380 broadcast_signal(SIGKILL
, true, false, arg_timeout
);
382 need_umount
= !in_container
;
383 need_swapoff
= !in_container
;
384 need_loop_detach
= !in_container
;
385 need_dm_detach
= !in_container
;
386 can_initrd
= !in_container
&& !in_initrd() && access("/run/initramfs/shutdown", X_OK
) == 0;
388 /* Unmount all mountpoints, swaps, and loopback devices */
390 bool changed
= false;
393 (void) watchdog_ping();
395 /* Let's trim the cgroup tree on each iteration so
396 that we leave an empty cgroup tree around, so that
397 container managers get a nice notify event when we
400 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, cgroup
, false);
403 log_info("Unmounting file systems.");
404 r
= umount_all(&changed
, umount_log_level
);
407 log_info("All filesystems unmounted.");
409 log_info("Not all file systems unmounted, %d left.", r
);
411 log_error_errno(r
, "Failed to unmount file systems: %m");
415 log_info("Deactivating swaps.");
416 r
= swapoff_all(&changed
);
418 need_swapoff
= false;
419 log_info("All swaps deactivated.");
421 log_info("Not all swaps deactivated, %d left.", r
);
423 log_error_errno(r
, "Failed to deactivate swaps: %m");
426 if (need_loop_detach
) {
427 log_info("Detaching loop devices.");
428 r
= loopback_detach_all(&changed
, umount_log_level
);
430 need_loop_detach
= false;
431 log_info("All loop devices detached.");
433 log_info("Not all loop devices detached, %d left.", r
);
435 log_error_errno(r
, "Failed to detach loop devices: %m");
438 if (need_dm_detach
) {
439 log_info("Detaching DM devices.");
440 r
= dm_detach_all(&changed
, umount_log_level
);
442 need_dm_detach
= false;
443 log_info("All DM devices detached.");
445 log_info("Not all DM devices detached, %d left.", r
);
447 log_error_errno(r
, "Failed to detach DM devices: %m");
450 if (!need_umount
&& !need_swapoff
&& !need_loop_detach
&& !need_dm_detach
) {
451 log_info("All filesystems, swaps, loop devices and DM devices detached.");
456 if (!changed
&& umount_log_level
== LOG_INFO
&& !can_initrd
) {
457 /* There are things we cannot get rid of. Loop one more time
458 * with LOG_ERR to inform the user. Note that we don't need
459 * to do this if there is a initrd to switch to, because that
460 * one is likely to get rid of the remounting mounts. If not,
461 * it will log about them. */
462 umount_log_level
= LOG_ERR
;
466 /* If in this iteration we didn't manage to
467 * unmount/deactivate anything, we simply give up */
469 log_info("Cannot finalize remaining%s%s%s%s continuing.",
470 need_umount
? " file systems," : "",
471 need_swapoff
? " swap devices," : "",
472 need_loop_detach
? " loop devices," : "",
473 need_dm_detach
? " DM devices," : "");
477 log_debug("Couldn't finalize remaining %s%s%s%s trying again.",
478 need_umount
? " file systems," : "",
479 need_swapoff
? " swap devices," : "",
480 need_loop_detach
? " loop devices," : "",
481 need_dm_detach
? " DM devices," : "");
484 /* We're done with the watchdog. */
485 watchdog_free_device();
488 arguments
[1] = arg_verb
;
490 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
492 (void) rlimit_nofile_safe();
495 r
= switch_root_initramfs();
497 argv
[0] = (char*) "/shutdown";
500 (void) make_console_stdio();
502 log_info("Successfully changed into root pivot.\n"
503 "Returning to initrd...");
505 execv("/shutdown", argv
);
506 log_error_errno(errno
, "Failed to execute shutdown binary: %m");
508 log_error_errno(r
, "Failed to switch root to \"/run/initramfs\": %m");
512 if (need_umount
|| need_swapoff
|| need_loop_detach
|| need_dm_detach
)
513 log_error("Failed to finalize %s%s%s%s ignoring",
514 need_umount
? " file systems," : "",
515 need_swapoff
? " swap devices," : "",
516 need_loop_detach
? " loop devices," : "",
517 need_dm_detach
? " DM devices," : "");
519 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
520 * sync'ed explicitly in advance. So let's do this here, but not needlessly slow down containers. Note that we
521 * sync'ed things already once above, but we did some more work since then which might have caused IO, hence
522 * let's do it once more. Do not remove this sync, data corruption will result. */
524 sync_with_progress();
526 if (streq(arg_verb
, "exit")) {
528 return arg_exit_code
;
530 cmd
= RB_POWER_OFF
; /* We cannot exit() on the host, fallback on another method. */
535 case LINUX_REBOOT_CMD_KEXEC
:
538 /* We cheat and exec kexec to avoid doing all its work */
539 log_info("Rebooting with kexec.");
541 r
= safe_fork("(sd-kexec)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_LOG
|FORK_WAIT
, NULL
);
543 const char * const args
[] = {
549 execv(args
[0], (char * const *) args
);
553 /* If we are still running, then the kexec can't have worked, let's fall through */
560 (void) reboot_with_parameter(REBOOT_LOG
);
561 log_info("Rebooting.");
565 log_info("Powering off.");
569 log_info("Halting system.");
573 assert_not_reached("Unknown magic");
577 if (errno
== EPERM
&& in_container
) {
578 /* If we are in a container, and we lacked
579 * CAP_SYS_BOOT just exit, this will kill our
580 * container for good. */
581 log_info("Exiting container.");
585 r
= log_error_errno(errno
, "Failed to invoke reboot(): %m");
588 log_emergency_errno(r
, "Critical error while doing system shutdown: %m");