]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/sleep/sleep.c
man: fix references to gethostname/sethostname
[thirdparty/systemd.git] / src / sleep / sleep.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
6edd7d0a 2/***
96b2fb93
LP
3 Copyright © 2010-2017 Canonical
4 Copyright © 2018 Dell Inc.
6edd7d0a
LP
5***/
6
6edd7d0a 7#include <errno.h>
ca78ad1d 8#include <fcntl.h>
19adb8a3 9#include <getopt.h>
17c40b3a 10#include <linux/fiemap.h>
1bbbefe7 11#include <poll.h>
ca78ad1d
ZJS
12#include <sys/stat.h>
13#include <sys/types.h>
1bbbefe7 14#include <sys/timerfd.h>
ca78ad1d 15#include <unistd.h>
6edd7d0a 16
f13f91f0 17#include "sd-bus.h"
aa62a893 18#include "sd-messages.h"
3f6fd1ba 19
319c4648 20#include "battery-util.h"
64602c84 21#include "btrfs-util.h"
d6b4d1c7 22#include "build.h"
ba0fb5ac 23#include "bus-error.h"
f13f91f0
SS
24#include "bus-locator.h"
25#include "bus-util.h"
28db6fbf 26#include "constants.h"
4560d99e 27#include "devnum-util.h"
89711996 28#include "exec-util.h"
3ffd4af2 29#include "fd-util.h"
a5c32cff 30#include "fileio.h"
ba0fb5ac 31#include "format-util.h"
0f2d351f 32#include "io-util.h"
3f6fd1ba 33#include "log.h"
5e332028 34#include "main-func.h"
ed698d30 35#include "parse-util.h"
294bf0c3 36#include "pretty-print.h"
4014172a 37#include "sleep-util.h"
f13f91f0 38#include "special.h"
c58493c0 39#include "stdio-util.h"
07630cea 40#include "string-util.h"
3f6fd1ba 41#include "strv.h"
1bbbefe7 42#include "time-util.h"
19adb8a3 43
f05b4bb9
MY
44#define DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY (2 * USEC_PER_HOUR)
45
c8cd8ca3 46static SleepOperation arg_operation = _SLEEP_OPERATION_INVALID;
98dc9d1f 47
7bdf56a2 48static int write_hibernate_location_info(const HibernateLocation *hibernate_location) {
17c40b3a 49 char offset_str[DECIMAL_STR_MAX(uint64_t)];
4560d99e 50 const char *resume_str;
17c40b3a
ML
51 int r;
52
7bdf56a2
ZS
53 assert(hibernate_location);
54 assert(hibernate_location->swap);
7bdf56a2 55
4560d99e
LP
56 resume_str = FORMAT_DEVNUM(hibernate_location->devno);
57
52133271 58 r = write_string_file("/sys/power/resume", resume_str, WRITE_STRING_FILE_DISABLE_BUFFER);
17c40b3a 59 if (r < 0)
7bdf56a2 60 return log_debug_errno(r, "Failed to write partition device to /sys/power/resume for '%s': '%s': %m",
8601ecbc 61 hibernate_location->swap->path, resume_str);
17c40b3a 62
8601ecbc 63 log_debug("Wrote resume= value for %s to /sys/power/resume: %s", hibernate_location->swap->path, resume_str);
ed698d30 64
7bdf56a2 65 /* if it's a swap partition, we're done */
1296b427
LP
66 if (hibernate_location->swap->type == SWAP_BLOCK)
67 return 0;
7bdf56a2 68
1296b427 69 assert(hibernate_location->swap->type == SWAP_FILE);
17c40b3a
ML
70
71 /* Only available in 4.17+ */
52133271 72 if (hibernate_location->offset > 0 && access("/sys/power/resume_offset", W_OK) < 0) {
c695101f 73 if (errno == ENOENT) {
7bdf56a2 74 log_debug("Kernel too old, can't configure resume_offset for %s, ignoring: %" PRIu64,
8601ecbc 75 hibernate_location->swap->path, hibernate_location->offset);
17c40b3a 76 return 0;
c695101f 77 }
ed698d30 78
3f2e15ab 79 return log_debug_errno(errno, "/sys/power/resume_offset not writable: %m");
c695101f 80 }
17c40b3a 81
52133271 82 xsprintf(offset_str, "%" PRIu64, hibernate_location->offset);
57512c89 83 r = write_string_file("/sys/power/resume_offset", offset_str, WRITE_STRING_FILE_DISABLE_BUFFER);
17c40b3a 84 if (r < 0)
7bdf56a2 85 return log_debug_errno(r, "Failed to write swap file offset to /sys/power/resume_offset for '%s': '%s': %m",
8601ecbc 86 hibernate_location->swap->path, offset_str);
17c40b3a 87
8601ecbc 88 log_debug("Wrote resume_offset= value for %s to /sys/power/resume_offset: %s", hibernate_location->swap->path, offset_str);
2002d8cd 89
17c40b3a
ML
90 return 0;
91}
92
19adb8a3
ZJS
93static int write_mode(char **modes) {
94 int r = 0;
19adb8a3
ZJS
95
96 STRV_FOREACH(mode, modes) {
aa62a893
LP
97 int k;
98
57512c89 99 k = write_string_file("/sys/power/disk", *mode, WRITE_STRING_FILE_DISABLE_BUFFER);
ed698d30 100 if (k >= 0)
19adb8a3 101 return 0;
aa62a893 102
ed698d30
LP
103 log_debug_errno(k, "Failed to write '%s' to /sys/power/disk: %m", *mode);
104 if (r >= 0)
19adb8a3
ZJS
105 r = k;
106 }
6edd7d0a 107
19adb8a3
ZJS
108 return r;
109}
6edd7d0a 110
2fd069b1 111static int write_state(FILE **f, char **states) {
19adb8a3
ZJS
112 int r = 0;
113
2c470205
LP
114 assert(f);
115 assert(*f);
116
19adb8a3
ZJS
117 STRV_FOREACH(state, states) {
118 int k;
119
57512c89 120 k = write_string_stream(*f, *state, WRITE_STRING_FILE_DISABLE_BUFFER);
ed698d30 121 if (k >= 0)
19adb8a3 122 return 0;
ed698d30
LP
123 log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m", *state);
124 if (r >= 0)
19adb8a3
ZJS
125 r = k;
126
2fd069b1
ZJS
127 fclose(*f);
128 *f = fopen("/sys/power/state", "we");
4a62c710 129 if (!*f)
0ca906ac 130 return -errno;
6edd7d0a
LP
131 }
132
19adb8a3
ZJS
133 return r;
134}
6edd7d0a 135
ba0fb5ac
LP
136static int lock_all_homes(void) {
137 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
138 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
139 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
140 int r;
141
142 /* Let's synchronously lock all home directories managed by homed that have been marked for it. This
143 * way the key material required to access these volumes is hopefully removed from memory. */
144
145 r = sd_bus_open_system(&bus);
146 if (r < 0)
147 return log_warning_errno(r, "Failed to connect to system bus, ignoring: %m");
148
a29f13f2 149 r = bus_message_new_method_call(bus, &m, bus_home_mgr, "LockAllHomes");
ba0fb5ac
LP
150 if (r < 0)
151 return bus_log_create_error(r);
152
153 /* If homed is not running it can't have any home directories active either. */
154 r = sd_bus_message_set_auto_start(m, false);
155 if (r < 0)
156 return log_error_errno(r, "Failed to disable auto-start of LockAllHomes() message: %m");
157
158 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC, &error, NULL);
159 if (r < 0) {
1c5950bd
ZJS
160 if (!bus_error_is_unknown_service(&error))
161 return log_error_errno(r, "Failed to lock home directories: %s", bus_error_message(&error, r));
ba0fb5ac 162
75029e15
ZJS
163 log_debug("systemd-homed is not running, locking of home directories skipped.");
164 } else
165 log_debug("Successfully requested locking of all home directories.");
166 return 0;
ba0fb5ac
LP
167}
168
c8cd8ca3
LP
169static int execute(
170 const SleepConfig *sleep_config,
171 SleepOperation operation,
172 const char *action) {
173
e2cc6eca
LP
174 char *arguments[] = {
175 NULL,
176 (char*) "pre",
c8cd8ca3
LP
177 /* NB: we use 'arg_operation' instead of 'operation' here, as we want to communicate the overall
178 * operation here, not the specific one, in case of s2h. */
179 (char*) sleep_operation_to_string(arg_operation),
e2cc6eca
LP
180 NULL
181 };
b5084605
LP
182 static const char* const dirs[] = {
183 SYSTEM_SLEEP_PATH,
184 NULL
185 };
e2cc6eca 186
7bdf56a2 187 _cleanup_(hibernate_location_freep) HibernateLocation *hibernate_location = NULL;
c8cd8ca3
LP
188 _cleanup_fclose_ FILE *f = NULL;
189 char **modes, **states;
7bdf56a2 190 int r;
6524990f 191
c8cd8ca3
LP
192 assert(sleep_config);
193 assert(operation >= 0);
194 assert(operation < _SLEEP_OPERATION_MAX);
195 assert(operation != SLEEP_SUSPEND_THEN_HIBERNATE); /* Handled by execute_s2h() instead */
196
197 states = sleep_config->states[operation];
198 modes = sleep_config->modes[operation];
199
200 if (strv_isempty(states))
201 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
202 "No sleep states configured for sleep operation %s, can't sleep.",
203 sleep_operation_to_string(operation));
204
19adb8a3 205 /* This file is opened first, so that if we hit an error,
09692409 206 * we can abort before modifying any state. */
6edd7d0a 207 f = fopen("/sys/power/state", "we");
4a62c710
MS
208 if (!f)
209 return log_error_errno(errno, "Failed to open /sys/power/state: %m");
6edd7d0a 210
57512c89
YW
211 setvbuf(f, NULL, _IONBF, 0);
212
c02540dc 213 /* Configure hibernation settings if we are supposed to hibernate */
17c40b3a 214 if (!strv_isempty(modes)) {
7bdf56a2 215 r = find_hibernate_location(&hibernate_location);
17c40b3a 216 if (r < 0)
c02540dc
LP
217 return log_error_errno(r, "Failed to find location to hibernate to: %m");
218 if (r == 0) { /* 0 means: no hibernation location was configured in the kernel so far, let's
219 * do it ourselves then. > 0 means: kernel already had a configured hibernation
220 * location which we shouldn't touch. */
7bdf56a2
ZS
221 r = write_hibernate_location_info(hibernate_location);
222 if (r < 0)
223 return log_error_errno(r, "Failed to prepare for hibernation: %m");
224 }
2002d8cd 225
17c40b3a
ML
226 r = write_mode(modes);
227 if (r < 0)
aea29a30 228 return log_error_errno(r, "Failed to write mode to /sys/power/disk: %m");
17c40b3a 229 }
19adb8a3 230
c8cd8ca3
LP
231 /* Pass an action string to the call-outs. This is mostly our operation string, except if the
232 * hibernate step of s-t-h fails, in which case we communicate that with a separate action. */
233 if (!action)
234 action = sleep_operation_to_string(operation);
235
ae463e4e
ZS
236 r = setenv("SYSTEMD_SLEEP_ACTION", action, 1);
237 if (r != 0)
c3565fe8 238 log_warning_errno(errno, "Error setting SYSTEMD_SLEEP_ACTION=%s, ignoring: %m", action);
ae463e4e 239
aed98342 240 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
ba0fb5ac 241 (void) lock_all_homes();
6edd7d0a 242
19adb8a3 243 log_struct(LOG_INFO,
2b044526 244 "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
c8cd8ca3
LP
245 LOG_MESSAGE("Entering sleep state '%s'...", sleep_operation_to_string(operation)),
246 "SLEEP=%s", sleep_operation_to_string(arg_operation));
19adb8a3 247
2fd069b1 248 r = write_state(&f, states);
19adb8a3 249 if (r < 0)
14250f09
LP
250 log_struct_errno(LOG_ERR, r,
251 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
c8cd8ca3
LP
252 LOG_MESSAGE("Failed to put system to sleep. System resumed again: %m"),
253 "SLEEP=%s", sleep_operation_to_string(arg_operation));
14250f09
LP
254 else
255 log_struct(LOG_INFO,
256 "MESSAGE_ID=" SD_MESSAGE_SLEEP_STOP_STR,
c8cd8ca3
LP
257 LOG_MESSAGE("System returned from sleep state."),
258 "SLEEP=%s", sleep_operation_to_string(arg_operation));
eb267289 259
6edd7d0a 260 arguments[1] = (char*) "post";
aed98342 261 (void) execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
6edd7d0a 262
19adb8a3
ZJS
263 return r;
264}
6edd7d0a 265
1afe3d71 266static int custom_timer_suspend(const SleepConfig *sleep_config) {
4f58b656 267 usec_t hibernate_timestamp;
c58493c0
ML
268 int r;
269
28ca9c24 270 assert(sleep_config);
c58493c0 271
4f58b656
YW
272 hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec);
273
e0b3a70f 274 while (battery_is_discharging_and_low() == 0) {
de5d8b40 275 _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL;
254d1313 276 _cleanup_close_ int tfd = -EBADF;
96d662fa 277 struct itimerspec ts = {};
2ed56afe 278 usec_t suspend_interval;
96d662fa 279 bool woken_by_timer;
96d662fa
SS
280
281 tfd = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_NONBLOCK|TFD_CLOEXEC);
282 if (tfd < 0)
283 return log_error_errno(errno, "Error creating timerfd: %m");
284
d812e104 285 /* Store current battery capacity before suspension */
746cf898 286 r = fetch_batteries_capacity_by_name(&last_capacity);
d812e104 287 if (r < 0)
96d662fa
SS
288 return log_error_errno(r, "Error fetching battery capacity percentage: %m");
289
4f58b656
YW
290 if (hashmap_isempty(last_capacity))
291 /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
f05b4bb9
MY
292 suspend_interval = timestamp_is_set(hibernate_timestamp)
293 ? sleep_config->hibernate_delay_usec : DEFAULT_HIBERNATE_DELAY_USEC_NO_BATTERY;
4f58b656
YW
294 else {
295 r = get_total_suspend_interval(last_capacity, &suspend_interval);
296 if (r < 0) {
297 log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
298 /* In case of any errors, especially when we do not know the battery
299 * discharging rate, system suspend interval will be set to
300 * SuspendEstimationSec=. */
301 suspend_interval = sleep_config->suspend_estimation_usec;
302 }
2ed56afe 303 }
746cf898 304
4f58b656 305 /* Do not suspend more than HibernateDelaySec= */
d812e104 306 usec_t before_timestamp = now(CLOCK_BOOTTIME);
4f58b656
YW
307 suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp));
308 if (suspend_interval <= 0)
309 break; /* system should hibernate */
d812e104 310
96d662fa
SS
311 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC));
312 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
313 timespec_store(&ts.it_value, suspend_interval);
314
315 if (timerfd_settime(tfd, 0, &ts, NULL) < 0)
316 return log_error_errno(errno, "Error setting battery estimate timer: %m");
317
318 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
319 if (r < 0)
320 return r;
c58493c0 321
96d662fa
SS
322 r = fd_wait_for_event(tfd, POLLIN, 0);
323 if (r < 0)
324 return log_error_errno(r, "Error polling timerfd: %m");
325 /* Store fd_wait status */
326 woken_by_timer = FLAGS_SET(r, POLLIN);
327
746cf898 328 r = fetch_batteries_capacity_by_name(&current_capacity);
d812e104 329 if (r < 0 || hashmap_isempty(current_capacity)) {
746cf898 330 /* In case of no battery or error while getting charge level, no need to measure
d812e104
YW
331 * discharge rate. Instead the system should wake up if it is manual wakeup or
332 * hibernate if this is a timer wakeup. */
333 if (r < 0)
334 log_debug_errno(r, "Battery capacity percentage unavailable, cannot estimate discharge rate: %m");
335 else
336 log_debug("No battery found.");
746cf898
SS
337 if (!woken_by_timer)
338 return 0;
96d662fa 339 break;
746cf898 340 }
96d662fa 341
d812e104 342 usec_t after_timestamp = now(CLOCK_BOOTTIME);
099810a6
ZJS
343 log_debug("Attempting to estimate battery discharge rate after wakeup from %s sleep",
344 FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_HOUR));
96d662fa 345
746cf898
SS
346 if (after_timestamp != before_timestamp) {
347 r = estimate_battery_discharge_rate_per_hour(last_capacity, current_capacity, before_timestamp, after_timestamp);
91ea7ebc 348 if (r < 0)
746cf898
SS
349 log_warning_errno(r, "Failed to estimate and update battery discharge rate, ignoring: %m");
350 } else
351 log_debug("System woke up too early to estimate discharge rate");
c58493c0 352
96d662fa
SS
353 if (!woken_by_timer)
354 /* Return as manual wakeup done. This also will return in case battery was charged during suspension */
355 return 0;
1afe3d71
SS
356
357 r = check_wakeup_type();
358 if (r < 0)
359 log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
360 if (r > 0) {
361 log_debug("wakeup type is APM timer");
362 /* system should hibernate */
363 break;
364 }
365 }
366
367 return 1;
368}
369
f13f91f0
SS
370/* Freeze when invoked and thaw on cleanup */
371static int freeze_thaw_user_slice(const char **method) {
372 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
373 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
374 int r;
375
376 if (!method || !*method)
377 return 0;
378
379 r = bus_connect_system_systemd(&bus);
380 if (r < 0)
381 return log_debug_errno(r, "Failed to open connection to systemd: %m");
382
f274f8bf 383 (void) sd_bus_set_method_call_timeout(bus, FREEZE_TIMEOUT);
432a3211 384
f13f91f0
SS
385 r = bus_call_method(bus, bus_systemd_mgr, *method, &error, NULL, "s", SPECIAL_USER_SLICE);
386 if (r < 0)
387 return log_debug_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
388
389 return 1;
390}
391
1afe3d71 392static int execute_s2h(const SleepConfig *sleep_config) {
efa736d3 393 _unused_ _cleanup_(freeze_thaw_user_slice) const char *auto_method_thaw = "ThawUnit";
4f58b656 394 int r;
1afe3d71
SS
395
396 assert(sleep_config);
397
f13f91f0
SS
398 r = freeze_thaw_user_slice(&(const char*) { "FreezeUnit" });
399 if (r < 0)
400 log_debug_errno(r, "Failed to freeze unit user.slice, ignoring: %m");
f13f91f0 401
4f58b656
YW
402 /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
403 * we'll busy poll for the configured interval instead */
404 if (!timestamp_is_set(sleep_config->hibernate_delay_usec)) {
405 r = check_wakeup_type();
406 if (r < 0)
407 log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
408 else {
409 r = battery_trip_point_alarm_exists();
410 if (r < 0)
411 log_debug_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
412 }
413 } else
414 r = 0; /* Force fallback path */
1afe3d71 415
4f58b656 416 if (r > 0) { /* If we have both wakeup alarms and battery trip point support, use them */
1afe3d71
SS
417 log_debug("Attempting to suspend...");
418 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
419 if (r < 0)
420 return r;
421
422 r = check_wakeup_type();
423 if (r < 0)
424 return log_debug_errno(r, "Failed to check hardware wakeup type: %m");
425
426 if (r == 0)
427 /* For APM Timer wakeup, system should hibernate else wakeup */
428 return 0;
429 } else {
430 r = custom_timer_suspend(sleep_config);
3c3f4601 431 if (r < 0)
1afe3d71 432 return log_debug_errno(r, "Suspend cycle with manual battery discharge rate estimation failed: %m");
3c3f4601 433 if (r == 0)
1afe3d71
SS
434 /* manual wakeup */
435 return 0;
96d662fa 436 }
1afe3d71 437 /* For above custom timer, if 1 is returned, system will directly hibernate */
28ca9c24 438
96d662fa 439 log_debug("Attempting to hibernate");
c8cd8ca3 440 r = execute(sleep_config, SLEEP_HIBERNATE, NULL);
f05e1ae6 441 if (r < 0) {
b0c035e3 442 log_notice("Couldn't hibernate, will try to suspend again.");
0f2d351f 443
c8cd8ca3 444 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hibernate");
0f2d351f 445 if (r < 0)
b0c035e3 446 return r;
f05e1ae6
LP
447 }
448
449 return 0;
c58493c0
ML
450}
451
37ec0fdd
LP
452static int help(void) {
453 _cleanup_free_ char *link = NULL;
454 int r;
455
456 r = terminal_urlify_man("systemd-suspend.service", "8", &link);
457 if (r < 0)
458 return log_oom();
459
19adb8a3
ZJS
460 printf("%s COMMAND\n\n"
461 "Suspend the system, hibernate the system, or both.\n\n"
37ec0fdd
LP
462 " -h --help Show this help and exit\n"
463 " --version Print version string and exit\n"
464 "\nCommands:\n"
465 " suspend Suspend the system\n"
466 " hibernate Hibernate the system\n"
467 " hybrid-sleep Both hibernate and suspend the system\n"
e68c79db 468 " suspend-then-hibernate Initially suspend and then hibernate\n"
37ec0fdd 469 " the system after a fixed period of time\n"
bc556335
DDM
470 "\nSee the %s for details.\n",
471 program_invocation_short_name,
472 link);
37ec0fdd
LP
473
474 return 0;
19adb8a3 475}
6edd7d0a 476
19adb8a3
ZJS
477static int parse_argv(int argc, char *argv[]) {
478 enum {
479 ARG_VERSION = 0x100,
480 };
481
482 static const struct option options[] = {
483 { "help", no_argument, NULL, 'h' },
484 { "version", no_argument, NULL, ARG_VERSION },
eb9da376 485 {}
19adb8a3
ZJS
486 };
487
488 int c;
489
490 assert(argc >= 0);
491 assert(argv);
492
601185b4 493 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
79893116 494 switch (c) {
19adb8a3 495 case 'h':
37ec0fdd 496 return help();
19adb8a3
ZJS
497
498 case ARG_VERSION:
3f6fd1ba 499 return version();
19adb8a3
ZJS
500
501 case '?':
502 return -EINVAL;
503
504 default:
04499a70 505 assert_not_reached();
19adb8a3
ZJS
506 }
507
baaa35ad
ZJS
508 if (argc - optind != 1)
509 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
510 "Usage: %s COMMAND",
511 program_invocation_short_name);
19adb8a3 512
c8cd8ca3
LP
513 arg_operation = sleep_operation_from_string(argv[optind]);
514 if (arg_operation < 0)
515 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'.", argv[optind]);
19adb8a3
ZJS
516
517 return 1 /* work to do */;
518}
519
7caefb81 520static int run(int argc, char *argv[]) {
28ca9c24 521 _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL;
19adb8a3
ZJS
522 int r;
523
d2acb93d 524 log_setup();
19adb8a3
ZJS
525
526 r = parse_argv(argc, argv);
527 if (r <= 0)
7caefb81 528 return r;
19adb8a3 529
28ca9c24
ZS
530 r = parse_sleep_config(&sleep_config);
531 if (r < 0)
532 return r;
533
c8cd8ca3 534 if (!sleep_config->allow[arg_operation])
baaa35ad 535 return log_error_errno(SYNTHETIC_ERRNO(EACCES),
c8cd8ca3
LP
536 "Sleep operation \"%s\" is disabled by configuration, refusing.",
537 sleep_operation_to_string(arg_operation));
e8f1d00d 538
3d132111
LP
539 switch (arg_operation) {
540
541 case SLEEP_SUSPEND_THEN_HIBERNATE:
542 r = execute_s2h(sleep_config);
543 break;
544
545 case SLEEP_HYBRID_SLEEP:
546 r = execute(sleep_config, SLEEP_HYBRID_SLEEP, NULL);
547 if (r < 0) {
548 /* If we can't hybrid sleep, then let's try to suspend at least. After all, the user
549 * asked us to do both: suspend + hibernate, and it's almost certainly the
550 * hibernation that failed, hence still do the other thing, the suspend. */
551
552 log_notice("Couldn't hybrid sleep, will try to suspend instead.");
553
554 r = execute(sleep_config, SLEEP_SUSPEND, "suspend-after-failed-hybrid-sleep");
555 }
556
557 break;
558
559 default:
560 r = execute(sleep_config, arg_operation, NULL);
561 break;
562 }
563
564 return r;
6edd7d0a 565}
7caefb81
ZJS
566
567DEFINE_MAIN_FUNCTION(run);