ac3a84
From db8a187c67e4829e39fe28e25003816b64db80db Mon Sep 17 00:00:00 2001
ac3a84
From: Yu Watanabe <watanabe.yu+github@gmail.com>
ac3a84
Date: Mon, 14 Nov 2022 02:08:05 +0900
ac3a84
Subject: [PATCH] sleep: introduce SuspendEstimationSec=
ac3a84
ac3a84
Before v252, HibernateDelaySec= specifies the maximum timespan that the
ac3a84
system in suspend state, and the system hibernate after the timespan.
ac3a84
ac3a84
However, after 96d662fa4c8cab24da57523c5e49e6ef3967fc13, the setting is
ac3a84
repurposed as the default interval to measure battery charge level and
ac3a84
estimate the battery discharging late. And if the system has enough
ac3a84
battery capacity, then the system will stay in suspend state and not
ac3a84
hibernate even if the time passed. See issue #25269.
ac3a84
ac3a84
To keep the backward compatibility, let's introduce another setting
ac3a84
SuspendEstimationSec= for controlling the interval to measure
ac3a84
battery charge level, and make HibernateDelaySec= work as of v251.
ac3a84
ac3a84
This also drops implementation details from the man page.
ac3a84
ac3a84
Fixes #25269.
ac3a84
ac3a84
(cherry picked from commit 4f58b656d92b09a953b7cffcfd1ee6d5136a57ed)
ac3a84
ac3a84
Resolves: #2151612
ac3a84
---
ac3a84
 man/systemd-sleep.conf.xml | 58 ++++++++++++++++++++------------------
ac3a84
 src/shared/sleep-config.c  | 11 ++++++--
ac3a84
 src/shared/sleep-config.h  |  3 ++
ac3a84
 src/sleep/sleep.c          | 48 ++++++++++++++++++++++---------
ac3a84
 src/sleep/sleep.conf       |  3 +-
ac3a84
 5 files changed, 77 insertions(+), 46 deletions(-)
ac3a84
ac3a84
diff --git a/man/systemd-sleep.conf.xml b/man/systemd-sleep.conf.xml
ac3a84
index be04f2cdf1..79ebef1fef 100644
ac3a84
--- a/man/systemd-sleep.conf.xml
ac3a84
+++ b/man/systemd-sleep.conf.xml
ac3a84
@@ -77,29 +77,16 @@
ac3a84
       <varlistentry>
ac3a84
         <term>suspend-then-hibernate</term>
ac3a84
 
ac3a84
-        <listitem><para>A low power state where initially user.slice unit is freezed.
ac3a84
-        If the hardware supports low-battery alarms (ACPI _BTP), then the system is
ac3a84
-        first suspended (the state is stored in RAM) and then hibernates if the system
ac3a84
-        is woken up by the hardware via ACPI low-battery signal. Unit user.slice is
ac3a84
-        thawed when system returns from hibernation. If the hardware does not support
ac3a84
-        low-battery alarms (ACPI _BTP), then the system is suspended based on battery's
ac3a84
-        current percentage capacity. If the current battery capacity is higher than 5%, the
ac3a84
-        system suspends for interval calculated using battery discharge rate per hour or
ac3a84
-        <command>HibernateDelaySec=</command>
ac3a84
-        if former is not available.
ac3a84
-        Battery discharge rate per hour is stored in a file which is created after
ac3a84
-        initial suspend-resume cycle. The value is calculated using battery decreasing
ac3a84
-        charge level over a timespan for which system was suspended. For each battery
ac3a84
-        connected to the system, there is a unique entry. After RTC alarm wakeup from
ac3a84
-        suspend, battery discharge rate per hour is again estimated. If the current battery
ac3a84
-        charge level is equal to or less than 5%, the system will be hibernated (the state
ac3a84
-        is then stored on disk) else the system goes back to suspend for the interval
ac3a84
-        calculated using battery discharge rate per hour.
ac3a84
-        In case of manual wakeup, if the battery was discharged while the system was
ac3a84
-        suspended, the battery discharge rate is estimated and stored on the filesystem.
ac3a84
-        In case the system is woken up by the hardware via the ACPI low-battery signal,
ac3a84
-        then it hibernates.
ac3a84
-        </para></listitem>
ac3a84
+        <listitem>
ac3a84
+          <para>A low power state where the system is initially suspended (the state is stored in
ac3a84
+          RAM). If the system supports low-battery alarms (ACPI _BTP), then the system will be woken up by
ac3a84
+          the ACPI low-battery signal and hibernated (the state is then stored on disk). Also, if not
ac3a84
+          interrupted within the timespan specified by <varname>HibernateDelaySec=</varname> or the estimated
ac3a84
+          timespan until the system battery charge level goes down to 5%, then the system will be woken up by the
ac3a84
+          RTC alarm and hibernated. The estimated timespan is calculated from the change of the battery
ac3a84
+          capacity level after the time specified by <varname>SuspendEstimationSec=</varname> or when
ac3a84
+          the system is woken up from the suspend.</para>
ac3a84
+        </listitem>
ac3a84
       </varlistentry>
