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