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>
17 #include "sd-messages.h"
19 #include "btrfs-util.h"
20 #include "bus-error.h"
22 #include "exec-util.h"
25 #include "format-util.h"
28 #include "main-func.h"
29 #include "parse-util.h"
30 #include "pretty-print.h"
31 #include "sleep-config.h"
32 #include "stdio-util.h"
33 #include "string-util.h"
35 #include "time-util.h"
38 static SleepOperation arg_operation
= _SLEEP_OPERATION_INVALID
;
40 static int write_hibernate_location_info(const HibernateLocation
*hibernate_location
) {
41 char offset_str
[DECIMAL_STR_MAX(uint64_t)];
42 char resume_str
[DECIMAL_STR_MAX(unsigned) * 2 + STRLEN(":")];
45 assert(hibernate_location
);
46 assert(hibernate_location
->swap
);
48 xsprintf(resume_str
, "%u:%u", major(hibernate_location
->devno
), minor(hibernate_location
->devno
));
49 r
= write_string_file("/sys/power/resume", resume_str
, WRITE_STRING_FILE_DISABLE_BUFFER
);
51 return log_debug_errno(r
, "Failed to write partition device to /sys/power/resume for '%s': '%s': %m",
52 hibernate_location
->swap
->device
, resume_str
);
54 log_debug("Wrote resume= value for %s to /sys/power/resume: %s", hibernate_location
->swap
->device
, resume_str
);
56 /* if it's a swap partition, we're done */
57 if (streq(hibernate_location
->swap
->type
, "partition"))
60 if (!streq(hibernate_location
->swap
->type
, "file"))
61 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
62 "Invalid hibernate type: %s", hibernate_location
->swap
->type
);
64 /* Only available in 4.17+ */
65 if (hibernate_location
->offset
> 0 && access("/sys/power/resume_offset", W_OK
) < 0) {
66 if (errno
== ENOENT
) {
67 log_debug("Kernel too old, can't configure resume_offset for %s, ignoring: %" PRIu64
,
68 hibernate_location
->swap
->device
, hibernate_location
->offset
);
72 return log_debug_errno(errno
, "/sys/power/resume_offset not writable: %m");
75 xsprintf(offset_str
, "%" PRIu64
, hibernate_location
->offset
);
76 r
= write_string_file("/sys/power/resume_offset", offset_str
, WRITE_STRING_FILE_DISABLE_BUFFER
);
78 return log_debug_errno(r
, "Failed to write swap file offset to /sys/power/resume_offset for '%s': '%s': %m",
79 hibernate_location
->swap
->device
, offset_str
);
81 log_debug("Wrote resume_offset= value for %s to /sys/power/resume_offset: %s", hibernate_location
->swap
->device
, offset_str
);
86 static int write_mode(char **modes
) {
90 STRV_FOREACH(mode
, modes
) {
93 k
= write_string_file("/sys/power/disk", *mode
, WRITE_STRING_FILE_DISABLE_BUFFER
);
97 log_debug_errno(k
, "Failed to write '%s' to /sys/power/disk: %m", *mode
);
105 static int write_state(FILE **f
, char **states
) {
112 STRV_FOREACH(state
, states
) {
115 k
= write_string_stream(*f
, *state
, WRITE_STRING_FILE_DISABLE_BUFFER
);
118 log_debug_errno(k
, "Failed to write '%s' to /sys/power/state: %m", *state
);
123 *f
= fopen("/sys/power/state", "we");
131 static int lock_all_homes(void) {
132 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
133 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
134 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
137 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
138 * way the key material required to access these volumes is hopefully removed from memory. */
140 r
= sd_bus_open_system(&bus
);
142 return log_warning_errno(r
, "Failed to connect to system bus, ignoring: %m");
144 r
= sd_bus_message_new_method_call(
147 "org.freedesktop.home1",
148 "/org/freedesktop/home1",
149 "org.freedesktop.home1.Manager",
152 return bus_log_create_error(r
);
154 /* If homed is not running it can't have any home directories active either. */
155 r
= sd_bus_message_set_auto_start(m
, false);
157 return log_error_errno(r
, "Failed to disable auto-start of LockAllHomes() message: %m");
159 r
= sd_bus_call(bus
, m
, DEFAULT_TIMEOUT_USEC
, &error
, NULL
);
161 if (!bus_error_is_unknown_service(&error
))
162 return log_error_errno(r
, "Failed to lock home directories: %s", bus_error_message(&error
, r
));
164 log_debug("systemd-homed is not running, locking of home directories skipped.");
166 log_debug("Successfully requested locking of all home directories.");
171 const SleepConfig
*sleep_config
,
172 SleepOperation operation
,
173 const char *action
) {
175 char *arguments
[] = {
178 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
179 * operation here, not the specific one, in case of s2h. */
180 (char*) sleep_operation_to_string(arg_operation
),
183 static const char* const dirs
[] = {
188 _cleanup_(hibernate_location_freep
) HibernateLocation
*hibernate_location
= NULL
;
189 _cleanup_fclose_
FILE *f
= NULL
;
190 char **modes
, **states
;
193 assert(sleep_config
);
194 assert(operation
>= 0);
195 assert(operation
< _SLEEP_OPERATION_MAX
);
196 assert(operation
!= SLEEP_SUSPEND_THEN_HIBERNATE
); /* Handled by execute_s2h() instead */
198 states
= sleep_config
->states
[operation
];
199 modes
= sleep_config
->modes
[operation
];
201 if (strv_isempty(states
))
202 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
203 "No sleep states configured for sleep operation %s, can't sleep.",
204 sleep_operation_to_string(operation
));
206 /* This file is opened first, so that if we hit an error,
207 * we can abort before modifying any state. */
208 f
= fopen("/sys/power/state", "we");
210 return log_error_errno(errno
, "Failed to open /sys/power/state: %m");
212 setvbuf(f
, NULL
, _IONBF
, 0);
214 /* Configure hibernation settings if we are supposed to hibernate */
215 if (!strv_isempty(modes
)) {
216 r
= find_hibernate_location(&hibernate_location
);
218 return log_error_errno(r
, "Failed to find location to hibernate to: %m");
219 if (r
== 0) { /* 0 means: no hibernation location was configured in the kernel so far, let's
220 * do it ourselves then. > 0 means: kernel already had a configured hibernation
221 * location which we shouldn't touch. */
222 r
= write_hibernate_location_info(hibernate_location
);
224 return log_error_errno(r
, "Failed to prepare for hibernation: %m");
227 r
= write_mode(modes
);
229 return log_error_errno(r
, "Failed to write mode to /sys/power/disk: %m");;
232 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
233 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
235 action
= sleep_operation_to_string(operation
);
237 r
= setenv("SYSTEMD_SLEEP_ACTION", action
, 1);
239 log_warning_errno(errno
, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action
);
241 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
242 (void) lock_all_homes();
245 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR
,
246 LOG_MESSAGE("Entering sleep state '%s'...", sleep_operation_to_string(operation
)),
247 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
249 r
= write_state(&f
, states
);
251 log_struct_errno(LOG_ERR
, r
,
252 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
253 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
254 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
257 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR
,
258 LOG_MESSAGE("System returned from sleep state."),
259 "SLEEP=%s", sleep_operation_to_string(arg_operation
));
261 arguments
[1] = (char*) "post";
262 (void) execute_directories(dirs
, DEFAULT_TIMEOUT_USEC
, NULL
, NULL
, arguments
, NULL
, EXEC_DIR_PARALLEL
| EXEC_DIR_IGNORE_ERRORS
);
267 static int execute_s2h(const SleepConfig
*sleep_config
) {
268 _cleanup_close_
int tfd
= -1;
269 struct itimerspec ts
= {};
272 assert(sleep_config
);
274 tfd
= timerfd_create(CLOCK_BOOTTIME_ALARM
, TFD_NONBLOCK
|TFD_CLOEXEC
);
276 return log_error_errno(errno
, "Error creating timerfd: %m");
278 log_debug("Set timerfd wake alarm for %s",
279 FORMAT_TIMESPAN(sleep_config
->hibernate_delay_sec
, USEC_PER_SEC
));
281 timespec_store(&ts
.it_value
, sleep_config
->hibernate_delay_sec
);
283 r
= timerfd_settime(tfd
, 0, &ts
, NULL
);
285 return log_error_errno(errno
, "Error setting hibernate timer: %m");
287 r
= execute(sleep_config
, SLEEP_SUSPEND
, NULL
);
291 r
= fd_wait_for_event(tfd
, POLLIN
, 0);
293 return log_error_errno(r
, "Error polling timerfd: %m");
294 if (!FLAGS_SET(r
, POLLIN
)) /* We woke up before the alarm time, we are done. */
297 tfd
= safe_close(tfd
);
299 /* If woken up after alarm time, hibernate */
300 log_debug("Attempting to hibernate after waking from %s timer",
301 FORMAT_TIMESPAN(sleep_config
->hibernate_delay_sec
, USEC_PER_SEC
));
303 r
= execute(sleep_config
, SLEEP_HIBERNATE
, NULL
);
305 log_notice("Couldn't hibernate, will try to suspend again.");
307 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hibernate");
315 static int help(void) {
316 _cleanup_free_
char *link
= NULL
;
319 r
= terminal_urlify_man("systemd-suspend.service", "8", &link
);
323 printf("%s COMMAND\n\n"
324 "Suspend the system, hibernate the system, or both.\n\n"
325 " -h --help Show this help and exit\n"
326 " --version Print version string and exit\n"
328 " suspend Suspend the system\n"
329 " hibernate Hibernate the system\n"
330 " hybrid-sleep Both hibernate and suspend the system\n"
331 " suspend-then-hibernate Initially suspend and then hibernate\n"
332 " the system after a fixed period of time\n"
333 "\nSee the %s for details.\n",
334 program_invocation_short_name
,
340 static int parse_argv(int argc
, char *argv
[]) {
345 static const struct option options
[] = {
346 { "help", no_argument
, NULL
, 'h' },
347 { "version", no_argument
, NULL
, ARG_VERSION
},
356 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
368 assert_not_reached("Unhandled option");
371 if (argc
- optind
!= 1)
372 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
374 program_invocation_short_name
);
376 arg_operation
= sleep_operation_from_string(argv
[optind
]);
377 if (arg_operation
< 0)
378 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown command '%s'.", argv
[optind
]);
380 return 1 /* work to do */;
383 static int run(int argc
, char *argv
[]) {
384 _cleanup_(free_sleep_configp
) SleepConfig
*sleep_config
= NULL
;
389 r
= parse_argv(argc
, argv
);
393 r
= parse_sleep_config(&sleep_config
);
397 if (!sleep_config
->allow
[arg_operation
])
398 return log_error_errno(SYNTHETIC_ERRNO(EACCES
),
399 "Sleep operation \"%s\" is disabled by configuration, refusing.",
400 sleep_operation_to_string(arg_operation
));
402 switch (arg_operation
) {
404 case SLEEP_SUSPEND_THEN_HIBERNATE
:
405 r
= execute_s2h(sleep_config
);
408 case SLEEP_HYBRID_SLEEP
:
409 r
= execute(sleep_config
, SLEEP_HYBRID_SLEEP
, NULL
);
411 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
412 * asked us to do both: suspend + hibernate, and it's almost certainly the
413 * hibernation that failed, hence still do the other thing, the suspend. */
415 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
417 r
= execute(sleep_config
, SLEEP_SUSPEND
, "suspend-after-failed-hybrid-sleep");
423 r
= execute(sleep_config
, arg_operation
, NULL
);
430 DEFINE_MAIN_FUNCTION(run
);