ac3a84
 
ac3a84
     </variablelist>
ac3a84
@@ -189,13 +176,28 @@
ac3a84
         uses the value of <varname>SuspendState=</varname> when suspending and the value of <varname>HibernateState=</varname> when hibernating.
ac3a84
         </para></listitem>
ac3a84
       </varlistentry>
ac3a84
+
ac3a84
       <varlistentry>
ac3a84
         <term><varname>HibernateDelaySec=</varname></term>
ac3a84
-        <listitem><para>The amount of time the system spends in suspend mode
ac3a84
-        before the RTC alarm wakes the system, before the battery discharge rate
ac3a84
-        can be estimated and used instead to calculate the suspension interval.
ac3a84
-        <citerefentry><refentrytitle>systemd-suspend-then-hibernate.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>. Defaults
ac3a84
-        to 2h.</para></listitem>
ac3a84
+
ac3a84
+        <listitem>
ac3a84
+          <para>The amount of time the system spends in suspend mode before the system is
ac3a84
+          automatically put into hibernate mode. Only used by
ac3a84
+          <citerefentry><refentrytitle>systemd-suspend-then-hibernate.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>.
ac3a84
+          If the system has a battery, then defaults to the estimated timespan until the system battery charge level goes down to 5%.
ac3a84
+          If the system has no battery, then defaults to 2h.</para>
ac3a84
+        </listitem>
ac3a84
+      </varlistentry>
ac3a84
+
ac3a84
+      <varlistentry>
ac3a84
+        <term><varname>SuspendEstimationSec=</varname></term>
ac3a84
+
ac3a84
+        <listitem>
ac3a84
+          <para>The RTC alarm will wake the system after the specified timespan to measure the system battery
ac3a84
+          capacity level and estimate battery discharging rate, which is used for estimating timespan until the system battery charge
ac3a84
+          level goes down to 5%. Only used by
ac3a84
+          <citerefentry><refentrytitle>systemd-suspend-then-hibernate.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>.
ac3a84
+          Defaults to 2h.</para></listitem>
ac3a84
       </varlistentry>
ac3a84
     </variablelist>
ac3a84
   </refsect1>
