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