]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sleep/sleep.c
Merge pull request #29249 from poettering/pid1-error-message
[thirdparty/systemd.git] / src / sleep / sleep.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
5 ***/
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <getopt.h>
10 #include <linux/fiemap.h>
11 #include <poll.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <sys/timerfd.h>
15 #include <sys/utsname.h>
16 #include <unistd.h>
17
18 #include "sd-bus.h"
19 #include "sd-device.h"
20 #include "sd-id128.h"
21 #include "sd-messages.h"
22
23 #include "battery-capacity.h"
24 #include "battery-util.h"
25 #include "btrfs-util.h"
26 #include "build.h"
27 #include "bus-error.h"
28 #include "bus-locator.h"
29 #include "bus-util.h"
30 #include "constants.h"
31 #include "devnum-util.h"
32 #include "efivars.h"
33 #include "exec-util.h"
34 #include "fd-util.h"
35 #include "fileio.h"
36 #include "format-util.h"
37 #include "hibernate-util.h"
38 #include "id128-util.h"
39 #include "io-util.h"
40 #include "json.h"
41 #include "log.h"
42 #include "main-func.h"
43 #include "os-util.h"
44 #include "parse-util.h"
45 #include "pretty-print.h"
46 #include "sleep-config.h"
47 #include "special.h"
48 #include "stdio-util.h"
49 #include "string-util.h"
50 #include "strv.h"
51 #include "time-util.h"
52
53 #define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
54
55 static SleepOperation arg_operation = _SLEEP_OPERATION_INVALID;
56
57 static int write_efi_hibernate_location(const HibernateLocation *hibernate_location, bool required) {
58 int log_level = required ? LOG_ERR : LOG_DEBUG;
59
60 #if ENABLE_EFI
61 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
62 _cleanup_free_ char *formatted = NULL, *id = NULL, *image_id = NULL,
63 *version_id = NULL, *image_version = NULL;
64 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
65 const char *uuid_str;
66 sd_id128_t uuid;
67 struct utsname uts = {};
68 int r, log_level_ignore = required ? LOG_WARNING : LOG_DEBUG;
69
70 assert(hibernate_location);
71 assert(hibernate_location->swap);
72
73 if (!is_efi_boot())
74 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
75 "Not an EFI boot, passing HibernateLocation via EFI variable is not possible.");
76
77 r = sd_device_new_from_devnum(&device, 'b', hibernate_location->devno);
78 if (r < 0)
79 return log_full_errno(log_level, r, "Failed to create sd-device object for '%s': %m",
80 hibernate_location->swap->path);
81
82 r = sd_device_get_property_value(device, "ID_FS_UUID", &uuid_str);
83 if (r < 0)
84 return log_full_errno(log_level, r, "Failed to get filesystem UUID for device '%s': %m",
85 hibernate_location->swap->path);
86
87 r = sd_id128_from_string(uuid_str, &uuid);
88 if (r < 0)
89 return log_full_errno(log_level, r, "Failed to parse ID_FS_UUID '%s' for device '%s': %m",
90 uuid_str, hibernate_location->swap->path);
91
92 if (uname(&uts) < 0)
93 log_full_errno(log_level_ignore, errno, "Failed to get kernel info, ignoring: %m");
94
95 r = parse_os_release(NULL,
96 "ID", &id,
97 "IMAGE_ID", &image_id,
98 "VERSION_ID", &version_id,
99 "IMAGE_VERSION", &image_version);
100 if (r < 0)
101 log_full_errno(log_level_ignore, r, "Failed to parse os-release, ignoring: %m");
102
103 r = json_build(&v, JSON_BUILD_OBJECT(
104 JSON_BUILD_PAIR_UUID("uuid", uuid),
105 JSON_BUILD_PAIR_UNSIGNED("offset", hibernate_location->offset),
106 JSON_BUILD_PAIR_CONDITION(!isempty(uts.release), "kernelVersion", JSON_BUILD_STRING(uts.release)),
107 JSON_BUILD_PAIR_CONDITION(id, "osReleaseId", JSON_BUILD_STRING(id)),
108 JSON_BUILD_PAIR_CONDITION(image_id, "osReleaseImageId", JSON_BUILD_STRING(image_id)),
109 JSON_BUILD_PAIR_CONDITION(version_id, "osReleaseVersionId", JSON_BUILD_STRING(version_id)),
110 JSON_BUILD_PAIR_CONDITION(image_version, "osReleaseImageVersion", JSON_BUILD_STRING(image_version))));
111 if (r < 0)
112 return log_full_errno(log_level, r, "Failed to build JSON object: %m");
113
114 r = json_variant_format(v, 0, &formatted);
115 if (r < 0)
116 return log_full_errno(log_level, r, "Failed to format JSON object: %m");
117
118 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(HibernateLocation), formatted);
119 if (r < 0)
120 return log_full_errno(log_level, r, "Failed to set EFI variable HibernateLocation: %m");
121
122 log_debug("Set EFI variable HibernateLocation to '%s'.", formatted);
123 return 0;
124 #else
125 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
126 "EFI support not enabled, passing HibernateLocation via EFI variable is not possible.");
127 #endif
128 }
129
130 static int write_kernel_hibernate_location(const HibernateLocation *hibernate_location) {
131 assert(hibernate_location);
132 assert(hibernate_location->swap);
133 assert(IN_SET(hibernate_location->swap->type, SWAP_BLOCK, SWAP_FILE));
134
135 return write_resume_config(hibernate_location->devno, hibernate_location->offset, hibernate_location->swap->path);
136 }
137
138 static int write_mode(char **modes) {
139 int r = 0;
140
141 STRV_FOREACH(mode, modes) {
142 int k;
143
144 k = write_string_file("/sys/power/disk", *mode, WRITE_STRING_FILE_DISABLE_BUFFER);
145 if (k >= 0)
146 return 0;
147
148 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m", *mode);
149 if (r >= 0)
150 r = k;
151 }
152
153 return r;
154 }
155
156 static int write_state(FILE **f, char **states) {
157 int r = 0;
158
159 assert(f);
160 assert(*f);
161
162 STRV_FOREACH(state, states) {
163 int k;
164
165 k = write_string_stream(*f, *state, WRITE_STRING_FILE_DISABLE_BUFFER);
166 if (k >= 0)
167 return 0;
168 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state);
169 if (r >= 0)
170 r = k;
171
172 fclose(*f);
173 *f = fopen("/sys/power/state", "we");
174 if (!*f)
175 return -errno;
176 }
177
178 return r;
179 }
180
181 /* Return true if wakeup type is APM timer */
182 static int check_wakeup_type(void) {
183 static const char dmi_object_path[] = "/sys/firmware/dmi/entries/1-0/raw";
184 uint8_t wakeup_type_byte, tablesize;
185 _cleanup_free_ char *buf = NULL;
186 size_t bufsize;
187 int r;
188
189 /* implementation via dmi/entries */
190 r = read_full_virtual_file(dmi_object_path, &buf, &bufsize);
191 if (r < 0)
192 return log_debug_errno(r, "Unable to read %s: %m", dmi_object_path);
193 if (bufsize < 25)
194 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
195 "Only read %zu bytes from %s (expected 25)",
196 bufsize, dmi_object_path);
197
198 /* index 1 stores the size of table */
199 tablesize = (uint8_t) buf[1];
200 if (tablesize < 25)
201 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
202 "Table size less than the index[0x18] where waketype byte is available.");
203
204 wakeup_type_byte = (uint8_t) buf[24];
205 /* 0 is Reserved and 8 is AC Power Restored. As per table 12 in
206 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf */
207 if (wakeup_type_byte >= 128)
208 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Expected value in range 0-127");
209
210 if (wakeup_type_byte == 3) {
211 log_debug("DMI BIOS System Information indicates wakeup type is APM Timer");
212 return true;
213 }
214
215 return false;
216 }
217
218 static int lock_all_homes(void) {
219 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
220 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
221 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
222 int r;
223
224 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
225 * way the key material required to access these volumes is hopefully removed from memory. */
226
227 r = sd_bus_open_system(&bus);
228 if (r < 0)
229 return log_warning_errno(r, "Failed to connect to system bus, ignoring: %m");
230
231 r = bus_message_new_method_call(bus, &m, bus_home_mgr, "LockAllHomes");
232 if (r < 0)
233 return bus_log_create_error(r);
234
235 /* If homed is not running it can't have any home directories active either. */
236 r = sd_bus_message_set_auto_start(m, false);
237 if (r < 0)
238 return log_error_errno(r, "Failed to disable auto-start of LockAllHomes() message: %m");
239
240 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC, &error, NULL);
241 if (r < 0) {
242 if (!bus_error_is_unknown_service(&error))
243 return log_error_errno(r, "Failed to lock home directories: %s", bus_error_message(&error, r));
244
245 log_debug("systemd-homed is not running, locking of home directories skipped.");
246 } else
247 log_debug("Successfully requested locking of all home directories.");
248 return 0;
249 }
250
251 static int execute(
252 const SleepConfig *sleep_config,
253 SleepOperation operation,
254 const char *action) {
255
256 char *arguments[] = {
257 NULL,
258 (char*) "pre",
259 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
260 * operation here, not the specific one, in case of s2h. */
261 (char*) sleep_operation_to_string(arg_operation),
262 NULL
263 };
264 static const char* const dirs[] = {
265 SYSTEM_SLEEP_PATH,
266 NULL
267 };
268
269 _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
270 _cleanup_fclose_ FILE *f = NULL;
271 char **modes, **states;
272 int r;
273
274 assert(sleep_config);
275 assert(operation >= 0);
276 assert(operation < _SLEEP_OPERATION_MAX);
277 assert(operation != SLEEP_SUSPEND_THEN_HIBERNATE); /* Handled by execute_s2h() instead */
278
279 states = sleep_config->states[operation];
280 modes = sleep_config->modes[operation];
281
282 if (strv_isempty(states))
283 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
284 "No sleep states configured for sleep operation %s, can't sleep.",
285 sleep_operation_to_string(operation));
286
287 /* This file is opened first, so that if we hit an error,
288 * we can abort before modifying any state. */
289 f = fopen("/sys/power/state", "we");
290 if (!f)
291 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
292
293 setvbuf(f, NULL, _IONBF, 0);
294
295 /* Configure hibernation settings if we are supposed to hibernate */
296 if (!strv_isempty(modes)) {
297 bool resume_set;
298
299 r = find_hibernate_location(&hibernate_location);
300 if (r < 0)
301 return log_error_errno(r, "Failed to find location to hibernate to: %m");
302 resume_set = r > 0;
303
304 r = write_efi_hibernate_location(hibernate_location, !resume_set);
305 if (!resume_set) {
306 if (r == -EOPNOTSUPP)
307 return log_error_errno(r, "No valid 'resume=' option found, refusing to hibernate.");
308 if (r < 0)
309 return r;
310
311 r = write_kernel_hibernate_location(hibernate_location);
312 if (r < 0) {
313 if (is_efi_boot())
314 (void) efi_set_variable(EFI_SYSTEMD_VARIABLE(HibernateLocation), NULL, 0);
315
316 return log_error_errno(r, "Failed to prepare for hibernation: %m");
317 }
318 }
319
320 r = write_mode(modes);
321 if (r < 0)
322 return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");
323 }
324
325 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
326 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
327 if (!action)
328 action = sleep_operation_to_string(operation);
329
330 r = setenv("SYSTEMD_SLEEP_ACTION", action, 1);
331 if (r != 0)
332 log_warning_errno(errno, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action);
333
334 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
335 (void) lock_all_homes();
336
337 log_struct(LOG_INFO,
338 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
339 LOG_MESSAGE("Entering sleep state '%s'...", sleep_operation_to_string(operation)),
340 "SLEEP=%s", sleep_operation_to_string(arg_operation));
341
342 r = write_state(&f, states);
343 if (r < 0)
344 log_struct_errno(LOG_ERR, r,
345 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
346 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
347 "SLEEP=%s", sleep_operation_to_string(arg_operation));
348 else
349 log_struct(LOG_INFO,
350 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
351 LOG_MESSAGE("System returned from sleep state."),
352 "SLEEP=%s", sleep_operation_to_string(arg_operation));
353
354 arguments[1] = (char*) "post";
355 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
356
357 return r;
358 }
359
360 static int custom_timer_suspend(const SleepConfig *sleep_config) {
361 usec_t hibernate_timestamp;
362 int r;
363
364 assert(sleep_config);
365
366 hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec);
367
368 while (battery_is_discharging_and_low() == 0) {
369 _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL;
370 _cleanup_close_ int tfd = -EBADF;
371 struct itimerspec ts = {};
372 usec_t suspend_interval;
373 bool woken_by_timer;
374
375 tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC);
376 if (tfd < 0)
377 return log_error_errno(errno, "Error creating timerfd: %m");
378
379 /* Store current battery capacity before suspension */
380 r = fetch_batteries_capacity_by_name(&last_capacity);
381 if (r < 0)
382 return log_error_errno(r, "Error fetching battery capacity percentage: %m");
383
384 if (hashmap_isempty(last_capacity))
385 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
386 suspend_interval = timestamp_is_set(hibernate_timestamp)
387 ? sleep_config->hibernate_delay_usec : DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY;
388 else {
389 r = get_total_suspend_interval(last_capacity, &suspend_interval);
390 if (r < 0) {
391 log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
392 /* In case of any errors, especially when we do not know the battery
393 * discharging rate, system suspend interval will be set to
394 * SuspendEstimationSec=. */
395 suspend_interval = sleep_config->suspend_estimation_usec;
396 }
397 }
398
399 /* Do not suspend more than HibernateDelaySec= */
400 usec_t before_timestamp = now(CLOCK_BOOTTIME);
401 suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp));
402 if (suspend_interval <= 0)
403 break; /* system should hibernate */
404
405 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC));
406 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
407 timespec_store(&ts.it_value, suspend_interval);
408
409 if (timerfd_settime(tfd, 0, &ts, NULL) < 0)
410 return log_error_errno(errno, "Error setting battery estimate timer: %m");
411
412 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
413 if (r < 0)
414 return r;
415
416 r = fd_wait_for_event(tfd, POLLIN, 0);
417 if (r < 0)
418 return log_error_errno(r, "Error polling timerfd: %m");
419 /* Store fd_wait status */
420 woken_by_timer = FLAGS_SET(r, POLLIN);
421
422 r = fetch_batteries_capacity_by_name(&current_capacity);
423 if (r < 0 || hashmap_isempty(current_capacity)) {
424 /* In case of no battery or error while getting charge level, no need to measure
425 * discharge rate. Instead the system should wake up if it is manual wakeup or
426 * hibernate if this is a timer wakeup. */
427 if (r < 0)
428 log_debug_errno(r, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
429 else
430 log_debug("No battery found.");
431 if (!woken_by_timer)
432 return 0;
433 break;
434 }
435
436 usec_t after_timestamp = now(CLOCK_BOOTTIME);
437 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
438 FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_HOUR));
439
440 if (after_timestamp != before_timestamp) {
441 r = estimate_battery_discharge_rate_per_hour(last_capacity, current_capacity, before_timestamp, after_timestamp);
442 if (r < 0)
443 log_warning_errno(r, "Failed to estimate and update battery discharge rate, ignoring: %m");
444 } else
445 log_debug("System woke up too early to estimate discharge rate");
446
447 if (!woken_by_timer)
448 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
449 return 0;
450
451 r = check_wakeup_type();
452 if (r < 0)
453 log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
454 if (r > 0) {
455 log_debug("wakeup type is APM timer");
456 /* system should hibernate */
457 break;
458 }
459 }
460
461 return 1;
462 }
463
464 /* Freeze when invoked and thaw on cleanup */
465 static int freeze_thaw_user_slice(const char **method) {
466 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
467 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
468 int r;
469
470 if (!method || !*method)
471 return 0;
472
473 r = bus_connect_system_systemd(&bus);
474 if (r < 0)
475 return log_debug_errno(r, "Failed to open connection to systemd: %m");
476
477 (void) sd_bus_set_method_call_timeout(bus, FREEZE_TIMEOUT);
478
479 r = bus_call_method(bus, bus_systemd_mgr, *method, &error, NULL, "s", SPECIAL_USER_SLICE);
480 if (r < 0)
481 return log_debug_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
482
483 return 1;
484 }
485
486 static int execute_s2h(const SleepConfig *sleep_config) {
487 _unused_ _cleanup_(freeze_thaw_user_slice) const char *auto_method_thaw = "ThawUnit";
488 int r;
489
490 assert(sleep_config);
491
492 r = freeze_thaw_user_slice(&(const char*) { "FreezeUnit" });
493 if (r < 0)
494 log_debug_errno(r, "Failed to freeze unit user.slice, ignoring: %m");
495
496 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
497 * we'll busy poll for the configured interval instead */
498 if (!timestamp_is_set(sleep_config->hibernate_delay_usec)) {
499 r = check_wakeup_type();
500 if (r < 0)
501 log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
502 else {
503 r = battery_trip_point_alarm_exists();
504 if (r < 0)
505 log_debug_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
506 }
507 } else
508 r = 0; /* Force fallback path */
509
510 if (r > 0) { /* If we have both wakeup alarms and battery trip point support, use them */
511 log_debug("Attempting to suspend...");
512 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
513 if (r < 0)
514 return r;
515
516 r = check_wakeup_type();
517 if (r < 0)
518 return log_debug_errno(r, "Failed to check hardware wakeup type: %m");
519
520 if (r == 0)
521 /* For APM Timer wakeup, system should hibernate else wakeup */
522 return 0;
523 } else {
524 r = custom_timer_suspend(sleep_config);
525 if (r < 0)
526 return log_debug_errno(r, "Suspend cycle with manual battery discharge rate estimation failed: %m");
527 if (r == 0)
528 /* manual wakeup */
529 return 0;
530 }
531 /* For above custom timer, if 1 is returned, system will directly hibernate */
532
533 log_debug("Attempting to hibernate");
534 r = execute(sleep_config, SLEEP_HIBERNATE, NULL);
535 if (r < 0) {
536 log_notice("Couldn't hibernate, will try to suspend again.");
537
538 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hibernate");
539 if (r < 0)
540 return r;
541 }
542
543 return 0;
544 }
545
546 static int help(void) {
547 _cleanup_free_ char *link = NULL;
548 int r;
549
550 r = terminal_urlify_man("systemd-suspend.service", "8", &link);
551 if (r < 0)
552 return log_oom();
553
554 printf("%s COMMAND\n\n"
555 "Suspend the system, hibernate the system, or both.\n\n"
556 " -h --help Show this help and exit\n"
557 " --version Print version string and exit\n"
558 "\nCommands:\n"
559 " suspend Suspend the system\n"
560 " hibernate Hibernate the system\n"
561 " hybrid-sleep Both hibernate and suspend the system\n"
562 " suspend-then-hibernate Initially suspend and then hibernate\n"
563 " the system after a fixed period of time\n"
564 "\nSee the %s for details.\n",
565 program_invocation_short_name,
566 link);
567
568 return 0;
569 }
570
571 static int parse_argv(int argc, char *argv[]) {
572 enum {
573 ARG_VERSION = 0x100,
574 };
575
576 static const struct option options[] = {
577 { "help", no_argument, NULL, 'h' },
578 { "version", no_argument, NULL, ARG_VERSION },
579 {}
580 };
581
582 int c;
583
584 assert(argc >= 0);
585 assert(argv);
586
587 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
588 switch (c) {
589 case 'h':
590 return help();
591
592 case ARG_VERSION:
593 return version();
594
595 case '?':
596 return -EINVAL;
597
598 default:
599 assert_not_reached();
600 }
601
602 if (argc - optind != 1)
603 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
604 "Usage: %s COMMAND",
605 program_invocation_short_name);
606
607 arg_operation = sleep_operation_from_string(argv[optind]);
608 if (arg_operation < 0)
609 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'.", argv[optind]);
610
611 return 1 /* work to do */;
612 }
613
614 static int run(int argc, char *argv[]) {
615 _cleanup_(sleep_config_freep) SleepConfig *sleep_config = NULL;
616 int r;
617
618 log_setup();
619
620 r = parse_argv(argc, argv);
621 if (r <= 0)
622 return r;
623
624 r = parse_sleep_config(&sleep_config);
625 if (r < 0)
626 return r;
627
628 if (!sleep_config->allow[arg_operation])
629 return log_error_errno(SYNTHETIC_ERRNO(EACCES),
630 "Sleep operation \"%s\" is disabled by configuration, refusing.",
631 sleep_operation_to_string(arg_operation));
632
633 switch (arg_operation) {
634
635 case SLEEP_SUSPEND_THEN_HIBERNATE:
636 r = execute_s2h(sleep_config);
637 break;
638
639 case SLEEP_HYBRID_SLEEP:
640 r = execute(sleep_config, SLEEP_HYBRID_SLEEP, NULL);
641 if (r < 0) {
642 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
643 * asked us to do both: suspend + hibernate, and it's almost certainly the
644 * hibernation that failed, hence still do the other thing, the suspend. */
645
646 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
647
648 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep");
649 }
650
651 break;
652
653 default:
654 r = execute(sleep_config, arg_operation, NULL);
655 break;
656 }
657
658 return r;
659 }
660
661 DEFINE_MAIN_FUNCTION(run);