1:255.13-alt1
[systemd_ALT.git] / src / backlight / backlight.c
blobb2032adaa50fc017d67312e8043d8cfb7cf8a2c4
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <sys/stat.h>
4 #include <sys/types.h>
5 #include <unistd.h>
7 #include "sd-device.h"
9 #include "alloc-util.h"
10 #include "device-util.h"
11 #include "escape.h"
12 #include "fileio.h"
13 #include "main-func.h"
14 #include "mkdir.h"
15 #include "parse-util.h"
16 #include "percent-util.h"
17 #include "pretty-print.h"
18 #include "process-util.h"
19 #include "reboot-util.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "terminal-util.h"
24 #define PCI_CLASS_GRAPHICS_CARD 0x30000
26 static int help(void) {
27 _cleanup_free_ char *link = NULL;
28 int r;
30 r = terminal_urlify_man("systemd-backlight", "8", &link);
31 if (r < 0)
32 return log_oom();
34 printf("%s save [backlight|leds]:DEVICE\n"
35 "%s load [backlight|leds]:DEVICE\n"
36 "\n%sSave and restore backlight brightness at shutdown and boot.%s\n\n"
37 " save Save current brightness\n"
38 " load Set brightness to be the previously saved value\n"
39 "\nSee the %s for details.\n",
40 program_invocation_short_name,
41 program_invocation_short_name,
42 ansi_highlight(),
43 ansi_normal(),
44 link);
46 return 0;
49 static int has_multiple_graphics_cards(void) {
50 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
51 bool found = false;
52 int r;
54 r = sd_device_enumerator_new(&e);
55 if (r < 0)
56 return r;
58 r = sd_device_enumerator_allow_uninitialized(e);
59 if (r < 0)
60 return r;
62 r = sd_device_enumerator_add_match_subsystem(e, "pci", /* match = */ true);
63 if (r < 0)
64 return r;
66 /* class is an unsigned number, let's validate the value later. */
67 r = sd_device_enumerator_add_match_sysattr(e, "class", NULL, /* match = */ true);
68 if (r < 0)
69 return r;
71 FOREACH_DEVICE(e, dev) {
72 const char *s;
73 unsigned long c;
75 if (sd_device_get_sysattr_value(dev, "class", &s) < 0)
76 continue;
78 if (safe_atolu(s, &c) < 0)
79 continue;
81 if (c != PCI_CLASS_GRAPHICS_CARD)
82 continue;
84 if (found)
85 return true; /* This is the second device. */
87 found = true; /* Found the first device. */
90 return false;
93 static int find_pci_or_platform_parent(sd_device *device, sd_device **ret) {
94 const char *subsystem, *sysname, *value;
95 sd_device *parent;
96 int r;
98 assert(device);
99 assert(ret);
101 r = sd_device_get_parent(device, &parent);
102 if (r < 0)
103 return r;
105 r = sd_device_get_subsystem(parent, &subsystem);
106 if (r < 0)
107 return r;
109 r = sd_device_get_sysname(parent, &sysname);
110 if (r < 0)
111 return r;
113 if (streq(subsystem, "drm")) {
114 const char *c;
116 c = startswith(sysname, "card");
117 if (!c)
118 return -ENODATA;
120 c += strspn(c, DIGITS);
121 if (*c == '-' && !STARTSWITH_SET(c, "-LVDS-", "-Embedded DisplayPort-", "-eDP-"))
122 /* A connector DRM device, let's ignore all but LVDS and eDP! */
123 return -EOPNOTSUPP;
125 } else if (streq(subsystem, "pci") &&
126 sd_device_get_sysattr_value(parent, "class", &value) >= 0) {
127 unsigned long class;
129 r = safe_atolu(value, &class);
130 if (r < 0)
131 return log_warning_errno(r, "Cannot parse PCI class '%s' of device %s:%s: %m",
132 value, subsystem, sysname);
134 /* Graphics card */
135 if (class == PCI_CLASS_GRAPHICS_CARD) {
136 *ret = parent;
137 return 0;
140 } else if (streq(subsystem, "platform")) {
141 *ret = parent;
142 return 0;
145 return find_pci_or_platform_parent(parent, ret);
148 static int same_device(sd_device *a, sd_device *b) {
149 const char *a_val, *b_val;
150 int r;
152 assert(a);
153 assert(b);
155 r = sd_device_get_subsystem(a, &a_val);
156 if (r < 0)
157 return r;
159 r = sd_device_get_subsystem(b, &b_val);
160 if (r < 0)
161 return r;
163 if (!streq(a_val, b_val))
164 return false;
166 r = sd_device_get_sysname(a, &a_val);
167 if (r < 0)
168 return r;
170 r = sd_device_get_sysname(b, &b_val);
171 if (r < 0)
172 return r;
174 return streq(a_val, b_val);
177 static int validate_device(sd_device *device) {
178 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *enumerate = NULL;
179 const char *v, *sysname, *subsystem;
180 sd_device *parent;
181 int r;
183 assert(device);
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. */
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");
198 r = sd_device_get_subsystem(device, &subsystem);
199 if (r < 0)
200 return log_device_debug_errno(device, r, "Failed to get subsystem: %m");
201 if (!streq(subsystem, "backlight"))
202 return true;
204 r = sd_device_get_sysattr_value(device, "type", &v);
205 if (r < 0)
206 return log_device_debug_errno(device, r, "Failed to read 'type' sysattr: %m");
207 if (!streq(v, "raw"))
208 return true;
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");
214 r = sd_device_get_subsystem(parent, &subsystem);
215 if (r < 0)
216 return log_device_debug_errno(parent, r, "Failed to get subsystem: %m");
218 if (DEBUG_LOGGING) {
219 const char *s = NULL;
221 (void) sd_device_get_syspath(parent, &s);
222 log_device_debug(device, "Found %s parent device: %s", subsystem, strna(s));
225 r = sd_device_enumerator_new(&enumerate);
226 if (r < 0)
227 return log_oom_debug();
229 r = sd_device_enumerator_allow_uninitialized(enumerate);
230 if (r < 0)
231 return log_debug_errno(r, "Failed to allow uninitialized devices: %m");
233 r = sd_device_enumerator_add_match_subsystem(enumerate, "backlight", /* match = */ true);
234 if (r < 0)
235 return log_debug_errno(r, "Failed to add subsystem match: %m");
237 r = sd_device_enumerator_add_nomatch_sysname(enumerate, sysname);
238 if (r < 0)
239 return log_debug_errno(r, "Failed to add sysname unmatch: %m");
241 r = sd_device_enumerator_add_match_sysattr(enumerate, "type", "platform", /* match = */ true);
242 if (r < 0)
243 return log_debug_errno(r, "Failed to add sysattr match: %m");
245 r = sd_device_enumerator_add_match_sysattr(enumerate, "type", "firmware", /* match = */ true);
246 if (r < 0)
247 return log_debug_errno(r, "Failed to add sysattr match: %m");
249 if (streq(subsystem, "pci")) {
250 r = has_multiple_graphics_cards();
251 if (r < 0)
252 return log_debug_errno(r, "Failed to check if the system has multiple graphics cards: %m");
253 if (r > 0) {
254 /* If the system has multiple graphics cards, then we cannot associate platform
255 * devices on non-PCI bus (especially WMI bus) with PCI devices. Let's ignore all
256 * backlight devices that do not have the same parent PCI device. */
257 log_debug("Found multiple graphics cards on PCI bus. "
258 "Skipping to associate platform backlight devices on non-PCI bus.");
260 r = sd_device_enumerator_add_match_parent(enumerate, parent);
261 if (r < 0)
262 return log_debug_errno(r, "Failed to add parent match: %m");
266 FOREACH_DEVICE(enumerate, other) {
267 const char *other_subsystem;
268 sd_device *other_parent;
270 /* OK, so there's another backlight device, and it's a platform or firmware device.
271 * Let's see if we can verify it belongs to the same device as ours. */
272 r = find_pci_or_platform_parent(other, &other_parent);
273 if (r < 0) {
274 log_device_debug_errno(other, r, "Failed to get PCI or platform parent, ignoring: %m");
275 continue;
278 if (same_device(parent, other_parent) > 0) {
279 /* Both have the same PCI parent, that means we are out. */
280 if (DEBUG_LOGGING) {
281 const char *other_sysname = NULL, *other_type = NULL;
283 (void) sd_device_get_sysname(other, &other_sysname);
284 (void) sd_device_get_sysattr_value(other, "type", &other_type);
285 log_device_debug(device,
286 "Found another %s backlight device %s on the same PCI, skipping.",
287 strna(other_type), strna(other_sysname));
289 return false;
292 r = sd_device_get_subsystem(other_parent, &other_subsystem);
293 if (r < 0) {
294 log_device_debug_errno(other_parent, r, "Failed to get subsystem, ignoring: %m");
295 continue;
298 if (streq(other_subsystem, "platform") && streq(subsystem, "pci")) {
299 /* The other is connected to the platform bus and we are a PCI device, that also means we are out. */
300 if (DEBUG_LOGGING) {
301 const char *other_sysname = NULL, *other_type = NULL;
303 (void) sd_device_get_sysname(other, &other_sysname);
304 (void) sd_device_get_sysattr_value(other, "type", &other_type);
305 log_device_debug(device,
306 "Found another %s backlight device %s, which has higher precedence, skipping.",
307 strna(other_type), strna(other_sysname));
309 return false;
313 return true;
316 static int get_max_brightness(sd_device *device, unsigned *ret) {
317 const char *s;
318 int r;
320 assert(device);
321 assert(ret);
323 r = sd_device_get_sysattr_value(device, "max_brightness", &s);
324 if (r < 0)
325 return log_device_warning_errno(device, r, "Failed to read 'max_brightness' attribute: %m");
327 r = safe_atou(s, ret);
328 if (r < 0)
329 return log_device_warning_errno(device, r, "Failed to parse 'max_brightness' \"%s\": %m", s);
331 return 0;
334 static int clamp_brightness(
335 sd_device *device,
336 unsigned percent,
337 bool saved,
338 unsigned max_brightness,
339 unsigned *brightness) {
341 unsigned new_brightness, min_brightness;
342 const char *subsystem;
343 int r;
345 assert(device);
346 assert(brightness);
348 /* Some systems turn the backlight all the way off at the lowest levels. This clamps the saved
349 * brightness to at least 1 or 5% of max_brightness in case of 'backlight' subsystem. This
350 * avoids preserving an unreadably dim screen, which would otherwise force the user to disable
351 * state restoration. */
353 r = sd_device_get_subsystem(device, &subsystem);
354 if (r < 0)
355 return log_device_warning_errno(device, r, "Failed to get device subsystem: %m");
357 if (streq(subsystem, "backlight"))
358 min_brightness = MAX(1U, (unsigned) ((double) max_brightness * percent / 100));
359 else
360 min_brightness = 0;
362 new_brightness = CLAMP(*brightness, min_brightness, max_brightness);
363 if (new_brightness != *brightness)
364 log_device_info(device, "%s brightness %u is %s to %u.",
365 saved ? "Saved" : "Current",
366 *brightness,
367 new_brightness > *brightness ?
368 "too low; increasing" : "too high; decreasing",
369 new_brightness);
371 *brightness = new_brightness;
372 return 0;
375 static bool shall_clamp(sd_device *d, unsigned *ret) {
376 const char *s;
377 int r;
379 assert(d);
380 assert(ret);
382 r = sd_device_get_property_value(d, "ID_BACKLIGHT_CLAMP", &s);
383 if (r < 0) {
384 if (r != -ENOENT)
385 log_device_debug_errno(d, r, "Failed to get ID_BACKLIGHT_CLAMP property, ignoring: %m");
386 *ret = 5; /* defaults to 5% */
387 return true;
390 r = parse_boolean(s);
391 if (r >= 0) {
392 *ret = r ? 5 : 0;
393 return r;
396 r = parse_percent(s);
397 if (r < 0) {
398 log_device_debug_errno(d, r, "Failed to parse ID_BACKLIGHT_CLAMP property, ignoring: %m");
399 *ret = 5;
400 return true;
403 *ret = r;
404 return true;
407 static int read_brightness(sd_device *device, unsigned max_brightness, unsigned *ret_brightness) {
408 const char *subsystem, *value;
409 unsigned brightness;
410 int r;
412 assert(device);
413 assert(ret_brightness);
415 r = sd_device_get_subsystem(device, &subsystem);
416 if (r < 0)
417 return log_device_debug_errno(device, r, "Failed to get subsystem: %m");
419 if (streq(subsystem, "backlight")) {
420 r = sd_device_get_sysattr_value(device, "actual_brightness", &value);
421 if (r == -ENOENT) {
422 log_device_debug_errno(device, r, "Failed to read 'actual_brightness' attribute, "
423 "fall back to use 'brightness' attribute: %m");
424 goto use_brightness;
426 if (r < 0)
427 return log_device_debug_errno(device, r, "Failed to read 'actual_brightness' attribute: %m");
429 r = safe_atou(value, &brightness);
430 if (r < 0) {
431 log_device_debug_errno(device, r, "Failed to parse 'actual_brightness' attribute, "
432 "fall back to use 'brightness' attribute: %s", value);
433 goto use_brightness;
436 if (brightness > max_brightness) {
437 log_device_debug(device, "actual_brightness=%u is larger than max_brightness=%u, "
438 "fall back to use 'brightness' attribute", brightness, max_brightness);
439 goto use_brightness;
442 log_device_debug(device, "Current actual_brightness is %u", brightness);
443 *ret_brightness = brightness;
444 return 0;
447 use_brightness:
448 r = sd_device_get_sysattr_value(device, "brightness", &value);
449 if (r < 0)
450 return log_device_debug_errno(device, r, "Failed to read 'brightness' attribute: %m");
452 r = safe_atou(value, &brightness);
453 if (r < 0)
454 return log_device_debug_errno(device, r, "Failed to parse 'brightness' attribute: %s", value);
456 if (brightness > max_brightness)
457 return log_device_debug_errno(device, SYNTHETIC_ERRNO(EINVAL),
458 "brightness=%u is larger than max_brightness=%u",
459 brightness, max_brightness);
461 log_device_debug(device, "Current brightness is %u", brightness);
462 *ret_brightness = brightness;
463 return 0;
466 static int run(int argc, char *argv[]) {
467 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
468 _cleanup_free_ char *escaped_ss = NULL, *escaped_sysname = NULL, *escaped_path_id = NULL;
469 const char *sysname, *path_id, *ss, *saved;
470 unsigned max_brightness, brightness;
471 int r;
473 log_setup();
475 if (argv_looks_like_help(argc, argv))
476 return help();
478 if (argc != 3)
479 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires two arguments.");
481 if (!STR_IN_SET(argv[1], "load", "save"))
482 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", argv[1]);
484 umask(0022);
486 r = mkdir_p("/var/lib/systemd/backlight", 0755);
487 if (r < 0)
488 return log_error_errno(r, "Failed to create backlight directory /var/lib/systemd/backlight: %m");
490 sysname = strchr(argv[2], ':');
491 if (!sysname)
492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Requires a subsystem and sysname pair specifying a backlight device.");
494 ss = strndupa_safe(argv[2], sysname - argv[2]);
496 sysname++;
498 if (!STR_IN_SET(ss, "backlight", "leds"))
499 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a backlight or LED device: '%s:%s'", ss, sysname);
501 r = sd_device_new_from_subsystem_sysname(&device, ss, sysname);
502 if (r < 0) {
503 bool ignore = r == -ENODEV;
505 /* Some drivers, e.g. for AMD GPU, removes acpi backlight device soon after it is added.
506 * See issue #21997. */
507 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r,
508 "Failed to get backlight or LED device '%s:%s'%s: %m",
509 ss, sysname, ignore ? ", ignoring" : "");
510 return ignore ? 0 : r;
513 /* If max_brightness is 0, then there is no actual backlight device. This happens on desktops
514 * with Asus mainboards that load the eeepc-wmi module. */
515 if (get_max_brightness(device, &max_brightness) < 0)
516 return 0;
518 if (max_brightness == 0) {
519 log_device_warning(device, "Maximum brightness is 0, ignoring device.");
520 return 0;
523 log_device_debug(device, "Maximum brightness is %u", max_brightness);
525 escaped_ss = cescape(ss);
526 if (!escaped_ss)
527 return log_oom();
529 escaped_sysname = cescape(sysname);
530 if (!escaped_sysname)
531 return log_oom();
533 if (sd_device_get_property_value(device, "ID_PATH", &path_id) >= 0) {
534 escaped_path_id = cescape(path_id);
535 if (!escaped_path_id)
536 return log_oom();
538 saved = strjoina("/var/lib/systemd/backlight/", escaped_path_id, ":", escaped_ss, ":", escaped_sysname);
539 } else
540 saved = strjoina("/var/lib/systemd/backlight/", escaped_ss, ":", escaped_sysname);
542 /* If there are multiple conflicting backlight devices, then their probing at boot-time might
543 * happen in any order. This means the validity checking of the device then is not reliable,
544 * since it might not see other devices conflicting with a specific backlight. To deal with
545 * this, we will actively delete backlight state files at shutdown (where device probing should
546 * be complete), so that the validity check at boot time doesn't have to be reliable. */
548 if (streq(argv[1], "load")) {
549 _cleanup_free_ char *value = NULL;
550 unsigned percent;
551 bool clamp;
553 if (!shall_restore_state())
554 return 0;
556 if (validate_device(device) == 0)
557 return 0;
559 clamp = shall_clamp(device, &percent);
561 r = read_one_line_file(saved, &value);
562 if (r < 0 && r != -ENOENT)
563 return log_error_errno(r, "Failed to read %s: %m", saved);
564 if (r > 0) {
565 r = safe_atou(value, &brightness);
566 if (r < 0) {
567 log_warning_errno(r, "Failed to parse saved brightness '%s', removing %s.",
568 value, saved);
569 (void) unlink(saved);
570 } else {
571 log_debug("Using saved brightness %u.", brightness);
572 if (clamp)
573 (void) clamp_brightness(device, percent, /* saved = */ true, max_brightness, &brightness);
575 /* Do not fall back to read current brightness below. */
576 r = 1;
579 if (r <= 0) {
580 /* Fallback to clamping current brightness or exit early if clamping is not
581 * supported/enabled. */
582 if (!clamp)
583 return 0;
585 r = read_brightness(device, max_brightness, &brightness);
586 if (r < 0)
587 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
589 (void) clamp_brightness(device, percent, /* saved = */ false, max_brightness, &brightness);
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");
596 } else if (streq(argv[1], "save")) {
597 if (validate_device(device) == 0) {
598 (void) unlink(saved);
599 return 0;
602 r = read_brightness(device, max_brightness, &brightness);
603 if (r < 0)
604 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
606 r = write_string_filef(saved, WRITE_STRING_FILE_CREATE, "%u", brightness);
607 if (r < 0)
608 return log_device_error_errno(device, r, "Failed to write %s: %m", saved);
610 } else
611 assert_not_reached();
613 return 0;
616 DEFINE_MAIN_FUNCTION(run);