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