chiark / gitweb /
Prep v239: A few cosmetic upgrades
[elogind.git] / src / shared / sleep-config.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright © 2018 Dell Inc.
4 ***/
5
6 //#include <errno.h>
7 #include <linux/fs.h>
8 //#include <stdbool.h>
9 //#include <stddef.h>
10 //#include <stdio.h>
11 //#include <string.h>
12 //#include <syslog.h>
13 //#include <unistd.h>
14
15 #include "alloc-util.h"
16 //#include "conf-parser.h"
17 //#include "def.h"
18 //#include "env-util.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 //#include "log.h"
22 //#include "macro.h"
23 #include "parse-util.h"
24 #include "sleep-config.h"
25 #include "string-util.h"
26 #include "strv.h"
27
28 #if 0 /// UNNEEDED by elogind
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("elogind/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 #endif // 0
104
105 #if 1 /// Only available in this file for elogind
106 static
107 #endif // 1
108 int can_sleep_state(char **types) {
109         char **type;
110         int r;
111         _cleanup_free_ char *p = NULL;
112
113         if (strv_isempty(types))
114                 return true;
115
116         /* If /sys is read-only we cannot sleep */
117         if (access("/sys/power/state", W_OK) < 0)
118                 return false;
119
120         r = read_one_line_file("/sys/power/state", &p);
121         if (r < 0)
122                 return false;
123
124         STRV_FOREACH(type, types) {
125                 const char *word, *state;
126                 size_t l, k;
127
128                 k = strlen(*type);
129                 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state)
130                         if (l == k && memcmp(word, *type, l) == 0)
131                                 return true;
132         }
133
134         return false;
135 }
136
137 #if 1 /// Only available in this file for elogind
138 static
139 #endif // 1
140 int can_sleep_disk(char **types) {
141         char **type;
142         int r;
143         _cleanup_free_ char *p = NULL;
144
145         if (strv_isempty(types))
146                 return true;
147
148         /* If /sys is read-only we cannot sleep */
149         if (access("/sys/power/disk", W_OK) < 0)
150                 return false;
151
152         r = read_one_line_file("/sys/power/disk", &p);
153         if (r < 0)
154                 return false;
155
156         STRV_FOREACH(type, types) {
157                 const char *word, *state;
158                 size_t l, k;
159
160                 k = strlen(*type);
161                 FOREACH_WORD_SEPARATOR(word, l, p, WHITESPACE, state) {
162                         if (l == k && memcmp(word, *type, l) == 0)
163                                 return true;
164
165                         if (l == k + 2 &&
166                             word[0] == '[' &&
167                             memcmp(word + 1, *type, l - 2) == 0 &&
168                             word[l-1] == ']')
169                                 return true;
170                 }
171         }
172
173         return false;
174 }
175
176 #define HIBERNATION_SWAP_THRESHOLD 0.98
177
178 int find_hibernate_location(char **device, char **type, size_t *size, size_t *used) {
179         _cleanup_fclose_ FILE *f;
180         unsigned i;
181
182         f = fopen("/proc/swaps", "re");
183         if (!f) {
184                 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
185                          "Failed to retrieve open /proc/swaps: %m");
186                 assert(errno > 0);
187                 return -errno;
188         }
189
190         (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
191
192         for (i = 1;; i++) {
193                 _cleanup_free_ char *dev_field = NULL, *type_field = NULL;
194                 size_t size_field, used_field;
195                 int k;
196
197                 k = fscanf(f,
198                            "%ms "   /* device/file */
199                            "%ms "   /* type of swap */
200                            "%zu "   /* swap size */
201                            "%zu "   /* used */
202                            "%*i\n", /* priority */
203                            &dev_field, &type_field, &size_field, &used_field);
204                 if (k != 4) {
205                         if (k == EOF)
206                                 break;
207
208                         log_warning("Failed to parse /proc/swaps:%u", i);
209                         continue;
210                 }
211
212                 if (streq(type_field, "partition") && endswith(dev_field, "\\040(deleted)")) {
213                         log_warning("Ignoring deleted swapfile '%s'.", dev_field);
214                         continue;
215                 }
216                 if (device)
217                         *device = TAKE_PTR(dev_field);
218                 if (type)
219                         *type = TAKE_PTR(type_field);
220                 if (size)
221                         *size = size_field;
222                 if (used)
223                         *used = used_field;
224                 return 0;
225         }
226
227         log_debug("No swap partitions were found.");
228         return -ENOSYS;
229 }
230
231 static bool enough_swap_for_hibernation(void) {
232         _cleanup_free_ char *active = NULL;
233         unsigned long long act = 0;
234         size_t size = 0, used = 0;
235         int r;
236
237 #if 0 /// elogind does not allow any bypass, we are never init!
238         if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
239                 return true;
240 #endif // 0
241
242         r = find_hibernate_location(NULL, NULL, &size, &used);
243         if (r < 0)
244                 return false;
245
246         r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
247         if (r < 0) {
248                 log_error_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
249                 return false;
250         }
251
252         r = safe_atollu(active, &act);
253         if (r < 0) {
254                 log_error_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m",
255                                 active);
256                 return false;
257         }
258
259         r = act <= (size - used) * HIBERNATION_SWAP_THRESHOLD;
260         log_debug("Hibernation is %spossible, Active(anon)=%llu kB, size=%zu kB, used=%zu kB, threshold=%.2g%%",
261                   r ? "" : "im", act, size, used, 100*HIBERNATION_SWAP_THRESHOLD);
262
263         return r;
264 }
265
266 int read_fiemap(int fd, struct fiemap **ret) {
267         _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
268         struct stat statinfo;
269         uint32_t result_extents = 0;
270         uint64_t fiemap_start = 0, fiemap_length;
271         const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
272         size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra;
273
274         if (fstat(fd, &statinfo) < 0)
275                 return log_debug_errno(errno, "Cannot determine file size: %m");
276         if (!S_ISREG(statinfo.st_mode))
277                 return -ENOTTY;
278         fiemap_length = statinfo.st_size;
279
280         /* Zero this out in case we run on a file with no extents */
281         fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
282         if (!fiemap)
283                 return -ENOMEM;
284
285         result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
286         if (!result_fiemap)
287                 return -ENOMEM;
288
289         /*  XFS filesystem has incorrect implementation of fiemap ioctl and
290          *  returns extents for only one block-group at a time, so we need
291          *  to handle it manually, starting the next fiemap call from the end
292          *  of the last extent
293          */
294         while (fiemap_start < fiemap_length) {
295                 *fiemap = (struct fiemap) {
296                         .fm_start = fiemap_start,
297                         .fm_length = fiemap_length,
298                         .fm_flags = FIEMAP_FLAG_SYNC,
299                 };
300
301                 /* Find out how many extents there are */
302                 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
303                         return log_debug_errno(errno, "Failed to read extents: %m");
304
305                 /* Nothing to process */
306                 if (fiemap->fm_mapped_extents == 0)
307                         break;
308
309                 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
310                  * the extents for the whole file. Add space for the initial struct fiemap. */
311                 if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated,
312                                      n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
313                         return -ENOMEM;
314
315                 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
316                 fiemap->fm_mapped_extents = 0;
317
318                 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
319                         return log_debug_errno(errno, "Failed to read extents: %m");
320
321                 /* Resize result_fiemap to allow us to copy in the extents */
322                 if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated,
323                                     n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
324                         return -ENOMEM;
325
326                 memcpy(result_fiemap->fm_extents + result_extents,
327                        fiemap->fm_extents,
328                        sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
329
330                 result_extents += fiemap->fm_mapped_extents;
331
332                 /* Highly unlikely that it is zero */
333                 if (_likely_(fiemap->fm_mapped_extents > 0)) {
334                         uint32_t i = fiemap->fm_mapped_extents - 1;
335
336                         fiemap_start = fiemap->fm_extents[i].fe_logical +
337                                        fiemap->fm_extents[i].fe_length;
338
339                         if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
340                                 break;
341                 }
342         }
343
344         memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
345         result_fiemap->fm_mapped_extents = result_extents;
346         *ret = TAKE_PTR(result_fiemap);
347         return 0;
348 }
349
350 #if 0 /// elogind has to ask the manager for some stuff
351 static bool can_s2h(void) {
352 #else
353 static bool can_s2h(Manager *m) {
354 #endif // 0
355         const char *p;
356         int r;
357
358         r = access("/sys/class/rtc/rtc0/wakealarm", W_OK);
359         if (r < 0) {
360                 log_full(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
361                          "/sys/class/rct/rct0/wakealarm is not writable %m");
362                 return false;
363         }
364
365         FOREACH_STRING(p, "suspend", "hibernate") {
366 #if 0 /// elogind must transport a pointer to its managers instance
367                 r = can_sleep(p);
368 #else
369                 r = can_sleep(m, p);
370 #endif // 0
371                 if (IN_SET(r, 0, -ENOSPC)) {
372                         log_debug("Unable to %s system.", p);
373                         return false;
374                 }
375                 if (r < 0)
376                         return log_debug_errno(r, "Failed to check if %s is possible: %m", p);
377         }
378
379         return true;
380 }
381
382
383 #if 0 /// elogind has to ask the manager for some stuff
384 int can_sleep(const char *verb) {
385         _cleanup_strv_free_ char **modes = NULL, **states = NULL;
386         int r;
387 #else
388 int can_sleep(Manager *m, const char *verb) {
389         assert(m);
390
391         char **modes  = streq(verb, "suspend")   ? m->suspend_mode     :
392                         streq(verb, "hibernate") ? m->hibernate_mode   :
393                                                        m->hybrid_sleep_mode;
394         char **states = streq(verb, "suspend")   ? m->suspend_state     :
395                         streq(verb, "hibernate") ? m->hibernate_state   :
396                                                    m->hybrid_sleep_state;
397 #endif // 0
398
399         assert(STR_IN_SET(verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
400
401         if (streq(verb, "suspend-then-hibernate"))
402 #if 0 /// elogind must transport a pointer to its managers instance
403                 return can_s2h();
404 #else
405                 return can_s2h(m);
406 #endif // 0
407
408 #if 0 /// already parsed by elogind config
409         r = parse_sleep_config(verb, &modes, &states, NULL);
410         if (r < 0)
411                 return false;
412 #endif // 0
413
414         if (!can_sleep_state(states) || !can_sleep_disk(modes))
415                 return false;
416
417         if (streq(verb, "suspend"))
418                 return true;
419
420         if (!enough_swap_for_hibernation())
421                 return -ENOSPC;
422
423         return true;
424 }