]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sleep/sleep.c
meson: fix error message
[thirdparty/systemd.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 <stdio.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <sys/timerfd.h>
16 #include <unistd.h>
17
18 #include "sd-messages.h"
19
20 #include "def.h"
21 #include "exec-util.h"
22 #include "fd-util.h"
23 #include "format-util.h"
24 #include "fileio.h"
25 #include "log.h"
26 #include "main-func.h"
27 #include "parse-util.h"
28 #include "pretty-print.h"
29 #include "sleep-config.h"
30 #include "stdio-util.h"
31 #include "string-util.h"
32 #include "strv.h"
33 #include "time-util.h"
34 #include "util.h"
35
36 static char* arg_verb = NULL;
37
38 static int write_hibernate_location_info(void) {
39 _cleanup_free_ char *device = NULL, *type = NULL;
40 _cleanup_free_ struct fiemap *fiemap = NULL;
41 char offset_str[DECIMAL_STR_MAX(uint64_t)];
42 char device_str[DECIMAL_STR_MAX(uint64_t)];
43 _cleanup_close_ int fd = -1;
44 struct stat stb;
45 uint64_t offset;
46 int r;
47
48 r = find_hibernate_location(&device, &type, NULL, NULL);
49 if (r < 0)
50 return log_debug_errno(r, "Unable to find hibernation location: %m");
51
52 /* if it's a swap partition, we just write the disk to /sys/power/resume */
53 if (streq(type, "partition")) {
54 r = write_string_file("/sys/power/resume", device, WRITE_STRING_FILE_DISABLE_BUFFER);
55 if (r < 0)
56 return log_debug_errno(r, "Failed to write partition device to /sys/power/resume: %m");
57
58 return r;
59 }
60 if (!streq(type, "file"))
61 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
62 "Invalid hibernate type: %s", type);
63
64 /* Only available in 4.17+ */
65 if (access("/sys/power/resume_offset", W_OK) < 0) {
66 if (errno == ENOENT) {
67 log_debug("Kernel too old, can't configure resume offset, ignoring.");
68 return 0;
69 }
70
71 return log_debug_errno(errno, "/sys/power/resume_offset not writeable: %m");
72 }
73
74 fd = open(device, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
75 if (fd < 0)
76 return log_debug_errno(errno, "Unable to open '%s': %m", device);
77 r = fstat(fd, &stb);
78 if (r < 0)
79 return log_debug_errno(errno, "Unable to stat %s: %m", device);
80
81 r = read_fiemap(fd, &fiemap);
82 if (r < 0)
83 return log_debug_errno(r, "Unable to read extent map for '%s': %m", device);
84 if (fiemap->fm_mapped_extents == 0)
85 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
86 "No extents found in '%s'", device);
87
88 offset = fiemap->fm_extents[0].fe_physical / page_size();
89 xsprintf(offset_str, "%" PRIu64, offset);
90 r = write_string_file("/sys/power/resume_offset", offset_str, WRITE_STRING_FILE_DISABLE_BUFFER);
91 if (r < 0)
92 return log_debug_errno(r, "Failed to write offset '%s': %m", offset_str);
93
94 xsprintf(device_str, "%lx", (unsigned long)stb.st_dev);
95 r = write_string_file("/sys/power/resume", device_str, WRITE_STRING_FILE_DISABLE_BUFFER);
96 if (r < 0)
97 return log_debug_errno(r, "Failed to write device '%s': %m", device_str);
98
99 return 0;
100 }
101
102 static int write_mode(char **modes) {
103 int r = 0;
104 char **mode;
105
106 STRV_FOREACH(mode, modes) {
107 int k;
108
109 k = write_string_file("/sys/power/disk", *mode, WRITE_STRING_FILE_DISABLE_BUFFER);
110 if (k >= 0)
111 return 0;
112
113 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m", *mode);
114 if (r >= 0)
115 r = k;
116 }
117
118 return r;
119 }
120
121 static int write_state(FILE **f, char **states) {
122 char **state;
123 int r = 0;
124
125 STRV_FOREACH(state, states) {
126 int k;
127
128 k = write_string_stream(*f, *state, WRITE_STRING_FILE_DISABLE_BUFFER);
129 if (k >= 0)
130 return 0;
131 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state);
132 if (r >= 0)
133 r = k;
134
135 fclose(*f);
136 *f = fopen("/sys/power/state", "we");
137 if (!*f)
138 return -errno;
139 }
140
141 return r;
142 }
143
144 static int execute(char **modes, char **states) {
145 char *arguments[] = {
146 NULL,
147 (char*) "pre",
148 arg_verb,
149 NULL
150 };
151 static const char* const dirs[] = {
152 SYSTEM_SLEEP_PATH,
153 NULL
154 };
155
156 int r;
157 _cleanup_fclose_ FILE *f = NULL;
158
159 /* This file is opened first, so that if we hit an error,
160 * we can abort before modifying any state. */
161 f = fopen("/sys/power/state", "we");
162 if (!f)
163 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
164
165 setvbuf(f, NULL, _IONBF, 0);
166
167 /* Configure the hibernation mode */
168 if (!strv_isempty(modes)) {
169 r = write_hibernate_location_info();
170 if (r < 0)
171 return log_error_errno(r, "Failed to write hibernation disk offset: %m");
172 r = write_mode(modes);
173 if (r < 0)
174 return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");;
175 }
176
177 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
178
179 log_struct(LOG_INFO,
180 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
181 LOG_MESSAGE("Suspending system..."),
182 "SLEEP=%s", arg_verb);
183
184 r = write_state(&f, states);
185 if (r < 0)
186 log_struct_errno(LOG_ERR, r,
187 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
188 LOG_MESSAGE("Failed to suspend system. System resumed again: %m"),
189 "SLEEP=%s", arg_verb);
190 else
191 log_struct(LOG_INFO,
192 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
193 LOG_MESSAGE("System resumed."),
194 "SLEEP=%s", arg_verb);
195
196 arguments[1] = (char*) "post";
197 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
198
199 return r;
200 }
201
202 static int execute_s2h(const SleepConfig *sleep_config) {
203 _cleanup_close_ int tfd = -1;
204 char buf[FORMAT_TIMESPAN_MAX];
205 struct itimerspec ts = {};
206 struct pollfd fds;
207 int r;
208
209 assert(sleep_config);
210
211 tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC);
212 if (tfd < 0)
213 return log_error_errno(errno, "Error creating timerfd: %m");
214
215 log_debug("Set timerfd wake alarm for %s",
216 format_timespan(buf, sizeof(buf), sleep_config->hibernate_delay_sec, USEC_PER_SEC));
217
218 timespec_store(&ts.it_value, sleep_config->hibernate_delay_sec);
219
220 r = timerfd_settime(tfd, 0, &ts, NULL);
221 if (r < 0)
222 return log_error_errno(errno, "Error setting hibernate timer: %m");
223
224 r = execute(sleep_config->suspend_modes, sleep_config->suspend_states);
225 if (r < 0)
226 return r;
227
228 fds = (struct pollfd) {
229 .fd = tfd,
230 .events = POLLIN,
231 };
232 r = poll(&fds, 1, 0);
233 if (r < 0)
234 return log_error_errno(errno, "Error polling timerfd: %m");
235
236 tfd = safe_close(tfd);
237
238 if (!FLAGS_SET(fds.revents, POLLIN)) /* We woke up before the alarm time, we are done. */
239 return 0;
240
241 /* If woken up after alarm time, hibernate */
242 log_debug("Attempting to hibernate after waking from %s timer",
243 format_timespan(buf, sizeof(buf), sleep_config->hibernate_delay_sec, USEC_PER_SEC));
244
245 r = execute(sleep_config->hibernate_modes, sleep_config->hibernate_states);
246 if (r < 0) {
247 log_notice("Couldn't hibernate, will try to suspend again.");
248 r = execute(sleep_config->suspend_modes, sleep_config->suspend_states);
249 if (r < 0) {
250 log_notice("Could neither hibernate nor suspend again, giving up.");
251 return r;
252 }
253 }
254
255 return 0;
256 }
257
258 static int help(void) {
259 _cleanup_free_ char *link = NULL;
260 int r;
261
262 r = terminal_urlify_man("systemd-suspend.service", "8", &link);
263 if (r < 0)
264 return log_oom();
265
266 printf("%s COMMAND\n\n"
267 "Suspend the system, hibernate the system, or both.\n\n"
268 " -h --help Show this help and exit\n"
269 " --version Print version string and exit\n"
270 "\nCommands:\n"
271 " suspend Suspend the system\n"
272 " hibernate Hibernate the system\n"
273 " hybrid-sleep Both hibernate and suspend the system\n"
274 " suspend-then-hibernate Initially suspend and then hibernate\n"
275 " the system after a fixed period of time\n"
276 "\nSee the %s for details.\n"
277 , program_invocation_short_name
278 , link
279 );
280
281 return 0;
282 }
283
284 static int parse_argv(int argc, char *argv[]) {
285 enum {
286 ARG_VERSION = 0x100,
287 };
288
289 static const struct option options[] = {
290 { "help", no_argument, NULL, 'h' },
291 { "version", no_argument, NULL, ARG_VERSION },
292 {}
293 };
294
295 int c;
296
297 assert(argc >= 0);
298 assert(argv);
299
300 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
301 switch(c) {
302 case 'h':
303 return help();
304
305 case ARG_VERSION:
306 return version();
307
308 case '?':
309 return -EINVAL;
310
311 default:
312 assert_not_reached("Unhandled option");
313 }
314
315 if (argc - optind != 1)
316 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
317 "Usage: %s COMMAND",
318 program_invocation_short_name);
319
320 arg_verb = argv[optind];
321
322 if (!STR_IN_SET(arg_verb, "suspend", "hibernate", "hybrid-sleep", "suspend-then-hibernate"))
323 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
324 "Unknown command '%s'.", arg_verb);
325
326 return 1 /* work to do */;
327 }
328
329 static int run(int argc, char *argv[]) {
330 bool allow;
331 char **modes = NULL, **states = NULL;
332 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
333 int r;
334
335 log_setup_service();
336
337 r = parse_argv(argc, argv);
338 if (r <= 0)
339 return r;
340
341 r = parse_sleep_config(&sleep_config);
342 if (r < 0)
343 return r;
344
345 r = sleep_settings(arg_verb, sleep_config, &allow, &modes, &states);
346 if (r < 0)
347 return r;
348
349 if (!allow)
350 return log_error_errno(SYNTHETIC_ERRNO(EACCES),
351 "Sleep mode \"%s\" is disabled by configuration, refusing.",
352 arg_verb);
353
354 if (streq(arg_verb, "suspend-then-hibernate"))
355 return execute_s2h(sleep_config);
356 else
357 return execute(modes, states);
358 }
359
360 DEFINE_MAIN_FUNCTION(run);