1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
10 #include <linux/fiemap.h>
13 #include <sys/types.h>
14 #include <sys/timerfd.h>
15 #include <sys/utsname.h>
19 #include "sd-device.h"
21 #include "sd-messages.h"
23 #include "battery-capacity.h"
24 #include "battery-util.h"
25 #include "btrfs-util.h"
27 #include "bus-error.h"
28 #include "bus-locator.h"
30 #include "constants.h"
31 #include "devnum-util.h"
33 #include "exec-util.h"
36 #include "format-util.h"
37 #include "hibernate-util.h"
38 #include "id128-util.h"
42 #include "main-func.h"
44 #include "parse-util.h"
45 #include "pretty-print.h"
46 #include "sleep-config.h"
48 #include "stdio-util.h"
49 #include "string-util.h"
51 #include "time-util.h"
53 #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
55 static SleepOperation arg_operation
= _SLEEP_OPERATION_INVALID
;
57 static int write_efi_hibernate_location(const HibernateLocation
*hibernate_location
, bool required
) {
58 int log_level
= required
? LOG_ERR
: LOG_DEBUG
;
61 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
62 _cleanup_free_
char *formatted
= NULL
, *id
= NULL
, *image_id
= NULL
,
63 *version_id
= NULL
, *image_version
= NULL
;
64 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
67 struct utsname uts
= {};
68 int r
, log_level_ignore
= required
? LOG_WARNING
: LOG_DEBUG
;
70 assert(hibernate_location
);
71 assert(hibernate_location
->swap
);
74 return log_full_errno(log_level
, SYNTHETIC_ERRNO(EOPNOTSUPP
),
75 "Not an EFI boot, passing HibernateLocation via EFI variable is not possible.");
77 r
= sd_device_new_from_devnum(&device
, 'b', hibernate_location
->devno
);
79 return log_full_errno(log_level
, r
, "Failed to create sd-device object for '%s': %m",
80 hibernate_location
->swap
->path
);
82 r
= sd_device_get_property_value(device
, "ID_FS_UUID", &uuid_str
);
84 return log_full_errno(log_level
, r
, "Failed to get filesystem UUID for device '%s': %m",
85 hibernate_location
->swap
->path
);
87 r
= sd_id128_from_string(uuid_str
, &uuid
);
89 return log_full_errno(log_level
, r
, "Failed to parse ID_FS_UUID '%s' for device '%s': %m",
90 uuid_str
, hibernate_location
->swap
->path
);
93 log_full_errno(log_level_ignore
, errno
, "Failed to get kernel info, ignoring: %m");
95 r
= parse_os_release(NULL
,
97 "IMAGE_ID", &image_id
,
98 "VERSION_ID", &version_id
,
99 "IMAGE_VERSION", &image_version
);
101 log_full_errno(log_level_ignore
, r
, "Failed to parse os-release, ignoring: %m");
103 r
= json_build(&v
, JSON_BUILD_OBJECT(
104 JSON_BUILD_PAIR_UUID("uuid", uuid
),
105 JSON_BUILD_PAIR_UNSIGNED("offset", hibernate_location
->offset
),
106 JSON_BUILD_PAIR_CONDITION(!isempty(uts
.release
), "kernelVersion", JSON_BUILD_STRING(uts
.release
)),
107 JSON_BUILD_PAIR_CONDITION(id
, "osReleaseId", JSON_BUILD_STRING(id
)),
108 JSON_BUILD_PAIR_CONDITION(image_id
, "osReleaseImageId", JSON_BUILD_STRING(image_id
)),
109 JSON_BUILD_PAIR_CONDITION(version_id
, "osReleaseVersionId", JSON_BUILD_STRING(version_id
)),
110 JSON_BUILD_PAIR_CONDITION(image_version
, "osReleaseImageVersion", JSON_BUILD_STRING(image_version
))));
112 return log_full_errno(log_level
, r
, "Failed to build JSON object: %m");
114 r
= json_variant_format(v
, 0, &formatted
);
116 return log_full_errno(log_level
, r
, "Failed to format JSON object: %m");
118 r
= efi_set_variable_string(EFI_SYSTEMD_VARIABLE(HibernateLocation
), formatted
);
120 return log_full_errno(log_level
, r
, "Failed to set EFI variable HibernateLocation: %m");
122 log_debug("Set EFI variable HibernateLocation to '%s'.", formatted
);
125 return log_full_errno(log_level
, SYNTHETIC_ERRNO(EOPNOTSUPP
),
126 "EFI support not enabled, passing HibernateLocation via EFI variable is not possible.");
130 static int write_kernel_hibernate_location(const HibernateLocation
*hibernate_location
) {
131 assert(hibernate_location
);
132 assert(hibernate_location
->swap
);
133 assert(IN_SET(hibernate_location
->swap
->type
, SWAP_BLOCK
, SWAP_FILE
));
135 return write_resume_config(hibernate_location
->devno
, hibernate_location
->offset
, hibernate_location
->swap
->path
);
138 static int write_mode(char **modes
) {
141 STRV_FOREACH(mode
, modes
) {
144 k
= write_string_file("/sys/power/disk", *mode
, WRITE_STRING_FILE_DISABLE_BUFFER
);
148 log_debug_errno(k
, "Failed to write '%s' to /sys/power/disk: %m", *mode
);
156 static int write_state(FILE **f
, char **states
) {
162 STRV_FOREACH(state
, states
) {
165 k
= write_string_stream(*f
, *state
, WRITE_STRING_FILE_DISABLE_BUFFER
);
168 log_debug_errno(k
, "Failed to write '%s' to /sys/power/state: %m", *state
);
173 *f
= fopen("/sys/power/state", "we");
181 /* Return true if wakeup type is APM timer */
182 static int check_wakeup_type(void) {
183 static const char dmi_object_path
[] = "/sys/firmware/dmi/entries/1-0/raw";
184 uint8_t wakeup_type_byte
, tablesize
;
185 _cleanup_free_
char *buf
= NULL
;
189 /* implementation via dmi/entries */
190 r
= read_full_virtual_file(dmi_object_path
, &buf
, &bufsize
);
192 return log_debug_errno(r
, "Unable to read %s: %m", dmi_object_path
);
194 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
195 "Only read %zu bytes from %s (expected 25)",
196 bufsize
, dmi_object_path
);
198 /* index 1 stores the size of table */
199 tablesize
= (uint8_t) buf
[1];
201 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
202 "Table size less than the index[0x18] where waketype byte is available.");
204 wakeup_type_byte
= (uint8_t) buf
[24];
205 /* 0 is Reserved and 8 is AC Power Restored. As per table 12 in
206 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */
207 if (wakeup_type_byte
>= 128)
208 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Expected value in range 0-127");
210 if (wakeup_type_byte
== 3) {
211 log_debug("DMI BIOS System Information indicates wakeup type is APM Timer");
218 static int lock_all_homes(void) {
219 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
220 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
221 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
224 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
225 * way the key material required to access these volumes is hopefully removed from memory. */
227 r
= sd_bus_open_system(&bus
);
229 return log_warning_errno(r
, "Failed to connect to system bus, ignoring: %m");
231 r
= bus_message_new_method_call(bus
, &m
, bus_home_mgr
, "LockAllHomes");
233 return bus_log_create_error(r
);
235 /* If homed is not running it can't have any home directories active either. */
236 r
= sd_bus_message_set_auto_start(m
, false);
238 return log_error_errno(r
, "Failed to disable auto-start of LockAllHomes() message: %m");
240 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
, &error
, NULL
);
242 if (!bus_error_is_unknown_service(&error
))
243 return log_error_errno(r
, "Failed to lock home directories: %s", bus_error_message(&error
, r
));
245 log_debug("systemd-homed is not running, locking of home directories skipped.");
247 log_debug("Successfully requested locking of all home directories.");
252 const SleepConfig
*sleep_config
,
253 SleepOperation operation
,
254 const char *action
) {
256 char *arguments
[] = {
259 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
260 * operation here, not the specific one, in case of s2h. */
261 (char*) sleep_operation_to_string(arg_operation
),
264 static const char* const dirs
[] = {
269 _cleanup_(hibernate_location_freep
) HibernateLocation
*hibernate_location
= NULL
;
270 _cleanup_fclose_
FILE *f
= NULL
;
271 char **modes
, **states
;
274 assert(sleep_config
);
275 assert(operation
>= 0);
276 assert(operation
< _SLEEP_OPERATION_MAX
);
277 assert(operation
!= SLEEP_SUSPEND_THEN_HIBERNATE
); /* Handled by execute_s2h() instead */
279 states
= sleep_config
->states
[operation
];
280 modes
= sleep_config
->modes
[operation
];
282 if (strv_isempty(states
))
283 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
284 "No sleep states configured for sleep operation %s, can't sleep.",
285 sleep_operation_to_string(operation
));
287 /* This file is opened first, so that if we hit an error,
288 * we can abort before modifying any state. */
289 f
= fopen("/sys/power/state", "we");
291 return log_error_errno(errno
, "Failed to open /sys/power/state: %m");
293 setvbuf(f
, NULL
, _IONBF
, 0);
295 /* Configure hibernation settings if we are supposed to hibernate */
296 if (!strv_isempty(modes
)) {
299 r
= find_hibernate_location(&hibernate_location
);
301 return log_error_errno(r
, "Failed to find location to hibernate to: %m");
304 r
= write_efi_hibernate_location(hibernate_location
, !resume_set
);
306 if (r
== -EOPNOTSUPP
)
307 return log_error_errno(r
, "No valid 'resume=' option found, refusing to hibernate.");
311 r
= write_kernel_hibernate_location(hibernate_location
);
314 (void) efi_set_variable(EFI_SYSTEMD_VARIABLE(HibernateLocation
), NULL
, 0);
316 return log_error_errno(r
, "Failed to prepare for hibernation: %m");
320 r
= write_mode(modes
);
322 return log_error_errno(r
, "Failed to write mode to /sys/power/disk: %m");
325 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
326 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
328 action
= sleep_operation_to_string(operation
);
330 r
= setenv("SYSTEMD_SLEEP_ACTION", action
, 1);
332 log_warning_errno(errno
, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action
);
334 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
335 (void) lock_all_homes();
338 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR
,
339 LOG_MESSAGE("Entering sleep state '%s'...", sleep_operation_to_string(operation
)),
340 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
342 r
= write_state(&f
, states
);
344 log_struct_errno(LOG_ERR
, r
,
345 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
346 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
347 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
350 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
351 LOG_MESSAGE("System returned from sleep state."),
352 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
354 arguments
[1] = (char*) "post";
355 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
360 static int custom_timer_suspend(const SleepConfig
*sleep_config
) {
361 usec_t hibernate_timestamp
;
364 assert(sleep_config
);
366 hibernate_timestamp
= usec_add(now(CLOCK_BOOTTIME
), sleep_config
->hibernate_delay_usec
);
368 while (battery_is_discharging_and_low() == 0) {
369 _cleanup_hashmap_free_ Hashmap
*last_capacity
= NULL
, *current_capacity
= NULL
;
370 _cleanup_close_
int tfd
= -EBADF
;
371 struct itimerspec ts
= {};
372 usec_t suspend_interval
;
375 tfd
= timerfd_create(CLOCK_BOOTTIME_ALARM
, TFD_NONBLOCK
|TFD_CLOEXEC
);
377 return log_error_errno(errno
, "Error creating timerfd: %m");
379 /* Store current battery capacity before suspension */
380 r
= fetch_batteries_capacity_by_name(&last_capacity
);
382 return log_error_errno(r
, "Error fetching battery capacity percentage: %m");
384 if (hashmap_isempty(last_capacity
))
385 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
386 suspend_interval
= timestamp_is_set(hibernate_timestamp
)
387 ? sleep_config
->hibernate_delay_usec
: DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY
;
389 r
= get_total_suspend_interval(last_capacity
, &suspend_interval
);
391 log_debug_errno(r
, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
392 /* In case of any errors, especially when we do not know the battery
393 * discharging rate, system suspend interval will be set to
394 * SuspendEstimationSec=. */
395 suspend_interval
= sleep_config
->suspend_estimation_usec
;
399 /* Do not suspend more than HibernateDelaySec= */
400 usec_t before_timestamp
= now(CLOCK_BOOTTIME
);
401 suspend_interval
= MIN(suspend_interval
, usec_sub_unsigned(hibernate_timestamp
, before_timestamp
));
402 if (suspend_interval
<= 0)
403 break; /* system should hibernate */
405 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval
, USEC_PER_SEC
));
406 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
407 timespec_store(&ts
.it_value
, suspend_interval
);
409 if (timerfd_settime(tfd
, 0, &ts
, NULL
) < 0)
410 return log_error_errno(errno
, "Error setting battery estimate timer: %m");
412 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
416 r
= fd_wait_for_event(tfd
, POLLIN
, 0);
418 return log_error_errno(r
, "Error polling timerfd: %m");
419 /* Store fd_wait status */
420 woken_by_timer
= FLAGS_SET(r
, POLLIN
);
422 r
= fetch_batteries_capacity_by_name(¤t_capacity
);
423 if (r
< 0 || hashmap_isempty(current_capacity
)) {
424 /* In case of no battery or error while getting charge level, no need to measure
425 * discharge rate. Instead the system should wake up if it is manual wakeup or
426 * hibernate if this is a timer wakeup. */
428 log_debug_errno(r
, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
430 log_debug("No battery found.");
436 usec_t after_timestamp
= now(CLOCK_BOOTTIME
);
437 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
438 FORMAT_TIMESPAN(after_timestamp
- before_timestamp
, USEC_PER_HOUR
));
440 if (after_timestamp
!= before_timestamp
) {
441 r
= estimate_battery_discharge_rate_per_hour(last_capacity
, current_capacity
, before_timestamp
, after_timestamp
);
443 log_warning_errno(r
, "Failed to estimate and update battery discharge rate, ignoring: %m");
445 log_debug("System woke up too early to estimate discharge rate");
448 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
451 r
= check_wakeup_type();
453 log_debug_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
455 log_debug("wakeup type is APM timer");
456 /* system should hibernate */
464 /* Freeze when invoked and thaw on cleanup */
465 static int freeze_thaw_user_slice(const char **method
) {
466 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
467 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
470 if (!method
|| !*method
)
473 r
= bus_connect_system_systemd(&bus
);
475 return log_debug_errno(r
, "Failed to open connection to systemd: %m");
477 (void) sd_bus_set_method_call_timeout(bus
, FREEZE_TIMEOUT
);
479 r
= bus_call_method(bus
, bus_systemd_mgr
, *method
, &error
, NULL
, "s", SPECIAL_USER_SLICE
);
481 return log_debug_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
486 static int execute_s2h(const SleepConfig
*sleep_config
) {
487 _unused_
_cleanup_(freeze_thaw_user_slice
) const char *auto_method_thaw
= "ThawUnit";
490 assert(sleep_config
);
492 r
= freeze_thaw_user_slice(&(const char*) { "FreezeUnit" });
494 log_debug_errno(r
, "Failed to freeze unit user.slice, ignoring: %m");
496 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
497 * we'll busy poll for the configured interval instead */
498 if (!timestamp_is_set(sleep_config
->hibernate_delay_usec
)) {
499 r
= check_wakeup_type();
501 log_debug_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
503 r
= battery_trip_point_alarm_exists();
505 log_debug_errno(r
, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
508 r
= 0; /* Force fallback path */
510 if (r
> 0) { /* If we have both wakeup alarms and battery trip point support, use them */
511 log_debug("Attempting to suspend...");
512 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
516 r
= check_wakeup_type();
518 return log_debug_errno(r
, "Failed to check hardware wakeup type: %m");
521 /* For APM Timer wakeup, system should hibernate else wakeup */
524 r
= custom_timer_suspend(sleep_config
);
526 return log_debug_errno(r
, "Suspend cycle with manual battery discharge rate estimation failed: %m");
531 /* For above custom timer, if 1 is returned, system will directly hibernate */
533 log_debug("Attempting to hibernate");
534 r
= execute(sleep_config
, SLEEP_HIBERNATE
, NULL
);
536 log_notice("Couldn't hibernate, will try to suspend again.");
538 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hibernate");
546 static int help(void) {
547 _cleanup_free_
char *link
= NULL
;
550 r
= terminal_urlify_man("systemd-suspend.service", "8", &link
);
554 printf("%s COMMAND\n\n"
555 "Suspend the system, hibernate the system, or both.\n\n"
556 " -h --help Show this help and exit\n"
557 " --version Print version string and exit\n"
559 " suspend Suspend the system\n"
560 " hibernate Hibernate the system\n"
561 " hybrid-sleep Both hibernate and suspend the system\n"
562 " suspend-then-hibernate Initially suspend and then hibernate\n"
563 " the system after a fixed period of time\n"
564 "\nSee the %s for details.\n",
565 program_invocation_short_name
,
571 static int parse_argv(int argc
, char *argv
[]) {
576 static const struct option options
[] = {
577 { "help", no_argument
, NULL
, 'h' },
578 { "version", no_argument
, NULL
, ARG_VERSION
},
587 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
599 assert_not_reached();
602 if (argc
- optind
!= 1)
603 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
605 program_invocation_short_name
);
607 arg_operation
= sleep_operation_from_string(argv
[optind
]);
608 if (arg_operation
< 0)
609 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown command '%s'.", argv
[optind
]);
611 return 1 /* work to do */;
614 static int run(int argc
, char *argv
[]) {
615 _cleanup_(sleep_config_freep
) SleepConfig
*sleep_config
= NULL
;
620 r
= parse_argv(argc
, argv
);
624 r
= parse_sleep_config(&sleep_config
);
628 if (!sleep_config
->allow
[arg_operation
])
629 return log_error_errno(SYNTHETIC_ERRNO(EACCES
),
630 "Sleep operation \"%s\" is disabled by configuration, refusing.",
631 sleep_operation_to_string(arg_operation
));
633 switch (arg_operation
) {
635 case SLEEP_SUSPEND_THEN_HIBERNATE
:
636 r
= execute_s2h(sleep_config
);
639 case SLEEP_HYBRID_SLEEP
:
640 r
= execute(sleep_config
, SLEEP_HYBRID_SLEEP
, NULL
);
642 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
643 * asked us to do both: suspend + hibernate, and it's almost certainly the
644 * hibernation that failed, hence still do the other thing, the suspend. */
646 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
648 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hybrid-sleep");
654 r
= execute(sleep_config
, arg_operation
, NULL
);
661 DEFINE_MAIN_FUNCTION(run
);