1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2018 Dell Inc.
12 #include <sys/ioctl.h>
13 #include <sys/utsname.h>
19 #include "alloc-util.h"
20 #include "conf-parser.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "sleep-config.h"
30 #include "string-util.h"
33 int parse_sleep_config(const char *verb
, bool *ret_allow
, char ***ret_modes
, char ***ret_states
, usec_t
*ret_delay
) {
34 int allow_suspend
= -1, allow_hibernate
= -1,
35 allow_s2h
= -1, allow_hybrid_sleep
= -1;
37 _cleanup_strv_free_
char
38 **suspend_mode
= NULL
, **suspend_state
= NULL
,
39 **hibernate_mode
= NULL
, **hibernate_state
= NULL
,
40 **hybrid_mode
= NULL
, **hybrid_state
= NULL
;
41 _cleanup_strv_free_
char **modes
, **states
; /* always initialized below */
42 usec_t delay
= 180 * USEC_PER_MINUTE
;
44 const ConfigTableItem items
[] = {
45 { "Sleep", "AllowSuspend", config_parse_tristate
, 0, &allow_suspend
},
46 { "Sleep", "AllowHibernation", config_parse_tristate
, 0, &allow_hibernate
},
47 { "Sleep", "AllowSuspendThenHibernate", config_parse_tristate
, 0, &allow_s2h
},
48 { "Sleep", "AllowHybridSleep", config_parse_tristate
, 0, &allow_hybrid_sleep
},
50 { "Sleep", "SuspendMode", config_parse_strv
, 0, &suspend_mode
},
51 { "Sleep", "SuspendState", config_parse_strv
, 0, &suspend_state
},
52 { "Sleep", "HibernateMode", config_parse_strv
, 0, &hibernate_mode
},
53 { "Sleep", "HibernateState", config_parse_strv
, 0, &hibernate_state
},
54 { "Sleep", "HybridSleepMode", config_parse_strv
, 0, &hybrid_mode
},
55 { "Sleep", "HybridSleepState", config_parse_strv
, 0, &hybrid_state
},
57 { "Sleep", "HibernateDelaySec", config_parse_sec
, 0, &delay
},
61 (void) config_parse_many_nulstr(PKGSYSCONFDIR
"/sleep.conf",
62 CONF_PATHS_NULSTR("systemd/sleep.conf.d"),
63 "Sleep\0", config_item_table_lookup
, items
,
64 CONFIG_PARSE_WARN
, NULL
);
66 if (streq(verb
, "suspend")) {
67 allow
= allow_suspend
!= 0;
69 /* empty by default */
70 modes
= TAKE_PTR(suspend_mode
);
73 states
= TAKE_PTR(suspend_state
);
75 states
= strv_new("mem", "standby", "freeze");
77 } else if (streq(verb
, "hibernate")) {
78 allow
= allow_hibernate
!= 0;
81 modes
= TAKE_PTR(hibernate_mode
);
83 modes
= strv_new("platform", "shutdown");
86 states
= TAKE_PTR(hibernate_state
);
88 states
= strv_new("disk");
90 } else if (streq(verb
, "hybrid-sleep")) {
91 allow
= allow_hybrid_sleep
> 0 ||
92 (allow_suspend
!= 0 && allow_hibernate
!= 0);
95 modes
= TAKE_PTR(hybrid_mode
);
97 modes
= strv_new("suspend", "platform", "shutdown");
100 states
= TAKE_PTR(hybrid_state
);
102 states
= strv_new("disk");
104 } else if (streq(verb
, "suspend-then-hibernate")) {
105 allow
= allow_s2h
> 0 ||
106 (allow_suspend
!= 0 && allow_hibernate
!= 0);
108 modes
= states
= NULL
;
110 assert_not_reached("what verb");
112 if ((!modes
&& STR_IN_SET(verb
, "hibernate", "hybrid-sleep")) ||
113 (!states
&& !streq(verb
, "suspend-then-hibernate")))
119 *ret_modes
= TAKE_PTR(modes
);
121 *ret_states
= TAKE_PTR(states
);
128 int can_sleep_state(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/state", W_OK
) < 0)
140 r
= read_one_line_file("/sys/power/state", &p
);
144 STRV_FOREACH(type
, types
) {
145 const char *word
, *state
;
149 FOREACH_WORD_SEPARATOR(word
, l
, p
, WHITESPACE
, state
)
150 if (l
== k
&& memcmp(word
, *type
, l
) == 0)
157 int can_sleep_disk(char **types
) {
160 _cleanup_free_
char *p
= NULL
;
162 if (strv_isempty(types
))
165 /* If /sys is read-only we cannot sleep */
166 if (access("/sys/power/disk", W_OK
) < 0) {
167 log_debug_errno(errno
, "/sys/power/disk is not writable: %m");
171 r
= read_one_line_file("/sys/power/disk", &p
);
173 log_debug_errno(r
, "Couldn't read /sys/power/disk: %m");
177 STRV_FOREACH(type
, types
) {
178 const char *word
, *state
;
182 FOREACH_WORD_SEPARATOR(word
, l
, p
, WHITESPACE
, state
) {
183 if (l
== k
&& memcmp(word
, *type
, l
) == 0)
188 memcmp(word
+ 1, *type
, l
- 2) == 0 &&
197 #define HIBERNATION_SWAP_THRESHOLD 0.98
199 int find_hibernate_location(char **device
, char **type
, size_t *size
, size_t *used
) {
200 _cleanup_fclose_
FILE *f
;
203 f
= fopen("/proc/swaps", "re");
205 log_full(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
,
206 "Failed to retrieve open /proc/swaps: %m");
211 (void) fscanf(f
, "%*s %*s %*s %*s %*s\n");
214 _cleanup_free_
char *dev_field
= NULL
, *type_field
= NULL
;
215 size_t size_field
, used_field
;
219 "%ms " /* device/file */
220 "%ms " /* type of swap */
221 "%zu " /* swap size */
223 "%*i\n", /* priority */
224 &dev_field
, &type_field
, &size_field
, &used_field
);
228 log_warning("Failed to parse /proc/swaps:%u", i
);
232 if (streq(type_field
, "file")) {
234 if (endswith(dev_field
, "\\040(deleted)")) {
235 log_warning("Ignoring deleted swap file '%s'.", dev_field
);
239 } else if (streq(type_field
, "partition")) {
242 fn
= path_startswith(dev_field
, "/dev/");
243 if (fn
&& startswith(fn
, "zram")) {
244 log_debug("Ignoring compressed RAM swap device '%s'.", dev_field
);
250 *device
= TAKE_PTR(dev_field
);
252 *type
= TAKE_PTR(type_field
);
260 return log_debug_errno(SYNTHETIC_ERRNO(ENOSYS
),
261 "No swap partitions were found.");
264 static bool enough_swap_for_hibernation(void) {
265 _cleanup_free_
char *active
= NULL
;
266 unsigned long long act
= 0;
267 size_t size
= 0, used
= 0;
270 if (getenv_bool("SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK") > 0)
273 r
= find_hibernate_location(NULL
, NULL
, &size
, &used
);
277 r
= get_proc_field("/proc/meminfo", "Active(anon)", WHITESPACE
, &active
);
279 log_debug_errno(r
, "Failed to retrieve Active(anon) from /proc/meminfo: %m");
283 r
= safe_atollu(active
, &act
);
285 log_debug_errno(r
, "Failed to parse Active(anon) from /proc/meminfo: %s: %m", active
);
289 r
= act
<= (size
- used
) * HIBERNATION_SWAP_THRESHOLD
;
290 log_debug("%s swap for hibernation, Active(anon)=%llu kB, size=%zu kB, used=%zu kB, threshold=%.2g%%",
291 r
? "Enough" : "Not enough", act
, size
, used
, 100*HIBERNATION_SWAP_THRESHOLD
);
296 static int kernel_exists(void) {
301 /* Do some superficial checks whether the kernel we are currently running is still around. If it isn't we
302 * shouldn't offer hibernation as we couldn't possible resume from hibernation again. Of course, this check is
303 * very superficial, as the kernel's mere existance is hardly enough to know whether the hibernate/resume cycle
304 * will succeed. However, the common case of kernel updates can be caught this way, and it's definitely worth
308 _cleanup_free_
char *path
= NULL
;
313 /* First, let's look in /lib/modules/`uname -r`/vmlinuz. This is where current Fedora places
314 * its RPM-managed kernels. It's a good place, as it means compiled vendor code is monopolized
315 * in /usr, and then the kernel image is stored along with its modules in the same
316 * hierarchy. It's also what our 'kernel-install' script is written for. */
318 return log_debug_errno(errno
, "Failed to acquire kernel release: %m");
320 path
= strjoin("/lib/modules/", u
.release
, "/vmlinuz");
324 /* Secondly, let's look in /boot/vmlinuz-`uname -r`. This is where older Fedora and other
325 * distributions tend to place the kernel. */
326 path
= strjoin("/boot/vmlinuz-", u
.release
);
330 /* For the other cases, we look in the EFI/boot partition, at the place where our
331 * "kernel-install" script copies the kernel on install by default. */
332 r
= sd_id128_get_machine(&m
);
334 return log_debug_errno(r
, "Failed to read machine ID: %m");
336 (void) asprintf(&path
, "/efi/" SD_ID128_FORMAT_STR
"/%s/linux", SD_ID128_FORMAT_VAL(m
), u
.release
);
339 (void) asprintf(&path
, "/boot/" SD_ID128_FORMAT_STR
"/%s/linux", SD_ID128_FORMAT_VAL(m
), u
.release
);
342 (void) asprintf(&path
, "/boot/efi/" SD_ID128_FORMAT_STR
"/%s/linux", SD_ID128_FORMAT_VAL(m
), u
.release
);
352 log_debug("Testing whether %s exists.", path
);
354 if (access(path
, F_OK
) >= 0)
358 log_debug_errno(errno
, "Failed to determine whether '%s' exists, ignoring: %m", path
);
362 int read_fiemap(int fd
, struct fiemap
**ret
) {
363 _cleanup_free_
struct fiemap
*fiemap
= NULL
, *result_fiemap
= NULL
;
364 struct stat statinfo
;
365 uint32_t result_extents
= 0;
366 uint64_t fiemap_start
= 0, fiemap_length
;
367 const size_t n_extra
= DIV_ROUND_UP(sizeof(struct fiemap
), sizeof(struct fiemap_extent
));
368 size_t fiemap_allocated
= n_extra
, result_fiemap_allocated
= n_extra
;
370 if (fstat(fd
, &statinfo
) < 0)
371 return log_debug_errno(errno
, "Cannot determine file size: %m");
372 if (!S_ISREG(statinfo
.st_mode
))
374 fiemap_length
= statinfo
.st_size
;
376 /* Zero this out in case we run on a file with no extents */
377 fiemap
= calloc(n_extra
, sizeof(struct fiemap_extent
));
381 result_fiemap
= malloc_multiply(n_extra
, sizeof(struct fiemap_extent
));
385 /* XFS filesystem has incorrect implementation of fiemap ioctl and
386 * returns extents for only one block-group at a time, so we need
387 * to handle it manually, starting the next fiemap call from the end
390 while (fiemap_start
< fiemap_length
) {
391 *fiemap
= (struct fiemap
) {
392 .fm_start
= fiemap_start
,
393 .fm_length
= fiemap_length
,
394 .fm_flags
= FIEMAP_FLAG_SYNC
,
397 /* Find out how many extents there are */
398 if (ioctl(fd
, FS_IOC_FIEMAP
, fiemap
) < 0)
399 return log_debug_errno(errno
, "Failed to read extents: %m");
401 /* Nothing to process */
402 if (fiemap
->fm_mapped_extents
== 0)
405 /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all
406 * the extents for the whole file. Add space for the initial struct fiemap. */
407 if (!greedy_realloc0((void**) &fiemap
, &fiemap_allocated
,
408 n_extra
+ fiemap
->fm_mapped_extents
, sizeof(struct fiemap_extent
)))
411 fiemap
->fm_extent_count
= fiemap
->fm_mapped_extents
;
412 fiemap
->fm_mapped_extents
= 0;
414 if (ioctl(fd
, FS_IOC_FIEMAP
, fiemap
) < 0)
415 return log_debug_errno(errno
, "Failed to read extents: %m");
417 /* Resize result_fiemap to allow us to copy in the extents */
418 if (!greedy_realloc((void**) &result_fiemap
, &result_fiemap_allocated
,
419 n_extra
+ result_extents
+ fiemap
->fm_mapped_extents
, sizeof(struct fiemap_extent
)))
422 memcpy(result_fiemap
->fm_extents
+ result_extents
,
424 sizeof(struct fiemap_extent
) * fiemap
->fm_mapped_extents
);
426 result_extents
+= fiemap
->fm_mapped_extents
;
428 /* Highly unlikely that it is zero */
429 if (_likely_(fiemap
->fm_mapped_extents
> 0)) {
430 uint32_t i
= fiemap
->fm_mapped_extents
- 1;
432 fiemap_start
= fiemap
->fm_extents
[i
].fe_logical
+
433 fiemap
->fm_extents
[i
].fe_length
;
435 if (fiemap
->fm_extents
[i
].fe_flags
& FIEMAP_EXTENT_LAST
)
440 memcpy(result_fiemap
, fiemap
, sizeof(struct fiemap
));
441 result_fiemap
->fm_mapped_extents
= result_extents
;
442 *ret
= TAKE_PTR(result_fiemap
);
446 static int can_sleep_internal(const char *verb
, bool check_allowed
);
448 static bool can_s2h(void) {
452 r
= access("/sys/class/rtc/rtc0/wakealarm", W_OK
);
454 log_full(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
,
455 "/sys/class/rct/rct0/wakealarm is not writable %m");
459 FOREACH_STRING(p
, "suspend", "hibernate") {
460 r
= can_sleep_internal(p
, false);
461 if (IN_SET(r
, 0, -ENOSPC
, -ENOMEDIUM
, -EADV
)) {
462 log_debug("Unable to %s system.", p
);
466 return log_debug_errno(r
, "Failed to check if %s is possible: %m", p
);
472 static int can_sleep_internal(const char *verb
, bool check_allowed
) {
474 _cleanup_strv_free_
char **modes
= NULL
, **states
= NULL
;
477 assert(STR_IN_SET(verb
, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"));
479 r
= parse_sleep_config(verb
, &allow
, &modes
, &states
, NULL
);
483 if (check_allowed
&& !allow
) {
484 log_debug("Sleep mode \"%s\" is disabled by configuration.", verb
);
488 if (streq(verb
, "suspend-then-hibernate"))
491 if (!can_sleep_state(states
) || !can_sleep_disk(modes
))
494 if (streq(verb
, "suspend"))
497 if (kernel_exists() <= 0) {
498 log_debug_errno(errno
, "Couldn't find kernel, not offering hibernation.");
502 if (!enough_swap_for_hibernation())
508 int can_sleep(const char *verb
) {
509 return can_sleep_internal(verb
, true);