ac3a84
diff --git a/src/shared/sleep-config.c b/src/shared/sleep-config.c
ac3a84
index 359d293fd0..74653effa2 100644
ac3a84
--- a/src/shared/sleep-config.c
ac3a84
+++ b/src/shared/sleep-config.c
ac3a84
@@ -65,10 +65,14 @@ int parse_sleep_config(SleepConfig **ret_sleep_config) {
ac3a84
         int allow_suspend = -1, allow_hibernate = -1,
ac3a84
             allow_s2h = -1, allow_hybrid_sleep = -1;
ac3a84
 
ac3a84
-        sc = new0(SleepConfig, 1);
ac3a84
+        sc = new(SleepConfig, 1);
ac3a84
         if (!sc)
ac3a84
                 return log_oom();
ac3a84
 
ac3a84
+        *sc = (SleepConfig) {
ac3a84
+                .hibernate_delay_usec = USEC_INFINITY,
ac3a84
+        };
ac3a84
+
ac3a84
         const ConfigTableItem items[] = {
ac3a84
                 { "Sleep", "AllowSuspend",              config_parse_tristate, 0, &allow_suspend                  },
ac3a84
                 { "Sleep", "AllowHibernation",          config_parse_tristate, 0, &allow_hibernate                },
ac3a84
@@ -83,6 +87,7 @@ int parse_sleep_config(SleepConfig **ret_sleep_config) {
ac3a84
                 { "Sleep", "HybridSleepState",          config_parse_strv,     0, sc->states + SLEEP_HYBRID_SLEEP },
ac3a84
 
ac3a84
                 { "Sleep", "HibernateDelaySec",         config_parse_sec,      0, &sc->hibernate_delay_usec       },
ac3a84
+                { "Sleep", "SuspendEstimationSec",      config_parse_sec,      0, &sc->suspend_estimation_usec    },
ac3a84
                 {}
ac3a84
         };
ac3a84
 
ac3a84
@@ -113,8 +118,8 @@ int parse_sleep_config(SleepConfig **ret_sleep_config) {
ac3a84
                 sc->modes[SLEEP_HYBRID_SLEEP] = strv_new("suspend", "platform", "shutdown");
ac3a84
         if (!sc->states[SLEEP_HYBRID_SLEEP])
ac3a84
                 sc->states[SLEEP_HYBRID_SLEEP] = strv_new("disk");
ac3a84
-        if (sc->hibernate_delay_usec == 0)
ac3a84
-                sc->hibernate_delay_usec = 2 * USEC_PER_HOUR;
ac3a84
+        if (sc->suspend_estimation_usec == 0)
ac3a84
+                sc->suspend_estimation_usec = DEFAULT_SUSPEND_ESTIMATION_USEC;
ac3a84
 
ac3a84
         /* ensure values set for all required fields */
ac3a84
         if (!sc->states[SLEEP_SUSPEND] || !sc->modes[SLEEP_HIBERNATE]
ac3a84
diff --git a/src/shared/sleep-config.h b/src/shared/sleep-config.h
ac3a84
index 226fab4b9f..480e90c95b 100644
ac3a84
--- a/src/shared/sleep-config.h
ac3a84
+++ b/src/shared/sleep-config.h
ac3a84
@@ -6,6 +6,8 @@
ac3a84
 #include "hashmap.h"
ac3a84
 #include "time-util.h"
ac3a84
 
ac3a84
+#define DEFAULT_SUSPEND_ESTIMATION_USEC (1 * USEC_PER_HOUR)
ac3a84
+
ac3a84
 typedef enum SleepOperation {
ac3a84
         SLEEP_SUSPEND,
ac3a84
         SLEEP_HIBERNATE,
ac3a84
@@ -20,6 +22,7 @@ typedef struct SleepConfig {
ac3a84
         char **modes[_SLEEP_OPERATION_MAX];
ac3a84
         char **states[_SLEEP_OPERATION_MAX];
ac3a84
         usec_t hibernate_delay_usec;
ac3a84
+        usec_t suspend_estimation_usec;
ac3a84
 } SleepConfig;
ac3a84
 
ac3a84
 SleepConfig* free_sleep_config(SleepConfig *sc);
ac3a84
diff --git a/src/sleep/sleep.c b/src/sleep/sleep.c
ac3a84
index 039b123dcc..0bbea9e856 100644
ac3a84
--- a/src/sleep/sleep.c
ac3a84
+++ b/src/sleep/sleep.c
ac3a84
@@ -268,10 +268,13 @@ static int execute(
ac3a84
 
ac3a84
 static int custom_timer_suspend(const SleepConfig *sleep_config) {
ac3a84
         _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL;
ac3a84
+        usec_t hibernate_timestamp;
ac3a84
         int r;
ac3a84
 
ac3a84
         assert(sleep_config);
ac3a84
 
ac3a84
+        hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec);
ac3a84
+
ac3a84
         while (battery_is_low() == 0) {
ac3a84
                 _cleanup_close_ int tfd = -1;
ac3a84
                 struct itimerspec ts = {};
ac3a84
@@ -287,14 +290,25 @@ static int custom_timer_suspend(const SleepConfig *sleep_config) {
ac3a84
                 if (r < 0)
ac3a84
                         return log_error_errno(r, "Error fetching battery capacity percentage: %m");
ac3a84
 
ac3a84
-                r = get_total_suspend_interval(last_capacity, &suspend_interval);
ac3a84
-                if (r < 0) {
ac3a84
-                        log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
ac3a84
-                        /* In case of no battery or any errors, system suspend interval will be set to HibernateDelaySec=. */
ac3a84
-                        suspend_interval = sleep_config->hibernate_delay_usec;
ac3a84
+                if (hashmap_isempty(last_capacity))
ac3a84
+                        /* In case of no battery, system suspend interval will be set to HibernateDelaySec= or 2 hours. */
ac3a84
+                        suspend_interval = timestamp_is_set(hibernate_timestamp) ? sleep_config->hibernate_delay_usec : DEFAULT_SUSPEND_ESTIMATION_USEC;
ac3a84
+                else {
ac3a84
+                        r = get_total_suspend_interval(last_capacity, &suspend_interval);
ac3a84
+                        if (r < 0) {
ac3a84
+                                log_debug_errno(r, "Failed to estimate suspend interval using previous discharge rate, ignoring: %m");
ac3a84
+                                /* In case of any errors, especially when we do not know the battery
ac3a84
+                                 * discharging rate, system suspend interval will be set to
ac3a84
+                                 * SuspendEstimationSec=. */
ac3a84
+                                suspend_interval = sleep_config->suspend_estimation_usec;
ac3a84
+                        }
ac3a84
                 }
ac3a84
 
ac3a84
+                /* Do not suspend more than HibernateDelaySec= */
ac3a84
                 usec_t before_timestamp = now(CLOCK_BOOTTIME);
ac3a84
+                suspend_interval = MIN(suspend_interval, usec_sub_unsigned(hibernate_timestamp, before_timestamp));
ac3a84
+                if (suspend_interval <= 0)
ac3a84
+                        break; /* system should hibernate */
ac3a84
 
ac3a84
                 log_debug("Set timerfd wake alarm for %s", FORMAT_TIMESPAN(suspend_interval, USEC_PER_SEC));
ac3a84
                 /* Wake alarm for system with or without battery to hibernate or estimate discharge rate whichever is applicable */
ac3a84
@@ -377,7 +391,7 @@ static int freeze_thaw_user_slice(const char **method) {
ac3a84
 
ac3a84
 static int execute_s2h(const SleepConfig *sleep_config) {
ac3a84
         _unused_ _cleanup_(freeze_thaw_user_slice) const char *auto_method_thaw = NULL;
ac3a84
-        int r, k;
ac3a84
+        int r;
ac3a84
 
ac3a84
         assert(sleep_config);
ac3a84
 
ac3a84
@@ -387,15 +401,21 @@ static int execute_s2h(const SleepConfig *sleep_config) {
ac3a84
         else
ac3a84
                 auto_method_thaw = "ThawUnit"; /* from now on we want automatic thawing */;
ac3a84
 
ac3a84
-        r = check_wakeup_type();
ac3a84
-        if (r < 0)
ac3a84
-                log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
ac3a84
-
ac3a84
-        k = battery_trip_point_alarm_exists();
ac3a84
-        if (k < 0)
ac3a84
-                log_debug_errno(k, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
ac3a84
+        /* Only check if we have automated battery alarms if HibernateDelaySec= is not set, as in that case
ac3a84
+         * we'll busy poll for the configured interval instead */
ac3a84
+        if (!timestamp_is_set(sleep_config->hibernate_delay_usec)) {
ac3a84
+                r = check_wakeup_type();
ac3a84
+                if (r < 0)
ac3a84
+                        log_debug_errno(r, "Failed to check hardware wakeup type, ignoring: %m");
ac3a84
+                else {
ac3a84
+                        r = battery_trip_point_alarm_exists();
ac3a84
+                        if (r < 0)
ac3a84
+                                log_debug_errno(r, "Failed to check whether acpi_btp support is enabled or not, ignoring: %m");
ac3a84
+                }
ac3a84
+        } else
ac3a84
+                r = 0;  /* Force fallback path */
ac3a84
 
ac3a84
-        if (r >= 0 && k > 0) {
ac3a84
+        if (r > 0) { /* If we have both wakeup alarms and battery trip point support, use them */
ac3a84
                 log_debug("Attempting to suspend...");
ac3a84
                 r = execute(sleep_config, SLEEP_SUSPEND, NULL);
ac3a84
                 if (r < 0)
ac3a84
diff --git a/src/sleep/sleep.conf b/src/sleep/sleep.conf
ac3a84
index a3d31140d8..4c8e8b9680 100644
ac3a84
--- a/src/sleep/sleep.conf
ac3a84
+++ b/src/sleep/sleep.conf
ac3a84
@@ -23,4 +23,5 @@
ac3a84
 #HibernateState=disk
ac3a84
 #HybridSleepMode=suspend platform shutdown
ac3a84
 #HybridSleepState=disk
ac3a84
-#HibernateDelaySec=120min
ac3a84
+#HibernateDelaySec=
ac3a84
+#SuspendEstimationSec=60min