1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 ProFUSION embedded systems
10 #include <linux/reboot.h>
15 #include <sys/mount.h>
16 #include <sys/reboot.h>
20 #include "alloc-util.h"
22 #include "cgroup-util.h"
24 #include "exec-util.h"
30 #include "parse-util.h"
31 #include "process-util.h"
32 #include "reboot-util.h"
33 #include "signal-util.h"
34 #include "string-util.h"
35 #include "switch-root.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.", optarg
);
87 r
= log_set_target_from_string(optarg
);
89 log_error_errno(r
, "Failed to parse log target %s, ignoring", optarg
);
96 r
= log_show_color_from_string(optarg
);
98 log_error_errno(r
, "Failed to parse log color setting %s, ignoring", 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", 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", optarg
);
122 r
= parse_sec(optarg
, &arg_timeout
);
124 log_error_errno(r
, "Failed to parse shutdown timeout %s, ignoring", optarg
);
132 log_error("Excess arguments, ignoring");
139 assert_not_reached("Unhandled option code.");
143 log_error("Verb argument missing.");
150 static int switch_root_initramfs(void) {
151 if (mount("/run/initramfs", "/run/initramfs", NULL
, MS_BIND
, NULL
) < 0)
152 return log_error_errno(errno
, "Failed to mount bind /run/initramfs on /run/initramfs: %m");
154 if (mount(NULL
, "/run/initramfs", NULL
, MS_PRIVATE
, NULL
) < 0)
155 return log_error_errno(errno
, "Failed to make /run/initramfs private mount: %m");
157 /* switch_root with MS_BIND, because there might still be processes lurking around, which have open file descriptors.
158 * /run/initramfs/shutdown will take care of these.
159 * Also do not detach the old root, because /run/initramfs/shutdown needs to access it.
161 return switch_root("/run/initramfs", "/oldroot", false, MS_BIND
);
164 /* Read the following fields from /proc/meminfo:
170 * Return true if the sum of these fields is greater than the previous
171 * value input. For all other issues, report the failure and indicate that
172 * the sync is not making progress.
174 static bool sync_making_progress(unsigned long long *prev_dirty
) {
175 _cleanup_fclose_
FILE *f
= NULL
;
178 unsigned long long val
= 0;
180 f
= fopen("/proc/meminfo", "re");
182 return log_warning_errno(errno
, "Failed to open /proc/meminfo: %m");
184 FOREACH_LINE(line
, f
, log_warning_errno(errno
, "Failed to parse /proc/meminfo: %m")) {
185 unsigned long long ull
= 0;
187 if (!first_word(line
, "NFS_Unstable:") && !first_word(line
, "Writeback:") && !first_word(line
, "Dirty:"))
191 if (sscanf(line
, "%*s %llu %*s", &ull
) != 1) {
193 log_warning_errno(errno
, "Failed to parse /proc/meminfo: %m");
195 log_warning("Failed to parse /proc/meminfo");
203 r
= *prev_dirty
> val
;
210 static void sync_with_progress(void) {
211 unsigned long long dirty
= ULONG_LONG_MAX
;
216 BLOCK_SIGNALS(SIGCHLD
);
218 /* Due to the possiblity of the sync operation hanging, we fork a child process and monitor the progress. If
219 * the timeout lapses, the assumption is that that particular sync stalled. */
221 r
= asynchronous_sync(&pid
);
223 log_error_errno(r
, "Failed to fork sync(): %m");
227 log_info("Syncing filesystems and block devices.");
229 /* Start monitoring the sync operation. If more than
230 * SYNC_PROGRESS_ATTEMPTS lapse without progress being made,
231 * we assume that the sync is stalled */
232 for (checks
= 0; checks
< SYNC_PROGRESS_ATTEMPTS
; checks
++) {
233 r
= wait_for_terminate_with_timeout(pid
, SYNC_TIMEOUT_USEC
);
235 /* Sync finished without error.
236 * (The sync itself does not return an error code) */
238 else if (r
== -ETIMEDOUT
) {
239 /* Reset the check counter if the "Dirty" value is
241 if (sync_making_progress(&dirty
))
244 log_error_errno(r
, "Failed to sync filesystems and block devices: %m");
249 /* Only reached in the event of a timeout. We should issue a kill
250 * to the stray process. */
251 log_error("Syncing filesystems and block devices - timed out, issuing SIGKILL to PID "PID_FMT
".", pid
);
252 (void) kill(pid
, SIGKILL
);
255 int main(int argc
, char *argv
[]) {
256 bool need_umount
, need_swapoff
, need_loop_detach
, need_dm_detach
;
257 bool in_container
, use_watchdog
= false, can_initrd
;
258 _cleanup_free_
char *cgroup
= NULL
;
260 int cmd
, r
, umount_log_level
= LOG_INFO
;
261 static const char* const dirs
[] = {SYSTEM_SHUTDOWN_PATH
, NULL
};
262 char *watchdog_device
;
264 /* The log target defaults to console, but the original systemd process will pass its log target in through a
265 * command line argument, which will override this default. Also, ensure we'll never log to the journal or
266 * syslog, as these logging daemons are either already dead or will die very soon. */
268 log_set_target(LOG_TARGET_CONSOLE
);
269 log_set_prohibit_ipc(true);
270 log_parse_environment();
272 r
= parse_argv(argc
, argv
);
280 if (getpid_cached() != 1) {
281 log_error("Not executed by init (PID 1).");
286 if (streq(arg_verb
, "reboot"))
288 else if (streq(arg_verb
, "poweroff"))
290 else if (streq(arg_verb
, "halt"))
291 cmd
= RB_HALT_SYSTEM
;
292 else if (streq(arg_verb
, "kexec"))
293 cmd
= LINUX_REBOOT_CMD_KEXEC
;
294 else if (streq(arg_verb
, "exit"))
295 cmd
= 0; /* ignored, just checking that arg_verb is valid */
297 log_error("Unknown action '%s'.", arg_verb
);
302 (void) cg_get_root_path(&cgroup
);
303 in_container
= detect_container() > 0;
305 use_watchdog
= !!getenv("WATCHDOG_USEC");
306 watchdog_device
= getenv("WATCHDOG_DEVICE");
307 if (watchdog_device
) {
308 r
= watchdog_set_device(watchdog_device
);
310 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m",
314 /* Lock us into memory */
315 (void) mlockall(MCL_CURRENT
|MCL_FUTURE
);
317 /* Synchronize everything that is not written to disk yet at this point already. This is a good idea so that
318 * slow IO is processed here already and the final process killing spree is not impacted by processes
319 * desperately trying to sync IO to disk within their timeout. Do not remove this sync, data corruption will
322 sync_with_progress();
326 log_info("Sending SIGTERM to remaining processes...");
327 broadcast_signal(SIGTERM
, true, true, arg_timeout
);
329 log_info("Sending SIGKILL to remaining processes...");
330 broadcast_signal(SIGKILL
, true, false, arg_timeout
);
332 need_umount
= !in_container
;
333 need_swapoff
= !in_container
;
334 need_loop_detach
= !in_container
;
335 need_dm_detach
= !in_container
;
336 can_initrd
= !in_container
&& !in_initrd() && access("/run/initramfs/shutdown", X_OK
) == 0;
338 /* Unmount all mountpoints, swaps, and loopback devices */
340 bool changed
= false;
345 /* Let's trim the cgroup tree on each iteration so
346 that we leave an empty cgroup tree around, so that
347 container managers get a nice notify event when we
350 cg_trim(SYSTEMD_CGROUP_CONTROLLER
, cgroup
, false);
353 log_info("Unmounting file systems.");
354 r
= umount_all(&changed
, umount_log_level
);
357 log_info("All filesystems unmounted.");
359 log_info("Not all file systems unmounted, %d left.", r
);
361 log_error_errno(r
, "Failed to unmount file systems: %m");
365 log_info("Deactivating swaps.");
366 r
= swapoff_all(&changed
);
368 need_swapoff
= false;
369 log_info("All swaps deactivated.");
371 log_info("Not all swaps deactivated, %d left.", r
);
373 log_error_errno(r
, "Failed to deactivate swaps: %m");
376 if (need_loop_detach
) {
377 log_info("Detaching loop devices.");
378 r
= loopback_detach_all(&changed
, umount_log_level
);
380 need_loop_detach
= false;
381 log_info("All loop devices detached.");
383 log_info("Not all loop devices detached, %d left.", r
);
385 log_error_errno(r
, "Failed to detach loop devices: %m");
388 if (need_dm_detach
) {
389 log_info("Detaching DM devices.");
390 r
= dm_detach_all(&changed
, umount_log_level
);
392 need_dm_detach
= false;
393 log_info("All DM devices detached.");
395 log_info("Not all DM devices detached, %d left.", r
);
397 log_error_errno(r
, "Failed to detach DM devices: %m");
400 if (!need_umount
&& !need_swapoff
&& !need_loop_detach
&& !need_dm_detach
) {
401 log_info("All filesystems, swaps, loop devices and DM devices detached.");
406 if (!changed
&& umount_log_level
== LOG_INFO
&& !can_initrd
) {
407 /* There are things we cannot get rid of. Loop one more time
408 * with LOG_ERR to inform the user. Note that we don't need
409 * to do this if there is a initrd to switch to, because that
410 * one is likely to get rid of the remounting mounts. If not,
411 * it will log about them. */
412 umount_log_level
= LOG_ERR
;
416 /* If in this iteration we didn't manage to
417 * unmount/deactivate anything, we simply give up */
419 log_info("Cannot finalize remaining%s%s%s%s continuing.",
420 need_umount
? " file systems," : "",
421 need_swapoff
? " swap devices," : "",
422 need_loop_detach
? " loop devices," : "",
423 need_dm_detach
? " DM devices," : "");
427 log_debug("Couldn't finalize remaining %s%s%s%s trying again.",
428 need_umount
? " file systems," : "",
429 need_swapoff
? " swap devices," : "",
430 need_loop_detach
? " loop devices," : "",
431 need_dm_detach
? " DM devices," : "");
434 /* We're done with the watchdog. */
435 watchdog_free_device();
438 arguments
[1] = arg_verb
;
440 execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
);
443 r
= switch_root_initramfs();
445 argv
[0] = (char*) "/shutdown";
448 make_console_stdio();
450 log_info("Successfully changed into root pivot.\n"
451 "Returning to initrd...");
453 execv("/shutdown", argv
);
454 log_error_errno(errno
, "Failed to execute shutdown binary: %m");
456 log_error_errno(r
, "Failed to switch root to \"/run/initramfs\": %m");
460 if (need_umount
|| need_swapoff
|| need_loop_detach
|| need_dm_detach
)
461 log_error("Failed to finalize %s%s%s%s ignoring",
462 need_umount
? " file systems," : "",
463 need_swapoff
? " swap devices," : "",
464 need_loop_detach
? " loop devices," : "",
465 need_dm_detach
? " DM devices," : "");
467 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
468 * sync'ed explicitly in advance. So let's do this here, but not needlessly slow down containers. Note that we
469 * sync'ed things already once above, but we did some more work since then which might have caused IO, hence
470 * let's do it once more. Do not remove this sync, data corruption will result. */
472 sync_with_progress();
474 if (streq(arg_verb
, "exit")) {
476 return arg_exit_code
;
478 cmd
= RB_POWER_OFF
; /* We cannot exit() on the host, fallback on another method. */
483 case LINUX_REBOOT_CMD_KEXEC
:
486 /* We cheat and exec kexec to avoid doing all its work */
487 log_info("Rebooting with kexec.");
489 r
= safe_fork("(sd-kexec)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_LOG
|FORK_WAIT
, NULL
);
491 const char * const args
[] = {
497 execv(args
[0], (char * const *) args
);
501 /* If we are still running, then the kexec can't have worked, let's fall through */
508 (void) reboot_with_parameter(REBOOT_LOG
);
509 log_info("Rebooting.");
513 log_info("Powering off.");
517 log_info("Halting system.");
521 assert_not_reached("Unknown magic");
525 if (errno
== EPERM
&& in_container
) {
526 /* If we are in a container, and we lacked
527 * CAP_SYS_BOOT just exit, this will kill our
528 * container for good. */
529 log_info("Exiting container.");
533 r
= log_error_errno(errno
, "Failed to invoke reboot(): %m");
536 log_emergency_errno(r
, "Critical error while doing system shutdown: %m");