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