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/utsname.h>
15 #include "sd-device.h"
18 #include "sd-messages.h"
20 #include "alloc-util.h"
21 #include "battery-capacity.h"
22 #include "battery-util.h"
23 #include "blockdev-util.h"
25 #include "bus-error.h"
26 #include "bus-locator.h"
27 #include "bus-unit-util.h"
29 #include "constants.h"
32 #include "errno-util.h"
33 #include "exec-util.h"
36 #include "hibernate-util.h"
39 #include "main-func.h"
41 #include "pretty-print.h"
42 #include "sleep-config.h"
45 #include "time-util.h"
47 #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
49 static SleepOperation arg_operation
= _SLEEP_OPERATION_INVALID
;
52 static int determine_auto_swap(sd_device
*device
) {
53 _cleanup_(sd_device_unrefp
) sd_device
*origin
= NULL
;
54 const char *part_designator
;
57 /* Check if the selected hibernation device is the "auto" one. Specifically, trace to the partition
58 * block device and check if ID_DISSECT_PART_DESIGNATOR property is set to "swap" by udev
59 * dissect_image builtin. Later hibernate-resume-generator will generate cryptsetup unit based on
64 r
= block_device_get_originating(device
, &origin
);
65 if (r
< 0 && r
!= -ENOENT
)
70 r
= sd_device_get_property_value(device
, "ID_DISSECT_PART_DESIGNATOR", &part_designator
);
76 return streq(part_designator
, "swap");
80 static int write_efi_hibernate_location(const HibernationDevice
*hibernation_device
, bool required
) {
81 int log_level
= required
? LOG_ERR
: LOG_DEBUG
;
84 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*v
= NULL
;
85 _cleanup_free_
char *formatted
= NULL
, *id
= NULL
, *image_id
= NULL
,
86 *version_id
= NULL
, *image_version
= NULL
;
87 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
90 struct utsname uts
= {};
91 int r
, auto_swap
, log_level_ignore
= required
? LOG_WARNING
: LOG_DEBUG
;
93 assert(hibernation_device
);
96 return log_full_errno(log_level
, SYNTHETIC_ERRNO(EOPNOTSUPP
),
97 "Not an EFI boot, passing HibernateLocation via EFI variable is not possible.");
99 r
= sd_device_new_from_devnum(&device
, 'b', hibernation_device
->devno
);
101 return log_full_errno(log_level
, r
, "Failed to create sd-device object for '%s': %m",
102 hibernation_device
->path
);
104 r
= sd_device_get_property_value(device
, "ID_FS_UUID", &uuid_str
);
106 return log_full_errno(log_level
, r
, "Failed to get filesystem UUID for device '%s': %m",
107 hibernation_device
->path
);
109 r
= sd_id128_from_string(uuid_str
, &uuid
);
111 return log_full_errno(log_level
, r
, "Failed to parse ID_FS_UUID '%s' for device '%s': %m",
112 uuid_str
, hibernation_device
->path
);
114 auto_swap
= determine_auto_swap(device
);
116 log_full_errno(log_level_ignore
, auto_swap
,
117 "Failed to get partition designator of '%s', ignoring: %m", hibernation_device
->path
);
120 log_full_errno(log_level_ignore
, errno
, "Failed to get kernel info, ignoring: %m");
122 r
= parse_os_release(NULL
,
124 "IMAGE_ID", &image_id
,
125 "VERSION_ID", &version_id
,
126 "IMAGE_VERSION", &image_version
);
128 log_full_errno(log_level_ignore
, r
, "Failed to parse os-release, ignoring: %m");
132 SD_JSON_BUILD_PAIR_UUID("uuid", uuid
),
133 SD_JSON_BUILD_PAIR_UNSIGNED("offset", hibernation_device
->offset
),
134 SD_JSON_BUILD_PAIR_CONDITION(auto_swap
>= 0, "autoSwap", SD_JSON_BUILD_BOOLEAN(auto_swap
)),
135 SD_JSON_BUILD_PAIR_CONDITION(!isempty(uts
.release
), "kernelVersion", SD_JSON_BUILD_STRING(uts
.release
)),
136 SD_JSON_BUILD_PAIR_CONDITION(!!id
, "osReleaseId", SD_JSON_BUILD_STRING(id
)),
137 SD_JSON_BUILD_PAIR_CONDITION(!!image_id
, "osReleaseImageId", SD_JSON_BUILD_STRING(image_id
)),
138 SD_JSON_BUILD_PAIR_CONDITION(!!version_id
, "osReleaseVersionId", SD_JSON_BUILD_STRING(version_id
)),
139 SD_JSON_BUILD_PAIR_CONDITION(!!image_version
, "osReleaseImageVersion", SD_JSON_BUILD_STRING(image_version
)));
141 return log_full_errno(log_level
, r
, "Failed to build JSON object: %m");
143 r
= sd_json_variant_format(v
, 0, &formatted
);
145 return log_full_errno(log_level
, r
, "Failed to format JSON object: %m");
147 r
= efi_set_variable_string(EFI_SYSTEMD_VARIABLE_STR("HibernateLocation"), formatted
);
149 return log_full_errno(log_level
, r
, "Failed to set EFI variable HibernateLocation: %m");
151 log_debug("Set EFI variable HibernateLocation to '%s'.", formatted
);
154 return log_full_errno(log_level
, SYNTHETIC_ERRNO(EOPNOTSUPP
),
155 "EFI support not enabled, passing HibernateLocation via EFI variable is not possible.");
159 static int write_state(int fd
, char * const *states
) {
165 STRV_FOREACH(state
, states
) {
166 _cleanup_fclose_
FILE *f
= NULL
;
169 k
= fdopen_independent(fd
, "we", &f
);
171 return RET_GATHER(r
, k
);
173 k
= write_string_stream(f
, *state
, WRITE_STRING_FILE_DISABLE_BUFFER
);
175 log_debug("Using sleep state '%s'.", *state
);
179 RET_GATHER(r
, log_debug_errno(k
, "Failed to write '%s' to /sys/power/state: %m", *state
));
185 static int write_mode(const char *path
, char * const *modes
) {
190 STRV_FOREACH(mode
, modes
) {
191 r
= write_string_file(path
, *mode
, WRITE_STRING_FILE_DISABLE_BUFFER
);
193 log_debug("Using sleep mode '%s' for %s.", *mode
, path
);
197 RET_GATHER(ret
, log_debug_errno(r
, "Failed to write '%s' to %s: %m", *mode
, path
));
203 static int lock_all_homes(void) {
204 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
205 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
206 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
209 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
210 * way the key material required to access these volumes is hopefully removed from memory. */
212 r
= sd_bus_open_system(&bus
);
214 return log_error_errno(r
, "Failed to connect to system bus: %m");
216 r
= bus_message_new_method_call(bus
, &m
, bus_home_mgr
, "LockAllHomes");
218 return bus_log_create_error(r
);
220 /* If homed is not running it can't have any home directories active either. */
221 r
= sd_bus_message_set_auto_start(m
, false);
223 return log_error_errno(r
, "Failed to disable auto-start of LockAllHomes() message: %m");
225 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
, &error
, NULL
);
227 if (!bus_error_is_unknown_service(&error
))
228 return log_error_errno(r
, "Failed to lock home directories: %s", bus_error_message(&error
, r
));
230 log_debug("systemd-homed is not running, locking of home directories skipped.");
232 log_debug("Successfully requested locking of all home directories.");
237 const SleepConfig
*sleep_config
,
238 SleepOperation operation
,
239 const char *action
) {
241 const char *arguments
[] = {
244 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
245 * operation here, not the specific one, in case of s2h. */
246 sleep_operation_to_string(arg_operation
),
249 static const char* const dirs
[] = {
254 _cleanup_close_
int state_fd
= -EBADF
;
257 assert(sleep_config
);
258 assert(operation
>= 0);
259 assert(operation
< _SLEEP_OPERATION_CONFIG_MAX
); /* Others are handled by execute_s2h() instead */
261 if (strv_isempty(sleep_config
->states
[operation
]))
262 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
263 "No sleep states configured for sleep operation %s, can't sleep.",
264 sleep_operation_to_string(operation
));
266 /* This file is opened first, so that if we hit an error, we can abort before modifying any state. */
267 state_fd
= open("/sys/power/state", O_WRONLY
|O_CLOEXEC
);
269 return log_error_errno(errno
, "Failed to open %s: %m", "/sys/power/state");
271 if (sleep_needs_mem_sleep(sleep_config
, operation
)) {
272 r
= write_mode("/sys/power/mem_sleep", sleep_config
->mem_modes
);
274 return log_error_errno(r
, "Failed to write mode to /sys/power/mem_sleep: %m");
277 /* Configure hibernation settings if we are supposed to hibernate */
278 if (SLEEP_OPERATION_IS_HIBERNATION(operation
)) {
279 _cleanup_(hibernation_device_done
) HibernationDevice hibernation_device
= {};
282 r
= find_suitable_hibernation_device(&hibernation_device
);
284 return log_error_errno(r
, "Failed to find location to hibernate to: %m");
287 r
= write_efi_hibernate_location(&hibernation_device
, !resume_set
);
289 if (r
== -EOPNOTSUPP
)
290 return log_error_errno(r
, "No valid 'resume=' option found, refusing to hibernate.");
294 r
= write_resume_config(hibernation_device
.devno
, hibernation_device
.offset
, hibernation_device
.path
);
299 r
= write_mode("/sys/power/disk", sleep_config
->modes
[operation
]);
301 log_error_errno(r
, "Failed to write mode to /sys/power/disk: %m");
306 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
307 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
309 action
= sleep_operation_to_string(operation
);
311 if (setenv("SYSTEMD_SLEEP_ACTION", action
, /* overwrite = */ 1) < 0)
312 log_warning_errno(errno
, "Failed to set SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action
);
314 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, (char **) arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
315 (void) lock_all_homes();
318 LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_START_STR
),
319 LOG_MESSAGE("Performing sleep operation '%s'...", sleep_operation_to_string(operation
)),
320 LOG_ITEM("SLEEP=%s", sleep_operation_to_string(arg_operation
)));
322 r
= write_state(state_fd
, sleep_config
->states
[operation
]);
324 log_struct_errno(LOG_ERR
, r
,
325 LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_STOP_STR
),
326 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
327 LOG_ITEM("SLEEP=%s", sleep_operation_to_string(arg_operation
)));
330 LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_STOP_STR
),
331 LOG_MESSAGE("System returned from sleep operation '%s'.", sleep_operation_to_string(arg_operation
)),
332 LOG_ITEM("SLEEP=%s", sleep_operation_to_string(arg_operation
)));
334 arguments
[1] = "post";
335 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, (char **) arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
341 if (SLEEP_OPERATION_IS_HIBERNATION(operation
))
342 (void) clear_efi_hibernate_location_and_warn();
347 /* Return true if wakeup type is APM timer */
348 static int check_wakeup_type(void) {
349 static const char dmi_object_path
[] = "/sys/firmware/dmi/entries/1-0/raw";
350 uint8_t wakeup_type_byte
, tablesize
;
351 _cleanup_free_
char *buf
= NULL
;
355 /* implementation via dmi/entries */
356 r
= read_full_virtual_file(dmi_object_path
, &buf
, &bufsize
);
358 return log_debug_errno(r
, "Unable to read %s: %m", dmi_object_path
);
360 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
361 "Only read %zu bytes from %s (expected 25)",
362 bufsize
, dmi_object_path
);
364 /* index 1 stores the size of table */
365 tablesize
= (uint8_t) buf
[1];
367 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
368 "Table size less than the index[0x18] where waketype byte is available.");
370 wakeup_type_byte
= (uint8_t) buf
[24];
371 /* 0 is Reserved and 8 is AC Power Restored. As per table 12 in
372 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */
373 if (wakeup_type_byte
>= 128)
374 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Expected value in range 0-127");
376 if (wakeup_type_byte
== 3) {
377 log_debug("DMI BIOS System Information indicates wakeup type is APM Timer");
384 static int custom_timer_suspend(const SleepConfig
*sleep_config
) {
385 usec_t hibernate_timestamp
;
388 assert(sleep_config
);
390 hibernate_timestamp
= usec_add(now(CLOCK_BOOTTIME
), sleep_config
->hibernate_delay_usec
);
392 while (battery_is_discharging_and_low() == 0) {
393 _cleanup_hashmap_free_ Hashmap
*last_capacity
= NULL
, *current_capacity
= NULL
;
394 _cleanup_close_
int tfd
= -EBADF
;
395 struct itimerspec ts
= {};
396 usec_t suspend_interval
;
399 tfd
= timerfd_create(CLOCK_BOOTTIME_ALARM
, TFD_NONBLOCK
|TFD_CLOEXEC
);
401 return log_error_errno(errno
, "Error creating timerfd: %m");
403 /* Store current battery capacity before suspension */
404 r
= fetch_batteries_capacity_by_name(&last_capacity
);
406 return log_error_errno(r
, "Error fetching battery capacity percentage: %m");
408 if (hashmap_isempty(last_capacity
))
409 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
410 suspend_interval
= timestamp_is_set(hibernate_timestamp
)
411 ? sleep_config
->hibernate_delay_usec
: DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY
;
413 r
= get_total_suspend_interval(last_capacity
, &suspend_interval
);
415 log_debug_errno(r
, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
416 /* In case of any errors, especially when we do not know the battery
417 * discharging rate, system suspend interval will be set to
418 * SuspendEstimationSec=. */
419 suspend_interval
= sleep_config
->suspend_estimation_usec
;
423 /* Do not suspend more than HibernateDelaySec= unless HibernateOnACPower=no and currently on AC power */
424 if (!sleep_config
->hibernate_on_ac_power
) {
425 /* Do not allow "decay" to suspend if the system has no battery. */
426 if (hashmap_isempty(last_capacity
))
427 log_once(LOG_WARNING
, "HibernateOnACPower=no was ignored because the system does not have a battery.");
428 else if (on_ac_power() > 0)
429 hibernate_timestamp
= usec_add(now(CLOCK_BOOTTIME
), sleep_config
->hibernate_delay_usec
);
432 usec_t before_timestamp
= now(CLOCK_BOOTTIME
);
433 suspend_interval
= MIN(suspend_interval
, usec_sub_unsigned(hibernate_timestamp
, before_timestamp
));
434 if (suspend_interval
<= 0)
435 break; /* system should hibernate */
437 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval
, USEC_PER_SEC
));
438 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
439 timespec_store(&ts
.it_value
, suspend_interval
);
441 if (timerfd_settime(tfd
, 0, &ts
, NULL
) < 0)
442 return log_error_errno(errno
, "Error setting battery estimate timer: %m");
444 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
448 r
= fd_wait_for_event(tfd
, POLLIN
, 0);
450 return log_error_errno(r
, "Error polling timerfd: %m");
451 /* Store fd_wait status */
452 woken_by_timer
= FLAGS_SET(r
, POLLIN
);
454 r
= fetch_batteries_capacity_by_name(¤t_capacity
);
455 if (r
< 0 || hashmap_isempty(current_capacity
)) {
456 /* In case of no battery or error while getting charge level, no need to measure
457 * discharge rate. Instead the system should wake up if it is manual wakeup or
458 * hibernate if this is a timer wakeup. */
460 log_debug_errno(r
, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
462 log_debug("No battery found.");
468 usec_t after_timestamp
= now(CLOCK_BOOTTIME
);
469 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
470 FORMAT_TIMESPAN(after_timestamp
- before_timestamp
, USEC_PER_HOUR
));
472 if (after_timestamp
!= before_timestamp
) {
473 r
= estimate_battery_discharge_rate_per_hour(last_capacity
, current_capacity
, before_timestamp
, after_timestamp
);
475 log_warning_errno(r
, "Failed to estimate and update battery discharge rate, ignoring: %m");
477 log_debug("System woke up too early to estimate discharge rate.");
480 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
483 r
= check_wakeup_type();
485 log_debug("wakeup type is APM timer");
486 /* system should hibernate */
494 static int execute_s2h(const SleepConfig
*sleep_config
) {
497 assert(sleep_config
);
499 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
500 * we'll busy poll for the configured interval instead */
501 if (!timestamp_is_set(sleep_config
->hibernate_delay_usec
)) {
502 r
= check_wakeup_type();
504 log_warning_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
506 r
= battery_trip_point_alarm_exists();
508 log_warning_errno(r
, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
511 r
= 0; /* Force fallback path */
513 if (r
> 0) { /* If we have both wakeup alarms and battery trip point support, use them */
514 log_debug("Attempting to suspend...");
515 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
519 r
= check_wakeup_type();
521 return log_error_errno(r
, "Failed to check hardware wakeup type: %m");
524 /* For APM Timer wakeup, system should hibernate else wakeup */
527 r
= custom_timer_suspend(sleep_config
);
529 return log_debug_errno(r
, "Suspend cycle with manual battery discharge rate estimation failed: %m");
534 /* For above custom timer, if 1 is returned, system will directly hibernate */
536 log_debug("Attempting to hibernate");
537 r
= execute(sleep_config
, SLEEP_HIBERNATE
, NULL
);
539 log_notice("Couldn't hibernate, will try to suspend again.");
541 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hibernate");
549 static int help(void) {
550 _cleanup_free_
char *link
= NULL
;
553 r
= terminal_urlify_man("systemd-suspend.service", "8", &link
);
557 printf("%s COMMAND\n\n"
558 "Suspend the system, hibernate the system, or both.\n\n"
559 " -h --help Show this help and exit\n"
560 " --version Print version string and exit\n"
562 " suspend Suspend the system\n"
563 " hibernate Hibernate the system\n"
564 " hybrid-sleep Both hibernate and suspend the system\n"
565 " suspend-then-hibernate Initially suspend and then hibernate\n"
566 " the system after a fixed period of time or\n"
567 " when battery is low\n"
568 "\nSee the %s for details.\n",
569 program_invocation_short_name
,
575 static int parse_argv(int argc
, char *argv
[]) {
581 static const struct option options
[] = {
582 { "help", no_argument
, NULL
, 'h' },
583 { "version", no_argument
, NULL
, ARG_VERSION
},
592 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
605 assert_not_reached();
609 if (argc
- optind
!= 1)
610 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
612 program_invocation_short_name
);
614 arg_operation
= sleep_operation_from_string(argv
[optind
]);
615 if (arg_operation
< 0)
616 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown command '%s'.", argv
[optind
]);
618 return 1 /* work to do */;
621 static int run(int argc
, char *argv
[]) {
622 _cleanup_(unit_freezer_freep
) UnitFreezer
*user_slice_freezer
= NULL
;
623 _cleanup_(sleep_config_freep
) SleepConfig
*sleep_config
= NULL
;
628 r
= parse_argv(argc
, argv
);
632 r
= parse_sleep_config(&sleep_config
);
636 if (!sleep_config
->allow
[arg_operation
])
637 return log_error_errno(SYNTHETIC_ERRNO(EACCES
),
638 "Sleep operation \"%s\" is disabled by configuration, refusing.",
639 sleep_operation_to_string(arg_operation
));
641 /* Freeze the user sessions */
642 r
= getenv_bool("SYSTEMD_SLEEP_FREEZE_USER_SESSIONS");
643 if (r
< 0 && r
!= -ENXIO
)
644 log_warning_errno(r
, "Cannot parse value of $SYSTEMD_SLEEP_FREEZE_USER_SESSIONS, ignoring: %m");
646 r
= unit_freezer_new(SPECIAL_USER_SLICE
, &user_slice_freezer
);
650 (void) unit_freezer_freeze(user_slice_freezer
);
652 log_notice("User sessions remain unfrozen on explicit request ($SYSTEMD_SLEEP_FREEZE_USER_SESSIONS=0).\n"
653 "This is not recommended, and might result in unexpected behavior, particularly\n"
654 "in suspend-then-hibernate operations or setups with encrypted home directories.");
656 switch (arg_operation
) {
658 case SLEEP_SUSPEND_THEN_HIBERNATE
:
659 r
= execute_s2h(sleep_config
);
662 case SLEEP_HYBRID_SLEEP
:
663 r
= execute(sleep_config
, SLEEP_HYBRID_SLEEP
, NULL
);
665 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
666 * asked us to do both: suspend + hibernate, and it's almost certainly the
667 * hibernation that failed, hence still do the other thing, the suspend. */
669 log_notice_errno(r
, "Couldn't hybrid sleep, will try to suspend instead: %m");
671 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hybrid-sleep");
677 case SLEEP_HIBERNATE
:
678 r
= execute(sleep_config
, arg_operation
, NULL
);
682 assert_not_reached();
685 if (user_slice_freezer
)
686 RET_GATHER(r
, unit_freezer_thaw(user_slice_freezer
));
691 DEFINE_MAIN_FUNCTION(run
);