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