]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/sleep-config.c
shared/sleep-config: make swap detection stricter again
[thirdparty/systemd.git] / src / shared / sleep-config.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
19adb8a3 2/***
96b2fb93 3 Copyright © 2018 Dell Inc.
19adb8a3
ZJS
4***/
5
a8fbdf54 6#include <errno.h>
ca78ad1d 7#include <fcntl.h>
17c40b3a 8#include <linux/fs.h>
a8fbdf54
TA
9#include <stdbool.h>
10#include <stddef.h>
36dd5ffd 11#include <sys/ioctl.h>
ca78ad1d
ZJS
12#include <sys/stat.h>
13#include <sys/types.h>
a8fbdf54
TA
14#include <syslog.h>
15#include <unistd.h>
19adb8a3 16
b5efdb8a 17#include "alloc-util.h"
52133271 18#include "blockdev-util.h"
7bdf56a2 19#include "btrfs-util.h"
19adb8a3 20#include "conf-parser.h"
a0f29c76 21#include "def.h"
490d20e6 22#include "env-util.h"
427646ea 23#include "errno-util.h"
3ffd4af2 24#include "fd-util.h"
19adb8a3
ZJS
25#include "fileio.h"
26#include "log.h"
a8fbdf54 27#include "macro.h"
a0f29c76 28#include "parse-util.h"
411ae92b 29#include "path-util.h"
3ffd4af2 30#include "sleep-config.h"
7bdf56a2 31#include "stdio-util.h"
07630cea 32#include "string-util.h"
19adb8a3 33#include "strv.h"
1bbbefe7 34#include "time-util.h"
19adb8a3 35
28ca9c24
ZS
36int parse_sleep_config(SleepConfig **ret_sleep_config) {
37 _cleanup_(free_sleep_configp) SleepConfig *sc;
e8f1d00d
ZJS
38 int allow_suspend = -1, allow_hibernate = -1,
39 allow_s2h = -1, allow_hybrid_sleep = -1;
28ca9c24
ZS
40
41 sc = new0(SleepConfig, 1);
42 if (!sc)
43 return log_oom();
19adb8a3
ZJS
44
45 const ConfigTableItem items[] = {
e8f1d00d
ZJS
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
28ca9c24
ZS
51 { "Sleep", "SuspendMode", config_parse_strv, 0, &sc->suspend_modes },
52 { "Sleep", "SuspendState", config_parse_strv, 0, &sc->suspend_states },
53 { "Sleep", "HibernateMode", config_parse_strv, 0, &sc->hibernate_modes },
54 { "Sleep", "HibernateState", config_parse_strv, 0, &sc->hibernate_states },
55 { "Sleep", "HybridSleepMode", config_parse_strv, 0, &sc->hybrid_modes },
56 { "Sleep", "HybridSleepState", config_parse_strv, 0, &sc->hybrid_states },
e8f1d00d 57
28ca9c24 58 { "Sleep", "HibernateDelaySec", config_parse_sec, 0, &sc->hibernate_delay_sec},
34c10968
LP
59 {}
60 };
19adb8a3 61
bcde742e
LP
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);
19adb8a3 66
28ca9c24
ZS
67 /* use default values unless set */
68 sc->allow_suspend = allow_suspend != 0;
69 sc->allow_hibernate = allow_hibernate != 0;
7874583d
ZS
70 sc->allow_hybrid_sleep = allow_hybrid_sleep >= 0 ? allow_hybrid_sleep
71 : (allow_suspend != 0 && allow_hibernate != 0);
72 sc->allow_s2h = allow_s2h >= 0 ? allow_s2h
73 : (allow_suspend != 0 && allow_hibernate != 0);
28ca9c24
ZS
74
75 if (!sc->suspend_states)
76 sc->suspend_states = strv_new("mem", "standby", "freeze");
77 if (!sc->hibernate_modes)
78 sc->hibernate_modes = strv_new("platform", "shutdown");
79 if (!sc->hibernate_states)
80 sc->hibernate_states = strv_new("disk");
81 if (!sc->hybrid_modes)
82 sc->hybrid_modes = strv_new("suspend", "platform", "shutdown");
83 if (!sc->hybrid_states)
84 sc->hybrid_states = strv_new("disk");
85 if (sc->hibernate_delay_sec == 0)
a077755a 86 sc->hibernate_delay_sec = 2 * USEC_PER_HOUR;
28ca9c24
ZS
87
88 /* ensure values set for all required fields */
89 if (!sc->suspend_states || !sc->hibernate_modes
90 || !sc->hibernate_states || !sc->hybrid_modes || !sc->hybrid_states)
19adb8a3 91 return log_oom();
19adb8a3 92
28ca9c24 93 *ret_sleep_config = TAKE_PTR(sc);
c58493c0 94
19adb8a3
ZJS
95 return 0;
96}
97
98int can_sleep_state(char **types) {
a2a5291b 99 char **type;
19adb8a3
ZJS
100 int r;
101 _cleanup_free_ char *p = NULL;
102
103 if (strv_isempty(types))
104 return true;
105
106 /* If /sys is read-only we cannot sleep */
107 if (access("/sys/power/state", W_OK) < 0)
108 return false;
109
110 r = read_one_line_file("/sys/power/state", &p);
111 if (r < 0)
112 return false;
113
114 STRV_FOREACH(type, types) {
a2a5291b 115 const char *word, *state;
19adb8a3
ZJS
116 size_t l, k;
117
118 k = strlen(*type);
a2a5291b
ZJS
119 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state)
120 if (l == k && memcmp(word, *type, l) == 0)
19adb8a3
ZJS
121 return true;
122 }
123
124 return false;
125}
126
127int can_sleep_disk(char **types) {
a2a5291b 128 char **type;
19adb8a3
ZJS
129 int r;
130 _cleanup_free_ char *p = NULL;
131
132 if (strv_isempty(types))
133 return true;
134
135 /* If /sys is read-only we cannot sleep */
7474f15b
LP
136 if (access("/sys/power/disk", W_OK) < 0) {
137 log_debug_errno(errno, "/sys/power/disk is not writable: %m");
19adb8a3 138 return false;
7474f15b 139 }
19adb8a3
ZJS
140
141 r = read_one_line_file("/sys/power/disk", &p);
7474f15b
LP
142 if (r < 0) {
143 log_debug_errno(r, "Couldn't read /sys/power/disk: %m");
19adb8a3 144 return false;
7474f15b 145 }
19adb8a3
ZJS
146
147 STRV_FOREACH(type, types) {
a2a5291b 148 const char *word, *state;
19adb8a3
ZJS
149 size_t l, k;
150
151 k = strlen(*type);
a2a5291b
ZJS
152 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state) {
153 if (l == k && memcmp(word, *type, l) == 0)
19adb8a3
ZJS
154 return true;
155
a2a5291b
ZJS
156 if (l == k + 2 &&
157 word[0] == '[' &&
158 memcmp(word + 1, *type, l - 2) == 0 &&
159 word[l-1] == ']')
19adb8a3
ZJS
160 return true;
161 }
162 }
163
164 return false;
165}
166
69ab8088
ZJS
167#define HIBERNATION_SWAP_THRESHOLD 0.98
168
7bdf56a2 169SwapEntry* swap_entry_free(SwapEntry *se) {
88bc86fc
ZS
170 if (!se)
171 return NULL;
172
173 free(se->device);
174 free(se->type);
175
176 return mfree(se);
177}
178
7bdf56a2
ZS
179HibernateLocation* hibernate_location_free(HibernateLocation *hl) {
180 if (!hl)
181 return NULL;
182
183 swap_entry_free(hl->swap);
7bdf56a2
ZS
184
185 return mfree(hl);
186}
187
52133271 188static int swap_device_to_device_id(const SwapEntry *swap, dev_t *ret_dev) {
7bdf56a2 189 struct stat sb;
7bdf56a2
ZS
190 int r;
191
192 assert(swap);
193 assert(swap->device);
194 assert(swap->type);
195
e9f0c5d0 196 r = stat(swap->device, &sb);
7bdf56a2 197 if (r < 0)
8efc2c16 198 return r;
7bdf56a2 199
52133271 200 if (streq(swap->type, "partition")) {
e9f0c5d0 201 if (!S_ISBLK(sb.st_mode))
52133271 202 return -ENOTBLK;
e9f0c5d0
ZJS
203 *ret_dev = sb.st_rdev;
204 return 0;
7bdf56a2 205
e9f0c5d0
ZJS
206 } else
207 return get_block_device(swap->device, ret_dev);
7bdf56a2
ZS
208}
209
52133271
ZS
210/*
211 * Attempt to calculate the swap file offset on supported filesystems. On unsuported
8efc2c16 212 * filesystems, a debug message is logged and ret_offset is set to UINT64_MAX.
52133271 213 */
7bdf56a2
ZS
214static int calculate_swap_file_offset(const SwapEntry *swap, uint64_t *ret_offset) {
215 _cleanup_close_ int fd = -1;
216 _cleanup_free_ struct fiemap *fiemap = NULL;
217 struct stat sb;
218 int r, btrfs;
219
220 assert(swap);
221 assert(swap->device);
222 assert(streq(swap->type, "file"));
223
224 fd = open(swap->device, O_RDONLY|O_CLOEXEC|O_NOCTTY);
e97c3691 225 if (fd < 0)
7bdf56a2
ZS
226 return log_error_errno(errno, "Failed to open %s: %m", swap->device);
227
e97c3691 228 if (fstat(fd, &sb) < 0)
7bdf56a2
ZS
229 return log_error_errno(errno, "Failed to stat %s: %m", swap->device);
230
231 btrfs = btrfs_is_filesystem(fd);
232 if (btrfs < 0)
b72571e0 233 return log_error_errno(btrfs, "Error checking %s for Btrfs filesystem: %m", swap->device);
7bdf56a2 234 else if (btrfs > 0) {
8efc2c16
ZJS
235 log_debug("%s: detection of swap file offset on Btrfs is not supported", swap->device);
236 *ret_offset = UINT64_MAX;
7bdf56a2
ZS
237 return 0;
238 }
239
240 r = read_fiemap(fd, &fiemap);
241 if (r < 0)
242 return log_debug_errno(r, "Unable to read extent map for '%s': %m", swap->device);
243
244 *ret_offset = fiemap->fm_extents[0].fe_physical / page_size();
245
246 return 0;
247}
88bc86fc 248
52133271
ZS
249static int read_resume_files(dev_t *ret_resume, uint64_t *ret_resume_offset) {
250 _cleanup_free_ char *resume_str = NULL, *resume_offset_str = NULL;
251 dev_t resume;
7bdf56a2
ZS
252 uint64_t resume_offset = 0;
253 int r;
254
52133271 255 r = read_one_line_file("/sys/power/resume", &resume_str);
7bdf56a2 256 if (r < 0)
5021735f 257 return log_debug_errno(r, "Error reading /sys/power/resume: %m");
7bdf56a2 258
52133271
ZS
259 r = parse_dev(resume_str, &resume);
260 if (r < 0)
261 return log_debug_errno(r, "Error parsing /sys/power/resume device: %s: %m", resume_str);
262
7bdf56a2 263 r = read_one_line_file("/sys/power/resume_offset", &resume_offset_str);
b72571e0
ZJS
264 if (r == -ENOENT)
265 log_debug("Kernel does not support resume_offset; swap file offset detection will be skipped.");
266 else if (r < 0)
5021735f 267 return log_debug_errno(r, "Error reading /sys/power/resume_offset: %m");
b72571e0 268 else {
7bdf56a2
ZS
269 r = safe_atou64(resume_offset_str, &resume_offset);
270 if (r < 0)
b72571e0 271 return log_error_errno(r, "Failed to parse value in /sys/power/resume_offset \"%s\": %m", resume_offset_str);
7bdf56a2
ZS
272 }
273
52133271 274 if (resume_offset > 0 && resume == 0) {
5021735f
ZJS
275 log_debug("Found offset in /sys/power/resume_offset: %" PRIu64 "; no device id found in /sys/power/resume; ignoring resume_offset",
276 resume_offset);
7bdf56a2
ZS
277 resume_offset = 0;
278 }
279
52133271 280 *ret_resume = resume;
7bdf56a2
ZS
281 *ret_resume_offset = resume_offset;
282
283 return 0;
284}
285
52133271
ZS
286/*
287 * Determine if the HibernateLocation matches the resume= (device) and resume_offset= (file).
288 */
289static bool location_is_resume_device(const HibernateLocation *location, dev_t sys_resume, uint64_t sys_offset) {
290 if (!location)
291 return false;
292
8efc2c16
ZJS
293 return sys_resume > 0 &&
294 sys_resume == location->devno &&
295 (sys_offset == location->offset || (sys_offset > 0 && location->offset == UINT64_MAX));
7bdf56a2
ZS
296}
297
298/*
299 * Attempt to find the hibernation location by parsing /proc/swaps, /sys/power/resume, and
300 * /sys/power/resume_offset.
301 *
302 * Returns:
52133271
ZS
303 * 1 - Values are set in /sys/power/resume and /sys/power/resume_offset.
304 * ret_hibernate_location will represent matching /proc/swap entry if identified or NULL if not.
305 *
306 * 0 - No values are set in /sys/power/resume and /sys/power/resume_offset.
307 ret_hibernate_location will represent the highest priority swap with most remaining space discovered in /proc/swaps.
308 *
309 * Negative value in the case of error.
7bdf56a2
ZS
310 */
311int find_hibernate_location(HibernateLocation **ret_hibernate_location) {
b72571e0 312 _cleanup_fclose_ FILE *f = NULL;
7bdf56a2 313 _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
52133271 314 dev_t sys_resume;
7bdf56a2 315 uint64_t sys_offset = 0;
8efc2c16 316 bool resume_match = false;
7bdf56a2
ZS
317 int r;
318
319 /* read the /sys/power/resume & /sys/power/resume_offset values */
320 r = read_resume_files(&sys_resume, &sys_offset);
321 if (r < 0)
322 return r;
9fb3675e 323
c8a202b7 324 f = fopen("/proc/swaps", "re");
9fb3675e
ZJS
325 if (!f) {
326 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
ea470720 327 "Failed to open /proc/swaps: %m");
427646ea 328 return negative_errno();
9fb3675e 329 }
69ab8088 330
9fb3675e 331 (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
8efc2c16 332 for (unsigned i = 1;; i++) {
88bc86fc 333 _cleanup_(swap_entry_freep) SwapEntry *swap = NULL;
7bdf56a2 334 uint64_t swap_offset = 0;
9fb3675e
ZJS
335 int k;
336
88bc86fc
ZS
337 swap = new0(SwapEntry, 1);
338 if (!swap)
339 return log_oom();
340
9fb3675e 341 k = fscanf(f,
88bc86fc
ZS
342 "%ms " /* device/file */
343 "%ms " /* type of swap */
344 "%" PRIu64 /* swap size */
345 "%" PRIu64 /* used */
346 "%i\n", /* priority */
347 &swap->device, &swap->type, &swap->size, &swap->used, &swap->priority);
3dea6886
LP
348 if (k == EOF)
349 break;
88bc86fc 350 if (k != 5) {
9fb3675e
ZJS
351 log_warning("Failed to parse /proc/swaps:%u", i);
352 continue;
353 }
354
88bc86fc 355 if (streq(swap->type, "file")) {
88bc86fc
ZS
356 if (endswith(swap->device, "\\040(deleted)")) {
357 log_warning("Ignoring deleted swap file '%s'.", swap->device);
411ae92b
AJ
358 continue;
359 }
360
7bdf56a2
ZS
361 r = calculate_swap_file_offset(swap, &swap_offset);
362 if (r < 0)
363 return r;
52133271 364
88bc86fc 365 } else if (streq(swap->type, "partition")) {
411ae92b 366 const char *fn;
3dea6886 367
88bc86fc 368 fn = path_startswith(swap->device, "/dev/");
411ae92b 369 if (fn && startswith(fn, "zram")) {
8efc2c16 370 log_debug("%s: ignoring zram swap", swap->device);
411ae92b
AJ
371 continue;
372 }
8efc2c16 373
7bdf56a2 374 } else {
8efc2c16 375 log_debug("%s: swap type %s is unsupported for hibernation, ignoring", swap->device, swap->type);
7bdf56a2 376 continue;
9fb3675e 377 }
3dea6886 378
7bdf56a2 379 /* prefer resume device or highest priority swap with most remaining space */
8efc2c16
ZJS
380 if (hibernate_location && swap->priority < hibernate_location->swap->priority) {
381 log_debug("%s: ignoring device with lower priority", swap->device);
382 continue;
383 }
384 if (hibernate_location &&
385 (swap->priority == hibernate_location->swap->priority
386 && swap->size - swap->used < hibernate_location->swap->size - hibernate_location->swap->used)) {
387 log_debug("%s: ignoring device with lower usable space", swap->device);
388 continue;
389 }
7bdf56a2 390
8efc2c16
ZJS
391 dev_t swap_device;
392 r = swap_device_to_device_id(swap, &swap_device);
393 if (r < 0)
394 return log_error_errno(r, "%s: failed to query device number: %m", swap->device);
7bdf56a2 395
8efc2c16
ZJS
396 hibernate_location = hibernate_location_free(hibernate_location);
397 hibernate_location = new(HibernateLocation, 1);
398 if (!hibernate_location)
399 return log_oom();
7bdf56a2 400
8efc2c16
ZJS
401 *hibernate_location = (HibernateLocation) {
402 .devno = swap_device,
403 .offset = swap_offset,
404 .swap = TAKE_PTR(swap),
405 };
7bdf56a2 406
8efc2c16
ZJS
407 /* if the swap is the resume device, stop the loop */
408 if (location_is_resume_device(hibernate_location, sys_resume, sys_offset)) {
409 log_debug("%s: device matches configured resume settings.", hibernate_location->swap->device);
410 resume_match = true;
411 break;
88bc86fc 412 }
8efc2c16
ZJS
413
414 log_debug("%s: is a candidate device.", hibernate_location->swap->device);
69ab8088
ZJS
415 }
416
8efc2c16
ZJS
417 /* We found nothing at all */
418 if (!hibernate_location)
419 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS),
420 "No possible swap partitions or files suitable for hibernation were found in /proc/swaps.");
52133271 421
8efc2c16
ZJS
422 /* resume= is set but a matching /proc/swaps entry was not found */
423 if (sys_resume != 0 && !resume_match)
424 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS),
425 "No swap partitions or files matching resume config were found in /proc/swaps.");
52133271 426
8efc2c16
ZJS
427 if (hibernate_location->offset == UINT64_MAX) {
428 if (sys_offset == 0)
429 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS), "Offset detection failed and /sys/power/resume_offset is not set.");
7bdf56a2 430
8efc2c16
ZJS
431 hibernate_location->offset = sys_offset;
432 }
7bdf56a2 433
52133271
ZS
434 if (resume_match)
435 log_debug("Hibernation will attempt to use swap entry with path: %s, device: %u:%u, offset: %" PRIu64 ", priority: %i",
436 hibernate_location->swap->device, major(hibernate_location->devno), minor(hibernate_location->devno),
437 hibernate_location->offset, hibernate_location->swap->priority);
438 else
8efc2c16 439 log_debug("/sys/power/resume is not configured; attempting to hibernate with path: %s, device: %u:%u, offset: %" PRIu64 ", priority: %i",
52133271
ZS
440 hibernate_location->swap->device, major(hibernate_location->devno), minor(hibernate_location->devno),
441 hibernate_location->offset, hibernate_location->swap->priority);
88bc86fc 442
7bdf56a2 443 *ret_hibernate_location = TAKE_PTR(hibernate_location);
88bc86fc 444
52133271 445 if (resume_match)
7bdf56a2 446 return 1;
88bc86fc
ZS
447
448 return 0;
9fb3675e
ZJS
449}
450
4638cd39 451static bool enough_swap_for_hibernation(void) {
9fb3675e 452 _cleanup_free_ char *active = NULL;
7bdf56a2 453 _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
39883f62 454 unsigned long long act = 0;
9fb3675e
ZJS
455 int r;
456
490d20e6
VV
457 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
458 return true;
459
7bdf56a2 460 r = find_hibernate_location(&hibernate_location);
9fb3675e 461 if (r < 0)
69ab8088 462 return false;
69ab8088 463
52133271
ZS
464 /* If /sys/power/{resume,resume_offset} is configured but a matching entry
465 * could not be identified in /proc/swaps, user is likely using Btrfs with a swapfile;
466 * return true and let the system attempt hibernation.
467 */
468 if (r > 0 && !hibernate_location) {
469 log_debug("Unable to determine remaining swap space; hibernation may fail");
470 return true;
471 }
472
473 if (!hibernate_location)
474 return false;
475
c4cd1d4d 476 r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
69ab8088 477 if (r < 0) {
904865b8 478 log_debug_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
69ab8088
ZJS
479 return false;
480 }
481
482 r = safe_atollu(active, &act);
483 if (r < 0) {
904865b8 484 log_debug_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active);
69ab8088
ZJS
485 return false;
486 }
487
7bdf56a2 488 r = act <= (hibernate_location->swap->size - hibernate_location->swap->used) * HIBERNATION_SWAP_THRESHOLD;
88bc86fc 489 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%" PRIu64 " kB, used=%" PRIu64 " kB, threshold=%.2g%%",
7bdf56a2 490 r ? "Enough" : "Not enough", act, hibernate_location->swap->size, hibernate_location->swap->used, 100*HIBERNATION_SWAP_THRESHOLD);
69ab8088
ZJS
491
492 return r;
493}
494
17c40b3a
ML
495int read_fiemap(int fd, struct fiemap **ret) {
496 _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
17c40b3a
ML
497 struct stat statinfo;
498 uint32_t result_extents = 0;
499 uint64_t fiemap_start = 0, fiemap_length;
6524f1a8
ZJS
500 const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
501 size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
17c40b3a
ML
502
503 if (fstat(fd, &statinfo) < 0)
504 return log_debug_errno(errno, "Cannot determine file size: %m");
505 if (!S_ISREG(statinfo.st_mode))
506 return -ENOTTY;
507 fiemap_length = statinfo.st_size;
508
6524f1a8
ZJS
509 /* Zero this out in case we run on a file with no extents */
510 fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
511 if (!fiemap)
512 return -ENOMEM;
513
6524f1a8 514 result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
515 if (!result_fiemap)
516 return -ENOMEM;
517
518 /* XFS filesystem has incorrect implementation of fiemap ioctl and
519 * returns extents for only one block-group at a time, so we need
520 * to handle it manually, starting the next fiemap call from the end
521 * of the last extent
522 */
523 while (fiemap_start < fiemap_length) {
524 *fiemap = (struct fiemap) {
525 .fm_start = fiemap_start,
526 .fm_length = fiemap_length,
527 .fm_flags = FIEMAP_FLAG_SYNC,
528 };
529
530 /* Find out how many extents there are */
531 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
532 return log_debug_errno(errno, "Failed to read extents: %m");
533
534 /* Nothing to process */
535 if (fiemap->fm_mapped_extents == 0)
536 break;
537
6524f1a8
ZJS
538 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
539 * the extents for the whole file. Add space for the initial struct fiemap. */
540 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
541 n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
542 return -ENOMEM;
543
544 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
545 fiemap->fm_mapped_extents = 0;
546
547 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
548 return log_debug_errno(errno, "Failed to read extents: %m");
549
6524f1a8
ZJS
550 /* Resize result_fiemap to allow us to copy in the extents */
551 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
552 n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
553 return -ENOMEM;
554
555 memcpy(result_fiemap->fm_extents + result_extents,
556 fiemap->fm_extents,
557 sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
558
559 result_extents += fiemap->fm_mapped_extents;
560
561 /* Highly unlikely that it is zero */
6524f1a8 562 if (_likely_(fiemap->fm_mapped_extents > 0)) {
17c40b3a
ML
563 uint32_t i = fiemap->fm_mapped_extents - 1;
564
565 fiemap_start = fiemap->fm_extents[i].fe_logical +
566 fiemap->fm_extents[i].fe_length;
567
568 if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
569 break;
570 }
571 }
572
573 memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
574 result_fiemap->fm_mapped_extents = result_extents;
575 *ret = TAKE_PTR(result_fiemap);
576 return 0;
577}
578
28ca9c24 579static int can_sleep_internal(const char *verb, bool check_allowed, const SleepConfig *sleep_config);
e8f1d00d 580
28ca9c24 581static bool can_s2h(const SleepConfig *sleep_config) {
c863dc05 582 const char *p;
c58493c0
ML
583 int r;
584
1bbbefe7 585 if (!clock_supported(CLOCK_BOOTTIME_ALARM)) {
c58493c0 586 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
1bbbefe7 587 "CLOCK_BOOTTIME_ALARM is not supported");
c58493c0
ML
588 return false;
589 }
590
c863dc05 591 FOREACH_STRING(p, "suspend", "hibernate") {
28ca9c24 592 r = can_sleep_internal(p, false, sleep_config);
8340b762 593 if (IN_SET(r, 0, -ENOSPC, -EADV)) {
c863dc05
ZJS
594 log_debug("Unable to %s system.", p);
595 return false;
596 }
b71c9758
ZJS
597 if (r < 0)
598 return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
c58493c0
ML
599 }
600
601 return true;
602}
603
28ca9c24 604static int can_sleep_internal(const char *verb, bool check_allowed, const SleepConfig *sleep_config) {
e8f1d00d 605 bool allow;
28ca9c24 606 char **modes = NULL, **states = NULL;
19adb8a3
ZJS
607 int r;
608
e68c79db 609 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
c58493c0 610
28ca9c24 611 r = sleep_settings(verb, sleep_config, &allow, &modes, &states);
19adb8a3
ZJS
612 if (r < 0)
613 return false;
614
e8f1d00d
ZJS
615 if (check_allowed && !allow) {
616 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb);
617 return false;
618 }
619
620 if (streq(verb, "suspend-then-hibernate"))
28ca9c24 621 return can_s2h(sleep_config);
e8f1d00d 622
69ab8088
ZJS
623 if (!can_sleep_state(states) || !can_sleep_disk(modes))
624 return false;
625
b71c9758
ZJS
626 if (streq(verb, "suspend"))
627 return true;
628
4638cd39 629 if (!enough_swap_for_hibernation())
b71c9758
ZJS
630 return -ENOSPC;
631
632 return true;
19adb8a3 633}
e8f1d00d
ZJS
634
635int can_sleep(const char *verb) {
28ca9c24
ZS
636 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
637 int r;
638
639 r = parse_sleep_config(&sleep_config);
640 if (r < 0)
641 return r;
642
643 return can_sleep_internal(verb, true, sleep_config);
644}
645
646int sleep_settings(const char *verb, const SleepConfig *sleep_config, bool *ret_allow, char ***ret_modes, char ***ret_states) {
647
648 assert(verb);
649 assert(sleep_config);
650 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
651
652 if (streq(verb, "suspend")) {
653 *ret_allow = sleep_config->allow_suspend;
654 *ret_modes = sleep_config->suspend_modes;
655 *ret_states = sleep_config->suspend_states;
656 } else if (streq(verb, "hibernate")) {
657 *ret_allow = sleep_config->allow_hibernate;
658 *ret_modes = sleep_config->hibernate_modes;
659 *ret_states = sleep_config->hibernate_states;
660 } else if (streq(verb, "hybrid-sleep")) {
661 *ret_allow = sleep_config->allow_hybrid_sleep;
662 *ret_modes = sleep_config->hybrid_modes;
663 *ret_states = sleep_config->hybrid_states;
664 } else if (streq(verb, "suspend-then-hibernate")) {
665 *ret_allow = sleep_config->allow_s2h;
666 *ret_modes = *ret_states = NULL;
667 }
668
669 /* suspend modes empty by default */
670 if ((!ret_modes && !streq(verb, "suspend")) || !ret_states)
671 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No modes or states set for %s; Check sleep.conf", verb);
672
673 return 0;
674}
675
676void free_sleep_config(SleepConfig *sc) {
677 if (!sc)
678 return;
679
680 strv_free(sc->suspend_modes);
681 strv_free(sc->suspend_states);
682
683 strv_free(sc->hibernate_modes);
684 strv_free(sc->hibernate_states);
685
686 strv_free(sc->hybrid_modes);
687 strv_free(sc->hybrid_states);
688
689 free(sc);
e8f1d00d 690}