chiark / gitweb /
3ae9039fb4605ec12191dc6015432eb6792c06b5
[elogind.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright 2013 Zbigniew JÄ™drzejewski-Szmek
4   Copyright 2010-2017 Canonical
5   Copyright 2018 Dell Inc.
6 ***/
7
8 //#include <errno.h>
9 //#include <getopt.h>
10 //#include <linux/fiemap.h>
11 //#include <stdio.h>
12
13 #include "sd-messages.h"
14
15 //#include "parse-util.h"
16 #include "def.h"
17 #include "exec-util.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 //#include "log.h"
21 //#include "sleep-config.h"
22 //#include "stdio-util.h"
23 //#include "string-util.h"
24 #include "strv.h"
25 //#include "util.h"
26
27 /// Additional includes needed by elogind
28 #include "sleep.h"
29
30 static char* arg_verb = NULL;
31
32 static int write_hibernate_location_info(void) {
33         _cleanup_free_ char *device = NULL, *type = NULL;
34         _cleanup_free_ struct fiemap *fiemap = NULL;
35         char offset_str[DECIMAL_STR_MAX(uint64_t)];
36         char device_str[DECIMAL_STR_MAX(uint64_t)];
37         _cleanup_close_ int fd = -1;
38         struct stat stb;
39         uint64_t offset;
40         int r;
41
42         r = find_hibernate_location(&device, &type, NULL, NULL);
43         if (r < 0)
44                 return log_debug_errno(r, "Unable to find hibernation location: %m");
45
46         /* if it's a swap partition, we just write the disk to /sys/power/resume */
47         if (streq(type, "partition"))
48                 return write_string_file("/sys/power/resume", device, 0);
49         else if (!streq(type, "file"))
50                 return log_debug_errno(EINVAL, "Invalid hibernate type %s: %m",
51                                        type);
52
53         /* Only available in 4.17+ */
54         if (access("/sys/power/resume_offset", F_OK) < 0) {
55                 if (errno == ENOENT)
56                         return 0;
57                 return log_debug_errno(errno, "/sys/power/resume_offset unavailable: %m");
58         }
59
60         r = access("/sys/power/resume_offset", W_OK);
61         if (r < 0)
62                 return log_debug_errno(errno, "/sys/power/resume_offset not writeable: %m");
63
64         fd = open(device, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
65         if (fd < 0)
66                 return log_debug_errno(errno, "Unable to open '%s': %m", device);
67         r = fstat(fd, &stb);
68         if (r < 0)
69                 return log_debug_errno(errno, "Unable to stat %s: %m", device);
70         r = read_fiemap(fd, &fiemap);
71         if (r < 0)
72                 return log_debug_errno(r, "Unable to read extent map for '%s': %m",
73                                        device);
74         if (fiemap->fm_mapped_extents == 0) {
75                 log_debug("No extents found in '%s'", device);
76                 return -EINVAL;
77         }
78         offset = fiemap->fm_extents[0].fe_physical / page_size();
79         xsprintf(offset_str, "%" PRIu64, offset);
80         r = write_string_file("/sys/power/resume_offset", offset_str, 0);
81         if (r < 0)
82                 return log_debug_errno(r, "Failed to write offset '%s': %m",
83                                        offset_str);
84
85         xsprintf(device_str, "%lx", (unsigned long)stb.st_dev);
86         r = write_string_file("/sys/power/resume", device_str, 0);
87         if (r < 0)
88                 return log_debug_errno(r, "Failed to write device '%s': %m",
89                                        device_str);
90         return 0;
91 }
92
93 static int write_mode(char **modes) {
94         int r = 0;
95         char **mode;
96
97         STRV_FOREACH(mode, modes) {
98                 int k;
99
100                 k = write_string_file("/sys/power/disk", *mode, 0);
101                 if (k == 0)
102                         return 0;
103
104                 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m",
105                                 *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, 0);
121                 if (k == 0)
122                         return 0;
123                 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m",
124                                 *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
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         /* 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);
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                 return log_error_errno(r, "Failed to write /sys/power/state: %m");
179
180         log_struct(LOG_INFO,
181                    "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
182                    LOG_MESSAGE("System resumed."),
183                    "SLEEP=%s", arg_verb);
184
185         arguments[1] = (char*) "post";
186         execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
187
188         return r;
189 }
190
191 static int read_wakealarm(uint64_t *result) {
192         _cleanup_free_ char *t = NULL;
193
194         if (read_one_line_file("/sys/class/rtc/rtc0/since_epoch", &t) >= 0)
195                 return safe_atou64(t, result);
196         return -EBADF;
197 }
198
199 static int write_wakealarm(const char *str) {
200
201         _cleanup_fclose_ FILE *f = NULL;
202         int r;
203
204         f = fopen("/sys/class/rtc/rtc0/wakealarm", "we");
205         if (!f)
206                 return log_error_errno(errno, "Failed to open /sys/class/rtc/rtc0/wakealarm: %m");
207
208         r = write_string_stream(f, str, 0);
209         if (r < 0)
210                 return log_error_errno(r, "Failed to write '%s' to /sys/class/rtc/rtc0/wakealarm: %m", str);
211
212         return 0;
213 }
214
215 static int execute_s2h(usec_t hibernate_delay_sec) {
216
217         _cleanup_strv_free_ char **hibernate_modes = NULL, **hibernate_states = NULL,
218                                  **suspend_modes = NULL, **suspend_states = NULL;
219         usec_t orig_time, cmp_time;
220         char time_str[DECIMAL_STR_MAX(uint64_t)];
221         int r;
222
223         r = parse_sleep_config("suspend", &suspend_modes, &suspend_states,
224                                NULL);
225         if (r < 0)
226                 return r;
227
228         r = parse_sleep_config("hibernate", &hibernate_modes,
229                                &hibernate_states, NULL);
230         if (r < 0)
231                 return r;
232
233         r = read_wakealarm(&orig_time);
234         if (r < 0)
235                 return log_error_errno(errno, "Failed to read time: %d", r);
236
237         orig_time += hibernate_delay_sec / USEC_PER_SEC;
238         xsprintf(time_str, "%" PRIu64, orig_time);
239
240         r = write_wakealarm(time_str);
241         if (r < 0)
242                 return r;
243
244         log_debug("Set RTC wake alarm for %s", time_str);
245
246         r = execute(suspend_modes, suspend_states);
247         if (r < 0)
248                 return r;
249
250         r = read_wakealarm(&cmp_time);
251         if (r < 0)
252                 return log_error_errno(errno, "Failed to read time: %d", r);
253
254         /* reset RTC */
255         r = write_wakealarm("0");
256         if (r < 0)
257                 return r;
258
259         log_debug("Woke up at %"PRIu64, cmp_time);
260
261         /* if woken up after alarm time, hibernate */
262         if (cmp_time >= orig_time)
263                 r = execute(hibernate_modes, hibernate_states);
264
265         return r;
266 }
267
268 #if 0 /// elogind calls execute() by itself and does not need another binary
269 static void help(void) {
270         printf("%s COMMAND\n\n"
271                "Suspend the system, hibernate the system, or both.\n\n"
272                "Commands:\n"
273                "  -h --help            Show this help and exit\n"
274                "  --version            Print version string and exit\n"
275                "  suspend              Suspend the system\n"
276                "  hibernate            Hibernate the system\n"
277                "  hybrid-sleep         Both hibernate and suspend the system\n"
278                "  suspend-then-hibernate Initially suspend and then hibernate\n"
279                "                       the system after a fixed period of time\n"
280                , program_invocation_short_name);
281 }
282
283 static int parse_argv(int argc, char *argv[]) {
284         enum {
285                 ARG_VERSION = 0x100,
286         };
287
288         static const struct option options[] = {
289                 { "help",         no_argument,       NULL, 'h'           },
290                 { "version",      no_argument,       NULL, ARG_VERSION   },
291                 {}
292         };
293
294         int c;
295
296         assert(argc >= 0);
297         assert(argv);
298
299         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
300                 switch(c) {
301                 case 'h':
302                         help();
303                         return 0; /* done */
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                 log_error("Usage: %s COMMAND",
317                           program_invocation_short_name);
318                 return -EINVAL;
319         }
320
321         arg_verb = argv[optind];
322
323         if (!streq(arg_verb, "suspend") &&
324             !streq(arg_verb, "hibernate") &&
325             !streq(arg_verb, "hybrid-sleep") &&
326             !streq(arg_verb, "suspend-then-hibernate")) {
327                 log_error("Unknown command '%s'.", arg_verb);
328                 return -EINVAL;
329         }
330
331         return 1 /* work to do */;
332 }
333
334 int main(int argc, char *argv[]) {
335         _cleanup_strv_free_ char **modes = NULL, **states = NULL;
336         usec_t delay = 0;
337         int r;
338
339         log_set_target(LOG_TARGET_AUTO);
340         log_parse_environment();
341         log_open();
342
343         r = parse_argv(argc, argv);
344         if (r <= 0)
345                 goto finish;
346
347         r = parse_sleep_config(arg_verb, &modes, &states, &delay);
348         if (r < 0)
349                 goto finish;
350
351         if (streq(arg_verb, "suspend-then-hibernate"))
352                 r = execute_s2h(delay);
353         else
354                 r = execute(modes, states);
355 finish:
356         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
357 }
358 #else
359 int do_sleep(const char *verb, char **modes, char **states) {
360         assert(verb);
361         arg_verb = (char*)verb;
362         return execute(modes, states);
363 }
364 #endif // 0