chiark / gitweb /
Drop my copyright headers
[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         r = parse_sleep_config("suspend", &suspend_modes, &suspend_states,
223                                NULL);
224         if (r < 0)
225                 return r;
226
227         r = parse_sleep_config("hibernate", &hibernate_modes,
228                                &hibernate_states, NULL);
229         if (r < 0)
230                 return r;
231
232         r = read_wakealarm(&orig_time);
233         if (r < 0)
234                 return log_error_errno(errno, "Failed to read time: %d", r);
235
236         orig_time += hibernate_delay_sec / USEC_PER_SEC;
237         xsprintf(time_str, "%" PRIu64, orig_time);
238
239         r = write_wakealarm(time_str);
240         if (r < 0)
241                 return r;
242
243         log_debug("Set RTC wake alarm for %s", time_str);
244
245         r = execute(suspend_modes, suspend_states);
246         if (r < 0)
247                 return r;
248
249         r = read_wakealarm(&cmp_time);
250         if (r < 0)
251                 return log_error_errno(errno, "Failed to read time: %d", r);
252
253         /* reset RTC */
254         r = write_wakealarm("0");
255         if (r < 0)
256                 return r;
257
258         log_debug("Woke up at %"PRIu64, cmp_time);
259
260         /* if woken up after alarm time, hibernate */
261         if (cmp_time >= orig_time)
262                 r = execute(hibernate_modes, hibernate_states);
263
264         return r;
265 }
266
267 #if 0 /// elogind calls execute() by itself and does not need another binary
268 static void help(void) {
269         printf("%s COMMAND\n\n"
270                "Suspend the system, hibernate the system, or both.\n\n"
271                "Commands:\n"
272                "  -h --help            Show this help and exit\n"
273                "  --version            Print version string and exit\n"
274                "  suspend              Suspend the system\n"
275                "  hibernate            Hibernate the system\n"
276                "  hybrid-sleep         Both hibernate and suspend the system\n"
277                "  suspend-then-hibernate Initially suspend and then hibernate\n"
278                "                       the system after a fixed period of time\n"
279                , program_invocation_short_name);
280 }
281
282 static int parse_argv(int argc, char *argv[]) {
283         enum {
284                 ARG_VERSION = 0x100,
285         };
286
287         static const struct option options[] = {
288                 { "help",         no_argument,       NULL, 'h'           },
289                 { "version",      no_argument,       NULL, ARG_VERSION   },
290                 {}
291         };
292
293         int c;
294
295         assert(argc >= 0);
296         assert(argv);
297
298         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
299                 switch(c) {
300                 case 'h':
301                         help();
302                         return 0; /* done */
303
304                 case ARG_VERSION:
305                         return version();
306
307                 case '?':
308                         return -EINVAL;
309
310                 default:
311                         assert_not_reached("Unhandled option");
312                 }
313
314         if (argc - optind != 1) {
315                 log_error("Usage: %s COMMAND",
316                           program_invocation_short_name);
317                 return -EINVAL;
318         }
319
320         arg_verb = argv[optind];
321
322         if (!streq(arg_verb, "suspend") &&
323             !streq(arg_verb, "hibernate") &&
324             !streq(arg_verb, "hybrid-sleep") &&
325             !streq(arg_verb, "suspend-then-hibernate")) {
326                 log_error("Unknown command '%s'.", arg_verb);
327                 return -EINVAL;
328         }
329
330         return 1 /* work to do */;
331 }
332
333 int main(int argc, char *argv[]) {
334         _cleanup_strv_free_ char **modes = NULL, **states = NULL;
335         usec_t delay = 0;
336         int r;
337
338         log_set_target(LOG_TARGET_AUTO);
339         log_parse_environment();
340         log_open();
341
342         r = parse_argv(argc, argv);
343         if (r <= 0)
344                 goto finish;
345
346         r = parse_sleep_config(arg_verb, &modes, &states, &delay);
347         if (r < 0)
348                 goto finish;
349
350         if (streq(arg_verb, "suspend-then-hibernate"))
351                 r = execute_s2h(delay);
352         else
353                 r = execute(modes, states);
354 finish:
355         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
356 }
357 #else
358 int do_sleep(const char *verb, char **modes, char **states) {
359         assert(verb);
360         arg_verb = (char*)verb;
361         return execute(modes, states);
362 }
363 #endif // 0