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