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 "terminal-util.h"
41 #define SYNC_PROGRESS_ATTEMPTS 3
42 #define SYNC_TIMEOUT_USEC (10*USEC_PER_SEC)
44 static char* arg_verb
;
45 static uint8_t arg_exit_code
;
46 static usec_t arg_timeout
= DEFAULT_TIMEOUT_USEC
;
48 static int parse_argv(int argc
, char *argv
[]) {
50 ARG_LOG_LEVEL
= 0x100,
58 static const struct option options
[] = {
59 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
60 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
61 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
62 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
63 { "exit-code", required_argument
, NULL
, ARG_EXIT_CODE
},
64 { "timeout", required_argument
, NULL
, ARG_TIMEOUT
},
73 /* "-" prevents getopt from permuting argv[] and moving the verb away
74 * from argv[1]. Our interface to initrd promises it'll be there. */
75 while ((c
= getopt_long(argc
, argv
, "-", options
, NULL
)) >= 0)
79 r
= log_set_max_level_from_string(optarg
);
81 log_error_errno(r
, "Failed to parse log level %s, ignoring: %m", optarg
);
86 r
= log_set_target_from_string(optarg
);
88 log_error_errno(r
, "Failed to parse log target %s, ignoring: %m", optarg
);
95 r
= log_show_color_from_string(optarg
);
97 log_error_errno(r
, "Failed to parse log color setting %s, ignoring: %m", optarg
);
103 case ARG_LOG_LOCATION
:
105 r
= log_show_location_from_string(optarg
);
107 log_error_errno(r
, "Failed to parse log location setting %s, ignoring: %m", optarg
);
109 log_show_location(true);
114 r
= safe_atou8(optarg
, &arg_exit_code
);
116 log_error_errno(r
, "Failed to parse exit code %s, ignoring: %m", optarg
);
121 r
= parse_sec(optarg
, &arg_timeout
);
123 log_error_errno(r
, "Failed to parse shutdown timeout %s, ignoring: %m", optarg
);
131 log_error("Excess arguments, ignoring");
138 assert_not_reached("Unhandled option code.");
142 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
143 "Verb argument missing.");
148 static int switch_root_initramfs(void) {
149 if (mount("/run/initramfs", "/run/initramfs", NULL
, MS_BIND
, NULL
) < 0)
150 return log_error_errno(errno
, "Failed to mount bind /run/initramfs on /run/initramfs: %m");
152 if (mount(NULL
, "/run/initramfs", NULL
, MS_PRIVATE
, NULL
) < 0)
153 return log_error_errno(errno
, "Failed to make /run/initramfs private mount: %m");
155 /* switch_root with MS_BIND, because there might still be processes lurking around, which have open file descriptors.
156 * /run/initramfs/shutdown will take care of these.
157 * Also do not detach the old root, because /run/initramfs/shutdown needs to access it.
159 return switch_root("/run/initramfs", "/oldroot", false, MS_BIND
);
162 /* Read the following fields from /proc/meminfo:
168 * Return true if the sum of these fields is greater than the previous
169 * value input. For all other issues, report the failure and indicate that
170 * the sync is not making progress.
172 static bool sync_making_progress(unsigned long long *prev_dirty
) {
173 _cleanup_fclose_
FILE *f
= NULL
;
174 unsigned long long val
= 0;
177 f
= fopen("/proc/meminfo", "re");
179 return log_warning_errno(errno
, "Failed to open /proc/meminfo: %m");
182 _cleanup_free_
char *line
= NULL
;
183 unsigned long long ull
= 0;
186 q
= read_line(f
, LONG_LINE_MAX
, &line
);
188 return log_warning_errno(q
, "Failed to parse /proc/meminfo: %m");
192 if (!first_word(line
, "NFS_Unstable:") && !first_word(line
, "Writeback:") && !first_word(line
, "Dirty:"))
196 if (sscanf(line
, "%*s %llu %*s", &ull
) != 1) {
198 log_warning_errno(errno
, "Failed to parse /proc/meminfo: %m");
200 log_warning("Failed to parse /proc/meminfo");
208 r
= *prev_dirty
> val
;
215 static void sync_with_progress(void) {
216 unsigned long long dirty
= ULONG_LONG_MAX
;
221 BLOCK_SIGNALS(SIGCHLD
);
223 /* Due to the possiblity of the sync operation hanging, we fork a child process and monitor the progress. If
224 * the timeout lapses, the assumption is that that particular sync stalled. */
226 r
= asynchronous_sync(&pid
);
228 log_error_errno(r
, "Failed to fork sync(): %m");
232 log_info("Syncing filesystems and block devices.");
234 /* Start monitoring the sync operation. If more than
235 * SYNC_PROGRESS_ATTEMPTS lapse without progress being made,
236 * we assume that the sync is stalled */
237 for (checks
= 0; checks
< SYNC_PROGRESS_ATTEMPTS
; checks
++) {
238 r
= wait_for_terminate_with_timeout(pid
, SYNC_TIMEOUT_USEC
);
240 /* Sync finished without error.
241 * (The sync itself does not return an error code) */
243 else if (r
== -ETIMEDOUT
) {
244 /* Reset the check counter if the "Dirty" value is
246 if (sync_making_progress(&dirty
))
249 log_error_errno(r
, "Failed to sync filesystems and block devices: %m");
254 /* Only reached in the event of a timeout. We should issue a kill
255 * to the stray process. */
256 log_error("Syncing filesystems and block devices - timed out, issuing SIGKILL to PID "PID_FMT
".", pid
);
257 (void) kill(pid
, SIGKILL
);
260 int main(int argc
, char *argv
[]) {
261 bool need_umount
, need_swapoff
, need_loop_detach
, need_dm_detach
;
262 bool in_container
, use_watchdog
= false, can_initrd
;
263 _cleanup_free_
char *cgroup
= NULL
;
265 int cmd
, r
, umount_log_level
= LOG_INFO
;
266 static const char* const dirs
[] = {SYSTEM_SHUTDOWN_PATH
, NULL
};
267 char *watchdog_device
;
269 /* The log target defaults to console, but the original systemd process will pass its log target in through a
270 * command line argument, which will override this default. Also, ensure we'll never log to the journal or
271 * syslog, as these logging daemons are either already dead or will die very soon. */
273 log_set_target(LOG_TARGET_CONSOLE
);
274 log_set_prohibit_ipc(true);
275 log_parse_environment();
277 r
= parse_argv(argc
, argv
);
285 if (getpid_cached() != 1) {
286 log_error("Not executed by init (PID 1).");
291 if (streq(arg_verb
, "reboot"))
293 else if (streq(arg_verb
, "poweroff"))
295 else if (streq(arg_verb
, "halt"))
296 cmd
= RB_HALT_SYSTEM
;
297 else if (streq(arg_verb
, "kexec"))
298 cmd
= LINUX_REBOOT_CMD_KEXEC
;
299 else if (streq(arg_verb
, "exit"))
300 cmd
= 0; /* ignored, just checking that arg_verb is valid */
302 log_error("Unknown action '%s'.", arg_verb
);
307 (void) cg_get_root_path(&cgroup
);
308 in_container
= detect_container() > 0;
310 use_watchdog
= getenv("WATCHDOG_USEC");
311 watchdog_device
= getenv("WATCHDOG_DEVICE");
312 if (watchdog_device
) {
313 r
= watchdog_set_device(watchdog_device
);
315 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m",
319 /* Lock us into memory */
320 (void) mlockall(MCL_CURRENT
|MCL_FUTURE
);
322 /* Synchronize everything that is not written to disk yet at this point already. This is a good idea so that
323 * slow IO is processed here already and the final process killing spree is not impacted by processes
324 * desperately trying to sync IO to disk within their timeout. Do not remove this sync, data corruption will
327 sync_with_progress();
331 log_info("Sending SIGTERM to remaining processes...");
332 broadcast_signal(SIGTERM
, true, true, arg_timeout
);
334 log_info("Sending SIGKILL to remaining processes...");
335 broadcast_signal(SIGKILL
, true, false, arg_timeout
);
337 need_umount
= !in_container
;
338 need_swapoff
= !in_container
;
339 need_loop_detach
= !in_container
;
340 need_dm_detach
= !in_container
;
341 can_initrd
= !in_container
&& !in_initrd() && access("/run/initramfs/shutdown", X_OK
) == 0;
343 /* Unmount all mountpoints, swaps, and loopback devices */
345 bool changed
= false;
350 /* Let's trim the cgroup tree on each iteration so
351 that we leave an empty cgroup tree around, so that
352 container managers get a nice notify event when we
355 cg_trim(SYSTEMD_CGROUP_CONTROLLER
, cgroup
, false);
358 log_info("Unmounting file systems.");
359 r
= umount_all(&changed
, umount_log_level
);
362 log_info("All filesystems unmounted.");
364 log_info("Not all file systems unmounted, %d left.", r
);
366 log_error_errno(r
, "Failed to unmount file systems: %m");
370 log_info("Deactivating swaps.");
371 r
= swapoff_all(&changed
);
373 need_swapoff
= false;
374 log_info("All swaps deactivated.");
376 log_info("Not all swaps deactivated, %d left.", r
);
378 log_error_errno(r
, "Failed to deactivate swaps: %m");
381 if (need_loop_detach
) {
382 log_info("Detaching loop devices.");
383 r
= loopback_detach_all(&changed
, umount_log_level
);
385 need_loop_detach
= false;
386 log_info("All loop devices detached.");
388 log_info("Not all loop devices detached, %d left.", r
);
390 log_error_errno(r
, "Failed to detach loop devices: %m");
393 if (need_dm_detach
) {
394 log_info("Detaching DM devices.");
395 r
= dm_detach_all(&changed
, umount_log_level
);
397 need_dm_detach
= false;
398 log_info("All DM devices detached.");
400 log_info("Not all DM devices detached, %d left.", r
);
402 log_error_errno(r
, "Failed to detach DM devices: %m");
405 if (!need_umount
&& !need_swapoff
&& !need_loop_detach
&& !need_dm_detach
) {
406 log_info("All filesystems, swaps, loop devices and DM devices detached.");
411 if (!changed
&& umount_log_level
== LOG_INFO
&& !can_initrd
) {
412 /* There are things we cannot get rid of. Loop one more time
413 * with LOG_ERR to inform the user. Note that we don't need
414 * to do this if there is a initrd to switch to, because that
415 * one is likely to get rid of the remounting mounts. If not,
416 * it will log about them. */
417 umount_log_level
= LOG_ERR
;
421 /* If in this iteration we didn't manage to
422 * unmount/deactivate anything, we simply give up */
424 log_info("Cannot finalize remaining%s%s%s%s continuing.",
425 need_umount
? " file systems," : "",
426 need_swapoff
? " swap devices," : "",
427 need_loop_detach
? " loop devices," : "",
428 need_dm_detach
? " DM devices," : "");
432 log_debug("Couldn't finalize remaining %s%s%s%s trying again.",
433 need_umount
? " file systems," : "",
434 need_swapoff
? " swap devices," : "",
435 need_loop_detach
? " loop devices," : "",
436 need_dm_detach
? " DM devices," : "");
439 /* We're done with the watchdog. */
440 watchdog_free_device();
443 arguments
[1] = arg_verb
;
445 execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
);
447 (void) rlimit_nofile_safe();
450 r
= switch_root_initramfs();
452 argv
[0] = (char*) "/shutdown";
455 make_console_stdio();
457 log_info("Successfully changed into root pivot.\n"
458 "Returning to initrd...");
460 execv("/shutdown", argv
);
461 log_error_errno(errno
, "Failed to execute shutdown binary: %m");
463 log_error_errno(r
, "Failed to switch root to \"/run/initramfs\": %m");
467 if (need_umount
|| need_swapoff
|| need_loop_detach
|| need_dm_detach
)
468 log_error("Failed to finalize %s%s%s%s ignoring",
469 need_umount
? " file systems," : "",
470 need_swapoff
? " swap devices," : "",
471 need_loop_detach
? " loop devices," : "",
472 need_dm_detach
? " DM devices," : "");
474 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
475 * sync'ed explicitly in advance. So let's do this here, but not needlessly slow down containers. Note that we
476 * sync'ed things already once above, but we did some more work since then which might have caused IO, hence
477 * let's do it once more. Do not remove this sync, data corruption will result. */
479 sync_with_progress();
481 if (streq(arg_verb
, "exit")) {
483 return arg_exit_code
;
485 cmd
= RB_POWER_OFF
; /* We cannot exit() on the host, fallback on another method. */
490 case LINUX_REBOOT_CMD_KEXEC
:
493 /* We cheat and exec kexec to avoid doing all its work */
494 log_info("Rebooting with kexec.");
496 r
= safe_fork("(sd-kexec)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_LOG
|FORK_WAIT
, NULL
);
498 const char * const args
[] = {
504 execv(args
[0], (char * const *) args
);
508 /* If we are still running, then the kexec can't have worked, let's fall through */
515 (void) reboot_with_parameter(REBOOT_LOG
);
516 log_info("Rebooting.");
520 log_info("Powering off.");
524 log_info("Halting system.");
528 assert_not_reached("Unknown magic");
532 if (errno
== EPERM
&& in_container
) {
533 /* If we are in a container, and we lacked
534 * CAP_SYS_BOOT just exit, this will kill our
535 * container for good. */
536 log_info("Exiting container.");
540 r
= log_error_errno(errno
, "Failed to invoke reboot(): %m");
543 log_emergency_errno(r
, "Critical error while doing system shutdown: %m");