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