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