]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/sleep-config.c
systemd-sleep: use swaps in priority order
[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>
19adb8a3 11#include <stdio.h>
a8fbdf54 12#include <string.h>
36dd5ffd 13#include <sys/ioctl.h>
ca78ad1d
ZJS
14#include <sys/stat.h>
15#include <sys/types.h>
a8fbdf54
TA
16#include <syslog.h>
17#include <unistd.h>
19adb8a3 18
b5efdb8a 19#include "alloc-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"
07630cea 31#include "string-util.h"
19adb8a3 32#include "strv.h"
1bbbefe7 33#include "time-util.h"
19adb8a3 34
28ca9c24
ZS
35int parse_sleep_config(SleepConfig **ret_sleep_config) {
36 _cleanup_(free_sleep_configp) SleepConfig *sc;
e8f1d00d
ZJS
37 int allow_suspend = -1, allow_hibernate = -1,
38 allow_s2h = -1, allow_hybrid_sleep = -1;
28ca9c24
ZS
39
40 sc = new0(SleepConfig, 1);
41 if (!sc)
42 return log_oom();
19adb8a3
ZJS
43
44 const ConfigTableItem items[] = {
e8f1d00d
ZJS
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
28ca9c24
ZS
50 { "Sleep", "SuspendMode", config_parse_strv, 0, &sc->suspend_modes },
51 { "Sleep", "SuspendState", config_parse_strv, 0, &sc->suspend_states },
52 { "Sleep", "HibernateMode", config_parse_strv, 0, &sc->hibernate_modes },
53 { "Sleep", "HibernateState", config_parse_strv, 0, &sc->hibernate_states },
54 { "Sleep", "HybridSleepMode", config_parse_strv, 0, &sc->hybrid_modes },
55 { "Sleep", "HybridSleepState", config_parse_strv, 0, &sc->hybrid_states },
e8f1d00d 56
28ca9c24 57 { "Sleep", "HibernateDelaySec", config_parse_sec, 0, &sc->hibernate_delay_sec},
34c10968
LP
58 {}
59 };
19adb8a3 60
bcde742e
LP
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);
19adb8a3 65
28ca9c24
ZS
66 /* use default values unless set */
67 sc->allow_suspend = allow_suspend != 0;
68 sc->allow_hibernate = allow_hibernate != 0;
7874583d
ZS
69 sc->allow_hybrid_sleep = allow_hybrid_sleep >= 0 ? allow_hybrid_sleep
70 : (allow_suspend != 0 && allow_hibernate != 0);
71 sc->allow_s2h = allow_s2h >= 0 ? allow_s2h
72 : (allow_suspend != 0 && allow_hibernate != 0);
28ca9c24
ZS
73
74 if (!sc->suspend_states)
75 sc->suspend_states = strv_new("mem", "standby", "freeze");
76 if (!sc->hibernate_modes)
77 sc->hibernate_modes = strv_new("platform", "shutdown");
78 if (!sc->hibernate_states)
79 sc->hibernate_states = strv_new("disk");
80 if (!sc->hybrid_modes)
81 sc->hybrid_modes = strv_new("suspend", "platform", "shutdown");
82 if (!sc->hybrid_states)
83 sc->hybrid_states = strv_new("disk");
84 if (sc->hibernate_delay_sec == 0)
85 sc->hibernate_delay_sec = 180 * USEC_PER_MINUTE;
86
87 /* ensure values set for all required fields */
88 if (!sc->suspend_states || !sc->hibernate_modes
89 || !sc->hibernate_states || !sc->hybrid_modes || !sc->hybrid_states)
19adb8a3 90 return log_oom();
19adb8a3 91
28ca9c24 92 *ret_sleep_config = TAKE_PTR(sc);
c58493c0 93
19adb8a3
ZJS
94 return 0;
95}
96
97int can_sleep_state(char **types) {
a2a5291b 98 char **type;
19adb8a3
ZJS
99 int r;
100 _cleanup_free_ char *p = NULL;
101
102 if (strv_isempty(types))
103 return true;
104
105 /* If /sys is read-only we cannot sleep */
106 if (access("/sys/power/state", W_OK) < 0)
107 return false;
108
109 r = read_one_line_file("/sys/power/state", &p);
110 if (r < 0)
111 return false;
112
113 STRV_FOREACH(type, types) {
a2a5291b 114 const char *word, *state;
19adb8a3
ZJS
115 size_t l, k;
116
117 k = strlen(*type);
a2a5291b
ZJS
118 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state)
119 if (l == k && memcmp(word, *type, l) == 0)
19adb8a3
ZJS
120 return true;
121 }
122
123 return false;
124}
125
126int can_sleep_disk(char **types) {
a2a5291b 127 char **type;
19adb8a3
ZJS
128 int r;
129 _cleanup_free_ char *p = NULL;
130
131 if (strv_isempty(types))
132 return true;
133
134 /* If /sys is read-only we cannot sleep */
7474f15b
LP
135 if (access("/sys/power/disk", W_OK) < 0) {
136 log_debug_errno(errno, "/sys/power/disk is not writable: %m");
19adb8a3 137 return false;
7474f15b 138 }
19adb8a3
ZJS
139
140 r = read_one_line_file("/sys/power/disk", &p);
7474f15b
LP
141 if (r < 0) {
142 log_debug_errno(r, "Couldn't read /sys/power/disk: %m");
19adb8a3 143 return false;
7474f15b 144 }
19adb8a3
ZJS
145
146 STRV_FOREACH(type, types) {
a2a5291b 147 const char *word, *state;
19adb8a3
ZJS
148 size_t l, k;
149
150 k = strlen(*type);
a2a5291b
ZJS
151 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state) {
152 if (l == k && memcmp(word, *type, l) == 0)
19adb8a3
ZJS
153 return true;
154
a2a5291b
ZJS
155 if (l == k + 2 &&
156 word[0] == '[' &&
157 memcmp(word + 1, *type, l - 2) == 0 &&
158 word[l-1] == ']')
19adb8a3
ZJS
159 return true;
160 }
161 }
162
163 return false;
164}
165
69ab8088
ZJS
166#define HIBERNATION_SWAP_THRESHOLD 0.98
167
88bc86fc
ZS
168/* entry in /proc/swaps */
169typedef struct SwapEntry {
170 char *device;
171 char *type;
172 uint64_t size;
173 uint64_t used;
174 int priority;
175} SwapEntry;
176
177static SwapEntry* swap_entry_free(SwapEntry *se) {
178 if (!se)
179 return NULL;
180
181 free(se->device);
182 free(se->type);
183
184 return mfree(se);
185}
186
187DEFINE_TRIVIAL_CLEANUP_FUNC(SwapEntry*, swap_entry_free);
188
189int find_hibernate_location(char **device, char **type, uint64_t *size, uint64_t *used) {
9fb3675e 190 _cleanup_fclose_ FILE *f;
88bc86fc 191 _cleanup_(swap_entry_freep) SwapEntry *selected_swap = NULL;
1fa2f38f 192 unsigned i;
9fb3675e 193
c8a202b7 194 f = fopen("/proc/swaps", "re");
9fb3675e
ZJS
195 if (!f) {
196 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
197 "Failed to retrieve open /proc/swaps: %m");
427646ea 198 return negative_errno();
9fb3675e 199 }
69ab8088 200
9fb3675e
ZJS
201 (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
202
203 for (i = 1;; i++) {
88bc86fc 204 _cleanup_(swap_entry_freep) SwapEntry *swap = NULL;
9fb3675e
ZJS
205 int k;
206
88bc86fc
ZS
207 swap = new0(SwapEntry, 1);
208 if (!swap)
209 return log_oom();
210
9fb3675e 211 k = fscanf(f,
88bc86fc
ZS
212 "%ms " /* device/file */
213 "%ms " /* type of swap */
214 "%" PRIu64 /* swap size */
215 "%" PRIu64 /* used */
216 "%i\n", /* priority */
217 &swap->device, &swap->type, &swap->size, &swap->used, &swap->priority);
3dea6886
LP
218 if (k == EOF)
219 break;
88bc86fc 220 if (k != 5) {
9fb3675e
ZJS
221 log_warning("Failed to parse /proc/swaps:%u", i);
222 continue;
223 }
224
88bc86fc 225 if (streq(swap->type, "file")) {
3dea6886 226
88bc86fc
ZS
227 if (endswith(swap->device, "\\040(deleted)")) {
228 log_warning("Ignoring deleted swap file '%s'.", swap->device);
411ae92b
AJ
229 continue;
230 }
231
88bc86fc 232 } else if (streq(swap->type, "partition")) {
411ae92b 233 const char *fn;
3dea6886 234
88bc86fc 235 fn = path_startswith(swap->device, "/dev/");
411ae92b 236 if (fn && startswith(fn, "zram")) {
88bc86fc 237 log_debug("Ignoring compressed RAM swap device '%s'.", swap->device);
411ae92b
AJ
238 continue;
239 }
9fb3675e 240 }
3dea6886 241
88bc86fc
ZS
242 /* prefer highest priority or swap with most remaining space when same priority */
243 if (!selected_swap || swap->priority > selected_swap->priority
244 || ((swap->priority == selected_swap->priority)
245 && (swap->size - swap->used) > (selected_swap->size - selected_swap->used))) {
246 selected_swap = swap_entry_free(selected_swap);
247 selected_swap = TAKE_PTR(swap);
248 }
69ab8088
ZJS
249 }
250
88bc86fc
ZS
251 if (!selected_swap)
252 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS), "No swap partitions or files were found.");
253
254 /* use the swap entry with the highest priority */
255 if (device)
256 *device = TAKE_PTR(selected_swap->device);
257 if (type)
258 *type = TAKE_PTR(selected_swap->type);
259 if (size)
260 *size = selected_swap->size;
261 if (used)
262 *used = selected_swap->used;
263
264 log_debug("Highest priority swap entry found %s: %i", selected_swap->device, selected_swap->priority);
265
266 return 0;
9fb3675e
ZJS
267}
268
4638cd39 269static bool enough_swap_for_hibernation(void) {
9fb3675e 270 _cleanup_free_ char *active = NULL;
39883f62 271 unsigned long long act = 0;
88bc86fc 272 uint64_t size = 0, used = 0;
9fb3675e
ZJS
273 int r;
274
490d20e6
VV
275 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
276 return true;
277
17c40b3a 278 r = find_hibernate_location(NULL, NULL, &size, &used);
9fb3675e 279 if (r < 0)
69ab8088 280 return false;
69ab8088 281
c4cd1d4d 282 r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
69ab8088 283 if (r < 0) {
904865b8 284 log_debug_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
69ab8088
ZJS
285 return false;
286 }
287
288 r = safe_atollu(active, &act);
289 if (r < 0) {
904865b8 290 log_debug_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active);
69ab8088
ZJS
291 return false;
292 }
293
9fb3675e 294 r = act <= (size - used) * HIBERNATION_SWAP_THRESHOLD;
88bc86fc 295 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%" PRIu64 " kB, used=%" PRIu64 " kB, threshold=%.2g%%",
5fdf2d51 296 r ? "Enough" : "Not enough", act, size, used, 100*HIBERNATION_SWAP_THRESHOLD);
69ab8088
ZJS
297
298 return r;
299}
300
17c40b3a
ML
301int read_fiemap(int fd, struct fiemap **ret) {
302 _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
17c40b3a
ML
303 struct stat statinfo;
304 uint32_t result_extents = 0;
305 uint64_t fiemap_start = 0, fiemap_length;
6524f1a8
ZJS
306 const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
307 size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
17c40b3a
ML
308
309 if (fstat(fd, &statinfo) < 0)
310 return log_debug_errno(errno, "Cannot determine file size: %m");
311 if (!S_ISREG(statinfo.st_mode))
312 return -ENOTTY;
313 fiemap_length = statinfo.st_size;
314
6524f1a8
ZJS
315 /* Zero this out in case we run on a file with no extents */
316 fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
317 if (!fiemap)
318 return -ENOMEM;
319
6524f1a8 320 result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
321 if (!result_fiemap)
322 return -ENOMEM;
323
324 /* XFS filesystem has incorrect implementation of fiemap ioctl and
325 * returns extents for only one block-group at a time, so we need
326 * to handle it manually, starting the next fiemap call from the end
327 * of the last extent
328 */
329 while (fiemap_start < fiemap_length) {
330 *fiemap = (struct fiemap) {
331 .fm_start = fiemap_start,
332 .fm_length = fiemap_length,
333 .fm_flags = FIEMAP_FLAG_SYNC,
334 };
335
336 /* Find out how many extents there are */
337 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
338 return log_debug_errno(errno, "Failed to read extents: %m");
339
340 /* Nothing to process */
341 if (fiemap->fm_mapped_extents == 0)
342 break;
343
6524f1a8
ZJS
344 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
345 * the extents for the whole file. Add space for the initial struct fiemap. */
346 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
347 n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
348 return -ENOMEM;
349
350 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
351 fiemap->fm_mapped_extents = 0;
352
353 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
354 return log_debug_errno(errno, "Failed to read extents: %m");
355
6524f1a8
ZJS
356 /* Resize result_fiemap to allow us to copy in the extents */
357 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
358 n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
359 return -ENOMEM;
360
361 memcpy(result_fiemap->fm_extents + result_extents,
362 fiemap->fm_extents,
363 sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
364
365 result_extents += fiemap->fm_mapped_extents;
366
367 /* Highly unlikely that it is zero */
6524f1a8 368 if (_likely_(fiemap->fm_mapped_extents > 0)) {
17c40b3a
ML
369 uint32_t i = fiemap->fm_mapped_extents - 1;
370
371 fiemap_start = fiemap->fm_extents[i].fe_logical +
372 fiemap->fm_extents[i].fe_length;
373
374 if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
375 break;
376 }
377 }
378
379 memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
380 result_fiemap->fm_mapped_extents = result_extents;
381 *ret = TAKE_PTR(result_fiemap);
382 return 0;
383}
384
28ca9c24 385static int can_sleep_internal(const char *verb, bool check_allowed, const SleepConfig *sleep_config);
e8f1d00d 386
28ca9c24 387static bool can_s2h(const SleepConfig *sleep_config) {
c863dc05 388 const char *p;
c58493c0
ML
389 int r;
390
1bbbefe7 391 if (!clock_supported(CLOCK_BOOTTIME_ALARM)) {
c58493c0 392 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
1bbbefe7 393 "CLOCK_BOOTTIME_ALARM is not supported");
c58493c0
ML
394 return false;
395 }
396
c863dc05 397 FOREACH_STRING(p, "suspend", "hibernate") {
28ca9c24 398 r = can_sleep_internal(p, false, sleep_config);
8340b762 399 if (IN_SET(r, 0, -ENOSPC, -EADV)) {
c863dc05
ZJS
400 log_debug("Unable to %s system.", p);
401 return false;
402 }
b71c9758
ZJS
403 if (r < 0)
404 return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
c58493c0
ML
405 }
406
407 return true;
408}
409
28ca9c24 410static int can_sleep_internal(const char *verb, bool check_allowed, const SleepConfig *sleep_config) {
e8f1d00d 411 bool allow;
28ca9c24 412 char **modes = NULL, **states = NULL;
19adb8a3
ZJS
413 int r;
414
e68c79db 415 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
c58493c0 416
28ca9c24 417 r = sleep_settings(verb, sleep_config, &allow, &modes, &states);
19adb8a3
ZJS
418 if (r < 0)
419 return false;
420
e8f1d00d
ZJS
421 if (check_allowed && !allow) {
422 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb);
423 return false;
424 }
425
426 if (streq(verb, "suspend-then-hibernate"))
28ca9c24 427 return can_s2h(sleep_config);
e8f1d00d 428
69ab8088
ZJS
429 if (!can_sleep_state(states) || !can_sleep_disk(modes))
430 return false;
431
b71c9758
ZJS
432 if (streq(verb, "suspend"))
433 return true;
434
4638cd39 435 if (!enough_swap_for_hibernation())
b71c9758
ZJS
436 return -ENOSPC;
437
438 return true;
19adb8a3 439}
e8f1d00d
ZJS
440
441int can_sleep(const char *verb) {
28ca9c24
ZS
442 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
443 int r;
444
445 r = parse_sleep_config(&sleep_config);
446 if (r < 0)
447 return r;
448
449 return can_sleep_internal(verb, true, sleep_config);
450}
451
452int sleep_settings(const char *verb, const SleepConfig *sleep_config, bool *ret_allow, char ***ret_modes, char ***ret_states) {
453
454 assert(verb);
455 assert(sleep_config);
456 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
457
458 if (streq(verb, "suspend")) {
459 *ret_allow = sleep_config->allow_suspend;
460 *ret_modes = sleep_config->suspend_modes;
461 *ret_states = sleep_config->suspend_states;
462 } else if (streq(verb, "hibernate")) {
463 *ret_allow = sleep_config->allow_hibernate;
464 *ret_modes = sleep_config->hibernate_modes;
465 *ret_states = sleep_config->hibernate_states;
466 } else if (streq(verb, "hybrid-sleep")) {
467 *ret_allow = sleep_config->allow_hybrid_sleep;
468 *ret_modes = sleep_config->hybrid_modes;
469 *ret_states = sleep_config->hybrid_states;
470 } else if (streq(verb, "suspend-then-hibernate")) {
471 *ret_allow = sleep_config->allow_s2h;
472 *ret_modes = *ret_states = NULL;
473 }
474
475 /* suspend modes empty by default */
476 if ((!ret_modes && !streq(verb, "suspend")) || !ret_states)
477 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No modes or states set for %s; Check sleep.conf", verb);
478
479 return 0;
480}
481
482void free_sleep_config(SleepConfig *sc) {
483 if (!sc)
484 return;
485
486 strv_free(sc->suspend_modes);
487 strv_free(sc->suspend_states);
488
489 strv_free(sc->hibernate_modes);
490 strv_free(sc->hibernate_states);
491
492 strv_free(sc->hybrid_modes);
493 strv_free(sc->hybrid_states);
494
495 free(sc);
e8f1d00d 496}