]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/sleep/sleep.c
meson: downgrade dep on libgcrypt
[thirdparty/systemd.git] / src / sleep / sleep.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
6edd7d0a 2/***
96b2fb93
LP
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
6edd7d0a
LP
5***/
6
ca78ad1d 7#include <fcntl.h>
19adb8a3 8#include <getopt.h>
1bbbefe7 9#include <poll.h>
8857aa74 10#include <stdlib.h>
1bbbefe7 11#include <sys/timerfd.h>
90efe8a6 12#include <sys/utsname.h>
6edd7d0a 13
f13f91f0 14#include "sd-bus.h"
90efe8a6
MY
15#include "sd-device.h"
16#include "sd-id128.h"
309a747f 17#include "sd-json.h"
aa62a893 18#include "sd-messages.h"
3f6fd1ba 19
decad482 20#include "alloc-util.h"
7d769198 21#include "battery-capacity.h"
319c4648 22#include "battery-util.h"
a88ee2c8 23#include "blockdev-util.h"
d6b4d1c7 24#include "build.h"
ba0fb5ac 25#include "bus-error.h"
f13f91f0 26#include "bus-locator.h"
0b958bb3 27#include "bus-unit-util.h"
f13f91f0 28#include "bus-util.h"
28db6fbf 29#include "constants.h"
90efe8a6 30#include "efivars.h"
0b958bb3 31#include "env-util.h"
8857aa74 32#include "errno-util.h"
89711996 33#include "exec-util.h"
3ffd4af2 34#include "fd-util.h"
a5c32cff 35#include "fileio.h"
54d7fcc6 36#include "hibernate-util.h"
0f2d351f 37#include "io-util.h"
3f6fd1ba 38#include "log.h"
5e332028 39#include "main-func.h"
90efe8a6 40#include "os-util.h"
294bf0c3 41#include "pretty-print.h"
54d7fcc6 42#include "sleep-config.h"
f13f91f0 43#include "special.h"
3f6fd1ba 44#include "strv.h"
1bbbefe7 45#include "time-util.h"
19adb8a3 46
f05b4bb9
MY
47#define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
48
c8cd8ca3 49static SleepOperation arg_operation = _SLEEP_OPERATION_INVALID;
98dc9d1f 50
a88ee2c8
MY
51#if ENABLE_EFI
52static 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);
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
596873c1 80static int write_efi_hibernate_location(const HibernationDevice *hibernation_device, bool required) {
03b70f06 81 int log_level = required ? LOG_ERR : LOG_DEBUG;
90efe8a6
MY
82
83#if ENABLE_EFI
309a747f 84 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
90efe8a6
MY
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 = {};
a88ee2c8 91 int r, auto_swap, log_level_ignore = required ? LOG_WARNING : LOG_DEBUG;
90efe8a6 92
596873c1 93 assert(hibernation_device);
90efe8a6
MY
94
95 if (!is_efi_boot())
7470b807
MY
96 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
97 "Not an EFI boot, passing HibernateLocation via EFI variable is not possible.");
90efe8a6 98
596873c1 99 r = sd_device_new_from_devnum(&device, 'b', hibernation_device->devno);
90efe8a6
MY
100 if (r < 0)
101 return log_full_errno(log_level, r, "Failed to create sd-device object for '%s': %m",
596873c1 102 hibernation_device->path);
90efe8a6
MY
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",
596873c1 107 hibernation_device->path);
90efe8a6
MY
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",
596873c1 112 uuid_str, hibernation_device->path);
90efe8a6 113
a88ee2c8
MY
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
90efe8a6
MY
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
be5bee2a
LP
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),
a88ee2c8 134 SD_JSON_BUILD_PAIR_CONDITION(auto_swap >= 0, "autoSwap", SD_JSON_BUILD_BOOLEAN(auto_swap)),
be5bee2a
LP
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)));
90efe8a6
MY
140 if (r < 0)
141 return log_full_errno(log_level, r, "Failed to build JSON object: %m");
142
309a747f 143 r = sd_json_variant_format(v, 0, &formatted);
90efe8a6
MY
144 if (r < 0)
145 return log_full_errno(log_level, r, "Failed to format JSON object: %m");
146
d5c12da9 147 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE_STR("HibernateLocation"), formatted);
90efe8a6
MY
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);
7470b807
MY
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.");
90efe8a6 156#endif
90efe8a6
MY
157}
158
78c21009 159static int write_state(int fd, char * const *states) {
19adb8a3 160 int r = 0;
19adb8a3 161
78c21009
MY
162 assert(fd >= 0);
163 assert(states);
164
165 STRV_FOREACH(state, states) {
166 _cleanup_fclose_ FILE *f = NULL;
aa62a893
LP
167 int k;
168
78c21009
MY
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);
19adb8a3 176 return 0;
78c21009 177 }
aa62a893 178
78c21009 179 RET_GATHER(r, log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state));
19adb8a3 180 }
6edd7d0a 181
19adb8a3
ZJS
182 return r;
183}
6edd7d0a 184
b7861283
MY
185static int write_mode(const char *path, char * const *modes) {
186 int r, ret = 0;
19adb8a3 187
b7861283 188 assert(path);
19adb8a3 189
b7861283
MY
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);
19adb8a3 194 return 0;
78c21009
MY
195 }
196
b7861283 197 RET_GATHER(ret, log_debug_errno(r, "Failed to write '%s' to %s: %m", *mode, path));
6edd7d0a
LP
198 }
199
b7861283 200 return ret;
19adb8a3 201}
6edd7d0a 202
ba0fb5ac
LP
203static 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
e14348c6 212 r = sd_bus_open_system(&bus);
ba0fb5ac 213 if (r < 0)
122f6f1e 214 return log_error_errno(r, "Failed to connect to system bus: %m");
ba0fb5ac 215
a29f13f2 216 r = bus_message_new_method_call(bus, &m, bus_home_mgr, "LockAllHomes");
ba0fb5ac
LP
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) {
1c5950bd
ZJS
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));
ba0fb5ac 229
75029e15
ZJS
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;
ba0fb5ac
LP
234}
235
c8cd8ca3
LP
236static int execute(
237 const SleepConfig *sleep_config,
238 SleepOperation operation,
239 const char *action) {
240
cc1c8d12 241 const char *arguments[] = {
e2cc6eca 242 NULL,
cc1c8d12 243 "pre",
c8cd8ca3
LP
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. */
cc1c8d12 246 sleep_operation_to_string(arg_operation),
e2cc6eca
LP
247 NULL
248 };
b5084605
LP
249 static const char* const dirs[] = {
250 SYSTEM_SLEEP_PATH,
251 NULL
252 };
e2cc6eca 253
78c21009 254 _cleanup_close_ int state_fd = -EBADF;
7bdf56a2 255 int r;
6524990f 256
c8cd8ca3
LP
257 assert(sleep_config);
258 assert(operation >= 0);
cc1c8d12 259 assert(operation < _SLEEP_OPERATION_CONFIG_MAX); /* Others are handled by execute_s2h() instead */
c8cd8ca3 260
cc1c8d12 261 if (strv_isempty(sleep_config->states[operation]))
c8cd8ca3
LP
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));
265
78c21009
MY
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);
268 if (state_fd < 0)
42ba9974 269 return log_error_errno(errno, "Failed to open %s: %m", "/sys/power/state");
57512c89 270
dbef7bcf 271 if (sleep_needs_mem_sleep(sleep_config, operation)) {
a2124b35
MY
272 r = write_mode("/sys/power/mem_sleep", sleep_config->mem_modes);
273 if (r < 0)
274 return log_error_errno(r, "Failed to write mode to /sys/power/mem_sleep: %m");
275 }
276
c02540dc 277 /* Configure hibernation settings if we are supposed to hibernate */
792dd6f4 278 if (SLEEP_OPERATION_IS_HIBERNATION(operation)) {
1fe536aa 279 _cleanup_(hibernation_device_done) HibernationDevice hibernation_device = {};
1923373a
MY
280 bool resume_set;
281
596873c1 282 r = find_suitable_hibernation_device(&hibernation_device);
17c40b3a 283 if (r < 0)
c02540dc 284 return log_error_errno(r, "Failed to find location to hibernate to: %m");
1923373a
MY
285 resume_set = r > 0;
286
596873c1 287 r = write_efi_hibernate_location(&hibernation_device, !resume_set);
1923373a 288 if (!resume_set) {
f1f331a2
FB
289 if (r == -EOPNOTSUPP)
290 return log_error_errno(r, "No valid 'resume=' option found, refusing to hibernate.");
291 if (r < 0)
292 return r;
293
596873c1 294 r = write_resume_config(hibernation_device.devno, hibernation_device.offset, hibernation_device.path);
fe33920c 295 if (r < 0)
cc1c8d12 296 goto fail;
7bdf56a2 297 }
2002d8cd 298
b7861283 299 r = write_mode("/sys/power/disk", sleep_config->modes[operation]);
cc1c8d12
MY
300 if (r < 0) {
301 log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");
302 goto fail;
303 }
17c40b3a 304 }
19adb8a3 305
c8cd8ca3
LP
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. */
308 if (!action)
309 action = sleep_operation_to_string(operation);
310
cc1c8d12
MY
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);
ae463e4e 313
66b2d758
ZJS
314 (void) execute_directories(
315 "system-sleep",
316 dirs,
317 DEFAULT_TIMEOUT_USEC,
318 /* callbacks= */ NULL,
319 /* callback_args= */ NULL,
320 (char **) arguments,
321 /* envp= */ NULL,
322 EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
ba0fb5ac 323 (void) lock_all_homes();
6edd7d0a 324
19adb8a3 325 log_struct(LOG_INFO,
3cf6a3a3 326 LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_START_STR),
cc1c8d12 327 LOG_MESSAGE("Performing sleep operation '%s'...", sleep_operation_to_string(operation)),
3cf6a3a3 328 LOG_ITEM("SLEEP=%s", sleep_operation_to_string(arg_operation)));
19adb8a3 329
cc1c8d12 330 r = write_state(state_fd, sleep_config->states[operation]);
19adb8a3 331 if (r < 0)
14250f09 332 log_struct_errno(LOG_ERR, r,
3cf6a3a3 333 LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_STOP_STR),
c8cd8ca3 334 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
3cf6a3a3 335 LOG_ITEM("SLEEP=%s", sleep_operation_to_string(arg_operation)));
14250f09
LP
336 else
337 log_struct(LOG_INFO,
3cf6a3a3 338 LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_STOP_STR),
cc1c8d12 339 LOG_MESSAGE("System returned from sleep operation '%s'.", sleep_operation_to_string(arg_operation)),
3cf6a3a3 340 LOG_ITEM("SLEEP=%s", sleep_operation_to_string(arg_operation)));
eb267289 341
cc1c8d12 342 arguments[1] = "post";
66b2d758
ZJS
343 (void) execute_directories(
344 "system-sleep",
345 dirs,
346 DEFAULT_TIMEOUT_USEC,
347 /* callbacks= */ NULL,
348 /* callback_args= */ NULL,
349 (char **) arguments,
350 /* envp= */ NULL,
351 EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
cc1c8d12
MY
352 if (r >= 0)
353 return 0;
354
355fail:
792dd6f4 356 if (SLEEP_OPERATION_IS_HIBERNATION(operation))
fbc88824 357 (void) clear_efi_hibernate_location_and_warn();
6edd7d0a 358
19adb8a3
ZJS
359 return r;
360}
6edd7d0a 361
cc1c8d12
MY
362/* Return true if wakeup type is APM timer */
363static int check_wakeup_type(void) {
364 static const char dmi_object_path[] = "/sys/firmware/dmi/entries/1-0/raw";
365 uint8_t wakeup_type_byte, tablesize;
366 _cleanup_free_ char *buf = NULL;
367 size_t bufsize;
368 int r;
369
370 /* implementation via dmi/entries */
371 r = read_full_virtual_file(dmi_object_path, &buf, &bufsize);
372 if (r < 0)
373 return log_debug_errno(r, "Unable to read %s: %m", dmi_object_path);
374 if (bufsize < 25)
375 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
376 "Only read %zu bytes from %s (expected 25)",
377 bufsize, dmi_object_path);
378
379 /* index 1 stores the size of table */
380 tablesize = (uint8_t) buf[1];
381 if (tablesize < 25)
382 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
383 "Table size less than the index[0x18] where waketype byte is available.");
384
385 wakeup_type_byte = (uint8_t) buf[24];
386 /* 0 is Reserved and 8 is AC Power Restored. As per table 12 in
387 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */
388 if (wakeup_type_byte >= 128)
389 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Expected value in range 0-127");
390
391 if (wakeup_type_byte == 3) {
392 log_debug("DMI BIOS System Information indicates wakeup type is APM Timer");
393 return true;
394 }
395
396 return false;
397}
398
1afe3d71 399static int custom_timer_suspend(const SleepConfig *sleep_config) {
4f58b656 400 usec_t hibernate_timestamp;
c58493c0
ML
401 int r;
402
28ca9c24 403 assert(sleep_config);
c58493c0 404
4f58b656
YW
405 hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec);
406
e0b3a70f 407 while (battery_is_discharging_and_low() == 0) {
de5d8b40 408 _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL;
254d1313 409 _cleanup_close_ int tfd = -EBADF;
96d662fa 410 struct itimerspec ts = {};
2ed56afe 411 usec_t suspend_interval;
96d662fa 412 bool woken_by_timer;
96d662fa
SS
413
414 tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC);
415 if (tfd < 0)
416 return log_error_errno(errno, "Error creating timerfd: %m");
417
d812e104 418 /* Store current battery capacity before suspension */
746cf898 419 r = fetch_batteries_capacity_by_name(&last_capacity);
d812e104 420 if (r < 0)
96d662fa
SS
421 return log_error_errno(r, "Error fetching battery capacity percentage: %m");
422
4f58b656
YW
423 if (hashmap_isempty(last_capacity))
424 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
f05b4bb9
MY
425 suspend_interval = timestamp_is_set(hibernate_timestamp)
426 ? sleep_config->hibernate_delay_usec : DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY;
4f58b656
YW
427 else {
428 r = get_total_suspend_interval(last_capacity, &suspend_interval);
429 if (r < 0) {
430 log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
431 /* In case of any errors, especially when we do not know the battery
432 * discharging rate, system suspend interval will be set to
433 * SuspendEstimationSec=. */
434 suspend_interval = sleep_config->suspend_estimation_usec;
435 }
2ed56afe 436 }
746cf898 437
2d00f4c3
MR
438 /* Do not suspend more than HibernateDelaySec= unless HibernateOnACPower=no and currently on AC power */
439 if (!sleep_config->hibernate_on_ac_power) {
440 /* Do not allow "decay" to suspend if the system has no battery. */
441 if (hashmap_isempty(last_capacity))
442 log_once(LOG_WARNING, "HibernateOnACPower=no was ignored because the system does not have a battery.");
443 else if (on_ac_power() > 0)
444 hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec);
445 }
446
d812e104 447 usec_t before_timestamp = now(CLOCK_BOOTTIME);
4f58b656
YW
448 suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp));
449 if (suspend_interval <= 0)
450 break; /* system should hibernate */
d812e104 451
96d662fa
SS
452 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC));
453 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
454 timespec_store(&ts.it_value, suspend_interval);
455
456 if (timerfd_settime(tfd, 0, &ts, NULL) < 0)
457 return log_error_errno(errno, "Error setting battery estimate timer: %m");
458
459 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
460 if (r < 0)
461 return r;
c58493c0 462
96d662fa
SS
463 r = fd_wait_for_event(tfd, POLLIN, 0);
464 if (r < 0)
465 return log_error_errno(r, "Error polling timerfd: %m");
466 /* Store fd_wait status */
467 woken_by_timer = FLAGS_SET(r, POLLIN);
468
746cf898 469 r = fetch_batteries_capacity_by_name(&current_capacity);
d812e104 470 if (r < 0 || hashmap_isempty(current_capacity)) {
746cf898 471 /* In case of no battery or error while getting charge level, no need to measure
d812e104
YW
472 * discharge rate. Instead the system should wake up if it is manual wakeup or
473 * hibernate if this is a timer wakeup. */
474 if (r < 0)
475 log_debug_errno(r, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
476 else
477 log_debug("No battery found.");
746cf898
SS
478 if (!woken_by_timer)
479 return 0;
96d662fa 480 break;
746cf898 481 }
96d662fa 482
d812e104 483 usec_t after_timestamp = now(CLOCK_BOOTTIME);
099810a6
ZJS
484 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
485 FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_HOUR));
96d662fa 486
746cf898
SS
487 if (after_timestamp != before_timestamp) {
488 r = estimate_battery_discharge_rate_per_hour(last_capacity, current_capacity, before_timestamp, after_timestamp);
91ea7ebc 489 if (r < 0)
746cf898
SS
490 log_warning_errno(r, "Failed to estimate and update battery discharge rate, ignoring: %m");
491 } else
b782080b 492 log_debug("System woke up too early to estimate discharge rate.");
c58493c0 493
96d662fa
SS
494 if (!woken_by_timer)
495 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
496 return 0;
1afe3d71
SS
497
498 r = check_wakeup_type();
1afe3d71
SS
499 if (r > 0) {
500 log_debug("wakeup type is APM timer");
501 /* system should hibernate */
502 break;
503 }
504 }
505
506 return 1;
507}
508
509static int execute_s2h(const SleepConfig *sleep_config) {
4f58b656 510 int r;
1afe3d71
SS
511
512 assert(sleep_config);
513
4f58b656
YW
514 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
515 * we'll busy poll for the configured interval instead */
516 if (!timestamp_is_set(sleep_config->hibernate_delay_usec)) {
517 r = check_wakeup_type();
518 if (r < 0)
75d27528 519 log_warning_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
4f58b656
YW
520 else {
521 r = battery_trip_point_alarm_exists();
522 if (r < 0)
75d27528 523 log_warning_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
4f58b656
YW
524 }
525 } else
526 r = 0; /* Force fallback path */
1afe3d71 527
4f58b656 528 if (r > 0) { /* If we have both wakeup alarms and battery trip point support, use them */
1afe3d71
SS
529 log_debug("Attempting to suspend...");
530 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
531 if (r < 0)
532 return r;
533
534 r = check_wakeup_type();
535 if (r < 0)
e7be8651 536 return log_error_errno(r, "Failed to check hardware wakeup type: %m");
1afe3d71
SS
537
538 if (r == 0)
539 /* For APM Timer wakeup, system should hibernate else wakeup */
540 return 0;
541 } else {
542 r = custom_timer_suspend(sleep_config);
3c3f4601 543 if (r < 0)
1afe3d71 544 return log_debug_errno(r, "Suspend cycle with manual battery discharge rate estimation failed: %m");
3c3f4601 545 if (r == 0)
1afe3d71
SS
546 /* manual wakeup */
547 return 0;
96d662fa 548 }
1afe3d71 549 /* For above custom timer, if 1 is returned, system will directly hibernate */
28ca9c24 550
96d662fa 551 log_debug("Attempting to hibernate");
c8cd8ca3 552 r = execute(sleep_config, SLEEP_HIBERNATE, NULL);
f05e1ae6 553 if (r < 0) {
b0c035e3 554 log_notice("Couldn't hibernate, will try to suspend again.");
0f2d351f 555
c8cd8ca3 556 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hibernate");
0f2d351f 557 if (r < 0)
b0c035e3 558 return r;
f05e1ae6
LP
559 }
560
561 return 0;
c58493c0
ML
562}
563
37ec0fdd
LP
564static int help(void) {
565 _cleanup_free_ char *link = NULL;
566 int r;
567
568 r = terminal_urlify_man("systemd-suspend.service", "8", &link);
569 if (r < 0)
570 return log_oom();
571
19adb8a3
ZJS
572 printf("%s COMMAND\n\n"
573 "Suspend the system, hibernate the system, or both.\n\n"
37ec0fdd
LP
574 " -h --help Show this help and exit\n"
575 " --version Print version string and exit\n"
576 "\nCommands:\n"
577 " suspend Suspend the system\n"
578 " hibernate Hibernate the system\n"
579 " hybrid-sleep Both hibernate and suspend the system\n"
e68c79db 580 " suspend-then-hibernate Initially suspend and then hibernate\n"
0374cbd6
MY
581 " the system after a fixed period of time or\n"
582 " when battery is low\n"
bc556335
DDM
583 "\nSee the %s for details.\n",
584 program_invocation_short_name,
585 link);
37ec0fdd
LP
586
587 return 0;
19adb8a3 588}
6edd7d0a 589
19adb8a3 590static int parse_argv(int argc, char *argv[]) {
37f80890 591
19adb8a3
ZJS
592 enum {
593 ARG_VERSION = 0x100,
594 };
595
596 static const struct option options[] = {
597 { "help", no_argument, NULL, 'h' },
598 { "version", no_argument, NULL, ARG_VERSION },
eb9da376 599 {}
19adb8a3
ZJS
600 };
601
602 int c;
603
604 assert(argc >= 0);
605 assert(argv);
606
601185b4 607 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
79893116 608 switch (c) {
37f80890 609
19adb8a3 610 case 'h':
37ec0fdd 611 return help();
19adb8a3
ZJS
612
613 case ARG_VERSION:
3f6fd1ba 614 return version();
19adb8a3
ZJS
615
616 case '?':
617 return -EINVAL;
618
619 default:
04499a70 620 assert_not_reached();
37f80890 621
19adb8a3
ZJS
622 }
623
baaa35ad
ZJS
624 if (argc - optind != 1)
625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
626 "Usage: %s COMMAND",
627 program_invocation_short_name);
19adb8a3 628
c8cd8ca3
LP
629 arg_operation = sleep_operation_from_string(argv[optind]);
630 if (arg_operation < 0)
631 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'.", argv[optind]);
19adb8a3
ZJS
632
633 return 1 /* work to do */;
634}
635
7caefb81 636static int run(int argc, char *argv[]) {
12904d53 637 _cleanup_(unit_freezer_freep) UnitFreezer *user_slice_freezer = NULL;
087a25d2 638 _cleanup_(sleep_config_freep) SleepConfig *sleep_config = NULL;
19adb8a3
ZJS
639 int r;
640
d2acb93d 641 log_setup();
19adb8a3
ZJS
642
643 r = parse_argv(argc, argv);
644 if (r <= 0)
7caefb81 645 return r;
19adb8a3 646
28ca9c24
ZS
647 r = parse_sleep_config(&sleep_config);
648 if (r < 0)
649 return r;
650
c8cd8ca3 651 if (!sleep_config->allow[arg_operation])
baaa35ad 652 return log_error_errno(SYNTHETIC_ERRNO(EACCES),
c8cd8ca3
LP
653 "Sleep operation \"%s\" is disabled by configuration, refusing.",
654 sleep_operation_to_string(arg_operation));
e8f1d00d 655
0b958bb3
AV
656 /* Freeze the user sessions */
657 r = getenv_bool("SYSTEMD_SLEEP_FREEZE_USER_SESSIONS");
658 if (r < 0 && r != -ENXIO)
1b5caddf 659 log_warning_errno(r, "Cannot parse value of $SYSTEMD_SLEEP_FREEZE_USER_SESSIONS, ignoring: %m");
b1ed7e67
MY
660 if (r != 0) {
661 r = unit_freezer_new(SPECIAL_USER_SLICE, &user_slice_freezer);
662 if (r < 0)
663 return r;
664
665 (void) unit_freezer_freeze(user_slice_freezer);
666 } else
61fbc58c
MY
667 log_notice("User sessions remain unfrozen on explicit request ($SYSTEMD_SLEEP_FREEZE_USER_SESSIONS=0).\n"
668 "This is not recommended, and might result in unexpected behavior, particularly\n"
669 "in suspend-then-hibernate operations or setups with encrypted home directories.");
0b958bb3 670
3d132111
LP
671 switch (arg_operation) {
672
673 case SLEEP_SUSPEND_THEN_HIBERNATE:
674 r = execute_s2h(sleep_config);
675 break;
676
677 case SLEEP_HYBRID_SLEEP:
678 r = execute(sleep_config, SLEEP_HYBRID_SLEEP, NULL);
679 if (r < 0) {
680 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
681 * asked us to do both: suspend + hibernate, and it's almost certainly the
682 * hibernation that failed, hence still do the other thing, the suspend. */
683
4706c3ec 684 log_notice_errno(r, "Couldn't hybrid sleep, will try to suspend instead: %m");
3d132111
LP
685
686 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep");
687 }
688
689 break;
690
a9993555
MY
691 case SLEEP_SUSPEND:
692 case SLEEP_HIBERNATE:
3d132111
LP
693 r = execute(sleep_config, arg_operation, NULL);
694 break;
37f80890 695
a9993555
MY
696 default:
697 assert_not_reached();
3d132111
LP
698 }
699
12904d53
MY
700 if (user_slice_freezer)
701 RET_GATHER(r, unit_freezer_thaw(user_slice_freezer));
702
3d132111 703 return r;
6edd7d0a 704}
7caefb81
ZJS
705
706DEFINE_MAIN_FUNCTION(run);