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