Debian Codegraph @

src/backlight/backlight.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/stat.h>
4 #include <unistd.h>
5
6 #include "sd-device.h"
7
8 #include "alloc-util.h"
9 #include "argv-util.h"
10 #include "device-private.h"
11 #include "device-util.h"
12 #include "escape.h"
13 #include "fileio.h"
14 #include "format-table.h"
15 #include "help-util.h"
16 #include "main-func.h"
17 #include "parse-util.h"
18 #include "percent-util.h"
19 #include "reboot-util.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "verbs.h"
23
24 #define PCI_CLASS_GRAPHICS_CARD 0x30000
25
26 static int help(void) {
27 _cleanup_(table_unrefp) Table *verbs = NULL;
28 int r;
29
30 r = verbs_get_help_table(&verbs);
31 if (r < 0)
32 return r;
33
34 help_cmdline("COMMAND [backlight|leds]:DEVICE");
35 help_abstract("Save and restore backlight brightness at shutdown and boot.");
36
37 help_section("Commands");
38 r = table_print_or_warn(verbs);
39 if (r < 0)
40 return r;
41
42 help_man_page_reference("systemd-backlight", "8");
43 return 0;
44 }
45
46 static int has_multiple_graphics_cards(void) {
47 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
48 bool found = false;
49 int r;
50
51 r = sd_device_enumerator_new(&e);
52 if (r < 0)
53 return r;
54
55 r = sd_device_enumerator_allow_uninitialized(e);
56 if (r < 0)
57 return r;
58
59 r = sd_device_enumerator_add_match_subsystem(e, "pci", /* match= */ true);
60 if (r < 0)
61 return r;
62
63 /* class is an unsigned number, let's validate the value later. */
64 r = sd_device_enumerator_add_match_sysattr(e, "class", NULL, /* match= */ true);
65 if (r < 0)
66 return r;
67
68 FOREACH_DEVICE(e, dev) {
69 uint32_t c;
70
71 if (device_get_sysattr_u32(dev, "class", &c) < 0)
72 continue;
73
74 if (c != PCI_CLASS_GRAPHICS_CARD)
75 continue;
76
77 if (found)
78 return true; /* This is the second device. */
79
80 found = true; /* Found the first device. */
81 }
82
83 return false;
84 }
85
86 static int find_pci_or_platform_parent(sd_device *device, sd_device **ret) {
87 int r;
88
89 assert(device);
90 assert(ret);
91
92 for (;;) {
93 r = sd_device_get_parent(device, &device);
94 if (r < 0)
95 return r;
96
97 r = device_in_subsystem(device, "drm");
98 if (r < 0)
99 return r;
100 if (r > 0) {
101 const char *s;
102
103 r = device_sysname_startswith_strv(device, STRV_MAKE("card"), &s);
104 if (r < 0)
105 return r;
106 if (r == 0)
107 return -ENODATA;
108
109 s += strspn(s, DIGITS);
110 if (*s == '-' && !STARTSWITH_SET(s, "-LVDS-", "-Embedded DisplayPort-", "-eDP-"))
111 /* A connector DRM device, let's ignore all but LVDS and eDP! */
112 return -EOPNOTSUPP;
113
114 continue;
115 }
116
117 r = device_in_subsystem(device, "pci");
118 if (r < 0)
119 return r;
120 if (r > 0) {
121 uint32_t class;
122
123 r = device_get_sysattr_u32(device, "class", &class);
124 if (r == -ENOENT)
125 continue;
126 if (r < 0)
127 return r;
128
129 /* Graphics card */
130 if (class == PCI_CLASS_GRAPHICS_CARD) {
131 *ret = device;
132 return 0;
133 }
134
135 continue;
136 }
137
138 r = device_in_subsystem(device, "platform");
139 if (r < 0)
140 return r;
141 if (r > 0) {
142 *ret = device;
143 return 0;
144 }
145 }
146 }
147
148 static int same_device(sd_device *a, sd_device *b) {
149 const char *a_val, *b_val;
150 int r;
151
152 assert(a);
153 assert(b);
154
155 r = sd_device_get_subsystem(a, &a_val);
156 if (r < 0)
157 return r;
158
159 r = sd_device_get_subsystem(b, &b_val);
160 if (r < 0)
161 return r;
162
163 if (!streq(a_val, b_val))
164 return false;
165
166 r = sd_device_get_sysname(a, &a_val);
167 if (r < 0)
168 return r;
169
170 r = sd_device_get_sysname(b, &b_val);
171 if (r < 0)
172 return r;
173
174 return streq(a_val, b_val);
175 }
176
177 static int validate_device(sd_device *device) {
178 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *enumerate = NULL;
179 const char *sysname;
180 sd_device *parent;
181 int r;
182
183 assert(device);
184
185 /* Verify whether we should actually care for a specific backlight device. For backlight devices
186 * there might be multiple ways to access the same control: "firmware" (i.e. ACPI), "platform"
187 * (i.e. via the machine's EC), and "raw" (via the graphics card). In general we should prefer
188 * "firmware" (i.e. ACPI) or "platform" access over "raw" access, in order not to confuse the
189 * BIOS/EC, and compatibility with possible low-level hotkey handling of screen brightness. The
190 * kernel will already make sure to expose only one of "firmware" and "platform" for the same
191 * device to userspace. However, we still need to make sure that we use "raw" only if no
192 * "firmware" or "platform" device for the same device exists. */
193
194 r = sd_device_get_sysname(device, &sysname);
195 if (r < 0)
196 return log_device_debug_errno(device, r, "Failed to get sysname: %m");
197
198 r = device_in_subsystem(device, "leds");
199 if (r < 0)
200 return log_device_debug_errno(device, r, "Failed to check if device is in leds subsystem: %m");
201 if (r > 0)
202 return true; /* We assume LED device is always valid. */
203
204 r = device_get_sysattr_streq(device, "type", "raw");
205 if (r < 0)
206 return log_device_debug_errno(device, r, "Failed to read 'type' sysattr: %m");
207 if (r == 0)
208 return true;
209
210 r = find_pci_or_platform_parent(device, &parent);
211 if (r < 0)
212 return log_device_debug_errno(device, r, "Failed to find PCI or platform parent: %m");
213
214 if (DEBUG_LOGGING) {
215 const char *s = NULL, *subsystem = NULL;
216
217 (void) sd_device_get_syspath(parent, &s);
218 (void) sd_device_get_subsystem(parent, &subsystem);
219 log_device_debug(device, "Found %s parent device: %s", strna(subsystem), strna(s));
220 }
221
222 r = sd_device_enumerator_new(&enumerate);
223 if (r < 0)
224 return log_oom_debug();
225
226 r = sd_device_enumerator_allow_uninitialized(enumerate);
227 if (r < 0)
228 return log_debug_errno(r, "Failed to allow uninitialized devices: %m");
229
230 r = sd_device_enumerator_add_match_subsystem(enumerate, "backlight", /* match= */ true);
231 if (r < 0)
232 return log_debug_errno(r, "Failed to add subsystem match: %m");
233
234 r = sd_device_enumerator_add_nomatch_sysname(enumerate, sysname);
235 if (r < 0)
236 return log_debug_errno(r, "Failed to add sysname unmatch: %m");
237
238 r = sd_device_enumerator_add_match_sysattr(enumerate, "type", "platform", /* match= */ true);
239 if (r < 0)
240 return log_debug_errno(r, "Failed to add sysattr match: %m");
241
242 r = sd_device_enumerator_add_match_sysattr(enumerate, "type", "firmware", /* match= */ true);
243 if (r < 0)
244 return log_debug_errno(r, "Failed to add sysattr match: %m");
245
246 if (device_in_subsystem(parent, "pci") > 0) {
247 r = has_multiple_graphics_cards();
248 if (r < 0)
249 return log_debug_errno(r, "Failed to check if the system has multiple graphics cards: %m");
250 if (r > 0) {
251 /* If the system has multiple graphics cards, then we cannot associate platform
252 * devices on non-PCI bus (especially WMI bus) with PCI devices. Let's ignore all
253 * backlight devices that do not have the same parent PCI device. */
254 log_debug("Found multiple graphics cards on PCI bus; "
255 "skipping deduplication of platform backlight devices not on PCI bus.");
256
257 r = sd_device_enumerator_add_match_parent(enumerate, parent);
258 if (r < 0)
259 return log_debug_errno(r, "Failed to add parent match: %m");
260 }
261 }
262
263 FOREACH_DEVICE(enumerate, other) {
264 sd_device *other_parent;
265
266 /* OK, so there's another backlight device, and it's a platform or firmware device.
267 * Let's see if we can verify it belongs to the same device as ours. */
268 r = find_pci_or_platform_parent(other, &other_parent);
269 if (r < 0) {
270 log_device_debug_errno(other, r, "Failed to get PCI or platform parent, ignoring: %m");
271 continue;
272 }
273
274 if (same_device(parent, other_parent) > 0) {
275 /* Both have the same PCI parent, that means we are out. */
276 if (DEBUG_LOGGING) {
277 const char *other_sysname = NULL, *other_type = NULL;
278
279 (void) sd_device_get_sysname(other, &other_sysname);
280 (void) device_get_sysattr_safe_string(other, "type", &other_type);
281 log_device_debug(device,
282 "Found another %s backlight device %s on the same PCI, skipping.",
283 strna(other_type), strna(other_sysname));
284 }
285 return false;
286 }
287
288 if (device_in_subsystem(other_parent, "platform") > 0 && device_in_subsystem(parent, "pci") > 0) {
289 /* The other is connected to the platform bus and we are a PCI device, that also means we are out. */
290 if (DEBUG_LOGGING) {
291 const char *other_sysname = NULL, *other_type = NULL;
292
293 (void) sd_device_get_sysname(other, &other_sysname);
294 (void) device_get_sysattr_safe_string(other, "type", &other_type);
295 log_device_debug(device,
296 "Found another %s backlight device %s, which has higher precedence, skipping.",
297 strna(other_type), strna(other_sysname));
298 }
299 return false;
300 }
301 }
302
303 return true;
304 }
305
306 static int read_max_brightness(sd_device *device, unsigned *ret) {
307 unsigned max_brightness;
308 int r;
309
310 assert(device);
311 assert(ret);
312
313 r = device_get_sysattr_unsigned(device, "max_brightness", &max_brightness);
314 if (r < 0)
315 return log_device_warning_errno(device, r, "Failed to read 'max_brightness' attribute: %m");
316
317 /* If max_brightness is 0, then there is no actual backlight device. This happens on desktops
318 * with Asus mainboards that load the eeepc-wmi module. */
319 if (max_brightness == 0) {
320 log_device_warning(device, "Maximum brightness is 0, ignoring device.");
321 *ret = 0;
322 return 0;
323 }
324
325 log_device_debug(device, "Maximum brightness is %u", max_brightness);
326
327 *ret = max_brightness;
328 return 1; /* valid max brightness */
329 }
330
331 static int clamp_brightness(
332 sd_device *device,
333 unsigned percent,
334 bool saved,
335 unsigned max_brightness,
336 unsigned *brightness) {
337
338 unsigned new_brightness, min_brightness;
339 int r;
340
341 assert(device);
342 assert(brightness);
343
344 /* Some systems turn the backlight all the way off at the lowest levels. This clamps the saved
345 * brightness to at least 1 or 1% of max_brightness (whichever is bigger) in case of 'backlight' subsystem.
346 * This avoids preserving an unreadably dim screen, which would otherwise force the user to disable
347 * state restoration. */
348
349 min_brightness = (unsigned) ((double) max_brightness * percent / 100);
350 r = device_in_subsystem(device, "backlight");
351 if (r < 0)
352 return r;
353 if (r > 0)
354 min_brightness = MAX(1U, min_brightness);
355
356 new_brightness = CLAMP(*brightness, min_brightness, max_brightness);
357 if (new_brightness != *brightness)
358 log_device_info(device, "%s brightness %u is %s to %u.",
359 saved ? "Saved" : "Current",
360 *brightness,
361 new_brightness > *brightness ?
362 "too low; increasing" : "too high; decreasing",
363 new_brightness);
364
365 *brightness = new_brightness;
366 return 0;
367 }
368
369 /* used as the default for devices in the backlight subsystem, or when ID_BACKLIGHT_CLAMP/ID_LEDS_CLAMP=yes. */
370 #define DEFAULT_CLAMP_PERCENT 1u
371
372 static int shall_clamp(sd_device *device, unsigned *ret) {
373 const char *property, *s;
374 unsigned default_percent;
375 int r;
376
377 assert(device);
378 assert(ret);
379
380 r = device_in_subsystem(device, "backlight");
381 if (r < 0)
382 return r;
383 if (r > 0) {
384 property = "ID_BACKLIGHT_CLAMP";
385 default_percent = DEFAULT_CLAMP_PERCENT;
386 } else {
387 property = "ID_LEDS_CLAMP";
388 default_percent = 0; /* The clamping is disabled by default. */
389 }
390
391 r = sd_device_get_property_value(device, property, &s);
392 if (r < 0) {
393 if (r != -ENOENT)
394 log_device_debug_errno(device, r, "Failed to get %s property, ignoring: %m", property);
395 *ret = default_percent;
396 return default_percent > 0;
397 }
398
399 r = parse_boolean(s);
400 if (r >= 0) {
401 *ret = r ? DEFAULT_CLAMP_PERCENT : 0;
402 return r;
403 }
404
405 r = parse_percent(s);
406 if (r < 0) {
407 log_device_debug_errno(device, r, "Failed to parse %s property, ignoring: %m", property);
408 *ret = default_percent;
409 return default_percent > 0;
410 }
411
412 *ret = r;
413 return true;
414 }
415
416 static int read_brightness(sd_device *device, unsigned max_brightness, unsigned *ret_brightness) {
417 unsigned brightness;
418 int r;
419
420 assert(device);
421 assert(ret_brightness);
422
423 r = device_get_sysattr_unsigned(device, "brightness", &brightness);
424 if (r < 0)
425 return log_device_debug_errno(device, r, "Failed to read 'brightness' attribute: %m");
426
427 if (brightness > max_brightness)
428 return log_device_debug_errno(device, SYNTHETIC_ERRNO(EINVAL),
429 "brightness=%u is larger than max_brightness=%u",
430 brightness, max_brightness);
431
432 log_device_debug(device, "Current brightness is %u", brightness);
433 *ret_brightness = brightness;
434 return 0;
435 }
436
437 static int build_save_file_path(sd_device *device, char **ret) {
438 _cleanup_free_ char *escaped_subsystem = NULL, *escaped_sysname = NULL, *path = NULL;
439 const char *s;
440 int r;
441
442 assert(device);
443 assert(ret);
444
445 r = sd_device_get_subsystem(device, &s);
446 if (r < 0)
447 return log_device_error_errno(device, r, "Failed to get subsystem: %m");
448
449 escaped_subsystem = cescape(s);
450 if (!escaped_subsystem)
451 return log_oom();
452
453 r = sd_device_get_sysname(device, &s);
454 if (r < 0)
455 return log_device_error_errno(device, r, "Failed to get sysname: %m");
456
457 escaped_sysname = cescape(s);
458 if (!escaped_sysname)
459 return log_oom();
460
461 if (sd_device_get_property_value(device, "ID_PATH", &s) >= 0) {
462 _cleanup_free_ char *escaped_path_id = cescape(s);
463 if (!escaped_path_id)
464 return log_oom();
465
466 path = strjoin("/var/lib/systemd/backlight/", escaped_path_id, ":", escaped_subsystem, ":", escaped_sysname);
467 } else
468 path = strjoin("/var/lib/systemd/backlight/", escaped_subsystem, ":", escaped_sysname);
469 if (!path)
470 return log_oom();
471
472 *ret = TAKE_PTR(path);
473 return 0;
474 }
475
476 static int read_saved_brightness(sd_device *device, unsigned *ret) {
477 _cleanup_free_ char *path = NULL, *value = NULL;
478 int r;
479
480 assert(device);
481 assert(ret);
482
483 r = build_save_file_path(device, &path);
484 if (r < 0)
485 return r;
486
487 r = read_one_line_file(path, &value);
488 if (r < 0) {
489 if (r != -ENOENT)
490 log_device_error_errno(device, r, "Failed to read %s: %m", path);
491 return r;
492 }
493
494 r = safe_atou(value, ret);
495 if (r < 0) {
496 log_device_warning_errno(device, r,
497 "Failed to parse saved brightness '%s', removing %s.",
498 value, path);
499 (void) unlink(path);
500 return r;
501 }
502
503 log_device_debug(device, "Using saved brightness %u.", *ret);
504 return 0;
505 }
506
507 static int device_new_from_arg(const char *s, sd_device **ret) {
508 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
509 _cleanup_free_ char *subsystem = NULL;
510 const char *sysname;
511 int r;
512
513 assert(s);
514 assert(ret);
515
516 sysname = strchr(s, ':');
517 if (!sysname)
518 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
519 "Requires a subsystem and sysname pair specifying a backlight or LED device.");
520
521 subsystem = strndup(s, sysname - s);
522 if (!subsystem)
523 return log_oom();
524
525 sysname++;
526
527 if (!STR_IN_SET(subsystem, "backlight", "leds"))
528 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
529 "Not a backlight or LED device: '%s:%s'",
530 subsystem, sysname);
531
532 r = sd_device_new_from_subsystem_sysname(&device, subsystem, sysname);
533 if (r == -ENODEV) {
534 /* Some drivers, e.g. for AMD GPU, removes acpi backlight device soon after it is added.
535 * See issue #21997. */
536 log_debug_errno(r, "Failed to get backlight or LED device '%s:%s', ignoring: %m", subsystem, sysname);
537 *ret = NULL;
538 return 0;
539 }
540 if (r < 0)
541 return log_error_errno(r, "Failed to get backlight or LED device '%s:%s': %m", subsystem, sysname);
542
543 *ret = TAKE_PTR(device);
544 return 1; /* Found. */
545 }
546
547 VERB(verb_load, "load", "[backlight|leds]:DEVICE", 2, 2, VERB_ONLINE_ONLY,
548 "Set brightness to be the previously saved value");
549 static int verb_load(int argc, char *argv[], uintptr_t _data, void *userdata) {
550 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
551 unsigned max_brightness, brightness, percent;
552 bool clamp;
553 int r;
554
555 assert(argc == 2);
556
557 if (!shall_restore_state())
558 return 0;
559
560 r = device_new_from_arg(argv[1], &device);
561 if (r <= 0)
562 return r;
563
564 r = read_max_brightness(device, &max_brightness);
565 if (r <= 0)
566 return r;
567
568 /* Ignore any errors in validation, and use the device as is. */
569 if (validate_device(device) == 0)
570 return 0;
571
572 r = shall_clamp(device, &percent);
573 if (r < 0)
574 return r;
575 clamp = r;
576
577 r = read_saved_brightness(device, &brightness);
578 if (r < 0) {
579 /* Fallback to clamping current brightness or exit early if clamping is not
580 * supported/enabled. */
581 if (!clamp)
582 return 0;
583
584 r = read_brightness(device, max_brightness, &brightness);
585 if (r < 0)
586 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
587
588 (void) clamp_brightness(device, percent, /* saved= */ false, max_brightness, &brightness);
589 } else if (clamp)
590 (void) clamp_brightness(device, percent, /* saved= */ true, max_brightness, &brightness);
591
592 r = sd_device_set_sysattr_valuef(device, "brightness", "%u", brightness);
593 if (r < 0)
594 return log_device_error_errno(device, r, "Failed to write system 'brightness' attribute: %m");
595
596 return 0;
597 }
598
599 VERB(verb_save, "save", "[backlight|leds]:DEVICE", 2, 2, VERB_ONLINE_ONLY,
600 "Save current brightness");
601 static int verb_save(int argc, char *argv[], uintptr_t _data, void *userdata) {
602 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
603 _cleanup_free_ char *path = NULL;
604 unsigned max_brightness, brightness;
605 int r;
606
607 assert(argc == 2);
608
609 r = device_new_from_arg(argv[1], &device);
610 if (r <= 0)
611 return r;
612
613 r = read_max_brightness(device, &max_brightness);
614 if (r <= 0)
615 return r;
616
617 r = build_save_file_path(device, &path);
618 if (r < 0)
619 return r;
620
621 /* If there are multiple conflicting backlight devices, then their probing at boot-time might
622 * happen in any order. This means the validity checking of the device then is not reliable,
623 * since it might not see other devices conflicting with a specific backlight. To deal with
624 * this, we will actively delete backlight state files at shutdown (where device probing should
625 * be complete), so that the validity check at boot time doesn't have to be reliable. */
626 if (validate_device(device) == 0) {
627 (void) unlink(path);
628 return 0;
629 }
630
631 r = read_brightness(device, max_brightness, &brightness);
632 if (r < 0)
633 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
634
635 r = write_string_filef(path, WRITE_STRING_FILE_CREATE | WRITE_STRING_FILE_MKDIR_0755, "%u", brightness);
636 if (r < 0)
637 return log_device_error_errno(device, r, "Failed to write %s: %m", path);
638
639 return 0;
640 }
641
642 static int run(int argc, char *argv[]) {
643 log_setup();
644
645 if (argv_looks_like_help(argc, argv))
646 return help();
647
648 umask(0022);
649
650 return dispatch_verb(strv_skip(argv, 1), /* userdata= */ NULL);
651 }
652
653 DEFINE_MAIN_FUNCTION(run);