Debian Codegraph @

src/sleep/battery-capacity.c

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