]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sleep/sleep.c
tree-wide: add FORMAT_TIMESPAN()
[thirdparty/systemd.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
5 ***/
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <getopt.h>
10 #include <linux/fiemap.h>
11 #include <poll.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <sys/timerfd.h>
15 #include <unistd.h>
16
17 #include "sd-messages.h"
18
19 #include "btrfs-util.h"
20 #include "bus-error.h"
21 #include "def.h"
22 #include "exec-util.h"
23 #include "fd-util.h"
24 #include "fileio.h"
25 #include "format-util.h"
26 #include "io-util.h"
27 #include "log.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"
34 #include "strv.h"
35 #include "time-util.h"
36 #include "util.h"
37
38 static SleepOperation arg_operation = _SLEEP_OPERATION_INVALID;
39
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(":")];
43 int r;
44
45 assert(hibernate_location);
46 assert(hibernate_location->swap);
47
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);
50 if (r < 0)
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);
53
54 log_debug("Wrote resume= value for %s to /sys/power/resume: %s", hibernate_location->swap->device, resume_str);
55
56 /* if it's a swap partition, we're done */
57 if (streq(hibernate_location->swap->type, "partition"))
58 return r;
59
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);
63
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);
69 return 0;
70 }
71
72 return log_debug_errno(errno, "/sys/power/resume_offset not writable: %m");
73 }
74
75 xsprintf(offset_str, "%" PRIu64, hibernate_location->offset);
76 r = write_string_file("/sys/power/resume_offset", offset_str, WRITE_STRING_FILE_DISABLE_BUFFER);
77 if (r < 0)
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);
80
81 log_debug("Wrote resume_offset= value for %s to /sys/power/resume_offset: %s", hibernate_location->swap->device, offset_str);
82
83 return 0;
84 }
85
86 static int write_mode(char **modes) {
87 int r = 0;
88 char **mode;
89
90 STRV_FOREACH(mode, modes) {
91 int k;
92
93 k = write_string_file("/sys/power/disk", *mode, WRITE_STRING_FILE_DISABLE_BUFFER);
94 if (k >= 0)
95 return 0;
96
97 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m", *mode);
98 if (r >= 0)
99 r = k;
100 }
101
102 return r;
103 }
104
105 static int write_state(FILE **f, char **states) {
106 char **state;
107 int r = 0;
108
109 assert(f);
110 assert(*f);
111
112 STRV_FOREACH(state, states) {
113 int k;
114
115 k = write_string_stream(*f, *state, WRITE_STRING_FILE_DISABLE_BUFFER);
116 if (k >= 0)
117 return 0;
118 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state);
119 if (r >= 0)
120 r = k;
121
122 fclose(*f);
123 *f = fopen("/sys/power/state", "we");
124 if (!*f)
125 return -errno;
126 }
127
128 return r;
129 }
130
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;
135 int r;
136
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. */
139
140 r = sd_bus_open_system(&bus);
141 if (r < 0)
142 return log_warning_errno(r, "Failed to connect to system bus, ignoring: %m");
143
144 r = sd_bus_message_new_method_call(
145 bus,
146 &m,
147 "org.freedesktop.home1",
148 "/org/freedesktop/home1",
149 "org.freedesktop.home1.Manager",
150 "LockAllHomes");
151 if (r < 0)
152 return bus_log_create_error(r);
153
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);
156 if (r < 0)
157 return log_error_errno(r, "Failed to disable auto-start of LockAllHomes() message: %m");
158
159 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC, &error, NULL);
160 if (r < 0) {
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));
163
164 log_debug("systemd-homed is not running, locking of home directories skipped.");
165 } else
166 log_debug("Successfully requested locking of all home directories.");
167 return 0;
168 }
169
170 static int execute(
171 const SleepConfig *sleep_config,
172 SleepOperation operation,
173 const char *action) {
174
175 char *arguments[] = {
176 NULL,
177 (char*) "pre",
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),
181 NULL
182 };
183 static const char* const dirs[] = {
184 SYSTEM_SLEEP_PATH,
185 NULL
186 };
187
188 _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
189 _cleanup_fclose_ FILE *f = NULL;
190 char **modes, **states;
191 int r;
192
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 */
197
198 states = sleep_config->states[operation];
199 modes = sleep_config->modes[operation];
200
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));
205
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");
209 if (!f)
210 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
211
212 setvbuf(f, NULL, _IONBF, 0);
213
214 /* Configure hibernation settings if we are supposed to hibernate */
215 if (!strv_isempty(modes)) {
216 r = find_hibernate_location(&hibernate_location);
217 if (r < 0)
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);
223 if (r < 0)
224 return log_error_errno(r, "Failed to prepare for hibernation: %m");
225 }
226
227 r = write_mode(modes);
228 if (r < 0)
229 return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");;
230 }
231
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. */
234 if (!action)
235 action = sleep_operation_to_string(operation);
236
237 r = setenv("SYSTEMD_SLEEP_ACTION", action, 1);
238 if (r != 0)
239 log_warning_errno(errno, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action);
240
241 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
242 (void) lock_all_homes();
243
244 log_struct(LOG_INFO,
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));
248
249 r = write_state(&f, states);
250 if (r < 0)
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));
255 else
256 log_struct(LOG_INFO,
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));
260
261 arguments[1] = (char*) "post";
262 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
263
264 return r;
265 }
266
267 static int execute_s2h(const SleepConfig *sleep_config) {
268 _cleanup_close_ int tfd = -1;
269 struct itimerspec ts = {};
270 int r;
271
272 assert(sleep_config);
273
274 tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC);
275 if (tfd < 0)
276 return log_error_errno(errno, "Error creating timerfd: %m");
277
278 log_debug("Set timerfd wake alarm for %s",
279 FORMAT_TIMESPAN(sleep_config->hibernate_delay_sec, USEC_PER_SEC));
280
281 timespec_store(&ts.it_value, sleep_config->hibernate_delay_sec);
282
283 r = timerfd_settime(tfd, 0, &ts, NULL);
284 if (r < 0)
285 return log_error_errno(errno, "Error setting hibernate timer: %m");
286
287 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
288 if (r < 0)
289 return r;
290
291 r = fd_wait_for_event(tfd, POLLIN, 0);
292 if (r < 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. */
295 return 0;
296
297 tfd = safe_close(tfd);
298
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));
302
303 r = execute(sleep_config, SLEEP_HIBERNATE, NULL);
304 if (r < 0) {
305 log_notice("Couldn't hibernate, will try to suspend again.");
306
307 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hibernate");
308 if (r < 0)
309 return r;
310 }
311
312 return 0;
313 }
314
315 static int help(void) {
316 _cleanup_free_ char *link = NULL;
317 int r;
318
319 r = terminal_urlify_man("systemd-suspend.service", "8", &link);
320 if (r < 0)
321 return log_oom();
322
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"
327 "\nCommands:\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,
335 link);
336
337 return 0;
338 }
339
340 static int parse_argv(int argc, char *argv[]) {
341 enum {
342 ARG_VERSION = 0x100,
343 };
344
345 static const struct option options[] = {
346 { "help", no_argument, NULL, 'h' },
347 { "version", no_argument, NULL, ARG_VERSION },
348 {}
349 };
350
351 int c;
352
353 assert(argc >= 0);
354 assert(argv);
355
356 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
357 switch(c) {
358 case 'h':
359 return help();
360
361 case ARG_VERSION:
362 return version();
363
364 case '?':
365 return -EINVAL;
366
367 default:
368 assert_not_reached("Unhandled option");
369 }
370
371 if (argc - optind != 1)
372 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
373 "Usage: %s COMMAND",
374 program_invocation_short_name);
375
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]);
379
380 return 1 /* work to do */;
381 }
382
383 static int run(int argc, char *argv[]) {
384 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
385 int r;
386
387 log_setup();
388
389 r = parse_argv(argc, argv);
390 if (r <= 0)
391 return r;
392
393 r = parse_sleep_config(&sleep_config);
394 if (r < 0)
395 return r;
396
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));
401
402 switch (arg_operation) {
403
404 case SLEEP_SUSPEND_THEN_HIBERNATE:
405 r = execute_s2h(sleep_config);
406 break;
407
408 case SLEEP_HYBRID_SLEEP:
409 r = execute(sleep_config, SLEEP_HYBRID_SLEEP, NULL);
410 if (r < 0) {
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. */
414
415 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
416
417 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep");
418 }
419
420 break;
421
422 default:
423 r = execute(sleep_config, arg_operation, NULL);
424 break;
425 }
426
427 return r;
428 }
429
430 DEFINE_MAIN_FUNCTION(run);