]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/sleep-config.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / shared / sleep-config.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2013 Zbigniew Jędrzejewski-Szmek
4 Copyright 2018 Dell Inc.
5 ***/
6
7 #include <errno.h>
8 #include <linux/fs.h>
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <syslog.h>
14 #include <unistd.h>
15
16 #include "alloc-util.h"
17 #include "conf-parser.h"
18 #include "def.h"
19 #include "env-util.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "log.h"
23 #include "macro.h"
24 #include "parse-util.h"
25 #include "sleep-config.h"
26 #include "string-util.h"
27 #include "strv.h"
28
29 int parse_sleep_config(const char *verb, char ***_modes, char ***_states, usec_t *_delay) {
30
31 _cleanup_strv_free_ char
32 **suspend_mode = NULL, **suspend_state = NULL,
33 **hibernate_mode = NULL, **hibernate_state = NULL,
34 **hybrid_mode = NULL, **hybrid_state = NULL;
35 _cleanup_strv_free_ char **modes, **states; /* always initialized below */
36 usec_t delay = 180 * USEC_PER_MINUTE;
37
38 const ConfigTableItem items[] = {
39 { "Sleep", "SuspendMode", config_parse_strv, 0, &suspend_mode },
40 { "Sleep", "SuspendState", config_parse_strv, 0, &suspend_state },
41 { "Sleep", "HibernateMode", config_parse_strv, 0, &hibernate_mode },
42 { "Sleep", "HibernateState", config_parse_strv, 0, &hibernate_state },
43 { "Sleep", "HybridSleepMode", config_parse_strv, 0, &hybrid_mode },
44 { "Sleep", "HybridSleepState", config_parse_strv, 0, &hybrid_state },
45 { "Sleep", "HibernateDelaySec", config_parse_sec, 0, &delay},
46 {}
47 };
48
49 (void) config_parse_many_nulstr(PKGSYSCONFDIR "/sleep.conf",
50 CONF_PATHS_NULSTR("systemd/sleep.conf.d"),
51 "Sleep\0", config_item_table_lookup, items,
52 CONFIG_PARSE_WARN, NULL);
53
54 if (streq(verb, "suspend")) {
55 /* empty by default */
56 modes = TAKE_PTR(suspend_mode);
57
58 if (suspend_state)
59 states = TAKE_PTR(suspend_state);
60 else
61 states = strv_new("mem", "standby", "freeze", NULL);
62
63 } else if (streq(verb, "hibernate")) {
64 if (hibernate_mode)
65 modes = TAKE_PTR(hibernate_mode);
66 else
67 modes = strv_new("platform", "shutdown", NULL);
68
69 if (hibernate_state)
70 states = TAKE_PTR(hibernate_state);
71 else
72 states = strv_new("disk", NULL);
73
74 } else if (streq(verb, "hybrid-sleep")) {
75 if (hybrid_mode)
76 modes = TAKE_PTR(hybrid_mode);
77 else
78 modes = strv_new("suspend", "platform", "shutdown", NULL);
79
80 if (hybrid_state)
81 states = TAKE_PTR(hybrid_state);
82 else
83 states = strv_new("disk", NULL);
84
85 } else if (streq(verb, "suspend-then-hibernate"))
86 modes = states = NULL;
87 else
88 assert_not_reached("what verb");
89
90 if ((!modes && STR_IN_SET(verb, "hibernate", "hybrid-sleep")) ||
91 (!states && !streq(verb, "suspend-then-hibernate")))
92 return log_oom();
93
94 if (_modes)
95 *_modes = TAKE_PTR(modes);
96 if (_states)
97 *_states = TAKE_PTR(states);
98 if (_delay)
99 *_delay = delay;
100
101 return 0;
102 }
103
104 int can_sleep_state(char **types) {
105 char **type;
106 int r;
107 _cleanup_free_ char *p = NULL;
108
109 if (strv_isempty(types))
110 return true;
111
112 /* If /sys is read-only we cannot sleep */
113 if (access("/sys/power/state", W_OK) < 0)
114 return false;
115
116 r = read_one_line_file("/sys/power/state", &p);
117 if (r < 0)
118 return false;
119
120 STRV_FOREACH(type, types) {
121 const char *word, *state;
122 size_t l, k;
123
124 k = strlen(*type);
125 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state)
126 if (l == k && memcmp(word, *type, l) == 0)
127 return true;
128 }
129
130 return false;
131 }
132
133 int can_sleep_disk(char **types) {
134 char **type;
135 int r;
136 _cleanup_free_ char *p = NULL;
137
138 if (strv_isempty(types))
139 return true;
140
141 /* If /sys is read-only we cannot sleep */
142 if (access("/sys/power/disk", W_OK) < 0)
143 return false;
144
145 r = read_one_line_file("/sys/power/disk", &p);
146 if (r < 0)
147 return false;
148
149 STRV_FOREACH(type, types) {
150 const char *word, *state;
151 size_t l, k;
152
153 k = strlen(*type);
154 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state) {
155 if (l == k && memcmp(word, *type, l) == 0)
156 return true;
157
158 if (l == k + 2 &&
159 word[0] == '[' &&
160 memcmp(word + 1, *type, l - 2) == 0 &&
161 word[l-1] == ']')
162 return true;
163 }
164 }
165
166 return false;
167 }
168
169 #define HIBERNATION_SWAP_THRESHOLD 0.98
170
171 int find_hibernate_location(char **device, char **type, size_t *size, size_t *used) {
172 _cleanup_fclose_ FILE *f;
173 unsigned i;
174
175 f = fopen("/proc/swaps", "re");
176 if (!f) {
177 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
178 "Failed to retrieve open /proc/swaps: %m");
179 assert(errno > 0);
180 return -errno;
181 }
182
183 (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
184
185 for (i = 1;; i++) {
186 _cleanup_free_ char *dev_field = NULL, *type_field = NULL;
187 size_t size_field, used_field;
188 int k;
189
190 k = fscanf(f,
191 "%ms " /* device/file */
192 "%ms " /* type of swap */
193 "%zu " /* swap size */
194 "%zu " /* used */
195 "%*i\n", /* priority */
196 &dev_field, &type_field, &size_field, &used_field);
197 if (k != 4) {
198 if (k == EOF)
199 break;
200
201 log_warning("Failed to parse /proc/swaps:%u", i);
202 continue;
203 }
204
205 if (streq(type_field, "partition") && endswith(dev_field, "\\040(deleted)")) {
206 log_warning("Ignoring deleted swapfile '%s'.", dev_field);
207 continue;
208 }
209 if (device)
210 *device = TAKE_PTR(dev_field);
211 if (type)
212 *type = TAKE_PTR(type_field);
213 if (size)
214 *size = size_field;
215 if (used)
216 *used = used_field;
217 return 0;
218 }
219
220 log_debug("No swap partitions were found.");
221 return -ENOSYS;
222 }
223
224 static bool enough_swap_for_hibernation(void) {
225 _cleanup_free_ char *active = NULL;
226 unsigned long long act = 0;
227 size_t size = 0, used = 0;
228 int r;
229
230 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
231 return true;
232
233 r = find_hibernate_location(NULL, NULL, &size, &used);
234 if (r < 0)
235 return false;
236
237 r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
238 if (r < 0) {
239 log_error_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
240 return false;
241 }
242
243 r = safe_atollu(active, &act);
244 if (r < 0) {
245 log_error_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m",
246 active);
247 return false;
248 }
249
250 r = act <= (size - used) * HIBERNATION_SWAP_THRESHOLD;
251 log_debug("Hibernation is %spossible, Active(anon)=%llu kB, size=%zu kB, used=%zu kB, threshold=%.2g%%",
252 r ? "" : "im", act, size, used, 100*HIBERNATION_SWAP_THRESHOLD);
253
254 return r;
255 }
256
257 int read_fiemap(int fd, struct fiemap **ret) {
258 _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
259 struct stat statinfo;
260 uint32_t result_extents = 0;
261 uint64_t fiemap_start = 0, fiemap_length;
262 const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
263 size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
264
265 if (fstat(fd, &statinfo) < 0)
266 return log_debug_errno(errno, "Cannot determine file size: %m");
267 if (!S_ISREG(statinfo.st_mode))
268 return -ENOTTY;
269 fiemap_length = statinfo.st_size;
270
271 /* Zero this out in case we run on a file with no extents */
272 fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
273 if (!fiemap)
274 return -ENOMEM;
275
276 result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
277 if (!result_fiemap)
278 return -ENOMEM;
279
280 /* XFS filesystem has incorrect implementation of fiemap ioctl and
281 * returns extents for only one block-group at a time, so we need
282 * to handle it manually, starting the next fiemap call from the end
283 * of the last extent
284 */
285 while (fiemap_start < fiemap_length) {
286 *fiemap = (struct fiemap) {
287 .fm_start = fiemap_start,
288 .fm_length = fiemap_length,
289 .fm_flags = FIEMAP_FLAG_SYNC,
290 };
291
292 /* Find out how many extents there are */
293 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
294 return log_debug_errno(errno, "Failed to read extents: %m");
295
296 /* Nothing to process */
297 if (fiemap->fm_mapped_extents == 0)
298 break;
299
300 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
301 * the extents for the whole file. Add space for the initial struct fiemap. */
302 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
303 n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
304 return -ENOMEM;
305
306 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
307 fiemap->fm_mapped_extents = 0;
308
309 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
310 return log_debug_errno(errno, "Failed to read extents: %m");
311
312 /* Resize result_fiemap to allow us to copy in the extents */
313 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
314 n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
315 return -ENOMEM;
316
317 memcpy(result_fiemap->fm_extents + result_extents,
318 fiemap->fm_extents,
319 sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
320
321 result_extents += fiemap->fm_mapped_extents;
322
323 /* Highly unlikely that it is zero */
324 if (_likely_(fiemap->fm_mapped_extents > 0)) {
325 uint32_t i = fiemap->fm_mapped_extents - 1;
326
327 fiemap_start = fiemap->fm_extents[i].fe_logical +
328 fiemap->fm_extents[i].fe_length;
329
330 if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
331 break;
332 }
333 }
334
335 memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
336 result_fiemap->fm_mapped_extents = result_extents;
337 *ret = TAKE_PTR(result_fiemap);
338 return 0;
339 }
340
341 static bool can_s2h(void) {
342 const char *p;
343 int r;
344
345 r = access("/sys/class/rtc/rtc0/wakealarm", W_OK);
346 if (r < 0) {
347 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
348 "/sys/class/rct/rct0/wakealarm is not writable %m");
349 return false;
350 }
351
352 FOREACH_STRING(p, "suspend", "hibernate") {
353 r = can_sleep(p);
354 if (IN_SET(r, 0, -ENOSPC)) {
355 log_debug("Unable to %s system.", p);
356 return false;
357 }
358 if (r < 0)
359 return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
360 }
361
362 return true;
363 }
364
365 int can_sleep(const char *verb) {
366 _cleanup_strv_free_ char **modes = NULL, **states = NULL;
367 int r;
368
369 assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
370
371 if (streq(verb, "suspend-then-hibernate"))
372 return can_s2h();
373
374 r = parse_sleep_config(verb, &modes, &states, NULL);
375 if (r < 0)
376 return false;
377
378 if (!can_sleep_state(states) || !can_sleep_disk(modes))
379 return false;
380
381 if (streq(verb, "suspend"))
382 return true;
383
384 if (!enough_swap_for_hibernation())
385 return -ENOSPC;
386
387 return true;
388 }