chiark / gitweb /
Prep v239: A few cosmetic upgrades
[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 #if 0 /// elogind uses the values stored in its manager instance
137 static int execute(char **modes, char **states) {
138 #else
139 static int execute(Manager *m, const char *verb) {
140         assert(m);
141
142         if (verb)
143                 arg_verb = (char*)verb;
144
145         char **modes  = streq(arg_verb, "suspend")   ? m->suspend_mode     :
146                         streq(arg_verb, "hibernate") ? m->hibernate_mode   :
147                                                        m->hybrid_sleep_mode;
148         char **states = streq(arg_verb, "suspend")   ? m->suspend_state     :
149                         streq(arg_verb, "hibernate") ? m->hibernate_state   :
150                                                        m->hybrid_sleep_state;
151 #endif // 0
152
153         char *arguments[] = {
154                 NULL,
155                 (char*) "pre",
156                 arg_verb,
157                 NULL
158         };
159         static const char* const dirs[] = {
160                 SYSTEM_SLEEP_PATH,
161                 NULL
162         };
163
164         int r;
165         _cleanup_fclose_ FILE *f = NULL;
166
167         /* This file is opened first, so that if we hit an error,
168          * we can abort before modifying any state. */
169         f = fopen("/sys/power/state", "we");
170         if (!f)
171                 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
172
173         /* Configure the hibernation mode */
174         if (!strv_isempty(modes)) {
175                 r = write_hibernate_location_info();
176                 if (r < 0)
177                         return log_error_errno(r, "Failed to write hibernation disk offset: %m");
178                 r = write_mode(modes);
179                 if (r < 0)
180                         return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");;
181         }
182
183         execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
184
185         log_struct(LOG_INFO,
186                    "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
187                    LOG_MESSAGE("Suspending system..."),
188                    "SLEEP=%s", arg_verb);
189
190         r = write_state(&f, states);
191         if (r < 0)
192                 return log_error_errno(r, "Failed to write /sys/power/state: %m");
193
194         log_struct(LOG_INFO,
195                    "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
196                    LOG_MESSAGE("System resumed."),
197                    "SLEEP=%s", arg_verb);
198
199         arguments[1] = (char*) "post";
200         execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
201
202         return r;
203 }
204
205 static int read_wakealarm(uint64_t *result) {
206         _cleanup_free_ char *t = NULL;
207
208         if (read_one_line_file("/sys/class/rtc/rtc0/since_epoch", &t) >= 0)
209                 return safe_atou64(t, result);
210         return -EBADF;
211 }
212
213 static int write_wakealarm(const char *str) {
214
215         _cleanup_fclose_ FILE *f = NULL;
216         int r;
217
218         f = fopen("/sys/class/rtc/rtc0/wakealarm", "we");
219         if (!f)
220                 return log_error_errno(errno, "Failed to open /sys/class/rtc/rtc0/wakealarm: %m");
221
222         r = write_string_stream(f, str, 0);
223         if (r < 0)
224                 return log_error_errno(r, "Failed to write '%s' to /sys/class/rtc/rtc0/wakealarm: %m", str);
225
226         return 0;
227 }
228
229 #if 0 /// elogind uses the values stored in its manager instance
230 static int execute_s2h(usec_t hibernate_delay_sec) {
231
232         _cleanup_strv_free_ char **hibernate_modes = NULL, **hibernate_states = NULL,
233                                  **suspend_modes = NULL, **suspend_states = NULL;
234 #else
235 static int execute_s2h(Manager *m) {
236         assert(m);
237
238         usec_t hibernate_delay_sec = m->hibernate_delay_sec;
239 #endif // 0
240         usec_t orig_time, cmp_time;
241         char time_str[DECIMAL_STR_MAX(uint64_t)];
242         int r;
243
244 #if 0 /// Already parsed by elogind config
245         r = parse_sleep_config("suspend", &suspend_modes, &suspend_states,
246                                NULL);
247         if (r < 0)
248                 return r;
249
250         r = parse_sleep_config("hibernate", &hibernate_modes,
251                                &hibernate_states, NULL);
252         if (r < 0)
253                 return r;
254 #endif // 0
255
256         r = read_wakealarm(&orig_time);
257         if (r < 0)
258                 return log_error_errno(errno, "Failed to read time: %d", r);
259
260         orig_time += hibernate_delay_sec / USEC_PER_SEC;
261         xsprintf(time_str, "%" PRIu64, orig_time);
262
263         r = write_wakealarm(time_str);
264         if (r < 0)
265                 return r;
266
267         log_debug("Set RTC wake alarm for %s", time_str);
268
269 #if 0 /// elogind uses its manager instance values
270         r = execute(suspend_modes, suspend_states);
271 #else
272         r = execute(m, "suspend");
273 #endif // 0
274         if (r < 0)
275                 return r;
276
277         r = read_wakealarm(&cmp_time);
278         if (r < 0)
279                 return log_error_errno(errno, "Failed to read time: %d", r);
280
281         /* reset RTC */
282         r = write_wakealarm("0");
283         if (r < 0)
284                 return r;
285
286         log_debug("Woke up at %"PRIu64, cmp_time);
287
288         /* if woken up after alarm time, hibernate */
289         if (cmp_time >= orig_time)
290 #if 0 /// elogind uses its manager instance values
291                 r = execute(hibernate_modes, hibernate_states);
292 #else
293                 r = execute(m, "hibernate");
294 #endif // 0
295
296         return r;
297 }
298
299 #if 0 /// elogind calls execute() by itself and does not need another binary
300 static void help(void) {
301         printf("%s COMMAND\n\n"
302                "Suspend the system, hibernate the system, or both.\n\n"
303                "Commands:\n"
304                "  -h --help            Show this help and exit\n"
305                "  --version            Print version string and exit\n"
306                "  suspend              Suspend the system\n"
307                "  hibernate            Hibernate the system\n"
308                "  hybrid-sleep         Both hibernate and suspend the system\n"
309                "  suspend-then-hibernate Initially suspend and then hibernate\n"
310                "                       the system after a fixed period of time\n"
311                , program_invocation_short_name);
312 }
313
314 static int parse_argv(int argc, char *argv[]) {
315         enum {
316                 ARG_VERSION = 0x100,
317         };
318
319         static const struct option options[] = {
320                 { "help",         no_argument,       NULL, 'h'           },
321                 { "version",      no_argument,       NULL, ARG_VERSION   },
322                 {}
323         };
324
325         int c;
326
327         assert(argc >= 0);
328         assert(argv);
329
330         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
331                 switch(c) {
332                 case 'h':
333                         help();
334                         return 0; /* done */
335
336                 case ARG_VERSION:
337                         return version();
338
339                 case '?':
340                         return -EINVAL;
341
342                 default:
343                         assert_not_reached("Unhandled option");
344                 }
345
346         if (argc - optind != 1) {
347                 log_error("Usage: %s COMMAND",
348                           program_invocation_short_name);
349                 return -EINVAL;
350         }
351
352         arg_verb = argv[optind];
353
354         if (!streq(arg_verb, "suspend") &&
355             !streq(arg_verb, "hibernate") &&
356             !streq(arg_verb, "hybrid-sleep") &&
357             !streq(arg_verb, "suspend-then-hibernate")) {
358                 log_error("Unknown command '%s'.", arg_verb);
359                 return -EINVAL;
360         }
361
362         return 1 /* work to do */;
363 }
364
365 int main(int argc, char *argv[]) {
366         _cleanup_strv_free_ char **modes = NULL, **states = NULL;
367         usec_t delay = 0;
368         int r;
369
370         log_set_target(LOG_TARGET_AUTO);
371         log_parse_environment();
372         log_open();
373
374         r = parse_argv(argc, argv);
375         if (r <= 0)
376                 goto finish;
377
378         r = parse_sleep_config(arg_verb, &modes, &states, &delay);
379         if (r < 0)
380                 goto finish;
381
382         if (streq(arg_verb, "suspend-then-hibernate"))
383                 r = execute_s2h(delay);
384         else
385                 r = execute(modes, states);
386 finish:
387         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
388 }
389 #else
390 int do_sleep(Manager *m, const char *verb) {
391         assert(verb);
392         assert(m);
393
394         arg_verb = (char*)verb;
395
396         if (streq(arg_verb, "suspend-then-hibernate"))
397                 return execute_s2h(m);
398
399         return execute(m, NULL);
400 }
401 #endif // 0