chiark / gitweb /
bec4cb9302820fdb7414fabd4e36f5eac1b44194
[elogind.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright 2012 Lennart Poettering
4   Copyright 2013 Zbigniew JÄ™drzejewski-Szmek
5   Copyright 2010-2017 Canonical
6   Copyright 2018 Dell Inc.
7 ***/
8
9 //#include <errno.h>
10 //#include <getopt.h>
11 //#include <linux/fiemap.h>
12 //#include <stdio.h>
13
14 #include "sd-messages.h"
15
16 //#include "parse-util.h"
17 #include "def.h"
18 #include "exec-util.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 //#include "log.h"
22 //#include "sleep-config.h"
23 //#include "stdio-util.h"
24 //#include "string-util.h"
25 #include "strv.h"
26 //#include "util.h"
27
28 /// Additional includes needed by elogind
29 #include "sleep.h"
30
31 static char* arg_verb = NULL;
32
33 static int write_hibernate_location_info(void) {
34         _cleanup_free_ char *device = NULL, *type = NULL;
35         _cleanup_free_ struct fiemap *fiemap = NULL;
36         char offset_str[DECIMAL_STR_MAX(uint64_t)];
37         char device_str[DECIMAL_STR_MAX(uint64_t)];
38         _cleanup_close_ int fd = -1;
39         struct stat stb;
40         uint64_t offset;
41         int r;
42
43         r = find_hibernate_location(&device, &type, NULL, NULL);
44         if (r < 0)
45                 return log_debug_errno(r, "Unable to find hibernation location: %m");
46
47         /* if it's a swap partition, we just write the disk to /sys/power/resume */
48         if (streq(type, "partition"))
49                 return write_string_file("/sys/power/resume", device, 0);
50         else if (!streq(type, "file"))
51                 return log_debug_errno(EINVAL, "Invalid hibernate type %s: %m",
52                                        type);
53
54         /* Only available in 4.17+ */
55         if (access("/sys/power/resume_offset", F_OK) < 0) {
56                 if (errno == ENOENT)
57                         return 0;
58                 return log_debug_errno(errno, "/sys/power/resume_offset unavailable: %m");
59         }
60
61         r = access("/sys/power/resume_offset", W_OK);
62         if (r < 0)
63                 return log_debug_errno(errno, "/sys/power/resume_offset not writeable: %m");
64
65         fd = open(device, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
66         if (fd < 0)
67                 return log_debug_errno(errno, "Unable to open '%s': %m", device);
68         r = fstat(fd, &stb);
69         if (r < 0)
70                 return log_debug_errno(errno, "Unable to stat %s: %m", device);
71         r = read_fiemap(fd, &fiemap);
72         if (r < 0)
73                 return log_debug_errno(r, "Unable to read extent map for '%s': %m",
74                                        device);
75         if (fiemap->fm_mapped_extents == 0) {
76                 log_debug("No extents found in '%s'", device);
77                 return -EINVAL;
78         }
79         offset = fiemap->fm_extents[0].fe_physical / page_size();
80         xsprintf(offset_str, "%" PRIu64, offset);
81         r = write_string_file("/sys/power/resume_offset", offset_str, 0);
82         if (r < 0)
83                 return log_debug_errno(r, "Failed to write offset '%s': %m",
84                                        offset_str);
85
86         xsprintf(device_str, "%lx", (unsigned long)stb.st_dev);
87         r = write_string_file("/sys/power/resume", device_str, 0);
88         if (r < 0)
89                 return log_debug_errno(r, "Failed to write device '%s': %m",
90                                        device_str);
91         return 0;
92 }
93
94 static int write_mode(char **modes) {
95         int r = 0;
96         char **mode;
97
98         STRV_FOREACH(mode, modes) {
99                 int k;
100
101                 k = write_string_file("/sys/power/disk", *mode, 0);
102                 if (k == 0)
103                         return 0;
104
105                 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m",
106                                 *mode);
107                 if (r == 0)
108                         r = k;
109         }
110
111         return r;
112 }
113
114 static int write_state(FILE **f, char **states) {
115         char **state;
116         int r = 0;
117
118         STRV_FOREACH(state, states) {
119                 int k;
120
121                 k = write_string_stream(*f, *state, 0);
122                 if (k == 0)
123                         return 0;
124                 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m",
125                                 *state);
126                 if (r == 0)
127                         r = k;
128
129                 fclose(*f);
130                 *f = fopen("/sys/power/state", "we");
131                 if (!*f)
132                         return -errno;
133         }
134
135         return r;
136 }
137
138 static int execute(char **modes, char **states) {
139
140         char *arguments[] = {
141                 NULL,
142                 (char*) "pre",
143                 arg_verb,
144                 NULL
145         };
146         static const char* const dirs[] = {
147                 SYSTEM_SLEEP_PATH,
148                 NULL
149         };
150
151         int r;
152         _cleanup_fclose_ FILE *f = NULL;
153
154         /* This file is opened first, so that if we hit an error,
155          * we can abort before modifying any state. */
156         f = fopen("/sys/power/state", "we");
157         if (!f)
158                 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
159
160         /* Configure the hibernation mode */
161         if (!strv_isempty(modes)) {
162                 r = write_hibernate_location_info();
163                 if (r < 0)
164                         return log_error_errno(r, "Failed to write hibernation disk offset: %m");
165                 r = write_mode(modes);
166                 if (r < 0)
167                         return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");;
168         }
169
170         execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
171
172         log_struct(LOG_INFO,
173                    "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
174                    LOG_MESSAGE("Suspending system..."),
175                    "SLEEP=%s", arg_verb);
176
177         r = write_state(&f, states);
178         if (r < 0)
179                 return log_error_errno(r, "Failed to write /sys/power/state: %m");
180
181         log_struct(LOG_INFO,
182                    "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
183                    LOG_MESSAGE("System resumed."),
184                    "SLEEP=%s", arg_verb);
185
186         arguments[1] = (char*) "post";
187         execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
188
189         return r;
190 }
191
192 static int read_wakealarm(uint64_t *result) {
193         _cleanup_free_ char *t = NULL;
194
195         if (read_one_line_file("/sys/class/rtc/rtc0/since_epoch", &t) >= 0)
196                 return safe_atou64(t, result);
197         return -EBADF;
198 }
199
200 static int write_wakealarm(const char *str) {
201
202         _cleanup_fclose_ FILE *f = NULL;
203         int r;
204
205         f = fopen("/sys/class/rtc/rtc0/wakealarm", "we");
206         if (!f)
207                 return log_error_errno(errno, "Failed to open /sys/class/rtc/rtc0/wakealarm: %m");
208
209         r = write_string_stream(f, str, 0);
210         if (r < 0)
211                 return log_error_errno(r, "Failed to write '%s' to /sys/class/rtc/rtc0/wakealarm: %m", str);
212
213         return 0;
214 }
215
216 static int execute_s2h(usec_t hibernate_delay_sec) {
217
218         _cleanup_strv_free_ char **hibernate_modes = NULL, **hibernate_states = NULL,
219                                  **suspend_modes = NULL, **suspend_states = NULL;
220         usec_t orig_time, cmp_time;
221         char time_str[DECIMAL_STR_MAX(uint64_t)];
222         int r;
223
224         r = parse_sleep_config("suspend", &suspend_modes, &suspend_states,
225                                NULL);
226         if (r < 0)
227                 return r;
228
229         r = parse_sleep_config("hibernate", &hibernate_modes,
230                                &hibernate_states, NULL);
231         if (r < 0)
232                 return r;
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         if (streq(arg_verb, "suspend-then-hibernate"))
353                 r = execute_s2h(delay);
354         else
355                 r = execute(modes, states);
356 finish:
357         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
358 }
359 #else
360 int do_sleep(const char *verb, char **modes, char **states) {
361         assert(verb);
362         arg_verb = (char*)verb;
363         return execute(modes, states);
364 }
365 #endif // 0