]>
Commit | Line | Data |
---|---|---|
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 | ||
6edd7d0a | 7 | #include <errno.h> |
ca78ad1d | 8 | #include <fcntl.h> |
19adb8a3 | 9 | #include <getopt.h> |
1bbbefe7 | 10 | #include <poll.h> |
1bbbefe7 | 11 | #include <sys/timerfd.h> |
37f80890 | 12 | #include <sys/types.h> |
90efe8a6 | 13 | #include <sys/utsname.h> |
ca78ad1d | 14 | #include <unistd.h> |
6edd7d0a | 15 | |
f13f91f0 | 16 | #include "sd-bus.h" |
90efe8a6 MY |
17 | #include "sd-device.h" |
18 | #include "sd-id128.h" | |
aa62a893 | 19 | #include "sd-messages.h" |
3f6fd1ba | 20 | |
7d769198 | 21 | #include "battery-capacity.h" |
319c4648 | 22 | #include "battery-util.h" |
d6b4d1c7 | 23 | #include "build.h" |
ba0fb5ac | 24 | #include "bus-error.h" |
f13f91f0 | 25 | #include "bus-locator.h" |
0b958bb3 | 26 | #include "bus-unit-util.h" |
f13f91f0 | 27 | #include "bus-util.h" |
28db6fbf | 28 | #include "constants.h" |
4560d99e | 29 | #include "devnum-util.h" |
90efe8a6 | 30 | #include "efivars.h" |
0b958bb3 | 31 | #include "env-util.h" |
89711996 | 32 | #include "exec-util.h" |
3ffd4af2 | 33 | #include "fd-util.h" |
a5c32cff | 34 | #include "fileio.h" |
ba0fb5ac | 35 | #include "format-util.h" |
54d7fcc6 | 36 | #include "hibernate-util.h" |
90efe8a6 | 37 | #include "id128-util.h" |
0f2d351f | 38 | #include "io-util.h" |
90efe8a6 | 39 | #include "json.h" |
3f6fd1ba | 40 | #include "log.h" |
5e332028 | 41 | #include "main-func.h" |
90efe8a6 | 42 | #include "os-util.h" |
ed698d30 | 43 | #include "parse-util.h" |
294bf0c3 | 44 | #include "pretty-print.h" |
54d7fcc6 | 45 | #include "sleep-config.h" |
f13f91f0 | 46 | #include "special.h" |
c58493c0 | 47 | #include "stdio-util.h" |
07630cea | 48 | #include "string-util.h" |
3f6fd1ba | 49 | #include "strv.h" |
1bbbefe7 | 50 | #include "time-util.h" |
19adb8a3 | 51 | |
f05b4bb9 MY |
52 | #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR) |
53 | ||
c8cd8ca3 | 54 | static SleepOperation arg_operation = _SLEEP_OPERATION_INVALID; |
98dc9d1f | 55 | |
596873c1 | 56 | static int write_efi_hibernate_location(const HibernationDevice *hibernation_device, bool required) { |
03b70f06 | 57 | int log_level = required ? LOG_ERR : LOG_DEBUG; |
90efe8a6 MY |
58 | |
59 | #if ENABLE_EFI | |
60 | _cleanup_(json_variant_unrefp) JsonVariant *v = NULL; | |
61 | _cleanup_free_ char *formatted = NULL, *id = NULL, *image_id = NULL, | |
62 | *version_id = NULL, *image_version = NULL; | |
63 | _cleanup_(sd_device_unrefp) sd_device *device = NULL; | |
64 | const char *uuid_str; | |
65 | sd_id128_t uuid; | |
66 | struct utsname uts = {}; | |
03b70f06 | 67 | int r, log_level_ignore = required ? LOG_WARNING : LOG_DEBUG; |
90efe8a6 | 68 | |
596873c1 | 69 | assert(hibernation_device); |
90efe8a6 MY |
70 | |
71 | if (!is_efi_boot()) | |
7470b807 MY |
72 | return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP), |
73 | "Not an EFI boot, passing HibernateLocation via EFI variable is not possible."); | |
90efe8a6 | 74 | |
596873c1 | 75 | r = sd_device_new_from_devnum(&device, 'b', hibernation_device->devno); |
90efe8a6 MY |
76 | if (r < 0) |
77 | return log_full_errno(log_level, r, "Failed to create sd-device object for '%s': %m", | |
596873c1 | 78 | hibernation_device->path); |
90efe8a6 MY |
79 | |
80 | r = sd_device_get_property_value(device, "ID_FS_UUID", &uuid_str); | |
81 | if (r < 0) | |
82 | return log_full_errno(log_level, r, "Failed to get filesystem UUID for device '%s': %m", | |
596873c1 | 83 | hibernation_device->path); |
90efe8a6 MY |
84 | |
85 | r = sd_id128_from_string(uuid_str, &uuid); | |
86 | if (r < 0) | |
87 | return log_full_errno(log_level, r, "Failed to parse ID_FS_UUID '%s' for device '%s': %m", | |
596873c1 | 88 | uuid_str, hibernation_device->path); |
90efe8a6 MY |
89 | |
90 | if (uname(&uts) < 0) | |
91 | log_full_errno(log_level_ignore, errno, "Failed to get kernel info, ignoring: %m"); | |
92 | ||
93 | r = parse_os_release(NULL, | |
94 | "ID", &id, | |
95 | "IMAGE_ID", &image_id, | |
96 | "VERSION_ID", &version_id, | |
97 | "IMAGE_VERSION", &image_version); | |
98 | if (r < 0) | |
99 | log_full_errno(log_level_ignore, r, "Failed to parse os-release, ignoring: %m"); | |
100 | ||
101 | r = json_build(&v, JSON_BUILD_OBJECT( | |
102 | JSON_BUILD_PAIR_UUID("uuid", uuid), | |
596873c1 | 103 | JSON_BUILD_PAIR_UNSIGNED("offset", hibernation_device->offset), |
90efe8a6 MY |
104 | JSON_BUILD_PAIR_CONDITION(!isempty(uts.release), "kernelVersion", JSON_BUILD_STRING(uts.release)), |
105 | JSON_BUILD_PAIR_CONDITION(id, "osReleaseId", JSON_BUILD_STRING(id)), | |
106 | JSON_BUILD_PAIR_CONDITION(image_id, "osReleaseImageId", JSON_BUILD_STRING(image_id)), | |
107 | JSON_BUILD_PAIR_CONDITION(version_id, "osReleaseVersionId", JSON_BUILD_STRING(version_id)), | |
108 | JSON_BUILD_PAIR_CONDITION(image_version, "osReleaseImageVersion", JSON_BUILD_STRING(image_version)))); | |
109 | if (r < 0) | |
110 | return log_full_errno(log_level, r, "Failed to build JSON object: %m"); | |
111 | ||
112 | r = json_variant_format(v, 0, &formatted); | |
113 | if (r < 0) | |
114 | return log_full_errno(log_level, r, "Failed to format JSON object: %m"); | |
115 | ||
116 | r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(HibernateLocation), formatted); | |
117 | if (r < 0) | |
118 | return log_full_errno(log_level, r, "Failed to set EFI variable HibernateLocation: %m"); | |
119 | ||
120 | log_debug("Set EFI variable HibernateLocation to '%s'.", formatted); | |
7470b807 MY |
121 | return 0; |
122 | #else | |
123 | return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP), | |
124 | "EFI support not enabled, passing HibernateLocation via EFI variable is not possible."); | |
90efe8a6 | 125 | #endif |
90efe8a6 MY |
126 | } |
127 | ||
78c21009 | 128 | static int write_state(int fd, char * const *states) { |
19adb8a3 | 129 | int r = 0; |
19adb8a3 | 130 | |
78c21009 MY |
131 | assert(fd >= 0); |
132 | assert(states); | |
133 | ||
134 | STRV_FOREACH(state, states) { | |
135 | _cleanup_fclose_ FILE *f = NULL; | |
aa62a893 LP |
136 | int k; |
137 | ||
78c21009 MY |
138 | k = fdopen_independent(fd, "we", &f); |
139 | if (k < 0) | |
140 | return RET_GATHER(r, k); | |
141 | ||
142 | k = write_string_stream(f, *state, WRITE_STRING_FILE_DISABLE_BUFFER); | |
143 | if (k >= 0) { | |
144 | log_debug("Using sleep state '%s'.", *state); | |
19adb8a3 | 145 | return 0; |
78c21009 | 146 | } |
aa62a893 | 147 | |
78c21009 | 148 | RET_GATHER(r, log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state)); |
19adb8a3 | 149 | } |
6edd7d0a | 150 | |
19adb8a3 ZJS |
151 | return r; |
152 | } | |
6edd7d0a | 153 | |
b7861283 MY |
154 | static int write_mode(const char *path, char * const *modes) { |
155 | int r, ret = 0; | |
19adb8a3 | 156 | |
b7861283 | 157 | assert(path); |
19adb8a3 | 158 | |
b7861283 MY |
159 | STRV_FOREACH(mode, modes) { |
160 | r = write_string_file(path, *mode, WRITE_STRING_FILE_DISABLE_BUFFER); | |
161 | if (r >= 0) { | |
162 | log_debug("Using sleep mode '%s' for %s.", *mode, path); | |
19adb8a3 | 163 | return 0; |
78c21009 MY |
164 | } |
165 | ||
b7861283 | 166 | RET_GATHER(ret, log_debug_errno(r, "Failed to write '%s' to %s: %m", *mode, path)); |
6edd7d0a LP |
167 | } |
168 | ||
b7861283 | 169 | return ret; |
19adb8a3 | 170 | } |
6edd7d0a | 171 | |
ba0fb5ac LP |
172 | static int lock_all_homes(void) { |
173 | _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; | |
174 | _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; | |
175 | _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; | |
176 | int r; | |
177 | ||
178 | /* Let's synchronously lock all home directories managed by homed that have been marked for it. This | |
179 | * way the key material required to access these volumes is hopefully removed from memory. */ | |
180 | ||
e14348c6 | 181 | r = sd_bus_open_system(&bus); |
ba0fb5ac | 182 | if (r < 0) |
122f6f1e | 183 | return log_error_errno(r, "Failed to connect to system bus: %m"); |
ba0fb5ac | 184 | |
a29f13f2 | 185 | r = bus_message_new_method_call(bus, &m, bus_home_mgr, "LockAllHomes"); |
ba0fb5ac LP |
186 | if (r < 0) |
187 | return bus_log_create_error(r); | |
188 | ||
189 | /* If homed is not running it can't have any home directories active either. */ | |
190 | r = sd_bus_message_set_auto_start(m, false); | |
191 | if (r < 0) | |
192 | return log_error_errno(r, "Failed to disable auto-start of LockAllHomes() message: %m"); | |
193 | ||
194 | r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC, &error, NULL); | |
195 | if (r < 0) { | |
1c5950bd ZJS |
196 | if (!bus_error_is_unknown_service(&error)) |
197 | return log_error_errno(r, "Failed to lock home directories: %s", bus_error_message(&error, r)); | |
ba0fb5ac | 198 | |
75029e15 ZJS |
199 | log_debug("systemd-homed is not running, locking of home directories skipped."); |
200 | } else | |
201 | log_debug("Successfully requested locking of all home directories."); | |
202 | return 0; | |
ba0fb5ac LP |
203 | } |
204 | ||
c8cd8ca3 LP |
205 | static int execute( |
206 | const SleepConfig *sleep_config, | |
207 | SleepOperation operation, | |
208 | const char *action) { | |
209 | ||
cc1c8d12 | 210 | const char *arguments[] = { |
e2cc6eca | 211 | NULL, |
cc1c8d12 | 212 | "pre", |
c8cd8ca3 LP |
213 | /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall |
214 | * operation here, not the specific one, in case of s2h. */ | |
cc1c8d12 | 215 | sleep_operation_to_string(arg_operation), |
e2cc6eca LP |
216 | NULL |
217 | }; | |
b5084605 LP |
218 | static const char* const dirs[] = { |
219 | SYSTEM_SLEEP_PATH, | |
220 | NULL | |
221 | }; | |
e2cc6eca | 222 | |
78c21009 | 223 | _cleanup_close_ int state_fd = -EBADF; |
7bdf56a2 | 224 | int r; |
6524990f | 225 | |
c8cd8ca3 LP |
226 | assert(sleep_config); |
227 | assert(operation >= 0); | |
cc1c8d12 | 228 | assert(operation < _SLEEP_OPERATION_CONFIG_MAX); /* Others are handled by execute_s2h() instead */ |
c8cd8ca3 | 229 | |
cc1c8d12 | 230 | if (strv_isempty(sleep_config->states[operation])) |
c8cd8ca3 LP |
231 | return log_error_errno(SYNTHETIC_ERRNO(EINVAL), |
232 | "No sleep states configured for sleep operation %s, can't sleep.", | |
233 | sleep_operation_to_string(operation)); | |
234 | ||
78c21009 MY |
235 | /* This file is opened first, so that if we hit an error, we can abort before modifying any state. */ |
236 | state_fd = open("/sys/power/state", O_WRONLY|O_CLOEXEC); | |
237 | if (state_fd < 0) | |
032bf2da | 238 | return log_error_errno(errno, "Failed to open /sys/power/state: %m"); |
57512c89 | 239 | |
a2124b35 MY |
240 | if (SLEEP_NEEDS_MEM_SLEEP(sleep_config, operation)) { |
241 | r = write_mode("/sys/power/mem_sleep", sleep_config->mem_modes); | |
242 | if (r < 0) | |
243 | return log_error_errno(r, "Failed to write mode to /sys/power/mem_sleep: %m"); | |
244 | } | |
245 | ||
c02540dc | 246 | /* Configure hibernation settings if we are supposed to hibernate */ |
792dd6f4 | 247 | if (SLEEP_OPERATION_IS_HIBERNATION(operation)) { |
1fe536aa | 248 | _cleanup_(hibernation_device_done) HibernationDevice hibernation_device = {}; |
1923373a MY |
249 | bool resume_set; |
250 | ||
596873c1 | 251 | r = find_suitable_hibernation_device(&hibernation_device); |
17c40b3a | 252 | if (r < 0) |
c02540dc | 253 | return log_error_errno(r, "Failed to find location to hibernate to: %m"); |
1923373a MY |
254 | resume_set = r > 0; |
255 | ||
596873c1 | 256 | r = write_efi_hibernate_location(&hibernation_device, !resume_set); |
1923373a | 257 | if (!resume_set) { |
f1f331a2 FB |
258 | if (r == -EOPNOTSUPP) |
259 | return log_error_errno(r, "No valid 'resume=' option found, refusing to hibernate."); | |
260 | if (r < 0) | |
261 | return r; | |
262 | ||
596873c1 | 263 | r = write_resume_config(hibernation_device.devno, hibernation_device.offset, hibernation_device.path); |
fe33920c | 264 | if (r < 0) |
cc1c8d12 | 265 | goto fail; |
7bdf56a2 | 266 | } |
2002d8cd | 267 | |
b7861283 | 268 | r = write_mode("/sys/power/disk", sleep_config->modes[operation]); |
cc1c8d12 MY |
269 | if (r < 0) { |
270 | log_error_errno(r, "Failed to write mode to /sys/power/disk: %m"); | |
271 | goto fail; | |
272 | } | |
17c40b3a | 273 | } |
19adb8a3 | 274 | |
c8cd8ca3 LP |
275 | /* Pass an action string to the call-outs. This is mostly our operation string, except if the |
276 | * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */ | |
277 | if (!action) | |
278 | action = sleep_operation_to_string(operation); | |
279 | ||
cc1c8d12 MY |
280 | if (setenv("SYSTEMD_SLEEP_ACTION", action, /* overwrite = */ 1) < 0) |
281 | log_warning_errno(errno, "Failed to set SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action); | |
ae463e4e | 282 | |
cc1c8d12 | 283 | (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, (char **) arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS); |
ba0fb5ac | 284 | (void) lock_all_homes(); |
6edd7d0a | 285 | |
19adb8a3 | 286 | log_struct(LOG_INFO, |
2b044526 | 287 | "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR, |
cc1c8d12 | 288 | LOG_MESSAGE("Performing sleep operation '%s'...", sleep_operation_to_string(operation)), |
c8cd8ca3 | 289 | "SLEEP=%s", sleep_operation_to_string(arg_operation)); |
19adb8a3 | 290 | |
cc1c8d12 | 291 | r = write_state(state_fd, sleep_config->states[operation]); |
19adb8a3 | 292 | if (r < 0) |
14250f09 LP |
293 | log_struct_errno(LOG_ERR, r, |
294 | "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR, | |
c8cd8ca3 LP |
295 | LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"), |
296 | "SLEEP=%s", sleep_operation_to_string(arg_operation)); | |
14250f09 LP |
297 | else |
298 | log_struct(LOG_INFO, | |
299 | "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR, | |
cc1c8d12 | 300 | LOG_MESSAGE("System returned from sleep operation '%s'.", sleep_operation_to_string(arg_operation)), |
c8cd8ca3 | 301 | "SLEEP=%s", sleep_operation_to_string(arg_operation)); |
eb267289 | 302 | |
cc1c8d12 MY |
303 | arguments[1] = "post"; |
304 | (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, (char **) arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS); | |
305 | ||
306 | if (r >= 0) | |
307 | return 0; | |
308 | ||
309 | fail: | |
792dd6f4 | 310 | if (SLEEP_OPERATION_IS_HIBERNATION(operation)) |
fbc88824 | 311 | (void) clear_efi_hibernate_location_and_warn(); |
6edd7d0a | 312 | |
19adb8a3 ZJS |
313 | return r; |
314 | } | |
6edd7d0a | 315 | |
cc1c8d12 MY |
316 | /* Return true if wakeup type is APM timer */ |
317 | static int check_wakeup_type(void) { | |
318 | static const char dmi_object_path[] = "/sys/firmware/dmi/entries/1-0/raw"; | |
319 | uint8_t wakeup_type_byte, tablesize; | |
320 | _cleanup_free_ char *buf = NULL; | |
321 | size_t bufsize; | |
322 | int r; | |
323 | ||
324 | /* implementation via dmi/entries */ | |
325 | r = read_full_virtual_file(dmi_object_path, &buf, &bufsize); | |
326 | if (r < 0) | |
327 | return log_debug_errno(r, "Unable to read %s: %m", dmi_object_path); | |
328 | if (bufsize < 25) | |
329 | return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), | |
330 | "Only read %zu bytes from %s (expected 25)", | |
331 | bufsize, dmi_object_path); | |
332 | ||
333 | /* index 1 stores the size of table */ | |
334 | tablesize = (uint8_t) buf[1]; | |
335 | if (tablesize < 25) | |
336 | return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), | |
337 | "Table size less than the index[0x18] where waketype byte is available."); | |
338 | ||
339 | wakeup_type_byte = (uint8_t) buf[24]; | |
340 | /* 0 is Reserved and 8 is AC Power Restored. As per table 12 in | |
341 | * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */ | |
342 | if (wakeup_type_byte >= 128) | |
343 | return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Expected value in range 0-127"); | |
344 | ||
345 | if (wakeup_type_byte == 3) { | |
346 | log_debug("DMI BIOS System Information indicates wakeup type is APM Timer"); | |
347 | return true; | |
348 | } | |
349 | ||
350 | return false; | |
351 | } | |
352 | ||
1afe3d71 | 353 | static int custom_timer_suspend(const SleepConfig *sleep_config) { |
4f58b656 | 354 | usec_t hibernate_timestamp; |
c58493c0 ML |
355 | int r; |
356 | ||
28ca9c24 | 357 | assert(sleep_config); |
c58493c0 | 358 | |
4f58b656 YW |
359 | hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec); |
360 | ||
e0b3a70f | 361 | while (battery_is_discharging_and_low() == 0) { |
de5d8b40 | 362 | _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL; |
254d1313 | 363 | _cleanup_close_ int tfd = -EBADF; |
96d662fa | 364 | struct itimerspec ts = {}; |
2ed56afe | 365 | usec_t suspend_interval; |
96d662fa | 366 | bool woken_by_timer; |
96d662fa SS |
367 | |
368 | tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC); | |
369 | if (tfd < 0) | |
370 | return log_error_errno(errno, "Error creating timerfd: %m"); | |
371 | ||
d812e104 | 372 | /* Store current battery capacity before suspension */ |
746cf898 | 373 | r = fetch_batteries_capacity_by_name(&last_capacity); |
d812e104 | 374 | if (r < 0) |
96d662fa SS |
375 | return log_error_errno(r, "Error fetching battery capacity percentage: %m"); |
376 | ||
4f58b656 YW |
377 | if (hashmap_isempty(last_capacity)) |
378 | /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */ | |
f05b4bb9 MY |
379 | suspend_interval = timestamp_is_set(hibernate_timestamp) |
380 | ? sleep_config->hibernate_delay_usec : DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY; | |
4f58b656 YW |
381 | else { |
382 | r = get_total_suspend_interval(last_capacity, &suspend_interval); | |
383 | if (r < 0) { | |
384 | log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m"); | |
385 | /* In case of any errors, especially when we do not know the battery | |
386 | * discharging rate, system suspend interval will be set to | |
387 | * SuspendEstimationSec=. */ | |
388 | suspend_interval = sleep_config->suspend_estimation_usec; | |
389 | } | |
2ed56afe | 390 | } |
746cf898 | 391 | |
4f58b656 | 392 | /* Do not suspend more than HibernateDelaySec= */ |
d812e104 | 393 | usec_t before_timestamp = now(CLOCK_BOOTTIME); |
4f58b656 YW |
394 | suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp)); |
395 | if (suspend_interval <= 0) | |
396 | break; /* system should hibernate */ | |
d812e104 | 397 | |
96d662fa SS |
398 | log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC)); |
399 | /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */ | |
400 | timespec_store(&ts.it_value, suspend_interval); | |
401 | ||
402 | if (timerfd_settime(tfd, 0, &ts, NULL) < 0) | |
403 | return log_error_errno(errno, "Error setting battery estimate timer: %m"); | |
404 | ||
405 | r = execute(sleep_config, SLEEP_SUSPEND, NULL); | |
406 | if (r < 0) | |
407 | return r; | |
c58493c0 | 408 | |
96d662fa SS |
409 | r = fd_wait_for_event(tfd, POLLIN, 0); |
410 | if (r < 0) | |
411 | return log_error_errno(r, "Error polling timerfd: %m"); | |
412 | /* Store fd_wait status */ | |
413 | woken_by_timer = FLAGS_SET(r, POLLIN); | |
414 | ||
746cf898 | 415 | r = fetch_batteries_capacity_by_name(¤t_capacity); |
d812e104 | 416 | if (r < 0 || hashmap_isempty(current_capacity)) { |
746cf898 | 417 | /* In case of no battery or error while getting charge level, no need to measure |
d812e104 YW |
418 | * discharge rate. Instead the system should wake up if it is manual wakeup or |
419 | * hibernate if this is a timer wakeup. */ | |
420 | if (r < 0) | |
421 | log_debug_errno(r, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m"); | |
422 | else | |
423 | log_debug("No battery found."); | |
746cf898 SS |
424 | if (!woken_by_timer) |
425 | return 0; | |
96d662fa | 426 | break; |
746cf898 | 427 | } |
96d662fa | 428 | |
d812e104 | 429 | usec_t after_timestamp = now(CLOCK_BOOTTIME); |
099810a6 ZJS |
430 | log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep", |
431 | FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_HOUR)); | |
96d662fa | 432 | |
746cf898 SS |
433 | if (after_timestamp != before_timestamp) { |
434 | r = estimate_battery_discharge_rate_per_hour(last_capacity, current_capacity, before_timestamp, after_timestamp); | |
91ea7ebc | 435 | if (r < 0) |
746cf898 SS |
436 | log_warning_errno(r, "Failed to estimate and update battery discharge rate, ignoring: %m"); |
437 | } else | |
b782080b | 438 | log_debug("System woke up too early to estimate discharge rate."); |
c58493c0 | 439 | |
96d662fa SS |
440 | if (!woken_by_timer) |
441 | /* Return as manual wakeup done. This also will return in case battery was charged during suspension */ | |
442 | return 0; | |
1afe3d71 SS |
443 | |
444 | r = check_wakeup_type(); | |
1afe3d71 SS |
445 | if (r > 0) { |
446 | log_debug("wakeup type is APM timer"); | |
447 | /* system should hibernate */ | |
448 | break; | |
449 | } | |
450 | } | |
451 | ||
452 | return 1; | |
453 | } | |
454 | ||
455 | static int execute_s2h(const SleepConfig *sleep_config) { | |
4f58b656 | 456 | int r; |
1afe3d71 SS |
457 | |
458 | assert(sleep_config); | |
459 | ||
4f58b656 YW |
460 | /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case |
461 | * we'll busy poll for the configured interval instead */ | |
462 | if (!timestamp_is_set(sleep_config->hibernate_delay_usec)) { | |
463 | r = check_wakeup_type(); | |
464 | if (r < 0) | |
75d27528 | 465 | log_warning_errno(r, "Failed to check hardware wakeup type, ignoring: %m"); |
4f58b656 YW |
466 | else { |
467 | r = battery_trip_point_alarm_exists(); | |
468 | if (r < 0) | |
75d27528 | 469 | log_warning_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m"); |
4f58b656 YW |
470 | } |
471 | } else | |
472 | r = 0; /* Force fallback path */ | |
1afe3d71 | 473 | |
4f58b656 | 474 | if (r > 0) { /* If we have both wakeup alarms and battery trip point support, use them */ |
1afe3d71 SS |
475 | log_debug("Attempting to suspend..."); |
476 | r = execute(sleep_config, SLEEP_SUSPEND, NULL); | |
477 | if (r < 0) | |
478 | return r; | |
479 | ||
480 | r = check_wakeup_type(); | |
481 | if (r < 0) | |
e7be8651 | 482 | return log_error_errno(r, "Failed to check hardware wakeup type: %m"); |
1afe3d71 SS |
483 | |
484 | if (r == 0) | |
485 | /* For APM Timer wakeup, system should hibernate else wakeup */ | |
486 | return 0; | |
487 | } else { | |
488 | r = custom_timer_suspend(sleep_config); | |
3c3f4601 | 489 | if (r < 0) |
1afe3d71 | 490 | return log_debug_errno(r, "Suspend cycle with manual battery discharge rate estimation failed: %m"); |
3c3f4601 | 491 | if (r == 0) |
1afe3d71 SS |
492 | /* manual wakeup */ |
493 | return 0; | |
96d662fa | 494 | } |
1afe3d71 | 495 | /* For above custom timer, if 1 is returned, system will directly hibernate */ |
28ca9c24 | 496 | |
96d662fa | 497 | log_debug("Attempting to hibernate"); |
c8cd8ca3 | 498 | r = execute(sleep_config, SLEEP_HIBERNATE, NULL); |
f05e1ae6 | 499 | if (r < 0) { |
b0c035e3 | 500 | log_notice("Couldn't hibernate, will try to suspend again."); |
0f2d351f | 501 | |
c8cd8ca3 | 502 | r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hibernate"); |
0f2d351f | 503 | if (r < 0) |
b0c035e3 | 504 | return r; |
f05e1ae6 LP |
505 | } |
506 | ||
507 | return 0; | |
c58493c0 ML |
508 | } |
509 | ||
37ec0fdd LP |
510 | static int help(void) { |
511 | _cleanup_free_ char *link = NULL; | |
512 | int r; | |
513 | ||
514 | r = terminal_urlify_man("systemd-suspend.service", "8", &link); | |
515 | if (r < 0) | |
516 | return log_oom(); | |
517 | ||
19adb8a3 ZJS |
518 | printf("%s COMMAND\n\n" |
519 | "Suspend the system, hibernate the system, or both.\n\n" | |
37ec0fdd LP |
520 | " -h --help Show this help and exit\n" |
521 | " --version Print version string and exit\n" | |
522 | "\nCommands:\n" | |
523 | " suspend Suspend the system\n" | |
524 | " hibernate Hibernate the system\n" | |
525 | " hybrid-sleep Both hibernate and suspend the system\n" | |
e68c79db | 526 | " suspend-then-hibernate Initially suspend and then hibernate\n" |
0374cbd6 MY |
527 | " the system after a fixed period of time or\n" |
528 | " when battery is low\n" | |
bc556335 DDM |
529 | "\nSee the %s for details.\n", |
530 | program_invocation_short_name, | |
531 | link); | |
37ec0fdd LP |
532 | |
533 | return 0; | |
19adb8a3 | 534 | } |
6edd7d0a | 535 | |
19adb8a3 | 536 | static int parse_argv(int argc, char *argv[]) { |
37f80890 | 537 | |
19adb8a3 ZJS |
538 | enum { |
539 | ARG_VERSION = 0x100, | |
540 | }; | |
541 | ||
542 | static const struct option options[] = { | |
543 | { "help", no_argument, NULL, 'h' }, | |
544 | { "version", no_argument, NULL, ARG_VERSION }, | |
eb9da376 | 545 | {} |
19adb8a3 ZJS |
546 | }; |
547 | ||
548 | int c; | |
549 | ||
550 | assert(argc >= 0); | |
551 | assert(argv); | |
552 | ||
601185b4 | 553 | while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) |
79893116 | 554 | switch (c) { |
37f80890 | 555 | |
19adb8a3 | 556 | case 'h': |
37ec0fdd | 557 | return help(); |
19adb8a3 ZJS |
558 | |
559 | case ARG_VERSION: | |
3f6fd1ba | 560 | return version(); |
19adb8a3 ZJS |
561 | |
562 | case '?': | |
563 | return -EINVAL; | |
564 | ||
565 | default: | |
04499a70 | 566 | assert_not_reached(); |
37f80890 | 567 | |
19adb8a3 ZJS |
568 | } |
569 | ||
baaa35ad ZJS |
570 | if (argc - optind != 1) |
571 | return log_error_errno(SYNTHETIC_ERRNO(EINVAL), | |
572 | "Usage: %s COMMAND", | |
573 | program_invocation_short_name); | |
19adb8a3 | 574 | |
c8cd8ca3 LP |
575 | arg_operation = sleep_operation_from_string(argv[optind]); |
576 | if (arg_operation < 0) | |
577 | return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'.", argv[optind]); | |
19adb8a3 ZJS |
578 | |
579 | return 1 /* work to do */; | |
580 | } | |
581 | ||
7caefb81 | 582 | static int run(int argc, char *argv[]) { |
0b958bb3 | 583 | _cleanup_(unit_freezer_done_thaw) UnitFreezer user_slice_freezer = {}; |
087a25d2 | 584 | _cleanup_(sleep_config_freep) SleepConfig *sleep_config = NULL; |
19adb8a3 ZJS |
585 | int r; |
586 | ||
d2acb93d | 587 | log_setup(); |
19adb8a3 ZJS |
588 | |
589 | r = parse_argv(argc, argv); | |
590 | if (r <= 0) | |
7caefb81 | 591 | return r; |
19adb8a3 | 592 | |
28ca9c24 ZS |
593 | r = parse_sleep_config(&sleep_config); |
594 | if (r < 0) | |
595 | return r; | |
596 | ||
c8cd8ca3 | 597 | if (!sleep_config->allow[arg_operation]) |
baaa35ad | 598 | return log_error_errno(SYNTHETIC_ERRNO(EACCES), |
c8cd8ca3 LP |
599 | "Sleep operation \"%s\" is disabled by configuration, refusing.", |
600 | sleep_operation_to_string(arg_operation)); | |
e8f1d00d | 601 | |
0b958bb3 AV |
602 | /* Freeze the user sessions */ |
603 | r = getenv_bool("SYSTEMD_SLEEP_FREEZE_USER_SESSIONS"); | |
604 | if (r < 0 && r != -ENXIO) | |
605 | log_warning_errno(r, "Cannot parse value of $SYSTEMD_SLEEP_FREEZE_USER_SESSIONS, ignoring."); | |
606 | if (r != 0) { | |
607 | r = unit_freezer_new_freeze(SPECIAL_USER_SLICE, &user_slice_freezer); | |
608 | if (r < 0) | |
609 | log_warning_errno(r, "Failed to freeze user sessions, ignoring: %m"); | |
610 | else | |
611 | log_info("Froze user sessions"); | |
612 | } else | |
613 | log_notice("User sessions remain unfrozen on explicit request " | |
614 | "($SYSTEMD_SLEEP_FREEZE_USER_SESSIONS is set to false). This is not recommended, " | |
45df233e | 615 | "and might result in unexpected behavior, particularly in suspend-then-hibernate " |
0b958bb3 AV |
616 | "operations or setups with encrypted home directories."); |
617 | ||
3d132111 LP |
618 | switch (arg_operation) { |
619 | ||
620 | case SLEEP_SUSPEND_THEN_HIBERNATE: | |
621 | r = execute_s2h(sleep_config); | |
622 | break; | |
623 | ||
624 | case SLEEP_HYBRID_SLEEP: | |
625 | r = execute(sleep_config, SLEEP_HYBRID_SLEEP, NULL); | |
626 | if (r < 0) { | |
627 | /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user | |
628 | * asked us to do both: suspend + hibernate, and it's almost certainly the | |
629 | * hibernation that failed, hence still do the other thing, the suspend. */ | |
630 | ||
4706c3ec | 631 | log_notice_errno(r, "Couldn't hybrid sleep, will try to suspend instead: %m"); |
3d132111 LP |
632 | |
633 | r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep"); | |
634 | } | |
635 | ||
636 | break; | |
637 | ||
638 | default: | |
639 | r = execute(sleep_config, arg_operation, NULL); | |
640 | break; | |
37f80890 | 641 | |
3d132111 LP |
642 | } |
643 | ||
644 | return r; | |
6edd7d0a | 645 | } |
7caefb81 ZJS |
646 | |
647 | DEFINE_MAIN_FUNCTION(run); |