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