]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/sleep-config.c
test-fileio: do not use variable before checking return value
[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>
17c40b3a 7#include <linux/fs.h>
a8fbdf54
TA
8#include <stdbool.h>
9#include <stddef.h>
19adb8a3 10#include <stdio.h>
a8fbdf54 11#include <string.h>
36dd5ffd 12#include <sys/ioctl.h>
a8fbdf54
TA
13#include <syslog.h>
14#include <unistd.h>
19adb8a3 15
b5efdb8a 16#include "alloc-util.h"
19adb8a3 17#include "conf-parser.h"
a0f29c76 18#include "def.h"
490d20e6 19#include "env-util.h"
427646ea 20#include "errno-util.h"
3ffd4af2 21#include "fd-util.h"
19adb8a3
ZJS
22#include "fileio.h"
23#include "log.h"
a8fbdf54 24#include "macro.h"
a0f29c76 25#include "parse-util.h"
411ae92b 26#include "path-util.h"
3ffd4af2 27#include "sleep-config.h"
07630cea 28#include "string-util.h"
19adb8a3 29#include "strv.h"
19adb8a3 30
e8f1d00d
ZJS
31int parse_sleep_config(const char *verb, bool *ret_allow, char ***ret_modes, char ***ret_states, usec_t *ret_delay) {
32 int allow_suspend = -1, allow_hibernate = -1,
33 allow_s2h = -1, allow_hybrid_sleep = -1;
34 bool allow;
19adb8a3
ZJS
35 _cleanup_strv_free_ char
36 **suspend_mode = NULL, **suspend_state = NULL,
37 **hibernate_mode = NULL, **hibernate_state = NULL,
38 **hybrid_mode = NULL, **hybrid_state = NULL;
db983479 39 _cleanup_strv_free_ char **modes, **states; /* always initialized below */
9aa2e409 40 usec_t delay = 180 * USEC_PER_MINUTE;
19adb8a3
ZJS
41
42 const ConfigTableItem items[] = {
e8f1d00d
ZJS
43 { "Sleep", "AllowSuspend", config_parse_tristate, 0, &allow_suspend },
44 { "Sleep", "AllowHibernation", config_parse_tristate, 0, &allow_hibernate },
45 { "Sleep", "AllowSuspendThenHibernate", config_parse_tristate, 0, &allow_s2h },
46 { "Sleep", "AllowHybridSleep", config_parse_tristate, 0, &allow_hybrid_sleep },
47
48 { "Sleep", "SuspendMode", config_parse_strv, 0, &suspend_mode },
49 { "Sleep", "SuspendState", config_parse_strv, 0, &suspend_state },
50 { "Sleep", "HibernateMode", config_parse_strv, 0, &hibernate_mode },
51 { "Sleep", "HibernateState", config_parse_strv, 0, &hibernate_state },
52 { "Sleep", "HybridSleepMode", config_parse_strv, 0, &hybrid_mode },
53 { "Sleep", "HybridSleepState", config_parse_strv, 0, &hybrid_state },
54
55 { "Sleep", "HibernateDelaySec", config_parse_sec, 0, &delay},
34c10968
LP
56 {}
57 };
19adb8a3 58
bcde742e
LP
59 (void) config_parse_many_nulstr(PKGSYSCONFDIR "/sleep.conf",
60 CONF_PATHS_NULSTR("systemd/sleep.conf.d"),
61 "Sleep\0", config_item_table_lookup, items,
62 CONFIG_PARSE_WARN, NULL);
19adb8a3 63
19adb8a3 64 if (streq(verb, "suspend")) {
e8f1d00d
ZJS
65 allow = allow_suspend != 0;
66
19adb8a3 67 /* empty by default */
2f4cefe6 68 modes = TAKE_PTR(suspend_mode);
19adb8a3
ZJS
69
70 if (suspend_state)
2f4cefe6 71 states = TAKE_PTR(suspend_state);
19adb8a3 72 else
bea1a013 73 states = strv_new("mem", "standby", "freeze");
19adb8a3 74
19adb8a3 75 } else if (streq(verb, "hibernate")) {
e8f1d00d
ZJS
76 allow = allow_hibernate != 0;
77
19adb8a3 78 if (hibernate_mode)
2f4cefe6 79 modes = TAKE_PTR(hibernate_mode);
19adb8a3 80 else
bea1a013 81 modes = strv_new("platform", "shutdown");
19adb8a3
ZJS
82
83 if (hibernate_state)
2f4cefe6 84 states = TAKE_PTR(hibernate_state);
19adb8a3 85 else
bea1a013 86 states = strv_new("disk");
19adb8a3 87
19adb8a3 88 } else if (streq(verb, "hybrid-sleep")) {
e8f1d00d
ZJS
89 allow = allow_hybrid_sleep > 0 ||
90 (allow_suspend != 0 && allow_hibernate != 0);
91
19adb8a3 92 if (hybrid_mode)
2f4cefe6 93 modes = TAKE_PTR(hybrid_mode);
19adb8a3 94 else
bea1a013 95 modes = strv_new("suspend", "platform", "shutdown");
19adb8a3
ZJS
96
97 if (hybrid_state)
2f4cefe6 98 states = TAKE_PTR(hybrid_state);
19adb8a3 99 else
bea1a013 100 states = strv_new("disk");
9aa2e409 101
e8f1d00d
ZJS
102 } else if (streq(verb, "suspend-then-hibernate")) {
103 allow = allow_s2h > 0 ||
104 (allow_suspend != 0 && allow_hibernate != 0);
105
9aa2e409 106 modes = states = NULL;
e8f1d00d 107 } else
19adb8a3
ZJS
108 assert_not_reached("what verb");
109
9aa2e409 110 if ((!modes && STR_IN_SET(verb, "hibernate", "hybrid-sleep")) ||
db983479 111 (!states && !streq(verb, "suspend-then-hibernate")))
19adb8a3 112 return log_oom();
19adb8a3 113
e8f1d00d
ZJS
114 if (ret_allow)
115 *ret_allow = allow;
116 if (ret_modes)
117 *ret_modes = TAKE_PTR(modes);
118 if (ret_states)
119 *ret_states = TAKE_PTR(states);
120 if (ret_delay)
121 *ret_delay = delay;
c58493c0 122
19adb8a3
ZJS
123 return 0;
124}
125
126int can_sleep_state(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 */
135 if (access("/sys/power/state", W_OK) < 0)
136 return false;
137
138 r = read_one_line_file("/sys/power/state", &p);
139 if (r < 0)
140 return false;
141
142 STRV_FOREACH(type, types) {
a2a5291b 143 const char *word, *state;
19adb8a3
ZJS
144 size_t l, k;
145
146 k = strlen(*type);
a2a5291b
ZJS
147 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state)
148 if (l == k && memcmp(word, *type, l) == 0)
19adb8a3
ZJS
149 return true;
150 }
151
152 return false;
153}
154
155int can_sleep_disk(char **types) {
a2a5291b 156 char **type;
19adb8a3
ZJS
157 int r;
158 _cleanup_free_ char *p = NULL;
159
160 if (strv_isempty(types))
161 return true;
162
163 /* If /sys is read-only we cannot sleep */
7474f15b
LP
164 if (access("/sys/power/disk", W_OK) < 0) {
165 log_debug_errno(errno, "/sys/power/disk is not writable: %m");
19adb8a3 166 return false;
7474f15b 167 }
19adb8a3
ZJS
168
169 r = read_one_line_file("/sys/power/disk", &p);
7474f15b
LP
170 if (r < 0) {
171 log_debug_errno(r, "Couldn't read /sys/power/disk: %m");
19adb8a3 172 return false;
7474f15b 173 }
19adb8a3
ZJS
174
175 STRV_FOREACH(type, types) {
a2a5291b 176 const char *word, *state;
19adb8a3
ZJS
177 size_t l, k;
178
179 k = strlen(*type);
a2a5291b
ZJS
180 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state) {
181 if (l == k && memcmp(word, *type, l) == 0)
19adb8a3
ZJS
182 return true;
183
a2a5291b
ZJS
184 if (l == k + 2 &&
185 word[0] == '[' &&
186 memcmp(word + 1, *type, l - 2) == 0 &&
187 word[l-1] == ']')
19adb8a3
ZJS
188 return true;
189 }
190 }
191
192 return false;
193}
194
69ab8088
ZJS
195#define HIBERNATION_SWAP_THRESHOLD 0.98
196
17c40b3a 197int find_hibernate_location(char **device, char **type, size_t *size, size_t *used) {
9fb3675e 198 _cleanup_fclose_ FILE *f;
1fa2f38f 199 unsigned i;
9fb3675e 200
c8a202b7 201 f = fopen("/proc/swaps", "re");
9fb3675e
ZJS
202 if (!f) {
203 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
204 "Failed to retrieve open /proc/swaps: %m");
427646ea 205 return negative_errno();
9fb3675e 206 }
69ab8088 207
9fb3675e
ZJS
208 (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
209
210 for (i = 1;; i++) {
17c40b3a 211 _cleanup_free_ char *dev_field = NULL, *type_field = NULL;
9fb3675e
ZJS
212 size_t size_field, used_field;
213 int k;
214
215 k = fscanf(f,
216 "%ms " /* device/file */
217 "%ms " /* type of swap */
1fa2f38f
ZJS
218 "%zu " /* swap size */
219 "%zu " /* used */
9fb3675e 220 "%*i\n", /* priority */
17c40b3a 221 &dev_field, &type_field, &size_field, &used_field);
3dea6886
LP
222 if (k == EOF)
223 break;
9fb3675e 224 if (k != 4) {
9fb3675e
ZJS
225 log_warning("Failed to parse /proc/swaps:%u", i);
226 continue;
227 }
228
3dea6886
LP
229 if (streq(type_field, "file")) {
230
411ae92b 231 if (endswith(dev_field, "\\040(deleted)")) {
3dea6886 232 log_warning("Ignoring deleted swap file '%s'.", dev_field);
411ae92b
AJ
233 continue;
234 }
235
3dea6886 236 } else if (streq(type_field, "partition")) {
411ae92b 237 const char *fn;
3dea6886 238
411ae92b
AJ
239 fn = path_startswith(dev_field, "/dev/");
240 if (fn && startswith(fn, "zram")) {
3dea6886 241 log_debug("Ignoring compressed RAM swap device '%s'.", dev_field);
411ae92b
AJ
242 continue;
243 }
9fb3675e 244 }
3dea6886 245
17c40b3a
ML
246 if (device)
247 *device = TAKE_PTR(dev_field);
248 if (type)
249 *type = TAKE_PTR(type_field);
250 if (size)
251 *size = size_field;
252 if (used)
253 *used = used_field;
9fb3675e 254 return 0;
69ab8088
ZJS
255 }
256
baaa35ad
ZJS
257 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS),
258 "No swap partitions were found.");
9fb3675e
ZJS
259}
260
4638cd39 261static bool enough_swap_for_hibernation(void) {
9fb3675e 262 _cleanup_free_ char *active = NULL;
39883f62
LP
263 unsigned long long act = 0;
264 size_t size = 0, used = 0;
9fb3675e
ZJS
265 int r;
266
490d20e6
VV
267 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
268 return true;
269
17c40b3a 270 r = find_hibernate_location(NULL, NULL, &size, &used);
9fb3675e 271 if (r < 0)
69ab8088 272 return false;
69ab8088 273
c4cd1d4d 274 r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
69ab8088 275 if (r < 0) {
904865b8 276 log_debug_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
69ab8088
ZJS
277 return false;
278 }
279
280 r = safe_atollu(active, &act);
281 if (r < 0) {
904865b8 282 log_debug_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active);
69ab8088
ZJS
283 return false;
284 }
285
9fb3675e 286 r = act <= (size - used) * HIBERNATION_SWAP_THRESHOLD;
5fdf2d51
ZJS
287 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%zu kB, used=%zu kB, threshold=%.2g%%",
288 r ? "Enough" : "Not enough", act, size, used, 100*HIBERNATION_SWAP_THRESHOLD);
69ab8088
ZJS
289
290 return r;
291}
292
17c40b3a
ML
293int read_fiemap(int fd, struct fiemap **ret) {
294 _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
17c40b3a
ML
295 struct stat statinfo;
296 uint32_t result_extents = 0;
297 uint64_t fiemap_start = 0, fiemap_length;
6524f1a8
ZJS
298 const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
299 size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
17c40b3a
ML
300
301 if (fstat(fd, &statinfo) < 0)
302 return log_debug_errno(errno, "Cannot determine file size: %m");
303 if (!S_ISREG(statinfo.st_mode))
304 return -ENOTTY;
305 fiemap_length = statinfo.st_size;
306
6524f1a8
ZJS
307 /* Zero this out in case we run on a file with no extents */
308 fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
309 if (!fiemap)
310 return -ENOMEM;
311
6524f1a8 312 result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
17c40b3a
ML
313 if (!result_fiemap)
314 return -ENOMEM;
315
316 /* XFS filesystem has incorrect implementation of fiemap ioctl and
317 * returns extents for only one block-group at a time, so we need
318 * to handle it manually, starting the next fiemap call from the end
319 * of the last extent
320 */
321 while (fiemap_start < fiemap_length) {
322 *fiemap = (struct fiemap) {
323 .fm_start = fiemap_start,
324 .fm_length = fiemap_length,
325 .fm_flags = FIEMAP_FLAG_SYNC,
326 };
327
328 /* Find out how many extents there are */
329 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
330 return log_debug_errno(errno, "Failed to read extents: %m");
331
332 /* Nothing to process */
333 if (fiemap->fm_mapped_extents == 0)
334 break;
335
6524f1a8
ZJS
336 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
337 * the extents for the whole file. Add space for the initial struct fiemap. */
338 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
339 n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
340 return -ENOMEM;
341
342 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
343 fiemap->fm_mapped_extents = 0;
344
345 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
346 return log_debug_errno(errno, "Failed to read extents: %m");
347
6524f1a8
ZJS
348 /* Resize result_fiemap to allow us to copy in the extents */
349 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
350 n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
17c40b3a
ML
351 return -ENOMEM;
352
353 memcpy(result_fiemap->fm_extents + result_extents,
354 fiemap->fm_extents,
355 sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
356
357 result_extents += fiemap->fm_mapped_extents;
358
359 /* Highly unlikely that it is zero */
6524f1a8 360 if (_likely_(fiemap->fm_mapped_extents > 0)) {
17c40b3a
ML
361 uint32_t i = fiemap->fm_mapped_extents - 1;
362
363 fiemap_start = fiemap->fm_extents[i].fe_logical +
364 fiemap->fm_extents[i].fe_length;
365
366 if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
367 break;
368 }
369 }
370
371 memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
372 result_fiemap->fm_mapped_extents = result_extents;
373 *ret = TAKE_PTR(result_fiemap);
374 return 0;
375}
376
e8f1d00d
ZJS
377static int can_sleep_internal(const char *verb, bool check_allowed);
378
c58493c0 379static bool can_s2h(void) {
c863dc05 380 const char *p;
c58493c0
ML
381 int r;
382
383 r = access("/sys/class/rtc/rtc0/wakealarm", W_OK);
384 if (r < 0) {
385 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
386 "/sys/class/rct/rct0/wakealarm is not writable %m");
387 return false;
388 }
389
c863dc05 390 FOREACH_STRING(p, "suspend", "hibernate") {
e8f1d00d 391 r = can_sleep_internal(p, false);
8340b762 392 if (IN_SET(r, 0, -ENOSPC, -EADV)) {
c863dc05
ZJS
393 log_debug("Unable to %s system.", p);
394 return false;
395 }
b71c9758
ZJS
396 if (r < 0)
397 return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
c58493c0
ML
398 }
399
400 return true;
401}
402
e8f1d00d
ZJS
403static int can_sleep_internal(const char *verb, bool check_allowed) {
404 bool allow;
19adb8a3
ZJS
405 _cleanup_strv_free_ char **modes = NULL, **states = NULL;
406 int r;
407
e68c79db 408 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
c58493c0 409
e8f1d00d 410 r = parse_sleep_config(verb, &allow, &modes, &states, NULL);
19adb8a3
ZJS
411 if (r < 0)
412 return false;
413
e8f1d00d
ZJS
414 if (check_allowed && !allow) {
415 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb);
416 return false;
417 }
418
419 if (streq(verb, "suspend-then-hibernate"))
420 return can_s2h();
421
69ab8088
ZJS
422 if (!can_sleep_state(states) || !can_sleep_disk(modes))
423 return false;
424
b71c9758
ZJS
425 if (streq(verb, "suspend"))
426 return true;
427
4638cd39 428 if (!enough_swap_for_hibernation())
b71c9758
ZJS
429 return -ENOSPC;
430
431 return true;
19adb8a3 432}
e8f1d00d
ZJS
433
434int can_sleep(const char *verb) {
435 return can_sleep_internal(verb, true);
436}