1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
11 #include <sys/timerfd.h>
12 #include <sys/types.h>
13 #include <sys/utsname.h>
17 #include "sd-device.h"
19 #include "sd-messages.h"
21 #include "battery-capacity.h"
22 #include "battery-util.h"
24 #include "bus-error.h"
25 #include "bus-locator.h"
27 #include "constants.h"
28 #include "devnum-util.h"
30 #include "exec-util.h"
33 #include "format-util.h"
34 #include "hibernate-util.h"
35 #include "id128-util.h"
39 #include "main-func.h"
41 #include "parse-util.h"
42 #include "pretty-print.h"
43 #include "sleep-config.h"
45 #include "stdio-util.h"
46 #include "string-util.h"
48 #include "time-util.h"
50 #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
52 static SleepOperation arg_operation
= _SLEEP_OPERATION_INVALID
;
54 static int write_efi_hibernate_location(const HibernationDevice
*hibernation_device
, bool required
) {
55 int log_level
= required
? LOG_ERR
: LOG_DEBUG
;
58 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
59 _cleanup_free_
char *formatted
= NULL
, *id
= NULL
, *image_id
= NULL
,
60 *version_id
= NULL
, *image_version
= NULL
;
61 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
64 struct utsname uts
= {};
65 int r
, log_level_ignore
= required
? LOG_WARNING
: LOG_DEBUG
;
67 assert(hibernation_device
);
70 return log_full_errno(log_level
, SYNTHETIC_ERRNO(EOPNOTSUPP
),
71 "Not an EFI boot, passing HibernateLocation via EFI variable is not possible.");
73 r
= sd_device_new_from_devnum(&device
, 'b', hibernation_device
->devno
);
75 return log_full_errno(log_level
, r
, "Failed to create sd-device object for '%s': %m",
76 hibernation_device
->path
);
78 r
= sd_device_get_property_value(device
, "ID_FS_UUID", &uuid_str
);
80 return log_full_errno(log_level
, r
, "Failed to get filesystem UUID for device '%s': %m",
81 hibernation_device
->path
);
83 r
= sd_id128_from_string(uuid_str
, &uuid
);
85 return log_full_errno(log_level
, r
, "Failed to parse ID_FS_UUID '%s' for device '%s': %m",
86 uuid_str
, hibernation_device
->path
);
89 log_full_errno(log_level_ignore
, errno
, "Failed to get kernel info, ignoring: %m");
91 r
= parse_os_release(NULL
,
93 "IMAGE_ID", &image_id
,
94 "VERSION_ID", &version_id
,
95 "IMAGE_VERSION", &image_version
);
97 log_full_errno(log_level_ignore
, r
, "Failed to parse os-release, ignoring: %m");
99 r
= json_build(&v
, JSON_BUILD_OBJECT(
100 JSON_BUILD_PAIR_UUID("uuid", uuid
),
101 JSON_BUILD_PAIR_UNSIGNED("offset", hibernation_device
->offset
),
102 JSON_BUILD_PAIR_CONDITION(!isempty(uts
.release
), "kernelVersion", JSON_BUILD_STRING(uts
.release
)),
103 JSON_BUILD_PAIR_CONDITION(id
, "osReleaseId", JSON_BUILD_STRING(id
)),
104 JSON_BUILD_PAIR_CONDITION(image_id
, "osReleaseImageId", JSON_BUILD_STRING(image_id
)),
105 JSON_BUILD_PAIR_CONDITION(version_id
, "osReleaseVersionId", JSON_BUILD_STRING(version_id
)),
106 JSON_BUILD_PAIR_CONDITION(image_version
, "osReleaseImageVersion", JSON_BUILD_STRING(image_version
))));
108 return log_full_errno(log_level
, r
, "Failed to build JSON object: %m");
110 r
= json_variant_format(v
, 0, &formatted
);
112 return log_full_errno(log_level
, r
, "Failed to format JSON object: %m");
114 r
= efi_set_variable_string(EFI_SYSTEMD_VARIABLE(HibernateLocation
), formatted
);
116 return log_full_errno(log_level
, r
, "Failed to set EFI variable HibernateLocation: %m");
118 log_debug("Set EFI variable HibernateLocation to '%s'.", formatted
);
121 return log_full_errno(log_level
, SYNTHETIC_ERRNO(EOPNOTSUPP
),
122 "EFI support not enabled, passing HibernateLocation via EFI variable is not possible.");
126 static int write_state(int fd
, char * const *states
) {
132 STRV_FOREACH(state
, states
) {
133 _cleanup_fclose_
FILE *f
= NULL
;
136 k
= fdopen_independent(fd
, "we", &f
);
138 return RET_GATHER(r
, k
);
140 k
= write_string_stream(f
, *state
, WRITE_STRING_FILE_DISABLE_BUFFER
);
142 log_debug("Using sleep state '%s'.", *state
);
146 RET_GATHER(r
, log_debug_errno(k
, "Failed to write '%s' to /sys/power/state: %m", *state
));
152 static int write_mode(char * const *modes
) {
155 STRV_FOREACH(mode
, modes
) {
158 k
= write_string_file("/sys/power/disk", *mode
, WRITE_STRING_FILE_DISABLE_BUFFER
);
160 log_debug("Using sleep disk mode '%s'.", *mode
);
164 RET_GATHER(r
, log_debug_errno(k
, "Failed to write '%s' to /sys/power/disk: %m", *mode
));
170 static int lock_all_homes(void) {
171 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
172 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
173 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
176 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
177 * way the key material required to access these volumes is hopefully removed from memory. */
179 r
= sd_bus_open_system(&bus
);
181 return log_error_errno(r
, "Failed to connect to system bus: %m");
183 r
= bus_message_new_method_call(bus
, &m
, bus_home_mgr
, "LockAllHomes");
185 return bus_log_create_error(r
);
187 /* If homed is not running it can't have any home directories active either. */
188 r
= sd_bus_message_set_auto_start(m
, false);
190 return log_error_errno(r
, "Failed to disable auto-start of LockAllHomes() message: %m");
192 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
, &error
, NULL
);
194 if (!bus_error_is_unknown_service(&error
))
195 return log_error_errno(r
, "Failed to lock home directories: %s", bus_error_message(&error
, r
));
197 log_debug("systemd-homed is not running, locking of home directories skipped.");
199 log_debug("Successfully requested locking of all home directories.");
204 const SleepConfig
*sleep_config
,
205 SleepOperation operation
,
206 const char *action
) {
208 const char *arguments
[] = {
211 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
212 * operation here, not the specific one, in case of s2h. */
213 sleep_operation_to_string(arg_operation
),
216 static const char* const dirs
[] = {
221 _cleanup_(hibernation_device_done
) HibernationDevice hibernation_device
= {};
222 _cleanup_close_
int state_fd
= -EBADF
;
225 assert(sleep_config
);
226 assert(operation
>= 0);
227 assert(operation
< _SLEEP_OPERATION_CONFIG_MAX
); /* Others are handled by execute_s2h() instead */
229 if (strv_isempty(sleep_config
->states
[operation
]))
230 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
231 "No sleep states configured for sleep operation %s, can't sleep.",
232 sleep_operation_to_string(operation
));
234 /* This file is opened first, so that if we hit an error, we can abort before modifying any state. */
235 state_fd
= open("/sys/power/state", O_WRONLY
|O_CLOEXEC
);
239 /* Configure hibernation settings if we are supposed to hibernate */
240 if (sleep_operation_is_hibernation(operation
)) {
243 r
= find_suitable_hibernation_device(&hibernation_device
);
245 return log_error_errno(r
, "Failed to find location to hibernate to: %m");
248 r
= write_efi_hibernate_location(&hibernation_device
, !resume_set
);
250 if (r
== -EOPNOTSUPP
)
251 return log_error_errno(r
, "No valid 'resume=' option found, refusing to hibernate.");
255 r
= write_resume_config(hibernation_device
.devno
, hibernation_device
.offset
, hibernation_device
.path
);
260 r
= write_mode(sleep_config
->modes
[operation
]);
262 log_error_errno(r
, "Failed to write mode to /sys/power/disk: %m");
267 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
268 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
270 action
= sleep_operation_to_string(operation
);
272 if (setenv("SYSTEMD_SLEEP_ACTION", action
, /* overwrite = */ 1) < 0)
273 log_warning_errno(errno
, "Failed to set SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action
);
275 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, (char **) arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
276 (void) lock_all_homes();
279 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR
,
280 LOG_MESSAGE("Performing sleep operation '%s'...", sleep_operation_to_string(operation
)),
281 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
283 r
= write_state(state_fd
, sleep_config
->states
[operation
]);
285 log_struct_errno(LOG_ERR
, r
,
286 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
287 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
288 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
291 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
292 LOG_MESSAGE("System returned from sleep operation '%s'.", sleep_operation_to_string(arg_operation
)),
293 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
295 arguments
[1] = "post";
296 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, (char **) arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
302 if (sleep_operation_is_hibernation(operation
) && is_efi_boot())
303 (void) efi_set_variable(EFI_SYSTEMD_VARIABLE(HibernateLocation
), NULL
, 0);
308 /* Return true if wakeup type is APM timer */
309 static int check_wakeup_type(void) {
310 static const char dmi_object_path
[] = "/sys/firmware/dmi/entries/1-0/raw";
311 uint8_t wakeup_type_byte
, tablesize
;
312 _cleanup_free_
char *buf
= NULL
;
316 /* implementation via dmi/entries */
317 r
= read_full_virtual_file(dmi_object_path
, &buf
, &bufsize
);
319 return log_debug_errno(r
, "Unable to read %s: %m", dmi_object_path
);
321 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
322 "Only read %zu bytes from %s (expected 25)",
323 bufsize
, dmi_object_path
);
325 /* index 1 stores the size of table */
326 tablesize
= (uint8_t) buf
[1];
328 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
329 "Table size less than the index[0x18] where waketype byte is available.");
331 wakeup_type_byte
= (uint8_t) buf
[24];
332 /* 0 is Reserved and 8 is AC Power Restored. As per table 12 in
333 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */
334 if (wakeup_type_byte
>= 128)
335 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Expected value in range 0-127");
337 if (wakeup_type_byte
== 3) {
338 log_debug("DMI BIOS System Information indicates wakeup type is APM Timer");
345 static int custom_timer_suspend(const SleepConfig
*sleep_config
) {
346 usec_t hibernate_timestamp
;
349 assert(sleep_config
);
351 hibernate_timestamp
= usec_add(now(CLOCK_BOOTTIME
), sleep_config
->hibernate_delay_usec
);
353 while (battery_is_discharging_and_low() == 0) {
354 _cleanup_hashmap_free_ Hashmap
*last_capacity
= NULL
, *current_capacity
= NULL
;
355 _cleanup_close_
int tfd
= -EBADF
;
356 struct itimerspec ts
= {};
357 usec_t suspend_interval
;
360 tfd
= timerfd_create(CLOCK_BOOTTIME_ALARM
, TFD_NONBLOCK
|TFD_CLOEXEC
);
362 return log_error_errno(errno
, "Error creating timerfd: %m");
364 /* Store current battery capacity before suspension */
365 r
= fetch_batteries_capacity_by_name(&last_capacity
);
367 return log_error_errno(r
, "Error fetching battery capacity percentage: %m");
369 if (hashmap_isempty(last_capacity
))
370 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
371 suspend_interval
= timestamp_is_set(hibernate_timestamp
)
372 ? sleep_config
->hibernate_delay_usec
: DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY
;
374 r
= get_total_suspend_interval(last_capacity
, &suspend_interval
);
376 log_debug_errno(r
, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
377 /* In case of any errors, especially when we do not know the battery
378 * discharging rate, system suspend interval will be set to
379 * SuspendEstimationSec=. */
380 suspend_interval
= sleep_config
->suspend_estimation_usec
;
384 /* Do not suspend more than HibernateDelaySec= */
385 usec_t before_timestamp
= now(CLOCK_BOOTTIME
);
386 suspend_interval
= MIN(suspend_interval
, usec_sub_unsigned(hibernate_timestamp
, before_timestamp
));
387 if (suspend_interval
<= 0)
388 break; /* system should hibernate */
390 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval
, USEC_PER_SEC
));
391 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
392 timespec_store(&ts
.it_value
, suspend_interval
);
394 if (timerfd_settime(tfd
, 0, &ts
, NULL
) < 0)
395 return log_error_errno(errno
, "Error setting battery estimate timer: %m");
397 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
401 r
= fd_wait_for_event(tfd
, POLLIN
, 0);
403 return log_error_errno(r
, "Error polling timerfd: %m");
404 /* Store fd_wait status */
405 woken_by_timer
= FLAGS_SET(r
, POLLIN
);
407 r
= fetch_batteries_capacity_by_name(¤t_capacity
);
408 if (r
< 0 || hashmap_isempty(current_capacity
)) {
409 /* In case of no battery or error while getting charge level, no need to measure
410 * discharge rate. Instead the system should wake up if it is manual wakeup or
411 * hibernate if this is a timer wakeup. */
413 log_debug_errno(r
, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
415 log_debug("No battery found.");
421 usec_t after_timestamp
= now(CLOCK_BOOTTIME
);
422 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
423 FORMAT_TIMESPAN(after_timestamp
- before_timestamp
, USEC_PER_HOUR
));
425 if (after_timestamp
!= before_timestamp
) {
426 r
= estimate_battery_discharge_rate_per_hour(last_capacity
, current_capacity
, before_timestamp
, after_timestamp
);
428 log_warning_errno(r
, "Failed to estimate and update battery discharge rate, ignoring: %m");
430 log_debug("System woke up too early to estimate discharge rate");
433 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
436 r
= check_wakeup_type();
438 log_debug_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
440 log_debug("wakeup type is APM timer");
441 /* system should hibernate */
449 /* Freeze when invoked and thaw on cleanup */
450 static int freeze_thaw_user_slice(const char **method
) {
451 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
452 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
455 if (!method
|| !*method
)
458 r
= bus_connect_system_systemd(&bus
);
460 return log_debug_errno(r
, "Failed to open connection to systemd: %m");
462 (void) sd_bus_set_method_call_timeout(bus
, FREEZE_TIMEOUT
);
464 r
= bus_call_method(bus
, bus_systemd_mgr
, *method
, &error
, NULL
, "s", SPECIAL_USER_SLICE
);
466 return log_debug_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
471 static int execute_s2h(const SleepConfig
*sleep_config
) {
472 _unused_
_cleanup_(freeze_thaw_user_slice
) const char *auto_method_thaw
= "ThawUnit";
475 assert(sleep_config
);
477 r
= freeze_thaw_user_slice(&(const char*) { "FreezeUnit" });
479 log_debug_errno(r
, "Failed to freeze unit user.slice, ignoring: %m");
481 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
482 * we'll busy poll for the configured interval instead */
483 if (!timestamp_is_set(sleep_config
->hibernate_delay_usec
)) {
484 r
= check_wakeup_type();
486 log_debug_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
488 r
= battery_trip_point_alarm_exists();
490 log_debug_errno(r
, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
493 r
= 0; /* Force fallback path */
495 if (r
> 0) { /* If we have both wakeup alarms and battery trip point support, use them */
496 log_debug("Attempting to suspend...");
497 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
501 r
= check_wakeup_type();
503 return log_debug_errno(r
, "Failed to check hardware wakeup type: %m");
506 /* For APM Timer wakeup, system should hibernate else wakeup */
509 r
= custom_timer_suspend(sleep_config
);
511 return log_debug_errno(r
, "Suspend cycle with manual battery discharge rate estimation failed: %m");
516 /* For above custom timer, if 1 is returned, system will directly hibernate */
518 log_debug("Attempting to hibernate");
519 r
= execute(sleep_config
, SLEEP_HIBERNATE
, NULL
);
521 log_notice("Couldn't hibernate, will try to suspend again.");
523 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hibernate");
531 static int help(void) {
532 _cleanup_free_
char *link
= NULL
;
535 r
= terminal_urlify_man("systemd-suspend.service", "8", &link
);
539 printf("%s COMMAND\n\n"
540 "Suspend the system, hibernate the system, or both.\n\n"
541 " -h --help Show this help and exit\n"
542 " --version Print version string and exit\n"
544 " suspend Suspend the system\n"
545 " hibernate Hibernate the system\n"
546 " hybrid-sleep Both hibernate and suspend the system\n"
547 " suspend-then-hibernate Initially suspend and then hibernate\n"
548 " the system after a fixed period of time or\n"
549 " when battery is low\n"
550 "\nSee the %s for details.\n",
551 program_invocation_short_name
,
557 static int parse_argv(int argc
, char *argv
[]) {
563 static const struct option options
[] = {
564 { "help", no_argument
, NULL
, 'h' },
565 { "version", no_argument
, NULL
, ARG_VERSION
},
574 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
587 assert_not_reached();
591 if (argc
- optind
!= 1)
592 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
594 program_invocation_short_name
);
596 arg_operation
= sleep_operation_from_string(argv
[optind
]);
597 if (arg_operation
< 0)
598 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown command '%s'.", argv
[optind
]);
600 return 1 /* work to do */;
603 static int run(int argc
, char *argv
[]) {
604 _cleanup_(sleep_config_freep
) SleepConfig
*sleep_config
= NULL
;
609 r
= parse_argv(argc
, argv
);
613 r
= parse_sleep_config(&sleep_config
);
617 if (!sleep_config
->allow
[arg_operation
])
618 return log_error_errno(SYNTHETIC_ERRNO(EACCES
),
619 "Sleep operation \"%s\" is disabled by configuration, refusing.",
620 sleep_operation_to_string(arg_operation
));
622 switch (arg_operation
) {
624 case SLEEP_SUSPEND_THEN_HIBERNATE
:
625 r
= execute_s2h(sleep_config
);
628 case SLEEP_HYBRID_SLEEP
:
629 r
= execute(sleep_config
, SLEEP_HYBRID_SLEEP
, NULL
);
631 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
632 * asked us to do both: suspend + hibernate, and it's almost certainly the
633 * hibernation that failed, hence still do the other thing, the suspend. */
635 log_notice_errno(r
, "Couldn't hybrid sleep, will try to suspend instead: %m");
637 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hybrid-sleep");
643 r
= execute(sleep_config
, arg_operation
, NULL
);
651 DEFINE_MAIN_FUNCTION(run
);