chiark / gitweb /
a0a07c134fce269ae7b304dd7944090365300f2e
[elogind.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2012 Lennart Poettering
6   Copyright 2013 Zbigniew JÄ™drzejewski-Szmek
7   Copyright 2010-2017 Canonical
8   Copyright 2018 Dell Inc.
9 ***/
10
11 //#include <errno.h>
12 //#include <getopt.h>
13 //#include <linux/fiemap.h>
14 //#include <stdio.h>
15
16 #include "sd-messages.h"
17
18 //#include "parse-util.h"
19 #include "def.h"
20 #include "exec-util.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 //#include "log.h"
24 //#include "sleep-config.h"
25 //#include "stdio-util.h"
26 //#include "string-util.h"
27 #include "strv.h"
28 //#include "util.h"
29
30 /// Additional includes needed by elogind
31 #include "sleep.h"
32
33 static char* arg_verb = NULL;
34
35 static int write_hibernate_location_info(void) {
36         _cleanup_free_ char *device = NULL, *type = NULL;
37         _cleanup_free_ struct fiemap *fiemap = NULL;
38         char offset_str[DECIMAL_STR_MAX(uint64_t)];
39         char device_str[DECIMAL_STR_MAX(uint64_t)];
40         _cleanup_close_ int fd = -1;
41         struct stat stb;
42         uint64_t offset;
43         int r;
44
45         r = find_hibernate_location(&device, &type, NULL, NULL);
46         if (r < 0)
47                 return log_debug_errno(r, "Unable to find hibernation location: %m");
48
49         /* if it's a swap partition, we just write the disk to /sys/power/resume */
50         if (streq(type, "partition"))
51                 return write_string_file("/sys/power/resume", device, 0);
52         else if (!streq(type, "file"))
53                 return log_debug_errno(EINVAL, "Invalid hibernate type %s: %m",
54                                        type);
55
56         /* Only available in 4.17+ */
57         if (access("/sys/power/resume_offset", F_OK) < 0) {
58                 if (errno == ENOENT)
59                         return 0;
60                 return log_debug_errno(errno, "/sys/power/resume_offset unavailable: %m");
61         }
62
63         r = access("/sys/power/resume_offset", W_OK);
64         if (r < 0)
65                 return log_debug_errno(errno, "/sys/power/resume_offset not writeable: %m");
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         r = read_fiemap(fd, &fiemap);
74         if (r < 0)
75                 return log_debug_errno(r, "Unable to read extent map for '%s': %m",
76                                        device);
77         if (fiemap->fm_mapped_extents == 0) {
78                 log_debug("No extents found in '%s'", device);
79                 return -EINVAL;
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, 0);
84         if (r < 0)
85                 return log_debug_errno(r, "Failed to write offset '%s': %m",
86                                        offset_str);
87
88         xsprintf(device_str, "%lx", (unsigned long)stb.st_dev);
89         r = write_string_file("/sys/power/resume", device_str, 0);
90         if (r < 0)
91                 return log_debug_errno(r, "Failed to write device '%s': %m",
92                                        device_str);
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, 0);
104                 if (k == 0)
105                         return 0;
106
107                 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m",
108                                 *mode);
109                 if (r == 0)
110                         r = k;
111         }
112
113         return r;
114 }
115
116 static int write_state(FILE **f, char **states) {
117         char **state;
118         int r = 0;
119
120         STRV_FOREACH(state, states) {
121                 int k;
122
123                 k = write_string_stream(*f, *state, 0);
124                 if (k == 0)
125                         return 0;
126                 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m",
127                                 *state);
128                 if (r == 0)
129                         r = k;
130
131                 fclose(*f);
132                 *f = fopen("/sys/power/state", "we");
133                 if (!*f)
134                         return -errno;
135         }
136
137         return r;
138 }
139
140 static int execute(char **modes, char **states) {
141
142         char *arguments[] = {
143                 NULL,
144                 (char*) "pre",
145                 arg_verb,
146                 NULL
147         };
148         static const char* const dirs[] = {
149                 SYSTEM_SLEEP_PATH,
150                 NULL
151         };
152
153         int r;
154         _cleanup_fclose_ FILE *f = NULL;
155
156         /* This file is opened first, so that if we hit an error,
157          * we can abort before modifying any state. */
158         f = fopen("/sys/power/state", "we");
159         if (!f)
160                 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
161
162         /* Configure the hibernation mode */
163         if (!strv_isempty(modes)) {
164                 r = write_hibernate_location_info();
165                 if (r < 0)
166                         return log_error_errno(r, "Failed to write hibernation disk offset: %m");
167                 r = write_mode(modes);
168                 if (r < 0)
169                         return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");;
170         }
171
172         execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
173
174         log_struct(LOG_INFO,
175                    "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
176                    LOG_MESSAGE("Suspending system..."),
177                    "SLEEP=%s", arg_verb);
178
179         r = write_state(&f, states);
180         if (r < 0)
181                 return log_error_errno(r, "Failed to write /sys/power/state: %m");
182
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);
190
191         return r;
192 }
193
194 static int read_wakealarm(uint64_t *result) {
195         _cleanup_free_ char *t = NULL;
196
197         if (read_one_line_file("/sys/class/rtc/rtc0/since_epoch", &t) >= 0)
198                 return safe_atou64(t, result);
199         return -EBADF;
200 }
201
202 static int write_wakealarm(const char *str) {
203
204         _cleanup_fclose_ FILE *f = NULL;
205         int r;
206
207         f = fopen("/sys/class/rtc/rtc0/wakealarm", "we");
208         if (!f)
209                 return log_error_errno(errno, "Failed to open /sys/class/rtc/rtc0/wakealarm: %m");
210
211         r = write_string_stream(f, str, 0);
212         if (r < 0)
213                 return log_error_errno(r, "Failed to write '%s' to /sys/class/rtc/rtc0/wakealarm: %m", str);
214
215         return 0;
216 }
217
218 static int execute_s2h(usec_t hibernate_delay_sec) {
219
220         _cleanup_strv_free_ char **hibernate_modes = NULL, **hibernate_states = NULL,
221                                  **suspend_modes = NULL, **suspend_states = NULL;
222         usec_t orig_time, cmp_time;
223         char time_str[DECIMAL_STR_MAX(uint64_t)];
224         int r;
225
226         r = parse_sleep_config("suspend", &suspend_modes, &suspend_states,
227                                NULL);
228         if (r < 0)
229                 return r;
230
231         r = parse_sleep_config("hibernate", &hibernate_modes,
232                                &hibernate_states, NULL);
233         if (r < 0)
234                 return r;
235
236         r = read_wakealarm(&orig_time);
237         if (r < 0)
238                 return log_error_errno(errno, "Failed to read time: %d", r);
239
240         orig_time += hibernate_delay_sec / USEC_PER_SEC;
241         xsprintf(time_str, "%" PRIu64, orig_time);
242
243         r = write_wakealarm(time_str);
244         if (r < 0)
245                 return r;
246
247         log_debug("Set RTC wake alarm for %s", time_str);
248
249         r = execute(suspend_modes, suspend_states);
250         if (r < 0)
251                 return r;
252
253         r = read_wakealarm(&cmp_time);
254         if (r < 0)
255                 return log_error_errno(errno, "Failed to read time: %d", r);
256
257         /* reset RTC */
258         r = write_wakealarm("0");
259         if (r < 0)
260                 return r;
261
262         log_debug("Woke up at %"PRIu64, cmp_time);
263
264         /* if woken up after alarm time, hibernate */
265         if (cmp_time >= orig_time)
266                 r = execute(hibernate_modes, hibernate_states);
267
268         return r;
269 }
270
271 #if 0 /// elogind calls execute() by itself and does not need another binary
272 static void help(void) {
273         printf("%s COMMAND\n\n"
274                "Suspend the system, hibernate the system, or both.\n\n"
275                "Commands:\n"
276                "  -h --help            Show this help and exit\n"
277                "  --version            Print version string and exit\n"
278                "  suspend              Suspend the system\n"
279                "  hibernate            Hibernate the system\n"
280                "  hybrid-sleep         Both hibernate and suspend the system\n"
281                "  suspend-then-hibernate Initially suspend and then hibernate\n"
282                "                       the system after a fixed period of time\n"
283                , program_invocation_short_name);
284 }
285
286 static int parse_argv(int argc, char *argv[]) {
287         enum {
288                 ARG_VERSION = 0x100,
289         };
290
291         static const struct option options[] = {
292                 { "help",         no_argument,       NULL, 'h'           },
293                 { "version",      no_argument,       NULL, ARG_VERSION   },
294                 {}
295         };
296
297         int c;
298
299         assert(argc >= 0);
300         assert(argv);
301
302         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
303                 switch(c) {
304                 case 'h':
305                         help();
306                         return 0; /* done */
307
308                 case ARG_VERSION:
309                         return version();
310
311                 case '?':
312                         return -EINVAL;
313
314                 default:
315                         assert_not_reached("Unhandled option");
316                 }
317
318         if (argc - optind != 1) {
319                 log_error("Usage: %s COMMAND",
320                           program_invocation_short_name);
321                 return -EINVAL;
322         }
323
324         arg_verb = argv[optind];
325
326         if (!streq(arg_verb, "suspend") &&
327             !streq(arg_verb, "hibernate") &&
328             !streq(arg_verb, "hybrid-sleep") &&
329             !streq(arg_verb, "suspend-then-hibernate")) {
330                 log_error("Unknown command '%s'.", arg_verb);
331                 return -EINVAL;
332         }
333
334         return 1 /* work to do */;
335 }
336
337 int main(int argc, char *argv[]) {
338         _cleanup_strv_free_ char **modes = NULL, **states = NULL;
339         usec_t delay = 0;
340         int r;
341
342         log_set_target(LOG_TARGET_AUTO);
343         log_parse_environment();
344         log_open();
345
346         r = parse_argv(argc, argv);
347         if (r <= 0)
348                 goto finish;
349
350         r = parse_sleep_config(arg_verb, &modes, &states, &delay);
351         if (r < 0)
352                 goto finish;
353
354         if (streq(arg_verb, "suspend-then-hibernate"))
355                 r = execute_s2h(delay);
356         else
357                 r = execute(modes, states);
358 finish:
359         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
360 }
361 #else
362 int do_sleep(const char *verb, char **modes, char **states) {
363         assert(verb);
364         arg_verb = (char*)verb;
365         return execute(modes, states);
366 }
367 #endif // 0