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