1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2018 Dell Inc.
13 #include <sys/ioctl.h>
15 #include <sys/types.h>
19 #include "alloc-util.h"
20 #include "btrfs-util.h"
21 #include "conf-parser.h"
24 #include "errno-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "sleep-config.h"
32 #include "stdio-util.h"
33 #include "string-util.h"
35 #include "time-util.h"
37 int parse_sleep_config(SleepConfig
**ret_sleep_config
) {
38 _cleanup_(free_sleep_configp
) SleepConfig
*sc
;
39 int allow_suspend
= -1, allow_hibernate
= -1,
40 allow_s2h
= -1, allow_hybrid_sleep
= -1;
42 sc
= new0(SleepConfig
, 1);
46 const ConfigTableItem items
[] = {
47 { "Sleep", "AllowSuspend", config_parse_tristate
, 0, &allow_suspend
},
48 { "Sleep", "AllowHibernation", config_parse_tristate
, 0, &allow_hibernate
},
49 { "Sleep", "AllowSuspendThenHibernate", config_parse_tristate
, 0, &allow_s2h
},
50 { "Sleep", "AllowHybridSleep", config_parse_tristate
, 0, &allow_hybrid_sleep
},
52 { "Sleep", "SuspendMode", config_parse_strv
, 0, &sc
->suspend_modes
},
53 { "Sleep", "SuspendState", config_parse_strv
, 0, &sc
->suspend_states
},
54 { "Sleep", "HibernateMode", config_parse_strv
, 0, &sc
->hibernate_modes
},
55 { "Sleep", "HibernateState", config_parse_strv
, 0, &sc
->hibernate_states
},
56 { "Sleep", "HybridSleepMode", config_parse_strv
, 0, &sc
->hybrid_modes
},
57 { "Sleep", "HybridSleepState", config_parse_strv
, 0, &sc
->hybrid_states
},
59 { "Sleep", "HibernateDelaySec", config_parse_sec
, 0, &sc
->hibernate_delay_sec
},
63 (void) config_parse_many_nulstr(PKGSYSCONFDIR
"/sleep.conf",
64 CONF_PATHS_NULSTR("systemd/sleep.conf.d"),
65 "Sleep\0", config_item_table_lookup
, items
,
66 CONFIG_PARSE_WARN
, NULL
);
68 /* use default values unless set */
69 sc
->allow_suspend
= allow_suspend
!= 0;
70 sc
->allow_hibernate
= allow_hibernate
!= 0;
71 sc
->allow_hybrid_sleep
= allow_hybrid_sleep
>= 0 ? allow_hybrid_sleep
72 : (allow_suspend
!= 0 && allow_hibernate
!= 0);
73 sc
->allow_s2h
= allow_s2h
>= 0 ? allow_s2h
74 : (allow_suspend
!= 0 && allow_hibernate
!= 0);
76 if (!sc
->suspend_states
)
77 sc
->suspend_states
= strv_new("mem", "standby", "freeze");
78 if (!sc
->hibernate_modes
)
79 sc
->hibernate_modes
= strv_new("platform", "shutdown");
80 if (!sc
->hibernate_states
)
81 sc
->hibernate_states
= strv_new("disk");
82 if (!sc
->hybrid_modes
)
83 sc
->hybrid_modes
= strv_new("suspend", "platform", "shutdown");
84 if (!sc
->hybrid_states
)
85 sc
->hybrid_states
= strv_new("disk");
86 if (sc
->hibernate_delay_sec
== 0)
87 sc
->hibernate_delay_sec
= 2 * USEC_PER_HOUR
;
89 /* ensure values set for all required fields */
90 if (!sc
->suspend_states
|| !sc
->hibernate_modes
91 || !sc
->hibernate_states
|| !sc
->hybrid_modes
|| !sc
->hybrid_states
)
94 *ret_sleep_config
= TAKE_PTR(sc
);
99 int can_sleep_state(char **types
) {
102 _cleanup_free_
char *p
= NULL
;
104 if (strv_isempty(types
))
107 /* If /sys is read-only we cannot sleep */
108 if (access("/sys/power/state", W_OK
) < 0)
111 r
= read_one_line_file("/sys/power/state", &p
);
115 STRV_FOREACH(type
, types
) {
116 const char *word
, *state
;
120 FOREACH_WORD_SEPARATOR(word
, l
, p
, WHITESPACE
, state
)
121 if (l
== k
&& memcmp(word
, *type
, l
) == 0)
128 int can_sleep_disk(char **types
) {
131 _cleanup_free_
char *p
= NULL
;
133 if (strv_isempty(types
))
136 /* If /sys is read-only we cannot sleep */
137 if (access("/sys/power/disk", W_OK
) < 0) {
138 log_debug_errno(errno
, "/sys/power/disk is not writable: %m");
142 r
= read_one_line_file("/sys/power/disk", &p
);
144 log_debug_errno(r
, "Couldn't read /sys/power/disk: %m");
148 STRV_FOREACH(type
, types
) {
149 const char *word
, *state
;
153 FOREACH_WORD_SEPARATOR(word
, l
, p
, WHITESPACE
, state
) {
154 if (l
== k
&& memcmp(word
, *type
, l
) == 0)
159 memcmp(word
+ 1, *type
, l
- 2) == 0 &&
168 #define HIBERNATION_SWAP_THRESHOLD 0.98
170 SwapEntry
* swap_entry_free(SwapEntry
*se
) {
180 HibernateLocation
* hibernate_location_free(HibernateLocation
*hl
) {
184 swap_entry_free(hl
->swap
);
190 static int swap_device_to_major_minor(const SwapEntry
*swap
, char **ret
) {
191 _cleanup_free_
char *major_minor
= NULL
;
192 _cleanup_close_
int fd
= -1;
198 assert(swap
->device
);
201 fd
= open(swap
->device
, O_RDONLY
| O_CLOEXEC
| O_NONBLOCK
);
203 return log_debug_errno(errno
, "Unable to open '%s': %m", swap
->device
);
207 return log_debug_errno(errno
, "Unable to stat %s: %m", swap
->device
);
209 swap_dev
= streq(swap
->type
, "partition") ? sb
.st_rdev
: sb
.st_dev
;
210 if (asprintf(&major_minor
, "%u:%u", major(swap_dev
), minor(swap_dev
)) < 0)
213 *ret
= TAKE_PTR(major_minor
);
218 static int calculate_swap_file_offset(const SwapEntry
*swap
, uint64_t *ret_offset
) {
219 _cleanup_close_
int fd
= -1;
220 _cleanup_free_
struct fiemap
*fiemap
= NULL
;
225 assert(swap
->device
);
226 assert(streq(swap
->type
, "file"));
228 fd
= open(swap
->device
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
230 return log_error_errno(errno
, "Failed to open %s: %m", swap
->device
);
232 if (fstat(fd
, &sb
) < 0)
233 return log_error_errno(errno
, "Failed to stat %s: %m", swap
->device
);
235 btrfs
= btrfs_is_filesystem(fd
);
237 return log_error_errno(btrfs
, "Error checking %s for Btrfs filesystem: %m", swap
->device
);
238 else if (btrfs
> 0) {
239 log_debug("Detection of swap file offset on Btrfs is not supported: %s; skipping", swap
->device
);
244 r
= read_fiemap(fd
, &fiemap
);
246 return log_debug_errno(r
, "Unable to read extent map for '%s': %m", swap
->device
);
248 *ret_offset
= fiemap
->fm_extents
[0].fe_physical
/ page_size();
253 static int read_resume_files(char **ret_resume
, uint64_t *ret_resume_offset
) {
254 _cleanup_free_
char *resume
, *resume_offset_str
= NULL
;
255 uint64_t resume_offset
= 0;
258 r
= read_one_line_file("/sys/power/resume", &resume
);
260 return log_debug_errno(r
, "Error reading from /sys/power/resume: %m");
262 r
= read_one_line_file("/sys/power/resume_offset", &resume_offset_str
);
264 log_debug("Kernel does not support resume_offset; swap file offset detection will be skipped.");
266 return log_debug_errno(r
, "Error reading from /sys/power/resume_offset: %m");
268 r
= safe_atou64(resume_offset_str
, &resume_offset
);
270 return log_error_errno(r
, "Failed to parse value in /sys/power/resume_offset \"%s\": %m", resume_offset_str
);
273 if (resume_offset
> 0 && streq(*ret_resume
, "0:0")) {
274 log_debug("Found offset in /sys/power/resume_offset: %" PRIu64
"; no device id found in /sys/power/resume; ignoring resume_offset", resume_offset
);
278 *ret_resume
= TAKE_PTR(resume
);
279 *ret_resume_offset
= resume_offset
;
284 static bool location_is_resume_device(const HibernateLocation
*location
, const char *sys_resume
, const uint64_t sys_offset
) {
286 assert(location
->resume
);
289 return streq(sys_resume
, location
->resume
) && sys_offset
== location
->resume_offset
;
293 * Attempt to find the hibernation location by parsing /proc/swaps, /sys/power/resume, and
294 * /sys/power/resume_offset.
297 * 1 - HibernateLocation matches values found in /sys/power/resume & /sys/power/resume_offset
298 * 0 - HibernateLocation is highest priority swap with most remaining space; no valid values exist in /sys/power/resume & /sys/power/resume_offset
299 * negative value in the case of error
301 int find_hibernate_location(HibernateLocation
**ret_hibernate_location
) {
302 _cleanup_fclose_
FILE *f
= NULL
;
303 _cleanup_(hibernate_location_freep
) HibernateLocation
*hibernate_location
= NULL
;
304 _cleanup_free_
char *sys_resume
= NULL
;
305 uint64_t sys_offset
= 0;
309 /* read the /sys/power/resume & /sys/power/resume_offset values */
310 r
= read_resume_files(&sys_resume
, &sys_offset
);
314 f
= fopen("/proc/swaps", "re");
316 log_full(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
,
317 "Failed to open /proc/swaps: %m");
318 return negative_errno();
321 (void) fscanf(f
, "%*s %*s %*s %*s %*s\n");
323 _cleanup_(swap_entry_freep
) SwapEntry
*swap
= NULL
;
324 uint64_t swap_offset
= 0;
327 swap
= new0(SwapEntry
, 1);
332 "%ms " /* device/file */
333 "%ms " /* type of swap */
334 "%" PRIu64
/* swap size */
335 "%" PRIu64
/* used */
336 "%i\n", /* priority */
337 &swap
->device
, &swap
->type
, &swap
->size
, &swap
->used
, &swap
->priority
);
341 log_warning("Failed to parse /proc/swaps:%u", i
);
345 if (streq(swap
->type
, "file")) {
346 if (endswith(swap
->device
, "\\040(deleted)")) {
347 log_warning("Ignoring deleted swap file '%s'.", swap
->device
);
351 r
= calculate_swap_file_offset(swap
, &swap_offset
);
354 } else if (streq(swap
->type
, "partition")) {
357 fn
= path_startswith(swap
->device
, "/dev/");
358 if (fn
&& startswith(fn
, "zram")) {
359 log_debug("Ignoring compressed RAM swap device '%s'.", swap
->device
);
363 log_debug("Swap type %s is unsupported for hibernation: %s; skipping", swap
->type
, swap
->device
);
367 /* prefer resume device or highest priority swap with most remaining space */
368 if (!hibernate_location
|| swap
->priority
> hibernate_location
->swap
->priority
369 || ((swap
->priority
== hibernate_location
->swap
->priority
)
370 && (swap
->size
- swap
->used
) > (hibernate_location
->swap
->size
- hibernate_location
->swap
->used
))) {
372 _cleanup_free_
char *swap_device_id
= NULL
;
373 r
= swap_device_to_major_minor(swap
, &swap_device_id
);
377 hibernate_location
= hibernate_location_free(hibernate_location
);
378 hibernate_location
= new(HibernateLocation
, 1);
379 if (!hibernate_location
)
382 *hibernate_location
= (HibernateLocation
) {
383 .resume
= TAKE_PTR(swap_device_id
),
384 .resume_offset
= swap_offset
,
385 .swap
= TAKE_PTR(swap
),
388 /* if the swap is the resume device, stop looping swaps */
389 if (location_is_resume_device(hibernate_location
, sys_resume
, sys_offset
))
394 if (!hibernate_location
)
395 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS
), "No swap partitions or files were found");
397 if (!streq(sys_resume
, "0:0") && !location_is_resume_device(hibernate_location
, sys_resume
, sys_offset
))
398 return log_warning_errno(SYNTHETIC_ERRNO(ENOSYS
), "/sys/power/resume and /sys/power/resume_offset has no matching entry in /proc/swaps; Hibernation will fail: resume=%s, resume_offset=%" PRIu64
,
399 sys_resume
, sys_offset
);
401 log_debug("Hibernation will attempt to use swap entry with path: %s, device: %s, offset: %" PRIu64
", priority: %i",
402 hibernate_location
->swap
->device
, hibernate_location
->resume
, hibernate_location
->resume_offset
, hibernate_location
->swap
->priority
);
404 *ret_hibernate_location
= TAKE_PTR(hibernate_location
);
406 if (location_is_resume_device(*ret_hibernate_location
, sys_resume
, sys_offset
))
412 static bool enough_swap_for_hibernation(void) {
413 _cleanup_free_
char *active
= NULL
;
414 _cleanup_(hibernate_location_freep
) HibernateLocation
*hibernate_location
= NULL
;
415 unsigned long long act
= 0;
418 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
421 r
= find_hibernate_location(&hibernate_location
);
425 r
= get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE
, &active
);
427 log_debug_errno(r
, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
431 r
= safe_atollu(active
, &act
);
433 log_debug_errno(r
, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active
);
437 r
= act
<= (hibernate_location
->swap
->size
- hibernate_location
->swap
->used
) * HIBERNATION_SWAP_THRESHOLD
;
438 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%" PRIu64
" kB, used=%" PRIu64
" kB, threshold=%.2g%%",
439 r
? "Enough" : "Not enough", act
, hibernate_location
->swap
->size
, hibernate_location
->swap
->used
, 100*HIBERNATION_SWAP_THRESHOLD
);
444 int read_fiemap(int fd
, struct fiemap
**ret
) {
445 _cleanup_free_
struct fiemap
*fiemap
= NULL
, *result_fiemap
= NULL
;
446 struct stat statinfo
;
447 uint32_t result_extents
= 0;
448 uint64_t fiemap_start
= 0, fiemap_length
;
449 const size_t n_extra
= DIV_ROUND_UP(sizeof(struct fiemap
), sizeof(struct fiemap_extent
));
450 size_t fiemap_allocated
= n_extra
, result_fiemap_allocated
= n_extra
;
452 if (fstat(fd
, &statinfo
) < 0)
453 return log_debug_errno(errno
, "Cannot determine file size: %m");
454 if (!S_ISREG(statinfo
.st_mode
))
456 fiemap_length
= statinfo
.st_size
;
458 /* Zero this out in case we run on a file with no extents */
459 fiemap
= calloc(n_extra
, sizeof(struct fiemap_extent
));
463 result_fiemap
= malloc_multiply(n_extra
, sizeof(struct fiemap_extent
));
467 /* XFS filesystem has incorrect implementation of fiemap ioctl and
468 * returns extents for only one block-group at a time, so we need
469 * to handle it manually, starting the next fiemap call from the end
472 while (fiemap_start
< fiemap_length
) {
473 *fiemap
= (struct fiemap
) {
474 .fm_start
= fiemap_start
,
475 .fm_length
= fiemap_length
,
476 .fm_flags
= FIEMAP_FLAG_SYNC
,
479 /* Find out how many extents there are */
480 if (ioctl(fd
, FS_IOC_FIEMAP
, fiemap
) < 0)
481 return log_debug_errno(errno
, "Failed to read extents: %m");
483 /* Nothing to process */
484 if (fiemap
->fm_mapped_extents
== 0)
487 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
488 * the extents for the whole file. Add space for the initial struct fiemap. */
489 if (!greedy_realloc0((void**) &fiemap
, &fiemap_allocated
,
490 n_extra
+ fiemap
->fm_mapped_extents
, sizeof(struct fiemap_extent
)))
493 fiemap
->fm_extent_count
= fiemap
->fm_mapped_extents
;
494 fiemap
->fm_mapped_extents
= 0;
496 if (ioctl(fd
, FS_IOC_FIEMAP
, fiemap
) < 0)
497 return log_debug_errno(errno
, "Failed to read extents: %m");
499 /* Resize result_fiemap to allow us to copy in the extents */
500 if (!greedy_realloc((void**) &result_fiemap
, &result_fiemap_allocated
,
501 n_extra
+ result_extents
+ fiemap
->fm_mapped_extents
, sizeof(struct fiemap_extent
)))
504 memcpy(result_fiemap
->fm_extents
+ result_extents
,
506 sizeof(struct fiemap_extent
) * fiemap
->fm_mapped_extents
);
508 result_extents
+= fiemap
->fm_mapped_extents
;
510 /* Highly unlikely that it is zero */
511 if (_likely_(fiemap
->fm_mapped_extents
> 0)) {
512 uint32_t i
= fiemap
->fm_mapped_extents
- 1;
514 fiemap_start
= fiemap
->fm_extents
[i
].fe_logical
+
515 fiemap
->fm_extents
[i
].fe_length
;
517 if (fiemap
->fm_extents
[i
].fe_flags
& FIEMAP_EXTENT_LAST
)
522 memcpy(result_fiemap
, fiemap
, sizeof(struct fiemap
));
523 result_fiemap
->fm_mapped_extents
= result_extents
;
524 *ret
= TAKE_PTR(result_fiemap
);
528 static int can_sleep_internal(const char *verb
, bool check_allowed
, const SleepConfig
*sleep_config
);
530 static bool can_s2h(const SleepConfig
*sleep_config
) {
534 if (!clock_supported(CLOCK_BOOTTIME_ALARM
)) {
535 log_full(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
,
536 "CLOCK_BOOTTIME_ALARM is not supported");
540 FOREACH_STRING(p
, "suspend", "hibernate") {
541 r
= can_sleep_internal(p
, false, sleep_config
);
542 if (IN_SET(r
, 0, -ENOSPC
, -EADV
)) {
543 log_debug("Unable to %s system.", p
);
547 return log_debug_errno(r
, "Failed to check if %s is possible: %m", p
);
553 static int can_sleep_internal(const char *verb
, bool check_allowed
, const SleepConfig
*sleep_config
) {
555 char **modes
= NULL
, **states
= NULL
;
558 assert(STR_IN_SET(verb
, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
560 r
= sleep_settings(verb
, sleep_config
, &allow
, &modes
, &states
);
564 if (check_allowed
&& !allow
) {
565 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb
);
569 if (streq(verb
, "suspend-then-hibernate"))
570 return can_s2h(sleep_config
);
572 if (!can_sleep_state(states
) || !can_sleep_disk(modes
))
575 if (streq(verb
, "suspend"))
578 if (!enough_swap_for_hibernation())
584 int can_sleep(const char *verb
) {
585 _cleanup_(free_sleep_configp
) SleepConfig
*sleep_config
= NULL
;
588 r
= parse_sleep_config(&sleep_config
);
592 return can_sleep_internal(verb
, true, sleep_config
);
595 int sleep_settings(const char *verb
, const SleepConfig
*sleep_config
, bool *ret_allow
, char ***ret_modes
, char ***ret_states
) {
598 assert(sleep_config
);
599 assert(STR_IN_SET(verb
, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
601 if (streq(verb
, "suspend")) {
602 *ret_allow
= sleep_config
->allow_suspend
;
603 *ret_modes
= sleep_config
->suspend_modes
;
604 *ret_states
= sleep_config
->suspend_states
;
605 } else if (streq(verb
, "hibernate")) {
606 *ret_allow
= sleep_config
->allow_hibernate
;
607 *ret_modes
= sleep_config
->hibernate_modes
;
608 *ret_states
= sleep_config
->hibernate_states
;
609 } else if (streq(verb
, "hybrid-sleep")) {
610 *ret_allow
= sleep_config
->allow_hybrid_sleep
;
611 *ret_modes
= sleep_config
->hybrid_modes
;
612 *ret_states
= sleep_config
->hybrid_states
;
613 } else if (streq(verb
, "suspend-then-hibernate")) {
614 *ret_allow
= sleep_config
->allow_s2h
;
615 *ret_modes
= *ret_states
= NULL
;
618 /* suspend modes empty by default */
619 if ((!ret_modes
&& !streq(verb
, "suspend")) || !ret_states
)
620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No modes or states set for %s; Check sleep.conf", verb
);
625 void free_sleep_config(SleepConfig
*sc
) {
629 strv_free(sc
->suspend_modes
);
630 strv_free(sc
->suspend_states
);
632 strv_free(sc
->hibernate_modes
);
633 strv_free(sc
->hibernate_states
);
635 strv_free(sc
->hybrid_modes
);
636 strv_free(sc
->hybrid_states
);