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