]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sleep/sleep.c
Merge pull request #28518 from yuwata/fstab-generator-fixes
[thirdparty/systemd.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
5 ***/
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <getopt.h>
10 #include <linux/fiemap.h>
11 #include <poll.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <sys/timerfd.h>
15 #include <sys/utsname.h>
16 #include <unistd.h>
17
18 #include "sd-bus.h"
19 #include "sd-device.h"
20 #include "sd-id128.h"
21 #include "sd-messages.h"
22
23 #include "battery-util.h"
24 #include "btrfs-util.h"
25 #include "build.h"
26 #include "bus-error.h"
27 #include "bus-locator.h"
28 #include "bus-util.h"
29 #include "constants.h"
30 #include "devnum-util.h"
31 #include "efivars.h"
32 #include "exec-util.h"
33 #include "fd-util.h"
34 #include "fileio.h"
35 #include "format-util.h"
36 #include "id128-util.h"
37 #include "io-util.h"
38 #include "json.h"
39 #include "log.h"
40 #include "main-func.h"
41 #include "os-util.h"
42 #include "parse-util.h"
43 #include "pretty-print.h"
44 #include "sleep-util.h"
45 #include "special.h"
46 #include "stdio-util.h"
47 #include "string-util.h"
48 #include "strv.h"
49 #include "time-util.h"
50
51 #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
52
53 static SleepOperation arg_operation = _SLEEP_OPERATION_INVALID;
54
55 static int write_efi_hibernate_location(const HibernateLocation *hibernate_location, bool required) {
56 int log_level = required ? LOG_ERR : LOG_DEBUG;
57
58 #if ENABLE_EFI
59 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
60 _cleanup_free_ char *formatted = NULL, *id = NULL, *image_id = NULL,
61 *version_id = NULL, *image_version = NULL;
62 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
63 const char *uuid_str;
64 sd_id128_t uuid;
65 struct utsname uts = {};
66 int r, log_level_ignore = required ? LOG_WARNING : LOG_DEBUG;
67
68 assert(hibernate_location);
69 assert(hibernate_location->swap);
70
71 if (!is_efi_boot())
72 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
73 "Not an EFI boot, passing HibernateLocation via EFI variable is not possible.");
74
75 r = sd_device_new_from_devnum(&device, 'b', hibernate_location->devno);
76 if (r < 0)
77 return log_full_errno(log_level, r, "Failed to create sd-device object for '%s': %m",
78 hibernate_location->swap->path);
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",
83 hibernate_location->swap->path);
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",
88 uuid_str, hibernate_location->swap->path);
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),
103 JSON_BUILD_PAIR_UNSIGNED("offset", hibernate_location->offset),
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);
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.");
125 #endif
126 }
127
128 static int write_kernel_hibernate_location(const HibernateLocation *hibernate_location) {
129 assert(hibernate_location);
130 assert(hibernate_location->swap);
131 assert(IN_SET(hibernate_location->swap->type, SWAP_BLOCK, SWAP_FILE));
132
133 return write_resume_config(hibernate_location->devno, hibernate_location->offset, hibernate_location->swap->path);
134 }
135
136 static int write_mode(char **modes) {
137 int r = 0;
138
139 STRV_FOREACH(mode, modes) {
140 int k;
141
142 k = write_string_file("/sys/power/disk", *mode, WRITE_STRING_FILE_DISABLE_BUFFER);
143 if (k >= 0)
144 return 0;
145
146 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m", *mode);
147 if (r >= 0)
148 r = k;
149 }
150
151 return r;
152 }
153
154 static int write_state(FILE **f, char **states) {
155 int r = 0;
156
157 assert(f);
158 assert(*f);
159
160 STRV_FOREACH(state, states) {
161 int k;
162
163 k = write_string_stream(*f, *state, WRITE_STRING_FILE_DISABLE_BUFFER);
164 if (k >= 0)
165 return 0;
166 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state);
167 if (r >= 0)
168 r = k;
169
170 fclose(*f);
171 *f = fopen("/sys/power/state", "we");
172 if (!*f)
173 return -errno;
174 }
175
176 return r;
177 }
178
179 static int lock_all_homes(void) {
180 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
181 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
182 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
183 int r;
184
185 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
186 * way the key material required to access these volumes is hopefully removed from memory. */
187
188 r = sd_bus_open_system(&bus);
189 if (r < 0)
190 return log_warning_errno(r, "Failed to connect to system bus, ignoring: %m");
191
192 r = bus_message_new_method_call(bus, &m, bus_home_mgr, "LockAllHomes");
193 if (r < 0)
194 return bus_log_create_error(r);
195
196 /* If homed is not running it can't have any home directories active either. */
197 r = sd_bus_message_set_auto_start(m, false);
198 if (r < 0)
199 return log_error_errno(r, "Failed to disable auto-start of LockAllHomes() message: %m");
200
201 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC, &error, NULL);
202 if (r < 0) {
203 if (!bus_error_is_unknown_service(&error))
204 return log_error_errno(r, "Failed to lock home directories: %s", bus_error_message(&error, r));
205
206 log_debug("systemd-homed is not running, locking of home directories skipped.");
207 } else
208 log_debug("Successfully requested locking of all home directories.");
209 return 0;
210 }
211
212 static int execute(
213 const SleepConfig *sleep_config,
214 SleepOperation operation,
215 const char *action) {
216
217 char *arguments[] = {
218 NULL,
219 (char*) "pre",
220 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
221 * operation here, not the specific one, in case of s2h. */
222 (char*) sleep_operation_to_string(arg_operation),
223 NULL
224 };
225 static const char* const dirs[] = {
226 SYSTEM_SLEEP_PATH,
227 NULL
228 };
229
230 _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
231 _cleanup_fclose_ FILE *f = NULL;
232 char **modes, **states;
233 int r;
234
235 assert(sleep_config);
236 assert(operation >= 0);
237 assert(operation < _SLEEP_OPERATION_MAX);
238 assert(operation != SLEEP_SUSPEND_THEN_HIBERNATE); /* Handled by execute_s2h() instead */
239
240 states = sleep_config->states[operation];
241 modes = sleep_config->modes[operation];
242
243 if (strv_isempty(states))
244 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
245 "No sleep states configured for sleep operation %s, can't sleep.",
246 sleep_operation_to_string(operation));
247
248 /* This file is opened first, so that if we hit an error,
249 * we can abort before modifying any state. */
250 f = fopen("/sys/power/state", "we");
251 if (!f)
252 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
253
254 setvbuf(f, NULL, _IONBF, 0);
255
256 /* Configure hibernation settings if we are supposed to hibernate */
257 if (!strv_isempty(modes)) {
258 bool resume_set;
259
260 r = find_hibernate_location(&hibernate_location);
261 if (r < 0)
262 return log_error_errno(r, "Failed to find location to hibernate to: %m");
263 resume_set = r > 0;
264
265 r = write_efi_hibernate_location(hibernate_location, !resume_set);
266 if (!resume_set) {
267 if (r == -EOPNOTSUPP)
268 return log_error_errno(r, "No valid 'resume=' option found, refusing to hibernate.");
269 if (r < 0)
270 return r;
271
272 r = write_kernel_hibernate_location(hibernate_location);
273 if (r < 0)
274 return log_error_errno(r, "Failed to prepare for hibernation: %m");
275 }
276
277 r = write_mode(modes);
278 if (r < 0)
279 return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");
280 }
281
282 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
283 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
284 if (!action)
285 action = sleep_operation_to_string(operation);
286
287 r = setenv("SYSTEMD_SLEEP_ACTION", action, 1);
288 if (r != 0)
289 log_warning_errno(errno, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action);
290
291 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
292 (void) lock_all_homes();
293
294 log_struct(LOG_INFO,
295 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
296 LOG_MESSAGE("Entering sleep state '%s'...", sleep_operation_to_string(operation)),
297 "SLEEP=%s", sleep_operation_to_string(arg_operation));
298
299 r = write_state(&f, states);
300 if (r < 0)
301 log_struct_errno(LOG_ERR, r,
302 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
303 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
304 "SLEEP=%s", sleep_operation_to_string(arg_operation));
305 else
306 log_struct(LOG_INFO,
307 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
308 LOG_MESSAGE("System returned from sleep state."),
309 "SLEEP=%s", sleep_operation_to_string(arg_operation));
310
311 arguments[1] = (char*) "post";
312 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
313
314 return r;
315 }
316
317 static int custom_timer_suspend(const SleepConfig *sleep_config) {
318 usec_t hibernate_timestamp;
319 int r;
320
321 assert(sleep_config);
322
323 hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec);
324
325 while (battery_is_discharging_and_low() == 0) {
326 _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL;
327 _cleanup_close_ int tfd = -EBADF;
328 struct itimerspec ts = {};
329 usec_t suspend_interval;
330 bool woken_by_timer;
331
332 tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC);
333 if (tfd < 0)
334 return log_error_errno(errno, "Error creating timerfd: %m");
335
336 /* Store current battery capacity before suspension */
337 r = fetch_batteries_capacity_by_name(&last_capacity);
338 if (r < 0)
339 return log_error_errno(r, "Error fetching battery capacity percentage: %m");
340
341 if (hashmap_isempty(last_capacity))
342 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
343 suspend_interval = timestamp_is_set(hibernate_timestamp)
344 ? sleep_config->hibernate_delay_usec : DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY;
345 else {
346 r = get_total_suspend_interval(last_capacity, &suspend_interval);
347 if (r < 0) {
348 log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
349 /* In case of any errors, especially when we do not know the battery
350 * discharging rate, system suspend interval will be set to
351 * SuspendEstimationSec=. */
352 suspend_interval = sleep_config->suspend_estimation_usec;
353 }
354 }
355
356 /* Do not suspend more than HibernateDelaySec= */
357 usec_t before_timestamp = now(CLOCK_BOOTTIME);
358 suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp));
359 if (suspend_interval <= 0)
360 break; /* system should hibernate */
361
362 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC));
363 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
364 timespec_store(&ts.it_value, suspend_interval);
365
366 if (timerfd_settime(tfd, 0, &ts, NULL) < 0)
367 return log_error_errno(errno, "Error setting battery estimate timer: %m");
368
369 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
370 if (r < 0)
371 return r;
372
373 r = fd_wait_for_event(tfd, POLLIN, 0);
374 if (r < 0)
375 return log_error_errno(r, "Error polling timerfd: %m");
376 /* Store fd_wait status */
377 woken_by_timer = FLAGS_SET(r, POLLIN);
378
379 r = fetch_batteries_capacity_by_name(&current_capacity);
380 if (r < 0 || hashmap_isempty(current_capacity)) {
381 /* In case of no battery or error while getting charge level, no need to measure
382 * discharge rate. Instead the system should wake up if it is manual wakeup or
383 * hibernate if this is a timer wakeup. */
384 if (r < 0)
385 log_debug_errno(r, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
386 else
387 log_debug("No battery found.");
388 if (!woken_by_timer)
389 return 0;
390 break;
391 }
392
393 usec_t after_timestamp = now(CLOCK_BOOTTIME);
394 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
395 FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_HOUR));
396
397 if (after_timestamp != before_timestamp) {
398 r = estimate_battery_discharge_rate_per_hour(last_capacity, current_capacity, before_timestamp, after_timestamp);
399 if (r < 0)
400 log_warning_errno(r, "Failed to estimate and update battery discharge rate, ignoring: %m");
401 } else
402 log_debug("System woke up too early to estimate discharge rate");
403
404 if (!woken_by_timer)
405 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
406 return 0;
407
408 r = check_wakeup_type();
409 if (r < 0)
410 log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
411 if (r > 0) {
412 log_debug("wakeup type is APM timer");
413 /* system should hibernate */
414 break;
415 }
416 }
417
418 return 1;
419 }
420
421 /* Freeze when invoked and thaw on cleanup */
422 static int freeze_thaw_user_slice(const char **method) {
423 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
424 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
425 int r;
426
427 if (!method || !*method)
428 return 0;
429
430 r = bus_connect_system_systemd(&bus);
431 if (r < 0)
432 return log_debug_errno(r, "Failed to open connection to systemd: %m");
433
434 (void) sd_bus_set_method_call_timeout(bus, FREEZE_TIMEOUT);
435
436 r = bus_call_method(bus, bus_systemd_mgr, *method, &error, NULL, "s", SPECIAL_USER_SLICE);
437 if (r < 0)
438 return log_debug_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
439
440 return 1;
441 }
442
443 static int execute_s2h(const SleepConfig *sleep_config) {
444 _unused_ _cleanup_(freeze_thaw_user_slice) const char *auto_method_thaw = "ThawUnit";
445 int r;
446
447 assert(sleep_config);
448
449 r = freeze_thaw_user_slice(&(const char*) { "FreezeUnit" });
450 if (r < 0)
451 log_debug_errno(r, "Failed to freeze unit user.slice, ignoring: %m");
452
453 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
454 * we'll busy poll for the configured interval instead */
455 if (!timestamp_is_set(sleep_config->hibernate_delay_usec)) {
456 r = check_wakeup_type();
457 if (r < 0)
458 log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
459 else {
460 r = battery_trip_point_alarm_exists();
461 if (r < 0)
462 log_debug_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
463 }
464 } else
465 r = 0; /* Force fallback path */
466
467 if (r > 0) { /* If we have both wakeup alarms and battery trip point support, use them */
468 log_debug("Attempting to suspend...");
469 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
470 if (r < 0)
471 return r;
472
473 r = check_wakeup_type();
474 if (r < 0)
475 return log_debug_errno(r, "Failed to check hardware wakeup type: %m");
476
477 if (r == 0)
478 /* For APM Timer wakeup, system should hibernate else wakeup */
479 return 0;
480 } else {
481 r = custom_timer_suspend(sleep_config);
482 if (r < 0)
483 return log_debug_errno(r, "Suspend cycle with manual battery discharge rate estimation failed: %m");
484 if (r == 0)
485 /* manual wakeup */
486 return 0;
487 }
488 /* For above custom timer, if 1 is returned, system will directly hibernate */
489
490 log_debug("Attempting to hibernate");
491 r = execute(sleep_config, SLEEP_HIBERNATE, NULL);
492 if (r < 0) {
493 log_notice("Couldn't hibernate, will try to suspend again.");
494
495 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hibernate");
496 if (r < 0)
497 return r;
498 }
499
500 return 0;
501 }
502
503 static int help(void) {
504 _cleanup_free_ char *link = NULL;
505 int r;
506
507 r = terminal_urlify_man("systemd-suspend.service", "8", &link);
508 if (r < 0)
509 return log_oom();
510
511 printf("%s COMMAND\n\n"
512 "Suspend the system, hibernate the system, or both.\n\n"
513 " -h --help Show this help and exit\n"
514 " --version Print version string and exit\n"
515 "\nCommands:\n"
516 " suspend Suspend the system\n"
517 " hibernate Hibernate the system\n"
518 " hybrid-sleep Both hibernate and suspend the system\n"
519 " suspend-then-hibernate Initially suspend and then hibernate\n"
520 " the system after a fixed period of time\n"
521 "\nSee the %s for details.\n",
522 program_invocation_short_name,
523 link);
524
525 return 0;
526 }
527
528 static int parse_argv(int argc, char *argv[]) {
529 enum {
530 ARG_VERSION = 0x100,
531 };
532
533 static const struct option options[] = {
534 { "help", no_argument, NULL, 'h' },
535 { "version", no_argument, NULL, ARG_VERSION },
536 {}
537 };
538
539 int c;
540
541 assert(argc >= 0);
542 assert(argv);
543
544 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
545 switch (c) {
546 case 'h':
547 return help();
548
549 case ARG_VERSION:
550 return version();
551
552 case '?':
553 return -EINVAL;
554
555 default:
556 assert_not_reached();
557 }
558
559 if (argc - optind != 1)
560 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
561 "Usage: %s COMMAND",
562 program_invocation_short_name);
563
564 arg_operation = sleep_operation_from_string(argv[optind]);
565 if (arg_operation < 0)
566 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'.", argv[optind]);
567
568 return 1 /* work to do */;
569 }
570
571 static int run(int argc, char *argv[]) {
572 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
573 int r;
574
575 log_setup();
576
577 r = parse_argv(argc, argv);
578 if (r <= 0)
579 return r;
580
581 r = parse_sleep_config(&sleep_config);
582 if (r < 0)
583 return r;
584
585 if (!sleep_config->allow[arg_operation])
586 return log_error_errno(SYNTHETIC_ERRNO(EACCES),
587 "Sleep operation \"%s\" is disabled by configuration, refusing.",
588 sleep_operation_to_string(arg_operation));
589
590 switch (arg_operation) {
591
592 case SLEEP_SUSPEND_THEN_HIBERNATE:
593 r = execute_s2h(sleep_config);
594 break;
595
596 case SLEEP_HYBRID_SLEEP:
597 r = execute(sleep_config, SLEEP_HYBRID_SLEEP, NULL);
598 if (r < 0) {
599 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
600 * asked us to do both: suspend + hibernate, and it's almost certainly the
601 * hibernation that failed, hence still do the other thing, the suspend. */
602
603 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
604
605 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep");
606 }
607
608 break;
609
610 default:
611 r = execute(sleep_config, arg_operation, NULL);
612 break;
613 }
614
615 return r;
616 }
617
618 DEFINE_MAIN_FUNCTION(run);