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