| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
/*** |
| 3 |
Copyright © 2010-2017 Canonical |
| 4 |
Copyright © 2018 Dell Inc. |
| 5 |
***/ |
| 6 |
|
| 7 |
#include <fcntl.h> |
| 8 |
#include <poll.h> |
| 9 |
#include <stdlib.h> |
| 10 |
#include <sys/timerfd.h> |
| 11 |
#include <sys/utsname.h> |
| 12 |
|
| 13 |
#include "sd-bus.h" |
| 14 |
#include "sd-device.h" |
| 15 |
#include "sd-id128.h" |
| 16 |
#include "sd-json.h" |
| 17 |
#include "sd-messages.h" |
| 18 |
|
| 19 |
#include "alloc-util.h" |
| 20 |
#include "battery-capacity.h" |
| 21 |
#include "battery-util.h" |
| 22 |
#include "blockdev-util.h" |
| 23 |
#include "build.h" |
| 24 |
#include "bus-error.h" |
| 25 |
#include "bus-locator.h" |
| 26 |
#include "bus-unit-util.h" |
| 27 |
#include "bus-util.h" |
| 28 |
#include "constants.h" |
| 29 |
#include "efivars.h" |
| 30 |
#include "env-util.h" |
| 31 |
#include "errno-util.h" |
| 32 |
#include "exec-util.h" |
| 33 |
#include "fd-util.h" |
| 34 |
#include "fileio.h" |
| 35 |
#include "format-table.h" |
| 36 |
#include "hibernate-util.h" |
| 37 |
#include "io-util.h" |
| 38 |
#include "log.h" |
| 39 |
#include "main-func.h" |
| 40 |
#include "options.h" |
| 41 |
#include "os-util.h" |
| 42 |
#include "pretty-print.h" |
| 43 |
#include "sleep-config.h" |
| 44 |
#include "special.h" |
| 45 |
#include "strv.h" |
| 46 |
#include "time-util.h" |
| 47 |
#include "verbs.h" |
| 48 |
|
| 49 |
#define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR) |
| 50 |
|
| 51 |
#if ENABLE_EFI |
| 52 |
static int determine_auto_swap(sd_device *device) { |
| 53 |
_cleanup_(sd_device_unrefp) sd_device *origin = NULL; |
| 54 |
const char *part_designator; |
| 55 |
int r; |
| 56 |
|
| 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 |
| 60 |
* this info. */ |
| 61 |
|
| 62 |
assert(device); |
| 63 |
|
| 64 |
r = block_device_get_originating(device, &origin, /* recursive= */ false); |
| 65 |
if (r < 0 && r != -ENOENT) |
| 66 |
return r; |
| 67 |
if (r >= 0) |
| 68 |
device = origin; |
| 69 |
|
| 70 |
r = sd_device_get_property_value(device, "ID_DISSECT_PART_DESIGNATOR", &part_designator); |
| 71 |
if (r == -ENOENT) |
| 72 |
return false; |
| 73 |
if (r < 0) |
| 74 |
return r; |
| 75 |
|
| 76 |
return streq(part_designator, "swap"); |
| 77 |
} |
| 78 |
#endif |
| 79 |
|
| 80 |
static int write_efi_hibernate_location(const HibernationDevice *hibernation_device, bool required) { |
| 81 |
int log_level = required ? LOG_ERR : LOG_DEBUG; |
| 82 |
|
| 83 |
#if ENABLE_EFI |
| 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; |
| 88 |
const char *uuid_str; |
| 89 |
sd_id128_t uuid; |
| 90 |
struct utsname uts = {}; |
| 91 |
int r, auto_swap, log_level_ignore = required ? LOG_WARNING : LOG_DEBUG; |
| 92 |
|
| 93 |
assert(hibernation_device); |
| 94 |
|
| 95 |
if (!is_efi_boot()) |
| 96 |
return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP), |
| 97 |
"Not an EFI boot, passing HibernateLocation via EFI variable is not possible."); |
| 98 |
|
| 99 |
r = sd_device_new_from_devnum(&device, 'b', hibernation_device->devno); |
| 100 |
if (r < 0) |
| 101 |
return log_full_errno(log_level, r, "Failed to create sd-device object for '%s': %m", |
| 102 |
hibernation_device->path); |
| 103 |
|
| 104 |
r = sd_device_get_property_value(device, "ID_FS_UUID", &uuid_str); |
| 105 |
if (r < 0) |
| 106 |
return log_full_errno(log_level, r, "Failed to get filesystem UUID for device '%s': %m", |
| 107 |
hibernation_device->path); |
| 108 |
|
| 109 |
r = sd_id128_from_string(uuid_str, &uuid); |
| 110 |
if (r < 0) |
| 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); |
| 113 |
|
| 114 |
auto_swap = determine_auto_swap(device); |
| 115 |
if (auto_swap < 0) |
| 116 |
log_full_errno(log_level_ignore, auto_swap, |
| 117 |
"Failed to get partition designator of '%s', ignoring: %m", hibernation_device->path); |
| 118 |
|
| 119 |
if (uname(&uts) < 0) |
| 120 |
log_full_errno(log_level_ignore, errno, "Failed to get kernel info, ignoring: %m"); |
| 121 |
|
| 122 |
r = parse_os_release(NULL, |
| 123 |
"ID", &id, |
| 124 |
"IMAGE_ID", &image_id, |
| 125 |
"VERSION_ID", &version_id, |
| 126 |
"IMAGE_VERSION", &image_version); |
| 127 |
if (r < 0) |
| 128 |
log_full_errno(log_level_ignore, r, "Failed to parse os-release, ignoring: %m"); |
| 129 |
|
| 130 |
r = sd_json_buildo( |
| 131 |
&v, |
| 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))); |
| 140 |
if (r < 0) |
| 141 |
return log_full_errno(log_level, r, "Failed to build JSON object: %m"); |
| 142 |
|
| 143 |
r = sd_json_variant_format(v, 0, &formatted); |
| 144 |
if (r < 0) |
| 145 |
return log_full_errno(log_level, r, "Failed to format JSON object: %m"); |
| 146 |
|
| 147 |
r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE_STR("HibernateLocation"), formatted); |
| 148 |
if (r < 0) |
| 149 |
return log_full_errno(log_level, r, "Failed to set EFI variable HibernateLocation: %m"); |
| 150 |
|
| 151 |
log_debug("Set EFI variable HibernateLocation to '%s'.", formatted); |
| 152 |
return 0; |
| 153 |
#else |
| 154 |
return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP), |
| 155 |
"EFI support not enabled, passing HibernateLocation via EFI variable is not possible."); |
| 156 |
#endif |
| 157 |
} |
| 158 |
|
| 159 |
static int write_state(int fd, char * const *states) { |
| 160 |
int r = 0; |
| 161 |
|
| 162 |
assert(fd >= 0); |
| 163 |
assert(states); |
| 164 |
|
| 165 |
STRV_FOREACH(state, states) { |
| 166 |
_cleanup_fclose_ FILE *f = NULL; |
| 167 |
int k; |
| 168 |
|
| 169 |
k = fdopen_independent(fd, "we", &f); |
| 170 |
if (k < 0) |
| 171 |
return RET_GATHER(r, k); |
| 172 |
|
| 173 |
k = write_string_stream(f, *state, WRITE_STRING_FILE_DISABLE_BUFFER); |
| 174 |
if (k >= 0) { |
| 175 |
log_debug("Using sleep state '%s'.", *state); |
| 176 |
return 0; |
| 177 |
} |
| 178 |
|
| 179 |
RET_GATHER(r, log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state)); |
| 180 |
} |
| 181 |
|
| 182 |
return r; |
| 183 |
} |
| 184 |
|
| 185 |
static int write_mode(const char *path, char * const *modes) { |
| 186 |
int r, ret = 0; |
| 187 |
|
| 188 |
assert(path); |
| 189 |
|
| 190 |
STRV_FOREACH(mode, modes) { |
| 191 |
r = write_string_file(path, *mode, WRITE_STRING_FILE_DISABLE_BUFFER); |
| 192 |
if (r >= 0) { |
| 193 |
log_debug("Using sleep mode '%s' for %s.", *mode, path); |
| 194 |
return 0; |
| 195 |
} |
| 196 |
|
| 197 |
RET_GATHER(ret, log_debug_errno(r, "Failed to write '%s' to %s: %m", *mode, path)); |
| 198 |
} |
| 199 |
|
| 200 |
return ret; |
| 201 |
} |
| 202 |
|
| 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; |
| 207 |
int r; |
| 208 |
|
| 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. */ |
| 211 |
|
| 212 |
r = sd_bus_open_system(&bus); |
| 213 |
if (r < 0) |
| 214 |
return log_error_errno(r, "Failed to connect to system bus: %m"); |
| 215 |
|
| 216 |
r = bus_message_new_method_call(bus, &m, bus_home_mgr, "LockAllHomes"); |
| 217 |
if (r < 0) |
| 218 |
return bus_log_create_error(r); |
| 219 |
|
| 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); |
| 222 |
if (r < 0) |
| 223 |
return log_error_errno(r, "Failed to disable auto-start of LockAllHomes() message: %m"); |
| 224 |
|
| 225 |
r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC, &error, NULL); |
| 226 |
if (r < 0) { |
| 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)); |
| 229 |
|
| 230 |
log_debug("systemd-homed is not running, locking of home directories skipped."); |
| 231 |
} else |
| 232 |
log_debug("Successfully requested locking of all home directories."); |
| 233 |
return 0; |
| 234 |
} |
| 235 |
|
| 236 |
static int execute( |
| 237 |
const SleepConfig *sleep_config, |
| 238 |
SleepOperation main_operation, |
| 239 |
SleepOperation operation, |
| 240 |
const char *action) { |
| 241 |
|
| 242 |
const char *arguments[] = { |
| 243 |
NULL, |
| 244 |
"pre", |
| 245 |
/* NB: we use 'main_operation' instead of 'operation' here, as we want to communicate |
| 246 |
* the overall operation here, not the specific one, in case of s2h. */ |
| 247 |
sleep_operation_to_string(main_operation), |
| 248 |
NULL |
| 249 |
}; |
| 250 |
static const char* const dirs[] = { |
| 251 |
SYSTEM_SLEEP_PATH, |
| 252 |
NULL |
| 253 |
}; |
| 254 |
|
| 255 |
_cleanup_close_ int state_fd = -EBADF; |
| 256 |
int r; |
| 257 |
|
| 258 |
assert(sleep_config); |
| 259 |
assert(operation >= 0); |
| 260 |
assert(operation < _SLEEP_OPERATION_CONFIG_MAX); /* Others are handled by execute_s2h() instead */ |
| 261 |
|
| 262 |
if (strv_isempty(sleep_config->states[operation])) |
| 263 |
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), |
| 264 |
"No sleep states configured for sleep operation %s, can't sleep.", |
| 265 |
sleep_operation_to_string(operation)); |
| 266 |
|
| 267 |
/* This file is opened first, so that if we hit an error, we can abort before modifying any state. */ |
| 268 |
state_fd = open("/sys/power/state", O_WRONLY|O_CLOEXEC); |
| 269 |
if (state_fd < 0) |
| 270 |
return log_error_errno(errno, "Failed to open %s: %m", "/sys/power/state"); |
| 271 |
|
| 272 |
if (sleep_needs_mem_sleep(sleep_config, operation)) { |
| 273 |
r = write_mode("/sys/power/mem_sleep", sleep_config->mem_modes); |
| 274 |
if (r < 0) |
| 275 |
return log_error_errno(r, "Failed to write mode to /sys/power/mem_sleep: %m"); |
| 276 |
} |
| 277 |
|
| 278 |
/* Configure hibernation settings if we are supposed to hibernate */ |
| 279 |
if (SLEEP_OPERATION_IS_HIBERNATION(operation)) { |
| 280 |
_cleanup_(hibernation_device_done) HibernationDevice hibernation_device = {}; |
| 281 |
bool resume_set; |
| 282 |
|
| 283 |
r = find_suitable_hibernation_device(&hibernation_device); |
| 284 |
if (r < 0) |
| 285 |
return log_error_errno(r, "Failed to find location to hibernate to: %m"); |
| 286 |
resume_set = r > 0; |
| 287 |
|
| 288 |
r = write_efi_hibernate_location(&hibernation_device, !resume_set); |
| 289 |
if (!resume_set) { |
| 290 |
if (r == -EOPNOTSUPP) |
| 291 |
return log_error_errno(r, "No valid 'resume=' option found, refusing to hibernate."); |
| 292 |
if (r < 0) |
| 293 |
return r; |
| 294 |
|
| 295 |
r = write_resume_config(hibernation_device.devno, hibernation_device.offset, hibernation_device.path); |
| 296 |
if (r < 0) |
| 297 |
goto fail; |
| 298 |
} |
| 299 |
|
| 300 |
r = write_mode("/sys/power/disk", sleep_config->modes[operation]); |
| 301 |
if (r < 0) { |
| 302 |
log_error_errno(r, "Failed to write mode to /sys/power/disk: %m"); |
| 303 |
goto fail; |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
/* Pass an action string to the call-outs. This is mostly our operation string, except if the |
| 308 |
* hibernate step of s-t-h fails, in which case we communicate that with a separate action. */ |
| 309 |
if (!action) |
| 310 |
action = sleep_operation_to_string(operation); |
| 311 |
|
| 312 |
if (setenv("SYSTEMD_SLEEP_ACTION", action, /* overwrite= */ 1) < 0) |
| 313 |
log_warning_errno(errno, "Failed to set SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action); |
| 314 |
|
| 315 |
(void) execute_directories( |
| 316 |
"system-sleep", |
| 317 |
dirs, |
| 318 |
DEFAULT_TIMEOUT_USEC, |
| 319 |
/* callbacks= */ NULL, |
| 320 |
/* callback_args= */ NULL, |
| 321 |
(char **) arguments, |
| 322 |
/* envp= */ NULL, |
| 323 |
EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS); |
| 324 |
(void) lock_all_homes(); |
| 325 |
|
| 326 |
log_struct(LOG_INFO, |
| 327 |
LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_START_STR), |
| 328 |
LOG_MESSAGE("Performing sleep operation '%s'...", sleep_operation_to_string(operation)), |
| 329 |
LOG_ITEM("SLEEP=%s", sleep_operation_to_string(main_operation))); |
| 330 |
|
| 331 |
r = write_state(state_fd, sleep_config->states[operation]); |
| 332 |
if (r < 0) |
| 333 |
log_struct_errno(LOG_ERR, r, |
| 334 |
LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_STOP_STR), |
| 335 |
LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"), |
| 336 |
LOG_ITEM("SLEEP=%s", sleep_operation_to_string(main_operation))); |
| 337 |
else |
| 338 |
log_struct(LOG_INFO, |
| 339 |
LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_STOP_STR), |
| 340 |
LOG_MESSAGE("System returned from sleep operation '%s'.", sleep_operation_to_string(main_operation)), |
| 341 |
LOG_ITEM("SLEEP=%s", sleep_operation_to_string(main_operation))); |
| 342 |
|
| 343 |
arguments[1] = "post"; |
| 344 |
(void) execute_directories( |
| 345 |
"system-sleep", |
| 346 |
dirs, |
| 347 |
DEFAULT_TIMEOUT_USEC, |
| 348 |
/* callbacks= */ NULL, |
| 349 |
/* callback_args= */ NULL, |
| 350 |
(char **) arguments, |
| 351 |
/* envp= */ NULL, |
| 352 |
EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS); |
| 353 |
if (r >= 0) |
| 354 |
return 0; |
| 355 |
|
| 356 |
fail: |
| 357 |
if (SLEEP_OPERATION_IS_HIBERNATION(operation)) |
| 358 |
(void) clear_efi_hibernate_location_and_warn(); |
| 359 |
|
| 360 |
return r; |
| 361 |
} |
| 362 |
|
| 363 |
/* Return true if wakeup type is APM timer */ |
| 364 |
static int check_wakeup_type(void) { |
| 365 |
static const char dmi_object_path[] = "/sys/firmware/dmi/entries/1-0/raw"; |
| 366 |
uint8_t wakeup_type_byte, tablesize; |
| 367 |
_cleanup_free_ char *buf = NULL; |
| 368 |
size_t bufsize; |
| 369 |
int r; |
| 370 |
|
| 371 |
/* implementation via dmi/entries */ |
| 372 |
r = read_full_virtual_file(dmi_object_path, &buf, &bufsize); |
| 373 |
if (r < 0) |
| 374 |
return log_debug_errno(r, "Unable to read %s: %m", dmi_object_path); |
| 375 |
if (bufsize < 25) |
| 376 |
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), |
| 377 |
"Only read %zu bytes from %s (expected 25)", |
| 378 |
bufsize, dmi_object_path); |
| 379 |
|
| 380 |
/* index 1 stores the size of table */ |
| 381 |
tablesize = (uint8_t) buf[1]; |
| 382 |
if (tablesize < 25) |
| 383 |
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), |
| 384 |
"Table size less than the index[0x18] where waketype byte is available."); |
| 385 |
|
| 386 |
wakeup_type_byte = (uint8_t) buf[24]; |
| 387 |
/* 0 is Reserved and 8 is AC Power Restored. As per table 12 in |
| 388 |
* https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */ |
| 389 |
if (wakeup_type_byte >= 128) |
| 390 |
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Expected value in range 0-127"); |
| 391 |
|
| 392 |
if (wakeup_type_byte == 3) { |
| 393 |
log_debug("DMI BIOS System Information indicates wakeup type is APM Timer"); |
| 394 |
return true; |
| 395 |
} |
| 396 |
|
| 397 |
return false; |
| 398 |
} |
| 399 |
|
| 400 |
static int custom_timer_suspend(const SleepConfig *sleep_config, SleepOperation main_operation) { |
| 401 |
usec_t hibernate_timestamp; |
| 402 |
int r; |
| 403 |
|
| 404 |
assert(sleep_config); |
| 405 |
|
| 406 |
hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec); |
| 407 |
|
| 408 |
while (battery_is_discharging_and_low() == 0) { |
| 409 |
_cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL; |
| 410 |
_cleanup_close_ int tfd = -EBADF; |
| 411 |
struct itimerspec ts = {}; |
| 412 |
usec_t suspend_interval; |
| 413 |
bool woken_by_timer; |
| 414 |
|
| 415 |
tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC); |
| 416 |
if (tfd < 0) |
| 417 |
return log_error_errno(errno, "Error creating timerfd: %m"); |
| 418 |
|
| 419 |
/* Store current battery capacity before suspension */ |
| 420 |
r = fetch_batteries_capacity_by_name(&last_capacity); |
| 421 |
if (r < 0) |
| 422 |
return log_error_errno(r, "Error fetching battery capacity percentage: %m"); |
| 423 |
|
| 424 |
if (hashmap_isempty(last_capacity)) |
| 425 |
/* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */ |
| 426 |
suspend_interval = timestamp_is_set(hibernate_timestamp) |
| 427 |
? sleep_config->hibernate_delay_usec : DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY; |
| 428 |
else { |
| 429 |
r = get_total_suspend_interval(last_capacity, &suspend_interval); |
| 430 |
if (r < 0) { |
| 431 |
log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m"); |
| 432 |
/* In case of any errors, especially when we do not know the battery |
| 433 |
* discharging rate, system suspend interval will be set to |
| 434 |
* SuspendEstimationSec=. */ |
| 435 |
suspend_interval = sleep_config->suspend_estimation_usec; |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
/* Do not suspend more than HibernateDelaySec= unless HibernateOnACPower=no and currently on AC power */ |
| 440 |
if (!sleep_config->hibernate_on_ac_power) { |
| 441 |
/* Do not allow "decay" to suspend if the system has no battery. */ |
| 442 |
if (hashmap_isempty(last_capacity)) |
| 443 |
log_once(LOG_WARNING, "HibernateOnACPower=no was ignored because the system does not have a battery."); |
| 444 |
else if (on_ac_power() > 0) |
| 445 |
hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec); |
| 446 |
} |
| 447 |
|
| 448 |
usec_t before_timestamp = now(CLOCK_BOOTTIME); |
| 449 |
suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp)); |
| 450 |
if (suspend_interval <= 0) |
| 451 |
break; /* system should hibernate */ |
| 452 |
|
| 453 |
log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC)); |
| 454 |
/* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */ |
| 455 |
timespec_store(&ts.it_value, suspend_interval); |
| 456 |
|
| 457 |
if (timerfd_settime(tfd, 0, &ts, NULL) < 0) |
| 458 |
return log_error_errno(errno, "Error setting battery estimate timer: %m"); |
| 459 |
|
| 460 |
r = execute(sleep_config, main_operation, SLEEP_SUSPEND, NULL); |
| 461 |
if (r < 0) |
| 462 |
return r; |
| 463 |
|
| 464 |
r = fd_wait_for_event(tfd, POLLIN, 0); |
| 465 |
if (r < 0) |
| 466 |
return log_error_errno(r, "Error polling timerfd: %m"); |
| 467 |
/* Store fd_wait status */ |
| 468 |
woken_by_timer = FLAGS_SET(r, POLLIN); |
| 469 |
|
| 470 |
r = fetch_batteries_capacity_by_name(¤t_capacity); |
| 471 |
if (r < 0 || hashmap_isempty(current_capacity)) { |
| 472 |
/* In case of no battery or error while getting charge level, no need to measure |
| 473 |
* discharge rate. Instead the system should wake up if it is manual wakeup or |
| 474 |
* hibernate if this is a timer wakeup. */ |
| 475 |
if (r < 0) |
| 476 |
log_debug_errno(r, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m"); |
| 477 |
else |
| 478 |
log_debug("No battery found."); |
| 479 |
if (!woken_by_timer) |
| 480 |
return 0; |
| 481 |
break; |
| 482 |
} |
| 483 |
|
| 484 |
usec_t after_timestamp = now(CLOCK_BOOTTIME); |
| 485 |
log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep", |
| 486 |
FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_HOUR)); |
| 487 |
|
| 488 |
if (after_timestamp != before_timestamp) { |
| 489 |
r = estimate_battery_discharge_rate_per_hour(last_capacity, current_capacity, before_timestamp, after_timestamp); |
| 490 |
if (r < 0) |
| 491 |
log_warning_errno(r, "Failed to estimate and update battery discharge rate, ignoring: %m"); |
| 492 |
} else |
| 493 |
log_debug("System woke up too early to estimate discharge rate."); |
| 494 |
|
| 495 |
if (!woken_by_timer) |
| 496 |
/* Return as manual wakeup done. This also will return in case battery was charged during suspension */ |
| 497 |
return 0; |
| 498 |
|
| 499 |
r = check_wakeup_type(); |
| 500 |
if (r > 0) { |
| 501 |
log_debug("wakeup type is APM timer"); |
| 502 |
/* system should hibernate */ |
| 503 |
break; |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
return 1; |
| 508 |
} |
| 509 |
|
| 510 |
static int execute_s2h(const SleepConfig *sleep_config, SleepOperation main_operation) { |
| 511 |
_cleanup_close_ int tfd = -EBADF; |
| 512 |
usec_t hibernate_timestamp = 0; |
| 513 |
int r; |
| 514 |
|
| 515 |
assert(sleep_config); |
| 516 |
|
| 517 |
/* Always check if we have automated battery alarms, regardless of HibernateDelaySec= setting. |
| 518 |
* This allows both low-battery hibernation AND timeout-based hibernation to work together. */ |
| 519 |
r = check_wakeup_type(); |
| 520 |
if (r < 0) |
| 521 |
log_warning_errno(r, "Failed to check hardware wakeup type, ignoring: %m"); |
| 522 |
else { |
| 523 |
r = battery_trip_point_alarm_exists(); |
| 524 |
if (r < 0) |
| 525 |
log_warning_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m"); |
| 526 |
} |
| 527 |
|
| 528 |
if (r > 0) { |
| 529 |
/* We have hardware battery alarm support (ACPI _BTP). If HibernateDelaySec= is also set, |
| 530 |
* set up an RTC alarm so we hibernate on whichever comes first: low battery or timeout. */ |
| 531 |
if (timestamp_is_set(sleep_config->hibernate_delay_usec)) { |
| 532 |
tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC); |
| 533 |
if (tfd < 0) |
| 534 |
return log_error_errno(errno, "Error creating timerfd: %m"); |
| 535 |
|
| 536 |
hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec); |
| 537 |
} |
| 538 |
|
| 539 |
for (;;) { |
| 540 |
if (tfd >= 0) { |
| 541 |
struct itimerspec ts = {}; |
| 542 |
usec_t time_left; |
| 543 |
|
| 544 |
/* Handle HibernateOnACPower=no: reset timer while on AC power */ |
| 545 |
if (!sleep_config->hibernate_on_ac_power && on_ac_power() > 0) { |
| 546 |
log_debug("On AC power with HibernateOnACPower=no, resetting hibernate timer"); |
| 547 |
hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec); |
| 548 |
} |
| 549 |
|
| 550 |
time_left = usec_sub_unsigned(hibernate_timestamp, now(CLOCK_BOOTTIME)); |
| 551 |
if (time_left <= 0) |
| 552 |
break; /* Timer expired, hibernate */ |
| 553 |
|
| 554 |
log_debug("Set timerfd wake alarm for %s", |
| 555 |
FORMAT_TIMESPAN(time_left, USEC_PER_SEC)); |
| 556 |
timespec_store(&ts.it_value, time_left); |
| 557 |
|
| 558 |
if (timerfd_settime(tfd, 0, &ts, NULL) < 0) |
| 559 |
return log_error_errno(errno, "Error setting hibernate delay timer: %m"); |
| 560 |
} |
| 561 |
|
| 562 |
log_debug("Attempting to suspend..."); |
| 563 |
r = execute(sleep_config, main_operation, SLEEP_SUSPEND, NULL); |
| 564 |
if (r < 0) |
| 565 |
return r; |
| 566 |
|
| 567 |
r = check_wakeup_type(); |
| 568 |
if (r < 0) |
| 569 |
return log_error_errno(r, "Failed to check hardware wakeup type: %m"); |
| 570 |
if (r > 0) { |
| 571 |
/* APM Timer wakeup - this means the battery alarm triggered, hibernate */ |
| 572 |
log_debug("Woken by APM Timer (battery low), proceeding to hibernate"); |
| 573 |
break; |
| 574 |
} |
| 575 |
|
| 576 |
if (tfd >= 0) { |
| 577 |
/* Check if our HibernateDelaySec timer fired */ |
| 578 |
r = fd_wait_for_event(tfd, POLLIN, 0); |
| 579 |
if (r < 0) |
| 580 |
return log_error_errno(r, "Error polling timerfd: %m"); |
| 581 |
if (FLAGS_SET(r, POLLIN)) { |
| 582 |
/* Timer fired - but respect HibernateOnACPower setting */ |
| 583 |
if (!sleep_config->hibernate_on_ac_power && on_ac_power() > 0) { |
| 584 |
log_debug("Timer fired but on AC power with HibernateOnACPower=no, continuing suspend"); |
| 585 |
continue; |
| 586 |
} |
| 587 |
log_debug("HibernateDelaySec timeout reached, proceeding to hibernate"); |
| 588 |
break; |
| 589 |
} |
| 590 |
} |
| 591 |
|
| 592 |
/* Manual wakeup - not battery alarm and not timer */ |
| 593 |
return 0; |
| 594 |
} |
| 595 |
} else { |
| 596 |
r = custom_timer_suspend(sleep_config, main_operation); |
| 597 |
if (r < 0) |
| 598 |
return log_debug_errno(r, "Suspend cycle with manual battery discharge rate estimation failed: %m"); |
| 599 |
if (r == 0) |
| 600 |
/* manual wakeup */ |
| 601 |
return 0; |
| 602 |
} |
| 603 |
/* For above custom timer, if 1 is returned, system will directly hibernate */ |
| 604 |
|
| 605 |
log_debug("Attempting to hibernate"); |
| 606 |
r = execute(sleep_config, main_operation, SLEEP_HIBERNATE, NULL); |
| 607 |
if (r < 0) { |
| 608 |
log_notice("Couldn't hibernate, will try to suspend again."); |
| 609 |
|
| 610 |
r = execute(sleep_config, main_operation, SLEEP_SUSPEND, "suspend-after-failed-hibernate"); |
| 611 |
if (r < 0) |
| 612 |
return r; |
| 613 |
} |
| 614 |
|
| 615 |
return 0; |
| 616 |
} |
| 617 |
|
| 618 |
static int help(void) { |
| 619 |
_cleanup_free_ char *link = NULL; |
| 620 |
_cleanup_(table_unrefp) Table *options = NULL, *verbs = NULL; |
| 621 |
int r; |
| 622 |
|
| 623 |
r = terminal_urlify_man("systemd-suspend.service", "8", &link); |
| 624 |
if (r < 0) |
| 625 |
return log_oom(); |
| 626 |
|
| 627 |
r = verbs_get_help_table(&verbs); |
| 628 |
if (r < 0) |
| 629 |
return r; |
| 630 |
|
| 631 |
r = option_parser_get_help_table(&options); |
| 632 |
if (r < 0) |
| 633 |
return r; |
| 634 |
|
| 635 |
(void) table_sync_column_widths(0, verbs, options); |
| 636 |
|
| 637 |
printf("%s [OPTIONS…] COMMAND\n" |
| 638 |
"\n%sSuspend the system, hibernate the system, or both.%s\n" |
| 639 |
"\nCommands:\n", |
| 640 |
program_invocation_short_name, |
| 641 |
ansi_highlight(), |
| 642 |
ansi_normal()); |
| 643 |
|
| 644 |
r = table_print_or_warn(verbs); |
| 645 |
if (r < 0) |
| 646 |
return r; |
| 647 |
|
| 648 |
printf("\nOptions:\n"); |
| 649 |
r = table_print_or_warn(options); |
| 650 |
if (r < 0) |
| 651 |
return r; |
| 652 |
|
| 653 |
printf("\nSee the %s for details.\n", link); |
| 654 |
return 0; |
| 655 |
} |
| 656 |
|
| 657 |
VERB_FULL(verb_operate, "suspend", NULL, VERB_ANY, 1, 0, SLEEP_SUSPEND, |
| 658 |
"Suspend the system"); |
| 659 |
VERB_FULL(verb_operate, "hibernate", NULL, VERB_ANY, 1, 0, SLEEP_HIBERNATE, |
| 660 |
"Hibernate the system"); |
| 661 |
VERB_FULL(verb_operate, "hybrid-sleep", NULL, VERB_ANY, 1, 0, SLEEP_HYBRID_SLEEP, |
| 662 |
"Both hibernate and suspend the system"); |
| 663 |
VERB_FULL(verb_operate, "suspend-then-hibernate", NULL, VERB_ANY, 1, 0, SLEEP_SUSPEND_THEN_HIBERNATE, |
| 664 |
"Initially suspend and then hibernate the system after a fixed period of time or when battery is low"); |
| 665 |
static int verb_operate(int argc, char *argv[], uintptr_t data, void *userdata) { |
| 666 |
_cleanup_(unit_freezer_freep) UnitFreezer *user_slice_freezer = NULL; |
| 667 |
SleepOperation operation = data; |
| 668 |
const SleepConfig *sleep_config = ASSERT_PTR(userdata); |
| 669 |
int r; |
| 670 |
|
| 671 |
assert(0 <= operation && operation < _SLEEP_OPERATION_MAX); |
| 672 |
|
| 673 |
if (!sleep_config->allow[operation]) |
| 674 |
return log_error_errno(SYNTHETIC_ERRNO(EACCES), |
| 675 |
"Sleep operation \"%s\" is disabled by configuration, refusing.", |
| 676 |
sleep_operation_to_string(operation)); |
| 677 |
|
| 678 |
/* Freeze the user sessions */ |
| 679 |
r = getenv_bool("SYSTEMD_SLEEP_FREEZE_USER_SESSIONS"); |
| 680 |
if (r < 0 && r != -ENXIO) |
| 681 |
log_warning_errno(r, "Cannot parse value of $SYSTEMD_SLEEP_FREEZE_USER_SESSIONS, ignoring: %m"); |
| 682 |
if (r != 0) { |
| 683 |
r = unit_freezer_new(SPECIAL_USER_SLICE, &user_slice_freezer); |
| 684 |
if (r < 0) |
| 685 |
return r; |
| 686 |
|
| 687 |
(void) unit_freezer_freeze(user_slice_freezer); |
| 688 |
} else |
| 689 |
log_notice("User sessions remain unfrozen on explicit request ($SYSTEMD_SLEEP_FREEZE_USER_SESSIONS=0).\n" |
| 690 |
"This is not recommended, and might result in unexpected behavior, particularly\n" |
| 691 |
"in suspend-then-hibernate operations or setups with encrypted home directories."); |
| 692 |
|
| 693 |
switch (operation) { |
| 694 |
|
| 695 |
case SLEEP_SUSPEND_THEN_HIBERNATE: |
| 696 |
r = execute_s2h(sleep_config, operation); |
| 697 |
break; |
| 698 |
|
| 699 |
case SLEEP_HYBRID_SLEEP: |
| 700 |
r = execute(sleep_config, operation, SLEEP_HYBRID_SLEEP, NULL); |
| 701 |
if (r < 0) { |
| 702 |
/* If we can't hybrid sleep, then let's try to suspend at least. After all, the user |
| 703 |
* asked us to do both: suspend + hibernate, and it's almost certainly the |
| 704 |
* hibernation that failed, hence still do the other thing, the suspend. */ |
| 705 |
|
| 706 |
log_notice_errno(r, "Couldn't hybrid sleep, will try to suspend instead: %m"); |
| 707 |
|
| 708 |
r = execute(sleep_config, operation, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep"); |
| 709 |
} |
| 710 |
break; |
| 711 |
|
| 712 |
case SLEEP_SUSPEND: |
| 713 |
case SLEEP_HIBERNATE: |
| 714 |
r = execute(sleep_config, operation, operation, NULL); |
| 715 |
break; |
| 716 |
|
| 717 |
default: |
| 718 |
assert_not_reached(); |
| 719 |
} |
| 720 |
|
| 721 |
if (user_slice_freezer) |
| 722 |
RET_GATHER(r, unit_freezer_thaw(user_slice_freezer)); |
| 723 |
|
| 724 |
return r; |
| 725 |
} |
| 726 |
|
| 727 |
static int parse_argv(int argc, char *argv[], char ***ret_args) { |
| 728 |
assert(argc >= 0); |
| 729 |
assert(argv); |
| 730 |
assert(ret_args); |
| 731 |
|
| 732 |
OptionParser opts = { argc, argv }; |
| 733 |
|
| 734 |
FOREACH_OPTION_OR_RETURN(c, &opts) |
| 735 |
switch (c) { |
| 736 |
|
| 737 |
OPTION_COMMON_HELP: |
| 738 |
return help(); |
| 739 |
|
| 740 |
OPTION_COMMON_VERSION: |
| 741 |
return version(); |
| 742 |
} |
| 743 |
|
| 744 |
*ret_args = option_parser_get_args(&opts); |
| 745 |
return 1; |
| 746 |
} |
| 747 |
|
| 748 |
static int run(int argc, char *argv[]) { |
| 749 |
_cleanup_(sleep_config_freep) SleepConfig *sleep_config = NULL; |
| 750 |
char **args = NULL; |
| 751 |
int r; |
| 752 |
|
| 753 |
log_setup(); |
| 754 |
|
| 755 |
r = parse_argv(argc, argv, &args); |
| 756 |
if (r <= 0) |
| 757 |
return r; |
| 758 |
|
| 759 |
r = parse_sleep_config(&sleep_config); |
| 760 |
if (r < 0) |
| 761 |
return r; |
| 762 |
|
| 763 |
return dispatch_verb(args, sleep_config); |
| 764 |
} |
| 765 |
|
| 766 |
DEFINE_MAIN_FUNCTION(run); |