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