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