1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3   Copyright © 2018 Dell Inc.
4 ***/
5 
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <linux/fs.h>
9 #include <linux/magic.h>
10 #include <stdbool.h>
11 #include <stddef.h>
12 #include <sys/ioctl.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <syslog.h>
16 #include <unistd.h>
17 
18 #include "alloc-util.h"
19 #include "blockdev-util.h"
20 #include "btrfs-util.h"
21 #include "conf-parser.h"
22 #include "def.h"
23 #include "devnum-util.h"
24 #include "env-util.h"
25 #include "errno-util.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "log.h"
29 #include "macro.h"
30 #include "path-util.h"
31 #include "sleep-config.h"
32 #include "stat-util.h"
33 #include "stdio-util.h"
34 #include "string-table.h"
35 #include "string-util.h"
36 #include "strv.h"
37 #include "time-util.h"
38 
parse_sleep_config(SleepConfig ** ret_sleep_config)39 int parse_sleep_config(SleepConfig **ret_sleep_config) {
40         _cleanup_(free_sleep_configp) SleepConfig *sc = NULL;
41         int allow_suspend = -1, allow_hibernate = -1,
42             allow_s2h = -1, allow_hybrid_sleep = -1;
43 
44         sc = new0(SleepConfig, 1);
45         if (!sc)
46                 return log_oom();
47 
48         const ConfigTableItem items[] = {
49                 { "Sleep", "AllowSuspend",              config_parse_tristate, 0, &allow_suspend                  },
50                 { "Sleep", "AllowHibernation",          config_parse_tristate, 0, &allow_hibernate                },
51                 { "Sleep", "AllowSuspendThenHibernate", config_parse_tristate, 0, &allow_s2h                      },
52                 { "Sleep", "AllowHybridSleep",          config_parse_tristate, 0, &allow_hybrid_sleep             },
53 
54                 { "Sleep", "SuspendMode",               config_parse_strv,     0, sc->modes + SLEEP_SUSPEND       },
55                 { "Sleep", "SuspendState",              config_parse_strv,     0, sc->states + SLEEP_SUSPEND      },
56                 { "Sleep", "HibernateMode",             config_parse_strv,     0, sc->modes + SLEEP_HIBERNATE     },
57                 { "Sleep", "HibernateState",            config_parse_strv,     0, sc->states + SLEEP_HIBERNATE    },
58                 { "Sleep", "HybridSleepMode",           config_parse_strv,     0, sc->modes + SLEEP_HYBRID_SLEEP  },
59                 { "Sleep", "HybridSleepState",          config_parse_strv,     0, sc->states + SLEEP_HYBRID_SLEEP },
60 
61                 { "Sleep", "HibernateDelaySec",         config_parse_sec,      0, &sc->hibernate_delay_sec        },
62                 {}
63         };
64 
65         (void) config_parse_many_nulstr(
66                         PKGSYSCONFDIR "/sleep.conf",
67                         CONF_PATHS_NULSTR("systemd/sleep.conf.d"),
68                         "Sleep\0",
69                         config_item_table_lookup, items,
70                         CONFIG_PARSE_WARN,
71                         NULL,
72                         NULL);
73 
74         /* use default values unless set */
75         sc->allow[SLEEP_SUSPEND] = allow_suspend != 0;
76         sc->allow[SLEEP_HIBERNATE] = allow_hibernate != 0;
77         sc->allow[SLEEP_HYBRID_SLEEP] = allow_hybrid_sleep >= 0 ? allow_hybrid_sleep
78                 : (allow_suspend != 0 && allow_hibernate != 0);
79         sc->allow[SLEEP_SUSPEND_THEN_HIBERNATE] = allow_s2h >= 0 ? allow_s2h
80                 : (allow_suspend != 0 && allow_hibernate != 0);
81 
82         if (!sc->states[SLEEP_SUSPEND])
83                 sc->states[SLEEP_SUSPEND] = strv_new("mem", "standby", "freeze");
84         if (!sc->modes[SLEEP_HIBERNATE])
85                 sc->modes[SLEEP_HIBERNATE] = strv_new("platform", "shutdown");
86         if (!sc->states[SLEEP_HIBERNATE])
87                 sc->states[SLEEP_HIBERNATE] = strv_new("disk");
88         if (!sc->modes[SLEEP_HYBRID_SLEEP])
89                 sc->modes[SLEEP_HYBRID_SLEEP] = strv_new("suspend", "platform", "shutdown");
90         if (!sc->states[SLEEP_HYBRID_SLEEP])
91                 sc->states[SLEEP_HYBRID_SLEEP] = strv_new("disk");
92         if (sc->hibernate_delay_sec == 0)
93                 sc->hibernate_delay_sec = 2 * USEC_PER_HOUR;
94 
95         /* ensure values set for all required fields */
96         if (!sc->states[SLEEP_SUSPEND] || !sc->modes[SLEEP_HIBERNATE]
97             || !sc->states[SLEEP_HIBERNATE] || !sc->modes[SLEEP_HYBRID_SLEEP] || !sc->states[SLEEP_HYBRID_SLEEP])
98                 return log_oom();
99 
100         *ret_sleep_config = TAKE_PTR(sc);
101 
102         return 0;
103 }
104 
can_sleep_state(char ** types)105 int can_sleep_state(char **types) {
106         _cleanup_free_ char *text = NULL;
107         int r;
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                 log_debug_errno(errno, "/sys/power/state is not writable, cannot sleep: %m");
115                 return false;
116         }
117 
118         r = read_one_line_file("/sys/power/state", &text);
119         if (r < 0) {
120                 log_debug_errno(r, "Failed to read /sys/power/state, cannot sleep: %m");
121                 return false;
122         }
123 
124         const char *found;
125         r = string_contains_word_strv(text, NULL, types, &found);
126         if (r < 0)
127                 return log_debug_errno(r, "Failed to parse /sys/power/state: %m");
128         if (r > 0)
129                 log_debug("Sleep mode \"%s\" is supported by the kernel.", found);
130         else if (DEBUG_LOGGING) {
131                 _cleanup_free_ char *t = strv_join(types, "/");
132                 log_debug("Sleep mode %s not supported by the kernel, sorry.", strnull(t));
133         }
134         return r;
135 }
136 
can_sleep_disk(char ** types)137 int can_sleep_disk(char **types) {
138         _cleanup_free_ char *text = NULL;
139         int r;
140 
141         if (strv_isempty(types))
142                 return true;
143 
144         /* If /sys is read-only we cannot sleep */
145         if (access("/sys/power/disk", W_OK) < 0) {
146                 log_debug_errno(errno, "/sys/power/disk is not writable: %m");
147                 return false;
148         }
149 
150         r = read_one_line_file("/sys/power/disk", &text);
151         if (r < 0) {
152                 log_debug_errno(r, "Couldn't read /sys/power/disk: %m");
153                 return false;
154         }
155 
156         for (const char *p = text;;) {
157                 _cleanup_free_ char *word = NULL;
158 
159                 r = extract_first_word(&p, &word, NULL, 0);
160                 if (r < 0)
161                         return log_debug_errno(r, "Failed to parse /sys/power/disk: %m");
162                 if (r == 0)
163                         break;
164 
165                 char *s = word;
166                 size_t l = strlen(s);
167                 if (s[0] == '[' && s[l-1] == ']') {
168                         s[l-1] = '\0';
169                         s++;
170                 }
171 
172                 if (strv_contains(types, s)) {
173                         log_debug("Disk sleep mode \"%s\" is supported by the kernel.", s);
174                         return true;
175                 }
176         }
177 
178         if (DEBUG_LOGGING) {
179                 _cleanup_free_ char *t = strv_join(types, "/");
180                 log_debug("Disk sleep mode %s not supported by the kernel, sorry.", strnull(t));
181         }
182         return false;
183 }
184 
185 #define HIBERNATION_SWAP_THRESHOLD 0.98
186 
swap_entry_free(SwapEntry * se)187 SwapEntry* swap_entry_free(SwapEntry *se) {
188         if (!se)
189                 return NULL;
190 
191         free(se->device);
192         free(se->type);
193 
194         return mfree(se);
195 }
196 
hibernate_location_free(HibernateLocation * hl)197 HibernateLocation* hibernate_location_free(HibernateLocation *hl) {
198         if (!hl)
199                 return NULL;
200 
201         swap_entry_free(hl->swap);
202 
203         return mfree(hl);
204 }
205 
swap_device_to_device_id(const SwapEntry * swap,dev_t * ret_dev)206 static int swap_device_to_device_id(const SwapEntry *swap, dev_t *ret_dev) {
207         struct stat sb;
208         int r;
209 
210         assert(swap);
211         assert(swap->device);
212         assert(swap->type);
213 
214         r = stat(swap->device, &sb);
215         if (r < 0)
216                 return -errno;
217 
218         if (streq(swap->type, "partition")) {
219                 if (!S_ISBLK(sb.st_mode))
220                         return -ENOTBLK;
221 
222                 *ret_dev = sb.st_rdev;
223                 return 0;
224         }
225 
226         return get_block_device(swap->device, ret_dev);
227 }
228 
229 /*
230  * Attempt to calculate the swap file offset on supported filesystems. On unsupported
231  * filesystems, a debug message is logged and ret_offset is set to UINT64_MAX.
232  */
calculate_swap_file_offset(const SwapEntry * swap,uint64_t * ret_offset)233 static int calculate_swap_file_offset(const SwapEntry *swap, uint64_t *ret_offset) {
234         _cleanup_close_ int fd = -1;
235         _cleanup_free_ struct fiemap *fiemap = NULL;
236         struct stat sb;
237         int r;
238 
239         assert(swap);
240         assert(swap->device);
241         assert(streq(swap->type, "file"));
242 
243         fd = open(swap->device, O_RDONLY|O_CLOEXEC|O_NOCTTY);
244         if (fd < 0)
245                 return log_debug_errno(errno, "Failed to open swap file %s to determine on-disk offset: %m", swap->device);
246 
247         if (fstat(fd, &sb) < 0)
248                 return log_debug_errno(errno, "Failed to stat %s: %m", swap->device);
249 
250         r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
251         if (r < 0)
252                 return log_debug_errno(r, "Error checking %s for Btrfs filesystem: %m", swap->device);
253         if (r > 0) {
254                 log_debug("%s: detection of swap file offset on Btrfs is not supported", swap->device);
255                 *ret_offset = UINT64_MAX;
256                 return 0;
257         }
258 
259         r = read_fiemap(fd, &fiemap);
260         if (r < 0)
261                 return log_debug_errno(r, "Unable to read extent map for '%s': %m", swap->device);
262 
263         *ret_offset = fiemap->fm_extents[0].fe_physical / page_size();
264         return 0;
265 }
266 
read_resume_files(dev_t * ret_resume,uint64_t * ret_resume_offset)267 static int read_resume_files(dev_t *ret_resume, uint64_t *ret_resume_offset) {
268         _cleanup_free_ char *resume_str = NULL, *resume_offset_str = NULL;
269         uint64_t resume_offset = 0;
270         dev_t resume;
271         int r;
272 
273         r = read_one_line_file("/sys/power/resume", &resume_str);
274         if (r < 0)
275                 return log_debug_errno(r, "Error reading /sys/power/resume: %m");
276 
277         r = parse_devnum(resume_str, &resume);
278         if (r < 0)
279                 return log_debug_errno(r, "Error parsing /sys/power/resume device: %s: %m", resume_str);
280 
281         r = read_one_line_file("/sys/power/resume_offset", &resume_offset_str);
282         if (r == -ENOENT)
283                 log_debug_errno(r, "Kernel does not support resume_offset; swap file offset detection will be skipped.");
284         else if (r < 0)
285                 return log_debug_errno(r, "Error reading /sys/power/resume_offset: %m");
286         else {
287                 r = safe_atou64(resume_offset_str, &resume_offset);
288                 if (r < 0)
289                         return log_debug_errno(r, "Failed to parse value in /sys/power/resume_offset \"%s\": %m", resume_offset_str);
290         }
291 
292         if (resume_offset > 0 && resume == 0)
293                 log_debug("Warning: found /sys/power/resume_offset==%" PRIu64 ", but /sys/power/resume unset. Misconfiguration?",
294                           resume_offset);
295 
296         *ret_resume = resume;
297         *ret_resume_offset = resume_offset;
298 
299         return 0;
300 }
301 
302 /*
303  * Determine if the HibernateLocation matches the resume= (device) and resume_offset= (file).
304  */
location_is_resume_device(const HibernateLocation * location,dev_t sys_resume,uint64_t sys_offset)305 static bool location_is_resume_device(const HibernateLocation *location, dev_t sys_resume, uint64_t sys_offset) {
306         if (!location)
307                 return false;
308 
309         return  sys_resume > 0 &&
310                 sys_resume == location->devno &&
311                 (sys_offset == location->offset || (sys_offset > 0 && location->offset == UINT64_MAX));
312 }
313 
314 /*
315  * Attempt to find the hibernation location by parsing /proc/swaps, /sys/power/resume, and
316  * /sys/power/resume_offset.
317  *
318  * Returns:
319  *  1 - Values are set in /sys/power/resume and /sys/power/resume_offset.
320  *      ret_hibernate_location will represent matching /proc/swap entry if identified or NULL if not.
321  *
322  *  0 - No values are set in /sys/power/resume and /sys/power/resume_offset.
323         ret_hibernate_location will represent the highest priority swap with most remaining space discovered in /proc/swaps.
324  *
325  *  Negative value in the case of error.
326  */
find_hibernate_location(HibernateLocation ** ret_hibernate_location)327 int find_hibernate_location(HibernateLocation **ret_hibernate_location) {
328         _cleanup_fclose_ FILE *f = NULL;
329         _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
330         dev_t sys_resume = 0; /* Unnecessary initialization to appease gcc */
331         uint64_t sys_offset = 0;
332         bool resume_match = false;
333         int r;
334 
335         /* read the /sys/power/resume & /sys/power/resume_offset values */
336         r = read_resume_files(&sys_resume, &sys_offset);
337         if (r < 0)
338                 return r;
339 
340         f = fopen("/proc/swaps", "re");
341         if (!f) {
342                 log_debug_errno(errno, "Failed to open /proc/swaps: %m");
343                 return errno == ENOENT ? -EOPNOTSUPP : -errno; /* Convert swap not supported to a recognizable error */
344         }
345 
346         (void) fscanf(f, "%*s %*s %*s %*s %*s\n");
347         for (unsigned i = 1;; i++) {
348                 _cleanup_(swap_entry_freep) SwapEntry *swap = NULL;
349                 uint64_t swap_offset = 0;
350                 int k;
351 
352                 swap = new0(SwapEntry, 1);
353                 if (!swap)
354                         return -ENOMEM;
355 
356                 k = fscanf(f,
357                            "%ms "       /* device/file */
358                            "%ms "       /* type of swap */
359                            "%" PRIu64   /* swap size */
360                            "%" PRIu64   /* used */
361                            "%i\n",      /* priority */
362                            &swap->device, &swap->type, &swap->size, &swap->used, &swap->priority);
363                 if (k == EOF)
364                         break;
365                 if (k != 5) {
366                         log_debug("Failed to parse /proc/swaps:%u, ignoring", i);
367                         continue;
368                 }
369 
370                 if (streq(swap->type, "file")) {
371                         if (endswith(swap->device, "\\040(deleted)")) {
372                                 log_debug("Ignoring deleted swap file '%s'.", swap->device);
373                                 continue;
374                         }
375 
376                         r = calculate_swap_file_offset(swap, &swap_offset);
377                         if (r < 0)
378                                 return r;
379 
380                 } else if (streq(swap->type, "partition")) {
381                         const char *fn;
382 
383                         fn = path_startswith(swap->device, "/dev/");
384                         if (fn && startswith(fn, "zram")) {
385                                 log_debug("%s: ignoring zram swap", swap->device);
386                                 continue;
387                         }
388 
389                 } else {
390                         log_debug("%s: swap type %s is unsupported for hibernation, ignoring", swap->device, swap->type);
391                         continue;
392                 }
393 
394                 /* prefer resume device or highest priority swap with most remaining space */
395                 if (sys_resume == 0) {
396                         if (hibernate_location && swap->priority < hibernate_location->swap->priority) {
397                                 log_debug("%s: ignoring device with lower priority", swap->device);
398                                 continue;
399                         }
400                         if (hibernate_location &&
401                             (swap->priority == hibernate_location->swap->priority
402                              && swap->size - swap->used < hibernate_location->swap->size - hibernate_location->swap->used)) {
403                                 log_debug("%s: ignoring device with lower usable space", swap->device);
404                                 continue;
405                         }
406                 }
407 
408                 dev_t swap_device;
409                 r = swap_device_to_device_id(swap, &swap_device);
410                 if (r < 0)
411                         return log_debug_errno(r, "%s: failed to query device number: %m", swap->device);
412                 if (swap_device == 0)
413                         return log_debug_errno(SYNTHETIC_ERRNO(ENODEV), "%s: not backed by block device.", swap->device);
414 
415                 hibernate_location = hibernate_location_free(hibernate_location);
416                 hibernate_location = new(HibernateLocation, 1);
417                 if (!hibernate_location)
418                         return -ENOMEM;
419 
420                 *hibernate_location = (HibernateLocation) {
421                         .devno = swap_device,
422                         .offset = swap_offset,
423                         .swap = TAKE_PTR(swap),
424                 };
425 
426                 /* if the swap is the resume device, stop the loop */
427                 if (location_is_resume_device(hibernate_location, sys_resume, sys_offset)) {
428                         log_debug("%s: device matches configured resume settings.", hibernate_location->swap->device);
429                         resume_match = true;
430                         break;
431                 }
432 
433                 log_debug("%s: is a candidate device.", hibernate_location->swap->device);
434         }
435 
436         /* We found nothing at all */
437         if (!hibernate_location)
438                 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS),
439                                        "No possible swap partitions or files suitable for hibernation were found in /proc/swaps.");
440 
441         /* resume= is set but a matching /proc/swaps entry was not found */
442         if (sys_resume != 0 && !resume_match)
443                 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS),
444                                        "No swap partitions or files matching resume config were found in /proc/swaps.");
445 
446         if (hibernate_location->offset == UINT64_MAX) {
447                 if (sys_offset == 0)
448                         return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS), "Offset detection failed and /sys/power/resume_offset is not set.");
449 
450                 hibernate_location->offset = sys_offset;
451         }
452 
453         if (resume_match)
454                 log_debug("Hibernation will attempt to use swap entry with path: %s, device: %u:%u, offset: %" PRIu64 ", priority: %i",
455                           hibernate_location->swap->device, major(hibernate_location->devno), minor(hibernate_location->devno),
456                           hibernate_location->offset, hibernate_location->swap->priority);
457         else
458                 log_debug("/sys/power/resume is not configured; attempting to hibernate with path: %s, device: %u:%u, offset: %" PRIu64 ", priority: %i",
459                           hibernate_location->swap->device, major(hibernate_location->devno), minor(hibernate_location->devno),
460                           hibernate_location->offset, hibernate_location->swap->priority);
461 
462         *ret_hibernate_location = TAKE_PTR(hibernate_location);
463 
464         if (resume_match)
465                 return 1;
466 
467         return 0;
468 }
469 
enough_swap_for_hibernation(void)470 static bool enough_swap_for_hibernation(void) {
471         _cleanup_free_ char *active = NULL;
472         _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
473         unsigned long long act = 0;
474         int r;
475 
476         if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
477                 return true;
478 
479         r = find_hibernate_location(&hibernate_location);
480         if (r < 0)
481                 return false;
482 
483         /* If /sys/power/{resume,resume_offset} is configured but a matching entry
484          * could not be identified in /proc/swaps, user is likely using Btrfs with a swapfile;
485          * return true and let the system attempt hibernation.
486          */
487         if (r > 0 && !hibernate_location) {
488                 log_debug("Unable to determine remaining swap space; hibernation may fail");
489                 return true;
490         }
491 
492         if (!hibernate_location)
493                 return false;
494 
495         r = get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE, &active);
496         if (r < 0) {
497                 log_debug_errno(r, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
498                 return false;
499         }
500 
501         r = safe_atollu(active, &act);
502         if (r < 0) {
503                 log_debug_errno(r, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active);
504                 return false;
505         }
506 
507         r = act <= (hibernate_location->swap->size - hibernate_location->swap->used) * HIBERNATION_SWAP_THRESHOLD;
508         log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%" PRIu64 " kB, used=%" PRIu64 " kB, threshold=%.2g%%",
509                   r ? "Enough" : "Not enough", act, hibernate_location->swap->size, hibernate_location->swap->used, 100*HIBERNATION_SWAP_THRESHOLD);
510 
511         return r;
512 }
513 
read_fiemap(int fd,struct fiemap ** ret)514 int read_fiemap(int fd, struct fiemap **ret) {
515         _cleanup_free_ struct fiemap *fiemap = NULL, *result_fiemap = NULL;
516         struct stat statinfo;
517         uint32_t result_extents = 0;
518         uint64_t fiemap_start = 0, fiemap_length;
519         const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent));
520 
521         if (fstat(fd, &statinfo) < 0)
522                 return log_debug_errno(errno, "Cannot determine file size: %m");
523         if (!S_ISREG(statinfo.st_mode))
524                 return -ENOTTY;
525         fiemap_length = statinfo.st_size;
526 
527         /* Zero this out in case we run on a file with no extents */
528         fiemap = calloc(n_extra, sizeof(struct fiemap_extent));
529         if (!fiemap)
530                 return -ENOMEM;
531 
532         result_fiemap = malloc_multiply(n_extra, sizeof(struct fiemap_extent));
533         if (!result_fiemap)
534                 return -ENOMEM;
535 
536         /*  XFS filesystem has incorrect implementation of fiemap ioctl and
537          *  returns extents for only one block-group at a time, so we need
538          *  to handle it manually, starting the next fiemap call from the end
539          *  of the last extent
540          */
541         while (fiemap_start < fiemap_length) {
542                 *fiemap = (struct fiemap) {
543                         .fm_start = fiemap_start,
544                         .fm_length = fiemap_length,
545                         .fm_flags = FIEMAP_FLAG_SYNC,
546                 };
547 
548                 /* Find out how many extents there are */
549                 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
550                         return log_debug_errno(errno, "Failed to read extents: %m");
551 
552                 /* Nothing to process */
553                 if (fiemap->fm_mapped_extents == 0)
554                         break;
555 
556                 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
557                  * the extents for the whole file. Add space for the initial struct fiemap. */
558                 if (!greedy_realloc0((void**) &fiemap, n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
559                         return -ENOMEM;
560 
561                 fiemap->fm_extent_count = fiemap->fm_mapped_extents;
562                 fiemap->fm_mapped_extents = 0;
563 
564                 if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0)
565                         return log_debug_errno(errno, "Failed to read extents: %m");
566 
567                 /* Resize result_fiemap to allow us to copy in the extents */
568                 if (!greedy_realloc((void**) &result_fiemap,
569                                     n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent)))
570                         return -ENOMEM;
571 
572                 memcpy(result_fiemap->fm_extents + result_extents,
573                        fiemap->fm_extents,
574                        sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents);
575 
576                 result_extents += fiemap->fm_mapped_extents;
577 
578                 /* Highly unlikely that it is zero */
579                 if (_likely_(fiemap->fm_mapped_extents > 0)) {
580                         uint32_t i = fiemap->fm_mapped_extents - 1;
581 
582                         fiemap_start = fiemap->fm_extents[i].fe_logical +
583                                        fiemap->fm_extents[i].fe_length;
584 
585                         if (fiemap->fm_extents[i].fe_flags & FIEMAP_EXTENT_LAST)
586                                 break;
587                 }
588         }
589 
590         memcpy(result_fiemap, fiemap, sizeof(struct fiemap));
591         result_fiemap->fm_mapped_extents = result_extents;
592         *ret = TAKE_PTR(result_fiemap);
593         return 0;
594 }
595 
596 static int can_sleep_internal(const SleepConfig *sleep_config, SleepOperation operation, bool check_allowed);
597 
can_s2h(const SleepConfig * sleep_config)598 static bool can_s2h(const SleepConfig *sleep_config) {
599 
600         static const SleepOperation operations[] = {
601                 SLEEP_SUSPEND,
602                 SLEEP_HIBERNATE,
603         };
604 
605         int r;
606 
607         if (!clock_supported(CLOCK_BOOTTIME_ALARM)) {
608                 log_debug("CLOCK_BOOTTIME_ALARM is not supported.");
609                 return false;
610         }
611 
612         for (size_t i = 0; i < ELEMENTSOF(operations); i++) {
613                 r = can_sleep_internal(sleep_config, operations[i], false);
614                 if (IN_SET(r, 0, -ENOSPC)) {
615                         log_debug("Unable to %s system.", sleep_operation_to_string(operations[i]));
616                         return false;
617                 }
618                 if (r < 0)
619                         return log_debug_errno(r, "Failed to check if %s is possible: %m", sleep_operation_to_string(operations[i]));
620         }
621 
622         return true;
623 }
624 
can_sleep_internal(const SleepConfig * sleep_config,SleepOperation operation,bool check_allowed)625 static int can_sleep_internal(
626                 const SleepConfig *sleep_config,
627                 SleepOperation operation,
628                 bool check_allowed) {
629 
630         assert(operation >= 0);
631         assert(operation < _SLEEP_OPERATION_MAX);
632 
633         if (check_allowed && !sleep_config->allow[operation]) {
634                 log_debug("Sleep mode \"%s\" is disabled by configuration.", sleep_operation_to_string(operation));
635                 return false;
636         }
637 
638         if (operation == SLEEP_SUSPEND_THEN_HIBERNATE)
639                 return can_s2h(sleep_config);
640 
641         if (can_sleep_state(sleep_config->states[operation]) <= 0 ||
642             can_sleep_disk(sleep_config->modes[operation]) <= 0)
643                 return false;
644 
645         if (operation == SLEEP_SUSPEND)
646                 return true;
647 
648         if (!enough_swap_for_hibernation())
649                 return -ENOSPC;
650 
651         return true;
652 }
653 
can_sleep(SleepOperation operation)654 int can_sleep(SleepOperation operation) {
655         _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
656         int r;
657 
658         r = parse_sleep_config(&sleep_config);
659         if (r < 0)
660                 return r;
661 
662         return can_sleep_internal(sleep_config, operation, true);
663 }
664 
free_sleep_config(SleepConfig * sc)665 SleepConfig* free_sleep_config(SleepConfig *sc) {
666         if (!sc)
667                 return NULL;
668 
669         for (SleepOperation i = 0; i < _SLEEP_OPERATION_MAX; i++) {
670                 strv_free(sc->modes[i]);
671                 strv_free(sc->states[i]);
672         }
673 
674         return mfree(sc);
675 }
676 
677 static const char* const sleep_operation_table[_SLEEP_OPERATION_MAX] = {
678         [SLEEP_SUSPEND]                = "suspend",
679         [SLEEP_HIBERNATE]              = "hibernate",
680         [SLEEP_HYBRID_SLEEP]           = "hybrid-sleep",
681         [SLEEP_SUSPEND_THEN_HIBERNATE] = "suspend-then-hibernate",
682 };
683 
684 DEFINE_STRING_TABLE_LOOKUP(sleep_operation, SleepOperation);
685