1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
10 #include <linux/fiemap.h>
13 #include <sys/types.h>
14 #include <sys/timerfd.h>
18 #include "sd-messages.h"
20 #include "btrfs-util.h"
22 #include "bus-error.h"
23 #include "bus-locator.h"
25 #include "constants.h"
26 #include "exec-util.h"
29 #include "format-util.h"
32 #include "main-func.h"
33 #include "parse-util.h"
34 #include "pretty-print.h"
35 #include "sleep-config.h"
37 #include "stdio-util.h"
38 #include "string-util.h"
40 #include "time-util.h"
42 #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
44 static SleepOperation arg_operation
= _SLEEP_OPERATION_INVALID
;
46 static int write_hibernate_location_info(const HibernateLocation
*hibernate_location
) {
47 char offset_str
[DECIMAL_STR_MAX(uint64_t)];
48 char resume_str
[DECIMAL_STR_MAX(unsigned) * 2 + STRLEN(":")];
51 assert(hibernate_location
);
52 assert(hibernate_location
->swap
);
54 xsprintf(resume_str
, "%u:%u", major(hibernate_location
->devno
), minor(hibernate_location
->devno
));
55 r
= write_string_file("/sys/power/resume", resume_str
, WRITE_STRING_FILE_DISABLE_BUFFER
);
57 return log_debug_errno(r
, "Failed to write partition device to /sys/power/resume for '%s': '%s': %m",
58 hibernate_location
->swap
->device
, resume_str
);
60 log_debug("Wrote resume= value for %s to /sys/power/resume: %s", hibernate_location
->swap
->device
, resume_str
);
62 /* if it's a swap partition, we're done */
63 if (streq(hibernate_location
->swap
->type
, "partition"))
66 if (!streq(hibernate_location
->swap
->type
, "file"))
67 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
68 "Invalid hibernate type: %s", hibernate_location
->swap
->type
);
70 /* Only available in 4.17+ */
71 if (hibernate_location
->offset
> 0 && access("/sys/power/resume_offset", W_OK
) < 0) {
72 if (errno
== ENOENT
) {
73 log_debug("Kernel too old, can't configure resume_offset for %s, ignoring: %" PRIu64
,
74 hibernate_location
->swap
->device
, hibernate_location
->offset
);
78 return log_debug_errno(errno
, "/sys/power/resume_offset not writable: %m");
81 xsprintf(offset_str
, "%" PRIu64
, hibernate_location
->offset
);
82 r
= write_string_file("/sys/power/resume_offset", offset_str
, WRITE_STRING_FILE_DISABLE_BUFFER
);
84 return log_debug_errno(r
, "Failed to write swap file offset to /sys/power/resume_offset for '%s': '%s': %m",
85 hibernate_location
->swap
->device
, offset_str
);
87 log_debug("Wrote resume_offset= value for %s to /sys/power/resume_offset: %s", hibernate_location
->swap
->device
, offset_str
);
92 static int write_mode(char **modes
) {
95 STRV_FOREACH(mode
, modes
) {
98 k
= write_string_file("/sys/power/disk", *mode
, WRITE_STRING_FILE_DISABLE_BUFFER
);
102 log_debug_errno(k
, "Failed to write '%s' to /sys/power/disk: %m", *mode
);
110 static int write_state(FILE **f
, char **states
) {
116 STRV_FOREACH(state
, states
) {
119 k
= write_string_stream(*f
, *state
, WRITE_STRING_FILE_DISABLE_BUFFER
);
122 log_debug_errno(k
, "Failed to write '%s' to /sys/power/state: %m", *state
);
127 *f
= fopen("/sys/power/state", "we");
135 static int lock_all_homes(void) {
136 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
137 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
138 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
141 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
142 * way the key material required to access these volumes is hopefully removed from memory. */
144 r
= sd_bus_open_system(&bus
);
146 return log_warning_errno(r
, "Failed to connect to system bus, ignoring: %m");
148 r
= sd_bus_message_new_method_call(
151 "org.freedesktop.home1",
152 "/org/freedesktop/home1",
153 "org.freedesktop.home1.Manager",
156 return bus_log_create_error(r
);
158 /* If homed is not running it can't have any home directories active either. */
159 r
= sd_bus_message_set_auto_start(m
, false);
161 return log_error_errno(r
, "Failed to disable auto-start of LockAllHomes() message: %m");
163 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
, &error
, NULL
);
165 if (!bus_error_is_unknown_service(&error
))
166 return log_error_errno(r
, "Failed to lock home directories: %s", bus_error_message(&error
, r
));
168 log_debug("systemd-homed is not running, locking of home directories skipped.");
170 log_debug("Successfully requested locking of all home directories.");
175 const SleepConfig
*sleep_config
,
176 SleepOperation operation
,
177 const char *action
) {
179 char *arguments
[] = {
182 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
183 * operation here, not the specific one, in case of s2h. */
184 (char*) sleep_operation_to_string(arg_operation
),
187 static const char* const dirs
[] = {
192 _cleanup_(hibernate_location_freep
) HibernateLocation
*hibernate_location
= NULL
;
193 _cleanup_fclose_
FILE *f
= NULL
;
194 char **modes
, **states
;
197 assert(sleep_config
);
198 assert(operation
>= 0);
199 assert(operation
< _SLEEP_OPERATION_MAX
);
200 assert(operation
!= SLEEP_SUSPEND_THEN_HIBERNATE
); /* Handled by execute_s2h() instead */
202 states
= sleep_config
->states
[operation
];
203 modes
= sleep_config
->modes
[operation
];
205 if (strv_isempty(states
))
206 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
207 "No sleep states configured for sleep operation %s, can't sleep.",
208 sleep_operation_to_string(operation
));
210 /* This file is opened first, so that if we hit an error,
211 * we can abort before modifying any state. */
212 f
= fopen("/sys/power/state", "we");
214 return log_error_errno(errno
, "Failed to open /sys/power/state: %m");
216 setvbuf(f
, NULL
, _IONBF
, 0);
218 /* Configure hibernation settings if we are supposed to hibernate */
219 if (!strv_isempty(modes
)) {
220 r
= find_hibernate_location(&hibernate_location
);
222 return log_error_errno(r
, "Failed to find location to hibernate to: %m");
223 if (r
== 0) { /* 0 means: no hibernation location was configured in the kernel so far, let's
224 * do it ourselves then. > 0 means: kernel already had a configured hibernation
225 * location which we shouldn't touch. */
226 r
= write_hibernate_location_info(hibernate_location
);
228 return log_error_errno(r
, "Failed to prepare for hibernation: %m");
231 r
= write_mode(modes
);
233 return log_error_errno(r
, "Failed to write mode to /sys/power/disk: %m");
236 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
237 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
239 action
= sleep_operation_to_string(operation
);
241 r
= setenv("SYSTEMD_SLEEP_ACTION", action
, 1);
243 log_warning_errno(errno
, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action
);
245 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
246 (void) lock_all_homes();
249 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR
,
250 LOG_MESSAGE("Entering sleep state '%s'...", sleep_operation_to_string(operation
)),
251 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
253 r
= write_state(&f
, states
);
255 log_struct_errno(LOG_ERR
, r
,
256 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
257 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
258 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
261 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
262 LOG_MESSAGE("System returned from sleep state."),
263 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
265 arguments
[1] = (char*) "post";
266 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
271 static int custom_timer_suspend(const SleepConfig
*sleep_config
) {
272 usec_t hibernate_timestamp
;
275 assert(sleep_config
);
277 hibernate_timestamp
= usec_add(now(CLOCK_BOOTTIME
), sleep_config
->hibernate_delay_usec
);
279 while (battery_is_discharging_and_low() == 0) {
280 _cleanup_hashmap_free_ Hashmap
*last_capacity
= NULL
, *current_capacity
= NULL
;
281 _cleanup_close_
int tfd
= -EBADF
;
282 struct itimerspec ts
= {};
283 usec_t suspend_interval
;
286 tfd
= timerfd_create(CLOCK_BOOTTIME_ALARM
, TFD_NONBLOCK
|TFD_CLOEXEC
);
288 return log_error_errno(errno
, "Error creating timerfd: %m");
290 /* Store current battery capacity before suspension */
291 r
= fetch_batteries_capacity_by_name(&last_capacity
);
293 return log_error_errno(r
, "Error fetching battery capacity percentage: %m");
295 if (hashmap_isempty(last_capacity
))
296 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
297 suspend_interval
= timestamp_is_set(hibernate_timestamp
)
298 ? sleep_config
->hibernate_delay_usec
: DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY
;
300 r
= get_total_suspend_interval(last_capacity
, &suspend_interval
);
302 log_debug_errno(r
, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
303 /* In case of any errors, especially when we do not know the battery
304 * discharging rate, system suspend interval will be set to
305 * SuspendEstimationSec=. */
306 suspend_interval
= sleep_config
->suspend_estimation_usec
;
310 /* Do not suspend more than HibernateDelaySec= */
311 usec_t before_timestamp
= now(CLOCK_BOOTTIME
);
312 suspend_interval
= MIN(suspend_interval
, usec_sub_unsigned(hibernate_timestamp
, before_timestamp
));
313 if (suspend_interval
<= 0)
314 break; /* system should hibernate */
316 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval
, USEC_PER_SEC
));
317 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
318 timespec_store(&ts
.it_value
, suspend_interval
);
320 if (timerfd_settime(tfd
, 0, &ts
, NULL
) < 0)
321 return log_error_errno(errno
, "Error setting battery estimate timer: %m");
323 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
327 r
= fd_wait_for_event(tfd
, POLLIN
, 0);
329 return log_error_errno(r
, "Error polling timerfd: %m");
330 /* Store fd_wait status */
331 woken_by_timer
= FLAGS_SET(r
, POLLIN
);
333 r
= fetch_batteries_capacity_by_name(¤t_capacity
);
334 if (r
< 0 || hashmap_isempty(current_capacity
)) {
335 /* In case of no battery or error while getting charge level, no need to measure
336 * discharge rate. Instead the system should wake up if it is manual wakeup or
337 * hibernate if this is a timer wakeup. */
339 log_debug_errno(r
, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
341 log_debug("No battery found.");
347 usec_t after_timestamp
= now(CLOCK_BOOTTIME
);
348 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
349 FORMAT_TIMESPAN(after_timestamp
- before_timestamp
, USEC_PER_HOUR
));
351 if (after_timestamp
!= before_timestamp
) {
352 r
= estimate_battery_discharge_rate_per_hour(last_capacity
, current_capacity
, before_timestamp
, after_timestamp
);
354 log_warning_errno(r
, "Failed to estimate and update battery discharge rate, ignoring: %m");
356 log_debug("System woke up too early to estimate discharge rate");
359 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
362 r
= check_wakeup_type();
364 log_debug_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
366 log_debug("wakeup type is APM timer");
367 /* system should hibernate */
375 /* Freeze when invoked and thaw on cleanup */
376 static int freeze_thaw_user_slice(const char **method
) {
377 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
378 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
381 if (!method
|| !*method
)
384 r
= bus_connect_system_systemd(&bus
);
386 return log_debug_errno(r
, "Failed to open connection to systemd: %m");
388 (void) sd_bus_set_method_call_timeout(bus
, FREEZE_TIMEOUT
);
390 r
= bus_call_method(bus
, bus_systemd_mgr
, *method
, &error
, NULL
, "s", SPECIAL_USER_SLICE
);
392 return log_debug_errno(r
, "Failed to execute operation: %s", bus_error_message(&error
, r
));
397 static int execute_s2h(const SleepConfig
*sleep_config
) {
398 _unused_
_cleanup_(freeze_thaw_user_slice
) const char *auto_method_thaw
= "ThawUnit";
401 assert(sleep_config
);
403 r
= freeze_thaw_user_slice(&(const char*) { "FreezeUnit" });
405 log_debug_errno(r
, "Failed to freeze unit user.slice, ignoring: %m");
407 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
408 * we'll busy poll for the configured interval instead */
409 if (!timestamp_is_set(sleep_config
->hibernate_delay_usec
)) {
410 r
= check_wakeup_type();
412 log_debug_errno(r
, "Failed to check hardware wakeup type, ignoring: %m");
414 r
= battery_trip_point_alarm_exists();
416 log_debug_errno(r
, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
419 r
= 0; /* Force fallback path */
421 if (r
> 0) { /* If we have both wakeup alarms and battery trip point support, use them */
422 log_debug("Attempting to suspend...");
423 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
427 r
= check_wakeup_type();
429 return log_debug_errno(r
, "Failed to check hardware wakeup type: %m");
432 /* For APM Timer wakeup, system should hibernate else wakeup */
435 r
= custom_timer_suspend(sleep_config
);
437 return log_debug_errno(r
, "Suspend cycle with manual battery discharge rate estimation failed: %m");
442 /* For above custom timer, if 1 is returned, system will directly hibernate */
444 log_debug("Attempting to hibernate");
445 r
= execute(sleep_config
, SLEEP_HIBERNATE
, NULL
);
447 log_notice("Couldn't hibernate, will try to suspend again.");
449 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hibernate");
457 static int help(void) {
458 _cleanup_free_
char *link
= NULL
;
461 r
= terminal_urlify_man("systemd-suspend.service", "8", &link
);
465 printf("%s COMMAND\n\n"
466 "Suspend the system, hibernate the system, or both.\n\n"
467 " -h --help Show this help and exit\n"
468 " --version Print version string and exit\n"
470 " suspend Suspend the system\n"
471 " hibernate Hibernate the system\n"
472 " hybrid-sleep Both hibernate and suspend the system\n"
473 " suspend-then-hibernate Initially suspend and then hibernate\n"
474 " the system after a fixed period of time\n"
475 "\nSee the %s for details.\n",
476 program_invocation_short_name
,
482 static int parse_argv(int argc
, char *argv
[]) {
487 static const struct option options
[] = {
488 { "help", no_argument
, NULL
, 'h' },
489 { "version", no_argument
, NULL
, ARG_VERSION
},
498 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
510 assert_not_reached();
513 if (argc
- optind
!= 1)
514 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
516 program_invocation_short_name
);
518 arg_operation
= sleep_operation_from_string(argv
[optind
]);
519 if (arg_operation
< 0)
520 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown command '%s'.", argv
[optind
]);
522 return 1 /* work to do */;
525 static int run(int argc
, char *argv
[]) {
526 _cleanup_(free_sleep_configp
) SleepConfig
*sleep_config
= NULL
;
531 r
= parse_argv(argc
, argv
);
535 r
= parse_sleep_config(&sleep_config
);
539 if (!sleep_config
->allow
[arg_operation
])
540 return log_error_errno(SYNTHETIC_ERRNO(EACCES
),
541 "Sleep operation \"%s\" is disabled by configuration, refusing.",
542 sleep_operation_to_string(arg_operation
));
544 switch (arg_operation
) {
546 case SLEEP_SUSPEND_THEN_HIBERNATE
:
547 r
= execute_s2h(sleep_config
);
550 case SLEEP_HYBRID_SLEEP
:
551 r
= execute(sleep_config
, SLEEP_HYBRID_SLEEP
, NULL
);
553 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
554 * asked us to do both: suspend + hibernate, and it's almost certainly the
555 * hibernation that failed, hence still do the other thing, the suspend. */
557 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
559 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hybrid-sleep");
565 r
= execute(sleep_config
, arg_operation
, NULL
);
572 DEFINE_MAIN_FUNCTION(run
);