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