]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/sleep-config.c
Merge pull request #10307 from poettering/portable-path
[thirdparty/systemd.git] / src / shared / sleep-config.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright © 2018 Dell Inc.
4 ***/
5
6 #include <errno.h>
7 #include <linux/fs.h>
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/utsname.h>
13 #include <syslog.h>
14 #include <unistd.h>
15
16 #include "sd-id128.h"
17
18 #include "alloc-util.h"
19 #include "bootspec.h"
20 #include "conf-parser.h"
21 #include "def.h"
22 #include "env-util.h"
23 #include "fd-util.h"
24 #include "fileio.h"
25 #include "log.h"
26 #include "macro.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "proc-cmdline.h"
30 #include "sleep-config.h"
31 #include "string-util.h"
32 #include "strv.h"
33
34 int parse_sleep_config(const char *verb, bool *ret_allow, char ***ret_modes, char ***ret_states, usec_t *ret_delay) {
35 int allow_suspend = -1, allow_hibernate = -1,
36 allow_s2h = -1, allow_hybrid_sleep = -1;
37 bool allow;
38 _cleanup_strv_free_ char
39 **suspend_mode = NULL, **suspend_state = NULL,
40 **hibernate_mode = NULL, **hibernate_state = NULL,
41 **hybrid_mode = NULL, **hybrid_state = NULL;
42 _cleanup_strv_free_ char **modes, **states; /* always initialized below */
43 usec_t delay = 180 * USEC_PER_MINUTE;
44
45 const ConfigTableItem items[] = {
46 { "Sleep", "AllowSuspend", config_parse_tristate, 0, &allow_suspend },
47 { "Sleep", "AllowHibernation", config_parse_tristate, 0, &allow_hibernate },
48 { "Sleep", "AllowSuspendThenHibernate", config_parse_tristate, 0, &allow_s2h },
49 { "Sleep", "AllowHybridSleep", config_parse_tristate, 0, &allow_hybrid_sleep },
50
51 { "Sleep", "SuspendMode", config_parse_strv, 0, &suspend_mode },
52 { "Sleep", "SuspendState", config_parse_strv, 0, &suspend_state },
53 { "Sleep", "HibernateMode", config_parse_strv, 0, &hibernate_mode },
54 { "Sleep", "HibernateState", config_parse_strv, 0, &hibernate_state },
55 { "Sleep", "HybridSleepMode", config_parse_strv, 0, &hybrid_mode },
56 { "Sleep", "HybridSleepState", config_parse_strv, 0, &hybrid_state },
57
58 { "Sleep", "HibernateDelaySec", config_parse_sec, 0, &delay},
59 {}
60 };
61
62 (void) config_parse_many_nulstr(PKGSYSCONFDIR "/sleep.conf",
63 CONF_PATHS_NULSTR("systemd/sleep.conf.d"),
64 "Sleep\0", config_item_table_lookup, items,
65 CONFIG_PARSE_WARN, NULL);
66
67 if (streq(verb, "suspend")) {
68 allow = allow_suspend != 0;
69
70 /* empty by default */
71 modes = TAKE_PTR(suspend_mode);
72
73 if (suspend_state)
74 states = TAKE_PTR(suspend_state);
75 else
76 states = strv_new("mem", "standby", "freeze", NULL);
77
78 } else if (streq(verb, "hibernate")) {
79 allow = allow_hibernate != 0;
80
81 if (hibernate_mode)
82 modes = TAKE_PTR(hibernate_mode);
83 else
84 modes = strv_new("platform", "shutdown", NULL);
85
86 if (hibernate_state)
87 states = TAKE_PTR(hibernate_state);
88 else
89 states = strv_new("disk", NULL);
90
91 } else if (streq(verb, "hybrid-sleep")) {
92 allow = allow_hybrid_sleep > 0 ||
93 (allow_suspend != 0 && allow_hibernate != 0);
94
95 if (hybrid_mode)
96 modes = TAKE_PTR(hybrid_mode);
97 else
98 modes = strv_new("suspend", "platform", "shutdown", NULL);
99
100 if (hybrid_state)
101 states = TAKE_PTR(hybrid_state);
102 else
103 states = strv_new("disk", NULL);
104
105 } else if (streq(verb, "suspend-then-hibernate")) {
106 allow = allow_s2h > 0 ||
107 (allow_suspend != 0 && allow_hibernate != 0);
108
109 modes = states = NULL;
110 } else
111 assert_not_reached("what verb");
112
113 if ((!modes && STR_IN_SET(verb, "hibernate", "hybrid-sleep")) ||
114 (!states && !streq(verb, "suspend-then-hibernate")))
115 return log_oom();
116
117 if (ret_allow)
118 *ret_allow = allow;
119 if (ret_modes)
120 *ret_modes = TAKE_PTR(modes);
121 if (ret_states)
122 *ret_states = TAKE_PTR(states);
123 if (ret_delay)
124 *ret_delay = delay;
125
126 return 0;
127 }
128
129 int can_sleep_state(char **types) {
130 char **type;
131 int r;
132 _cleanup_free_ char *p = NULL;
133
134 if (strv_isempty(types))
135 return true;
136
137 /* If /sys is read-only we cannot sleep */
138 if (access("/sys/power/state", W_OK) < 0)
139 return false;
140
141 r = read_one_line_file("/sys/power/state", &p);
142 if (r < 0)
143 return false;
144
145 STRV_FOREACH(type, types) {
146 const char *word, *state;
147 size_t l, k;
148
149 k = strlen(*type);
150 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state)
151 if (l == k && memcmp(word, *type, l) == 0)
152 return true;
153 }
154
155 return false;
156 }
157
158 int can_sleep_disk(char **types) {
159 char **type;
160 int r;
161 _cleanup_free_ char *p = NULL;
162
163 if (strv_isempty(types))
164 return true;
165
166 /* If /sys is read-only we cannot sleep */
167 if (access("/sys/power/disk", W_OK) < 0) {
168 log_debug_errno(errno, "/sys/power/disk is not writable: %m");
169 return false;
170 }
171
172 r = read_one_line_file("/sys/power/disk", &p);
173 if (r < 0) {
174 log_debug_errno(r, "Couldn't read /sys/power/disk: %m");
175 return false;
176 }
177
178 STRV_FOREACH(type, types) {
179 const char *word, *state;
180 size_t l, k;
181
182 k = strlen(*type);
183 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state) {
184 if (l == k && memcmp(word, *type, l) == 0)
185 return true;
186
187 if (l == k + 2 &&
188 word[0] == '[' &&
189 memcmp(word + 1, *type, l - 2) == 0 &&
190 word[l-1] == ']')
191 return true;
192 }
193 }
194
195 return false;
196 }
197
198 #define HIBERNATION_SWAP_THRESHOLD 0.98
199
200 int find_hibernate_location(char **device, char **type, size_t *size, size_t *used) {
201 _cleanup_fclose_ FILE *f;
202 unsigned i;
203
204 f = fopen("/proc/swaps", "re");
205 if (!f) {
206 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
207 "Failed to retrieve open /proc/swaps: %m");
208 assert(errno > 0);
209 return -errno;
210 }
211
212 (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
213
214 for (i = 1;; i++) {
215 _cleanup_free_ char *dev_field = NULL, *type_field = NULL;
216 size_t size_field, used_field;
217 int k;
218
219 k = fscanf(f,
220 "%ms " /* device/file */
221 "%ms " /* type of swap */
222 "%zu " /* swap size */
223 "%zu " /* used */
224 "%*i\n", /* priority */
225 &dev_field, &type_field, &size_field, &used_field);
226 if (k == EOF)
227 break;
228 if (k != 4) {
229 log_warning("Failed to parse /proc/swaps:%u", i);
230 continue;
231 }
232
233 if (streq(type_field, "file")) {
234
235 if (endswith(dev_field, "\\040(deleted)")) {
236 log_warning("Ignoring deleted swap file '%s'.", dev_field);
237 continue;
238 }
239
240 } else if (streq(type_field, "partition")) {
241 const char *fn;
242
243 fn = path_startswith(dev_field, "/dev/");
244 if (fn && startswith(fn, "zram")) {
245 log_debug("Ignoring compressed RAM swap device '%s'.", dev_field);
246 continue;
247 }
248 }
249
250 if (device)
251 *device = TAKE_PTR(dev_field);
252 if (type)
253 *type = TAKE_PTR(type_field);
254 if (size)
255 *size = size_field;
256 if (used)
257 *used = used_field;
258 return 0;
259 }
260
261 log_debug("No swap partitions were found.");
262 return -ENOSYS;
263 }
264
265 static bool enough_swap_for_hibernation(void) {
266 _cleanup_free_ char *active = NULL;
267 unsigned long long act = 0;
268 size_t size = 0, used = 0;
269 int r;
270
271 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
272 return true;
273
274 r = find_hibernate_location(NULL, NULL, &size, &used);
275 if (r < 0)
276 return false;
277
278 r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
279 if (r < 0) {
280 log_debug_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
281 return false;
282 }
283
284 r = safe_atollu(active, &act);
285 if (r < 0) {
286 log_debug_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active);
287 return false;
288 }
289
290 r = act <= (size - used) * HIBERNATION_SWAP_THRESHOLD;
291 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%zu kB, used=%zu kB, threshold=%.2g%%",
292 r ? "Enough" : "Not enough", act, size, used, 100*HIBERNATION_SWAP_THRESHOLD);
293
294 return r;
295 }
296
297 static int check_resume_keys(const char *key, const char *value, void *data) {
298 assert_se(key);
299 assert_se(data);
300
301 int *resume = data;
302
303 if (*resume == 0)
304 /* Exit if we already know we can't resume. */
305 return 0;
306
307 if (streq(key, "noresume")) {
308 log_debug("Found \"noresume\" on the kernel command line, hibernation is disabled.");
309 *resume = 0;
310
311 } else if (streq(key, "resume")) {
312 log_debug("Found resume= option on the kernel command line, hibernation is possible.");
313 *resume = 1;
314 }
315
316 return 0;
317 }
318
319 static int resume_configured_in_options(const char *options) {
320 int resume = -1, r;
321
322 /* We don't use PROC_CMDLINE_STRIP_RD_PREFIX here, so rd.resume is *not* supported. */
323 r = proc_cmdline_parse_given(options, check_resume_keys, &resume, 0);
324 if (r < 0)
325 return r;
326
327 if (resume < 0)
328 log_debug("Couldn't find resume= option, hibernation is disabled.");
329 return resume > 0;
330 }
331
332 static int resume_configured(void) {
333 _cleanup_(boot_config_free) BootConfig config = {};
334 const BootEntry *e;
335 int r;
336
337 /* Check whether a valid resume= option is present. If possible, we query the boot options
338 * for the default kernel. If the system is not using sd-boot, fall back to checking the
339 * current kernel command line. This is not perfect, but should suffice for most cases. */
340
341 r = find_default_boot_entry(NULL, NULL, &config, &e);
342 if (r == -ENOKEY)
343 log_debug_errno(r, "Cannot find the ESP partition mount point, falling back to other checks.");
344 else if (r < 0)
345 return log_debug_errno(r, "Cannot read boot configuration from ESP, assuming hibernation is not possible.");
346 else {
347 _cleanup_free_ char *options = NULL;
348
349 options = strv_join(e->options, " ");
350 if (!options)
351 return log_oom();
352
353 r = resume_configured_in_options(options);
354 if (r < 0)
355 return log_error_errno(r, "Failed to parse kernel options in \"%s\": %m",
356 strnull(e->path));
357 return r;
358 }
359
360 /* If we can't figure out the default boot entry, let's fall back to current kernel cmdline */
361 _cleanup_free_ char *line = NULL;
362 r = proc_cmdline(&line);
363 if (IN_SET(r, -EPERM, -EACCES, -ENOENT))
364 log_debug_errno(r, "Cannot access /proc/cmdline: %m");
365 else if (r < 0)
366 return log_error_errno(r, "Failed to query /proc/cmdline: %m");
367 else {
368 r = resume_configured_in_options(line);
369 if (r < 0)
370 return log_error_errno(r, "Failed to parse kernel proc cmdline: %m");
371
372 return r;
373 }
374
375 log_debug("Couldn't detect any resume mechanism, hibernation is disabled.");
376 return false;
377 }
378
379 static int kernel_exists(void) {
380 struct utsname u;
381 sd_id128_t m;
382 int i, r;
383
384 /* Do some superficial checks whether the kernel we are currently running is still around. If it isn't we
385 * shouldn't offer hibernation as we couldn't possible resume from hibernation again. Of course, this check is
386 * very superficial, as the kernel's mere existance is hardly enough to know whether the hibernate/resume cycle
387 * will succeed. However, the common case of kernel updates can be caught this way, and it's definitely worth
388 * covering that. */
389
390 for (i = 0;; i++) {
391 _cleanup_free_ char *path = NULL;
392
393 switch (i) {
394
395 case 0:
396 /* First, let's look in /lib/modules/`uname -r`/vmlinuz. This is where current Fedora places
397 * its RPM-managed kernels. It's a good place, as it means compiled vendor code is monopolized
398 * in /usr, and then the kernel image is stored along with its modules in the same
399 * hierarchy. It's also what our 'kernel-install' script is written for. */
400 if (uname(&u) < 0)
401 return log_debug_errno(errno, "Failed to acquire kernel release: %m");
402
403 path = strjoin("/lib/modules/", u.release, "/vmlinuz");
404 break;
405
406 case 1:
407 /* Secondly, let's look in /boot/vmlinuz-`uname -r`. This is where older Fedora and other
408 * distributions tend to place the kernel. */
409 path = strjoin("/boot/vmlinuz-", u.release);
410 break;
411
412 case 2:
413 /* For the other cases, we look in the EFI/boot partition, at the place where our
414 * "kernel-install" script copies the kernel on install by default. */
415 r = sd_id128_get_machine(&m);
416 if (r < 0)
417 return log_debug_errno(r, "Failed to read machine ID: %m");
418
419 (void) asprintf(&path, "/efi/" SD_ID128_FORMAT_STR "/%s/linux", SD_ID128_FORMAT_VAL(m), u.release);
420 break;
421 case 3:
422 (void) asprintf(&path, "/boot/" SD_ID128_FORMAT_STR "/%s/linux", SD_ID128_FORMAT_VAL(m), u.release);
423 break;
424 case 4:
425 (void) asprintf(&path, "/boot/efi/" SD_ID128_FORMAT_STR "/%s/linux", SD_ID128_FORMAT_VAL(m), u.release);
426 break;
427
428 default:
429 return false;
430 }
431
432 if (!path)
433 return -ENOMEM;
434
435 log_debug("Testing whether %s exists.", path);
436
437 if (access(path, F_OK) >= 0)
438 return true;
439
440 if (errno != ENOENT)
441 log_debug_errno(errno, "Failed to determine whether '%s' exists, ignoring: %m", path);
442 }
443 }
444
445 int read_fiemap(int fd, struct fiemap **ret) {
446 _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
447 struct stat statinfo;
448 uint32_t result_extents = 0;
449 uint64_t fiemap_start = 0, fiemap_length;
450 const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
451 size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
452
453 if (fstat(fd, &statinfo) < 0)
454 return log_debug_errno(errno, "Cannot determine file size: %m");
455 if (!S_ISREG(statinfo.st_mode))
456 return -ENOTTY;
457 fiemap_length = statinfo.st_size;
458
459 /* Zero this out in case we run on a file with no extents */
460 fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
461 if (!fiemap)
462 return -ENOMEM;
463
464 result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
465 if (!result_fiemap)
466 return -ENOMEM;
467
468 /* XFS filesystem has incorrect implementation of fiemap ioctl and
469 * returns extents for only one block-group at a time, so we need
470 * to handle it manually, starting the next fiemap call from the end
471 * of the last extent
472 */
473 while (fiemap_start < fiemap_length) {
474 *fiemap = (struct fiemap) {
475 .fm_start = fiemap_start,
476 .fm_length = fiemap_length,
477 .fm_flags = FIEMAP_FLAG_SYNC,
478 };
479
480 /* Find out how many extents there are */
481 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
482 return log_debug_errno(errno, "Failed to read extents: %m");
483
484 /* Nothing to process */
485 if (fiemap->fm_mapped_extents == 0)
486 break;
487
488 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
489 * the extents for the whole file. Add space for the initial struct fiemap. */
490 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
491 n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
492 return -ENOMEM;
493
494 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
495 fiemap->fm_mapped_extents = 0;
496
497 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
498 return log_debug_errno(errno, "Failed to read extents: %m");
499
500 /* Resize result_fiemap to allow us to copy in the extents */
501 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
502 n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
503 return -ENOMEM;
504
505 memcpy(result_fiemap->fm_extents + result_extents,
506 fiemap->fm_extents,
507 sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
508
509 result_extents += fiemap->fm_mapped_extents;
510
511 /* Highly unlikely that it is zero */
512 if (_likely_(fiemap->fm_mapped_extents > 0)) {
513 uint32_t i = fiemap->fm_mapped_extents - 1;
514
515 fiemap_start = fiemap->fm_extents[i].fe_logical +
516 fiemap->fm_extents[i].fe_length;
517
518 if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
519 break;
520 }
521 }
522
523 memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
524 result_fiemap->fm_mapped_extents = result_extents;
525 *ret = TAKE_PTR(result_fiemap);
526 return 0;
527 }
528
529 static int can_sleep_internal(const char *verb, bool check_allowed);
530
531 static bool can_s2h(void) {
532 const char *p;
533 int r;
534
535 r = access("/sys/class/rtc/rtc0/wakealarm", W_OK);
536 if (r < 0) {
537 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
538 "/sys/class/rct/rct0/wakealarm is not writable %m");
539 return false;
540 }
541
542 FOREACH_STRING(p, "suspend", "hibernate") {
543 r = can_sleep_internal(p, false);
544 if (IN_SET(r, 0, -ENOSPC, -ENOMEDIUM, -EADV)) {
545 log_debug("Unable to %s system.", p);
546 return false;
547 }
548 if (r < 0)
549 return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
550 }
551
552 return true;
553 }
554
555 static int can_sleep_internal(const char *verb, bool check_allowed) {
556 bool allow;
557 _cleanup_strv_free_ char **modes = NULL, **states = NULL;
558 int r;
559
560 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
561
562 r = parse_sleep_config(verb, &allow, &modes, &states, NULL);
563 if (r < 0)
564 return false;
565
566 if (check_allowed && !allow) {
567 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb);
568 return false;
569 }
570
571 if (streq(verb, "suspend-then-hibernate"))
572 return can_s2h();
573
574 if (!can_sleep_state(states) || !can_sleep_disk(modes))
575 return false;
576
577 if (streq(verb, "suspend"))
578 return true;
579
580 if (kernel_exists() <= 0) {
581 log_debug_errno(errno, "Couldn't find kernel, not offering hibernation.");
582 return -ENOMEDIUM;
583 }
584
585 if (!enough_swap_for_hibernation())
586 return -ENOSPC;
587
588 r = resume_configured();
589 if (r <= 0)
590 /* We squash all errors (e.g. EPERM) into a single value for reporting. */
591 return -EADV;
592
593 return true;
594 }
595
596 int can_sleep(const char *verb) {
597 return can_sleep_internal(verb, true);
598 }