]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/sleep-config.c
more 243 news
[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
17c40b3a 168int find_hibernate_location(char **device, char **type, size_t *size, size_t *used) {
9fb3675e 169 _cleanup_fclose_ FILE *f;
1fa2f38f 170 unsigned i;
9fb3675e 171
c8a202b7 172 f = fopen("/proc/swaps", "re");
9fb3675e
ZJS
173 if (!f) {
174 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
175 "Failed to retrieve open /proc/swaps: %m");
427646ea 176 return negative_errno();
9fb3675e 177 }
69ab8088 178
9fb3675e
ZJS
179 (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
180
2002d8cd 181 // TODO: sort swaps in priority order rather than using first successful option
9fb3675e 182 for (i = 1;; i++) {
17c40b3a 183 _cleanup_free_ char *dev_field = NULL, *type_field = NULL;
9fb3675e
ZJS
184 size_t size_field, used_field;
185 int k;
186
187 k = fscanf(f,
188 "%ms " /* device/file */
189 "%ms " /* type of swap */
1fa2f38f
ZJS
190 "%zu " /* swap size */
191 "%zu " /* used */
9fb3675e 192 "%*i\n", /* priority */
17c40b3a 193 &dev_field, &type_field, &size_field, &used_field);
3dea6886
LP
194 if (k == EOF)
195 break;
9fb3675e 196 if (k != 4) {
9fb3675e
ZJS
197 log_warning("Failed to parse /proc/swaps:%u", i);
198 continue;
199 }
200
3dea6886
LP
201 if (streq(type_field, "file")) {
202
411ae92b 203 if (endswith(dev_field, "\\040(deleted)")) {
3dea6886 204 log_warning("Ignoring deleted swap file '%s'.", dev_field);
411ae92b
AJ
205 continue;
206 }
207
3dea6886 208 } else if (streq(type_field, "partition")) {
411ae92b 209 const char *fn;
3dea6886 210
411ae92b
AJ
211 fn = path_startswith(dev_field, "/dev/");
212 if (fn && startswith(fn, "zram")) {
3dea6886 213 log_debug("Ignoring compressed RAM swap device '%s'.", dev_field);
411ae92b
AJ
214 continue;
215 }
9fb3675e 216 }
3dea6886 217
17c40b3a
ML
218 if (device)
219 *device = TAKE_PTR(dev_field);
220 if (type)
221 *type = TAKE_PTR(type_field);
222 if (size)
223 *size = size_field;
224 if (used)
225 *used = used_field;
9fb3675e 226 return 0;
69ab8088
ZJS
227 }
228
baaa35ad
ZJS
229 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS),
230 "No swap partitions were found.");
9fb3675e
ZJS
231}
232
4638cd39 233static bool enough_swap_for_hibernation(void) {
9fb3675e 234 _cleanup_free_ char *active = NULL;
39883f62
LP
235 unsigned long long act = 0;
236 size_t size = 0, used = 0;
9fb3675e
ZJS
237 int r;
238
490d20e6
VV
239 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
240 return true;
241
17c40b3a 242 r = find_hibernate_location(NULL, NULL, &size, &used);
9fb3675e 243 if (r < 0)
69ab8088 244 return false;
69ab8088 245
c4cd1d4d 246 r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
69ab8088 247 if (r < 0) {
904865b8 248 log_debug_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
69ab8088
ZJS
249 return false;
250 }
251
252 r = safe_atollu(active, &act);
253 if (r < 0) {
904865b8 254 log_debug_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active);
69ab8088
ZJS
255 return false;
256 }
257
9fb3675e 258 r = act <= (size - used) * HIBERNATION_SWAP_THRESHOLD;
5fdf2d51
ZJS
259 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%zu kB, used=%zu kB, threshold=%.2g%%",
260 r ? "Enough" : "Not enough", act, size, used, 100*HIBERNATION_SWAP_THRESHOLD);
69ab8088
ZJS
261
262 return r;
263}
264
17c40b3a
ML
265int read_fiemap(int fd, struct fiemap **ret) {
266 _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
17c40b3a
ML
267 struct stat statinfo;
268 uint32_t result_extents = 0;
269 uint64_t fiemap_start = 0, fiemap_length;
6524f1a8
ZJS
270 const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
271 size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
17c40b3a
ML
272
273 if (fstat(fd, &statinfo) < 0)
274 return log_debug_errno(errno, "Cannot determine file size: %m");
275 if (!S_ISREG(statinfo.st_mode))
276 return -ENOTTY;
277 fiemap_length = statinfo.st_size;
278
6524f1a8
ZJS
279 /* Zero this out in case we run on a file with no extents */
280 fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
281 if (!fiemap)
282 return -ENOMEM;
283
6524f1a8 284 result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
285 if (!result_fiemap)
286 return -ENOMEM;
287
288 /* XFS filesystem has incorrect implementation of fiemap ioctl and
289 * returns extents for only one block-group at a time, so we need
290 * to handle it manually, starting the next fiemap call from the end
291 * of the last extent
292 */
293 while (fiemap_start < fiemap_length) {
294 *fiemap = (struct fiemap) {
295 .fm_start = fiemap_start,
296 .fm_length = fiemap_length,
297 .fm_flags = FIEMAP_FLAG_SYNC,
298 };
299
300 /* Find out how many extents there are */
301 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
302 return log_debug_errno(errno, "Failed to read extents: %m");
303
304 /* Nothing to process */
305 if (fiemap->fm_mapped_extents == 0)
306 break;
307
6524f1a8
ZJS
308 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
309 * the extents for the whole file. Add space for the initial struct fiemap. */
310 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
311 n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
312 return -ENOMEM;
313
314 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
315 fiemap->fm_mapped_extents = 0;
316
317 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
318 return log_debug_errno(errno, "Failed to read extents: %m");
319
6524f1a8
ZJS
320 /* Resize result_fiemap to allow us to copy in the extents */
321 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
322 n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
323 return -ENOMEM;
324
325 memcpy(result_fiemap->fm_extents + result_extents,
326 fiemap->fm_extents,
327 sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
328
329 result_extents += fiemap->fm_mapped_extents;
330
331 /* Highly unlikely that it is zero */
6524f1a8 332 if (_likely_(fiemap->fm_mapped_extents > 0)) {
17c40b3a
ML
333 uint32_t i = fiemap->fm_mapped_extents - 1;
334
335 fiemap_start = fiemap->fm_extents[i].fe_logical +
336 fiemap->fm_extents[i].fe_length;
337
338 if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
339 break;
340 }
341 }
342
343 memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
344 result_fiemap->fm_mapped_extents = result_extents;
345 *ret = TAKE_PTR(result_fiemap);
346 return 0;
347}
348
28ca9c24 349static int can_sleep_internal(const char *verb, bool check_allowed, const SleepConfig *sleep_config);
e8f1d00d 350
28ca9c24 351static bool can_s2h(const SleepConfig *sleep_config) {
c863dc05 352 const char *p;
c58493c0
ML
353 int r;
354
1bbbefe7 355 if (!clock_supported(CLOCK_BOOTTIME_ALARM)) {
c58493c0 356 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
1bbbefe7 357 "CLOCK_BOOTTIME_ALARM is not supported");
c58493c0
ML
358 return false;
359 }
360
c863dc05 361 FOREACH_STRING(p, "suspend", "hibernate") {
28ca9c24 362 r = can_sleep_internal(p, false, sleep_config);
8340b762 363 if (IN_SET(r, 0, -ENOSPC, -EADV)) {
c863dc05
ZJS
364 log_debug("Unable to %s system.", p);
365 return false;
366 }
b71c9758
ZJS
367 if (r < 0)
368 return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
c58493c0
ML
369 }
370
371 return true;
372}
373
28ca9c24 374static int can_sleep_internal(const char *verb, bool check_allowed, const SleepConfig *sleep_config) {
e8f1d00d 375 bool allow;
28ca9c24 376 char **modes = NULL, **states = NULL;
19adb8a3
ZJS
377 int r;
378
e68c79db 379 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
c58493c0 380
28ca9c24 381 r = sleep_settings(verb, sleep_config, &allow, &modes, &states);
19adb8a3
ZJS
382 if (r < 0)
383 return false;
384
e8f1d00d
ZJS
385 if (check_allowed && !allow) {
386 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb);
387 return false;
388 }
389
390 if (streq(verb, "suspend-then-hibernate"))
28ca9c24 391 return can_s2h(sleep_config);
e8f1d00d 392
69ab8088
ZJS
393 if (!can_sleep_state(states) || !can_sleep_disk(modes))
394 return false;
395
b71c9758
ZJS
396 if (streq(verb, "suspend"))
397 return true;
398
4638cd39 399 if (!enough_swap_for_hibernation())
b71c9758
ZJS
400 return -ENOSPC;
401
402 return true;
19adb8a3 403}
e8f1d00d
ZJS
404
405int can_sleep(const char *verb) {
28ca9c24
ZS
406 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
407 int r;
408
409 r = parse_sleep_config(&sleep_config);
410 if (r < 0)
411 return r;
412
413 return can_sleep_internal(verb, true, sleep_config);
414}
415
416int sleep_settings(const char *verb, const SleepConfig *sleep_config, bool *ret_allow, char ***ret_modes, char ***ret_states) {
417
418 assert(verb);
419 assert(sleep_config);
420 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
421
422 if (streq(verb, "suspend")) {
423 *ret_allow = sleep_config->allow_suspend;
424 *ret_modes = sleep_config->suspend_modes;
425 *ret_states = sleep_config->suspend_states;
426 } else if (streq(verb, "hibernate")) {
427 *ret_allow = sleep_config->allow_hibernate;
428 *ret_modes = sleep_config->hibernate_modes;
429 *ret_states = sleep_config->hibernate_states;
430 } else if (streq(verb, "hybrid-sleep")) {
431 *ret_allow = sleep_config->allow_hybrid_sleep;
432 *ret_modes = sleep_config->hybrid_modes;
433 *ret_states = sleep_config->hybrid_states;
434 } else if (streq(verb, "suspend-then-hibernate")) {
435 *ret_allow = sleep_config->allow_s2h;
436 *ret_modes = *ret_states = NULL;
437 }
438
439 /* suspend modes empty by default */
440 if ((!ret_modes && !streq(verb, "suspend")) || !ret_states)
441 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No modes or states set for %s; Check sleep.conf", verb);
442
443 return 0;
444}
445
446void free_sleep_config(SleepConfig *sc) {
447 if (!sc)
448 return;
449
450 strv_free(sc->suspend_modes);
451 strv_free(sc->suspend_states);
452
453 strv_free(sc->hibernate_modes);
454 strv_free(sc->hibernate_states);
455
456 strv_free(sc->hybrid_modes);
457 strv_free(sc->hybrid_states);
458
459 free(sc);
e8f1d00d 460}