]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/sleep/battery-capacity.c
extract-word: modernize extract_many_words
[thirdparty/systemd.git] / src / sleep / battery-capacity.c
CommitLineData
7d769198
MY
1/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3#include "sd-device.h"
4
5#include "battery-capacity.h"
6#include "battery-util.h"
7#include "device-private.h"
8#include "device-util.h"
9#include "extract-word.h"
10#include "fd-util.h"
11#include "fileio.h"
12#include "hexdecoct.h"
13#include "id128-util.h"
14#include "parse-util.h"
15#include "siphash24.h"
16
17#define DISCHARGE_RATE_FILEPATH "/var/lib/systemd/sleep/battery_discharge_percentage_rate_per_hour"
18#define BATTERY_DISCHARGE_RATE_HASH_KEY SD_ID128_MAKE(5f,9a,20,18,38,76,46,07,8d,36,58,0b,bb,c4,e0,63)
19
20static void *CAPACITY_TO_PTR(int capacity) {
21 assert(capacity >= 0);
22 assert(capacity <= 100);
23 return INT_TO_PTR(capacity + 1);
24}
25
26static int PTR_TO_CAPACITY(void *p) {
27 int capacity = PTR_TO_INT(p) - 1;
28 assert(capacity >= 0);
29 assert(capacity <= 100);
30 return capacity;
31}
32
7f88eee9
MY
33static int siphash24_compress_device_sysattr(
34 sd_device *dev,
35 const char *attr,
36 struct siphash *state) {
37
7d769198
MY
38 const char *x;
39 int r;
40
41 assert(dev);
42 assert(attr);
43 assert(state);
44
45 r = sd_device_get_sysattr_value(dev, attr, &x);
46 if (r < 0)
47 return log_device_debug_errno(dev, r, "Failed to read '%s' attribute: %m", attr);
48
49 if (!isempty(x))
50 siphash24_compress_string(x, state);
51
52 return 0;
53}
54
7f88eee9
MY
55static int siphash24_compress_id128(
56 int (*getter)(sd_id128_t *ret),
57 const char *name,
58 struct siphash *state) {
59
7d769198
MY
60 sd_id128_t id;
61 int r;
62
63 assert(getter);
7f88eee9 64 assert(name);
7d769198
MY
65 assert(state);
66
67 r = getter(&id);
68 if (r < 0)
69 return log_debug_errno(r, "Failed to get %s ID: %m", name);
70
c01a5c05 71 siphash24_compress_typesafe(id, state);
7d769198
MY
72 return 0;
73}
74
75/* Read system and battery identifier from specific location and generate hash of it */
7f88eee9 76static uint64_t system_battery_identifier_hash(sd_device *dev) {
7d769198
MY
77 struct siphash state;
78
7d769198
MY
79 assert(dev);
80
81 siphash24_init(&state, BATTERY_DISCHARGE_RATE_HASH_KEY.bytes);
82
83 (void) siphash24_compress_device_sysattr(dev, "manufacturer", &state);
84 (void) siphash24_compress_device_sysattr(dev, "model_name", &state);
85 (void) siphash24_compress_device_sysattr(dev, "serial_number", &state);
86 (void) siphash24_compress_id128(sd_id128_get_machine, "machine", &state);
87 (void) siphash24_compress_id128(id128_get_product, "product", &state);
88
7f88eee9 89 return siphash24_finalize(&state);
7d769198
MY
90}
91
92/* Return success if battery percentage discharge rate per hour is in the range 1–199 */
93static bool battery_discharge_rate_is_valid(int battery_discharge_rate) {
94 return battery_discharge_rate > 0 && battery_discharge_rate < 200;
95}
96
97/* Battery percentage discharge rate per hour is read from specific file. It is stored along with system
98 * and battery identifier hash to maintain the integrity of discharge rate value */
99static int get_battery_discharge_rate(sd_device *dev, int *ret) {
100 _cleanup_fclose_ FILE *f = NULL;
101 uint64_t current_hash_id;
102 const char *p;
103 int r;
104
105 assert(dev);
106 assert(ret);
107
108 f = fopen(DISCHARGE_RATE_FILEPATH, "re");
109 if (!f)
110 return log_debug_errno(errno, "Failed to read discharge rate from " DISCHARGE_RATE_FILEPATH ": %m");
111
7f88eee9 112 current_hash_id = system_battery_identifier_hash(dev);
7d769198
MY
113
114 for (;;) {
115 _cleanup_free_ char *stored_hash_id = NULL, *stored_discharge_rate = NULL, *line = NULL;
116 uint64_t hash_id;
117 int discharge_rate;
118
119 r = read_line(f, LONG_LINE_MAX, &line);
120 if (r < 0)
121 return log_debug_errno(r, "Failed to read discharge rate from " DISCHARGE_RATE_FILEPATH ": %m");
122 if (r == 0)
123 break;
124
125 p = line;
4f495126 126 r = extract_many_words(&p, NULL, 0, &stored_hash_id, &stored_discharge_rate);
7d769198
MY
127 if (r < 0)
128 return log_debug_errno(r, "Failed to parse hash_id and discharge_rate read from " DISCHARGE_RATE_FILEPATH ": %m");
129 if (r != 2)
130 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid number of items fetched from " DISCHARGE_RATE_FILEPATH);
131
132 r = safe_atou64(stored_hash_id, &hash_id);
133 if (r < 0)
134 return log_debug_errno(r, "Failed to parse hash ID read from " DISCHARGE_RATE_FILEPATH " location: %m");
135
136 if (current_hash_id != hash_id)
137 /* matching device not found, move to next line */
138 continue;
139
140 r = safe_atoi(stored_discharge_rate, &discharge_rate);
141 if (r < 0)
142 return log_device_debug_errno(dev, r, "Failed to parse discharge rate read from " DISCHARGE_RATE_FILEPATH ": %m");
143
144 if (!battery_discharge_rate_is_valid(discharge_rate))
145 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(ERANGE), "Invalid battery discharge percentage rate per hour: %m");
146
147 *ret = discharge_rate;
148 return 0; /* matching device found, exit iteration */
149 }
150
151 return -ENOENT;
152}
153
154/* Write battery percentage discharge rate per hour along with system and battery identifier hash to file */
155static int put_battery_discharge_rate(int estimated_battery_discharge_rate, uint64_t system_hash_id, bool trunc) {
156 int r;
157
158 if (!battery_discharge_rate_is_valid(estimated_battery_discharge_rate))
159 return log_debug_errno(SYNTHETIC_ERRNO(ERANGE),
160 "Invalid battery discharge rate %d%% per hour: %m",
161 estimated_battery_discharge_rate);
162
163 r = write_string_filef(
164 DISCHARGE_RATE_FILEPATH,
165 WRITE_STRING_FILE_CREATE | WRITE_STRING_FILE_MKDIR_0755 | (trunc ? WRITE_STRING_FILE_TRUNCATE : 0),
166 "%"PRIu64" %d",
167 system_hash_id,
168 estimated_battery_discharge_rate);
169 if (r < 0)
170 return log_debug_errno(r, "Failed to update %s: %m", DISCHARGE_RATE_FILEPATH);
171
172 log_debug("Estimated discharge rate %d%% per hour successfully saved to %s", estimated_battery_discharge_rate, DISCHARGE_RATE_FILEPATH);
173
174 return 0;
175}
176
f3afe9dc
MY
177/* Store current capacity of each battery before suspension and timestamp */
178int fetch_batteries_capacity_by_name(Hashmap **ret) {
179 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
180 _cleanup_hashmap_free_ Hashmap *batteries_capacity_by_name = NULL;
181 int r;
182
183 assert(ret);
184
185 batteries_capacity_by_name = hashmap_new(&string_hash_ops_free);
186 if (!batteries_capacity_by_name)
187 return log_oom_debug();
188
189 r = battery_enumerator_new(&e);
190 if (r < 0)
191 return log_debug_errno(r, "Failed to initialize battery enumerator: %m");
192
193 FOREACH_DEVICE(e, dev) {
194 _cleanup_free_ char *battery_name_copy = NULL;
195 const char *battery_name;
196 int battery_capacity;
197
198 battery_capacity = r = battery_read_capacity_percentage(dev);
199 if (r < 0)
200 continue;
201
202 r = sd_device_get_property_value(dev, "POWER_SUPPLY_NAME", &battery_name);
203 if (r < 0) {
204 log_device_debug_errno(dev, r, "Failed to get POWER_SUPPLY_NAME property, ignoring: %m");
205 continue;
206 }
207
208 battery_name_copy = strdup(battery_name);
209 if (!battery_name_copy)
210 return log_oom_debug();
211
212 r = hashmap_put(batteries_capacity_by_name, battery_name_copy, CAPACITY_TO_PTR(battery_capacity));
213 if (r < 0)
214 return log_device_debug_errno(dev, r, "Failed to store battery capacity: %m");
215
216 TAKE_PTR(battery_name_copy);
217 }
218
219 *ret = TAKE_PTR(batteries_capacity_by_name);
220
221 return 0;
222}
223
224int get_capacity_by_name(Hashmap *capacities_by_name, const char *name) {
225 void *p;
226
227 assert(capacities_by_name);
228 assert(name);
229
230 p = hashmap_get(capacities_by_name, name);
231 if (!p)
232 return -ENOENT;
233
234 return PTR_TO_CAPACITY(p);
235}
236
7d769198
MY
237/* Estimate battery discharge rate using stored previous and current capacity over timestamp difference */
238int estimate_battery_discharge_rate_per_hour(
239 Hashmap *last_capacity,
240 Hashmap *current_capacity,
241 usec_t before_timestamp,
242 usec_t after_timestamp) {
243
244 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
245 bool trunc = true;
246 int r;
247
248 assert(last_capacity);
249 assert(current_capacity);
250 assert(before_timestamp < after_timestamp);
251
252 r = battery_enumerator_new(&e);
253 if (r < 0)
254 return log_debug_errno(r, "Failed to initialize battery enumerator: %m");
255
256 FOREACH_DEVICE(e, dev) {
257 int battery_last_capacity, battery_current_capacity, battery_discharge_rate;
258 const char *battery_name;
259 uint64_t system_hash_id;
260
261 r = sd_device_get_property_value(dev, "POWER_SUPPLY_NAME", &battery_name);
262 if (r < 0) {
263 log_device_debug_errno(dev, r, "Failed to read battery name, ignoring: %m");
264 continue;
265 }
266
267 battery_last_capacity = get_capacity_by_name(last_capacity, battery_name);
268 if (battery_last_capacity < 0)
269 continue;
270
271 battery_current_capacity = get_capacity_by_name(current_capacity, battery_name);
272 if (battery_current_capacity < 0)
273 continue;
274
275 if (battery_current_capacity >= battery_last_capacity) {
276 log_device_debug(dev, "Battery was not discharged during suspension");
277 continue;
278 }
279
7f88eee9 280 system_hash_id = system_battery_identifier_hash(dev);
7d769198
MY
281
282 log_device_debug(dev,
283 "%d%% was discharged in %s. Estimating discharge rate...",
284 battery_last_capacity - battery_current_capacity,
285 FORMAT_TIMESPAN(after_timestamp - before_timestamp, USEC_PER_SEC));
286
287 battery_discharge_rate = (battery_last_capacity - battery_current_capacity) * USEC_PER_HOUR / (after_timestamp - before_timestamp);
288 r = put_battery_discharge_rate(battery_discharge_rate, system_hash_id, trunc);
289 if (r < 0)
290 log_device_warning_errno(dev, r, "Failed to update battery discharge rate, ignoring: %m");
291 else
292 trunc = false;
293 }
294
295 return 0;
296}
297
298/* Calculate the suspend interval for each battery and then return their sum */
299int get_total_suspend_interval(Hashmap *last_capacity, usec_t *ret) {
300 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
301 usec_t total_suspend_interval = 0;
302 int r;
303
304 assert(last_capacity);
305 assert(ret);
306
307 r = battery_enumerator_new(&e);
308 if (r < 0)
309 return log_debug_errno(r, "Failed to initialize battery enumerator: %m");
310
311 FOREACH_DEVICE(e, dev) {
312 int battery_last_capacity, previous_discharge_rate = 0;
313 const char *battery_name;
314 usec_t suspend_interval;
315
316 r = sd_device_get_property_value(dev, "POWER_SUPPLY_NAME", &battery_name);
317 if (r < 0) {
318 log_device_debug_errno(dev, r, "Failed to read battery name, ignoring: %m");
319 continue;
320 }
321
322 battery_last_capacity = get_capacity_by_name(last_capacity, battery_name);
323 if (battery_last_capacity <= 0)
324 continue;
325
326 r = get_battery_discharge_rate(dev, &previous_discharge_rate);
327 if (r < 0) {
328 log_device_debug_errno(dev, r, "Failed to get discharge rate, ignoring: %m");
329 continue;
330 }
331
332 if (previous_discharge_rate == 0)
333 continue;
334
335 if (battery_last_capacity * 2 <= previous_discharge_rate) {
336 log_device_debug(dev, "Current battery capacity percentage too low compared to discharge rate");
337 continue;
338 }
339 suspend_interval = battery_last_capacity * USEC_PER_HOUR / previous_discharge_rate;
340
341 total_suspend_interval = usec_add(total_suspend_interval, suspend_interval);
342 }
343 /* Previous discharge rate is stored in per hour basis converted to usec.
344 * Subtract 30 minutes from the result to keep a buffer of 30 minutes before battery gets critical */
345 total_suspend_interval = usec_sub_unsigned(total_suspend_interval, 30 * USEC_PER_MINUTE);
346 if (total_suspend_interval == 0)
347 return -ENOENT;
348
349 *ret = total_suspend_interval;
350
351 return 0;
352}
353
354/* Return true if all batteries have acpi_btp support */
355int battery_trip_point_alarm_exists(void) {
356 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
fbc1dbf2 357 bool has_battery = false;
7d769198
MY
358 int r;
359
360 r = battery_enumerator_new(&e);
361 if (r < 0)
362 return log_debug_errno(r, "Failed to initialize battery enumerator: %m");
363
364 FOREACH_DEVICE(e, dev) {
fbc1dbf2
MY
365 const char *alarm_attr;
366 int has_alarm;
7d769198 367
fbc1dbf2
MY
368 has_battery = true;
369
370 r = sd_device_get_sysattr_value(dev, "alarm", &alarm_attr);
7d769198 371 if (r < 0)
fbc1dbf2 372 return log_device_debug_errno(dev, r, "Failed to read battery alarm attribute: %m");
7d769198 373
fbc1dbf2 374 r = safe_atoi(alarm_attr, &has_alarm);
7d769198 375 if (r < 0)
fbc1dbf2
MY
376 return log_device_debug_errno(dev, r,
377 "Failed to parse battery alarm attribute '%s': %m",
378 alarm_attr);
379 if (has_alarm <= 0)
7d769198
MY
380 return false;
381 }
382
fbc1dbf2 383 return has_battery;
7d769198 384}