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