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