]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/backlight/backlight.c
Merge pull request #8575 from keszybz/non-absolute-paths
[thirdparty/systemd.git] / src / backlight / backlight.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2013 Lennart Poettering
6 ***/
7
8 #include "libudev.h"
9
10 #include "alloc-util.h"
11 #include "def.h"
12 #include "escape.h"
13 #include "fileio.h"
14 #include "mkdir.h"
15 #include "parse-util.h"
16 #include "proc-cmdline.h"
17 #include "string-util.h"
18 #include "udev-util.h"
19 #include "util.h"
20
21 static struct udev_device *find_pci_or_platform_parent(struct udev_device *device) {
22 struct udev_device *parent;
23 const char *subsystem, *sysname;
24
25 assert(device);
26
27 parent = udev_device_get_parent(device);
28 if (!parent)
29 return NULL;
30
31 subsystem = udev_device_get_subsystem(parent);
32 if (!subsystem)
33 return NULL;
34
35 sysname = udev_device_get_sysname(parent);
36 if (!sysname)
37 return NULL;
38
39 if (streq(subsystem, "drm")) {
40 const char *c;
41
42 c = startswith(sysname, "card");
43 if (!c)
44 return NULL;
45
46 c += strspn(c, DIGITS);
47 if (*c == '-') {
48 /* A connector DRM device, let's ignore all but LVDS and eDP! */
49
50 if (!startswith(c, "-LVDS-") &&
51 !startswith(c, "-Embedded DisplayPort-"))
52 return NULL;
53 }
54
55 } else if (streq(subsystem, "pci")) {
56 const char *value;
57
58 value = udev_device_get_sysattr_value(parent, "class");
59 if (value) {
60 unsigned long class = 0;
61
62 if (safe_atolu(value, &class) < 0) {
63 log_warning("Cannot parse PCI class %s of device %s:%s.",
64 value, subsystem, sysname);
65 return NULL;
66 }
67
68 /* Graphics card */
69 if (class == 0x30000)
70 return parent;
71 }
72
73 } else if (streq(subsystem, "platform"))
74 return parent;
75
76 return find_pci_or_platform_parent(parent);
77 }
78
79 static bool same_device(struct udev_device *a, struct udev_device *b) {
80 assert(a);
81 assert(b);
82
83 if (!streq_ptr(udev_device_get_subsystem(a), udev_device_get_subsystem(b)))
84 return false;
85
86 if (!streq_ptr(udev_device_get_sysname(a), udev_device_get_sysname(b)))
87 return false;
88
89 return true;
90 }
91
92 static bool validate_device(struct udev *udev, struct udev_device *device) {
93 _cleanup_udev_enumerate_unref_ struct udev_enumerate *enumerate = NULL;
94 struct udev_list_entry *item = NULL, *first = NULL;
95 struct udev_device *parent;
96 const char *v, *subsystem;
97 int r;
98
99 assert(udev);
100 assert(device);
101
102 /* Verify whether we should actually care for a specific
103 * backlight device. For backlight devices there might be
104 * multiple ways to access the same control: "firmware"
105 * (i.e. ACPI), "platform" (i.e. via the machine's EC) and
106 * "raw" (via the graphics card). In general we should prefer
107 * "firmware" (i.e. ACPI) or "platform" access over "raw"
108 * access, in order not to confuse the BIOS/EC, and
109 * compatibility with possible low-level hotkey handling of
110 * screen brightness. The kernel will already make sure to
111 * expose only one of "firmware" and "platform" for the same
112 * device to userspace. However, we still need to make sure
113 * that we use "raw" only if no "firmware" or "platform"
114 * device for the same device exists. */
115
116 subsystem = udev_device_get_subsystem(device);
117 if (!streq_ptr(subsystem, "backlight"))
118 return true;
119
120 v = udev_device_get_sysattr_value(device, "type");
121 if (!streq_ptr(v, "raw"))
122 return true;
123
124 parent = find_pci_or_platform_parent(device);
125 if (!parent)
126 return true;
127
128 subsystem = udev_device_get_subsystem(parent);
129 if (!subsystem)
130 return true;
131
132 enumerate = udev_enumerate_new(udev);
133 if (!enumerate)
134 return true;
135
136 r = udev_enumerate_add_match_subsystem(enumerate, "backlight");
137 if (r < 0)
138 return true;
139
140 r = udev_enumerate_scan_devices(enumerate);
141 if (r < 0)
142 return true;
143
144 first = udev_enumerate_get_list_entry(enumerate);
145 udev_list_entry_foreach(item, first) {
146 _cleanup_udev_device_unref_ struct udev_device *other;
147 struct udev_device *other_parent;
148 const char *other_subsystem;
149
150 other = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
151 if (!other)
152 return true;
153
154 if (same_device(device, other))
155 continue;
156
157 v = udev_device_get_sysattr_value(other, "type");
158 if (!STRPTR_IN_SET(v, "platform", "firmware"))
159 continue;
160
161 /* OK, so there's another backlight device, and it's a
162 * platform or firmware device, so, let's see if we
163 * can verify it belongs to the same device as
164 * ours. */
165 other_parent = find_pci_or_platform_parent(other);
166 if (!other_parent)
167 continue;
168
169 if (same_device(parent, other_parent)) {
170 /* Both have the same PCI parent, that means
171 * we are out. */
172 log_debug("Skipping backlight device %s, since device %s is on same PCI device and takes precedence.",
173 udev_device_get_sysname(device),
174 udev_device_get_sysname(other));
175 return false;
176 }
177
178 other_subsystem = udev_device_get_subsystem(other_parent);
179 if (streq_ptr(other_subsystem, "platform") && streq_ptr(subsystem, "pci")) {
180 /* The other is connected to the platform bus
181 * and we are a PCI device, that also means we
182 * are out. */
183 log_debug("Skipping backlight device %s, since device %s is a platform device and takes precedence.",
184 udev_device_get_sysname(device),
185 udev_device_get_sysname(other));
186 return false;
187 }
188 }
189
190 return true;
191 }
192
193 static unsigned get_max_brightness(struct udev_device *device) {
194 int r;
195 const char *max_brightness_str;
196 unsigned max_brightness;
197
198 max_brightness_str = udev_device_get_sysattr_value(device, "max_brightness");
199 if (!max_brightness_str) {
200 log_warning("Failed to read 'max_brightness' attribute.");
201 return 0;
202 }
203
204 r = safe_atou(max_brightness_str, &max_brightness);
205 if (r < 0) {
206 log_warning_errno(r, "Failed to parse 'max_brightness' \"%s\": %m", max_brightness_str);
207 return 0;
208 }
209
210 if (max_brightness <= 0) {
211 log_warning("Maximum brightness is 0, ignoring device.");
212 return 0;
213 }
214
215 return max_brightness;
216 }
217
218 /* Some systems turn the backlight all the way off at the lowest levels.
219 * clamp_brightness clamps the saved brightness to at least 1 or 5% of
220 * max_brightness in case of 'backlight' subsystem. This avoids preserving
221 * an unreadably dim screen, which would otherwise force the user to
222 * disable state restoration. */
223 static void clamp_brightness(struct udev_device *device, char **value, unsigned max_brightness) {
224 unsigned brightness, new_brightness, min_brightness;
225 const char *subsystem;
226 int r;
227
228 r = safe_atou(*value, &brightness);
229 if (r < 0) {
230 log_warning_errno(r, "Failed to parse brightness \"%s\": %m", *value);
231 return;
232 }
233
234 subsystem = udev_device_get_subsystem(device);
235 if (streq_ptr(subsystem, "backlight"))
236 min_brightness = MAX(1U, max_brightness/20);
237 else
238 min_brightness = 0;
239
240 new_brightness = CLAMP(brightness, min_brightness, max_brightness);
241 if (new_brightness != brightness) {
242 char *old_value = *value;
243
244 r = asprintf(value, "%u", new_brightness);
245 if (r < 0) {
246 log_oom();
247 return;
248 }
249
250 log_info("Saved brightness %s %s to %s.", old_value,
251 new_brightness > brightness ?
252 "too low; increasing" : "too high; decreasing",
253 *value);
254
255 free(old_value);
256 }
257 }
258
259 static bool shall_clamp(struct udev_device *d) {
260 const char *s;
261 int r;
262
263 assert(d);
264
265 s = udev_device_get_property_value(d, "ID_BACKLIGHT_CLAMP");
266 if (!s)
267 return true;
268
269 r = parse_boolean(s);
270 if (r < 0) {
271 log_debug_errno(r, "Failed to parse ID_BACKLIGHT_CLAMP property, ignoring: %m");
272 return true;
273 }
274
275 return r;
276 }
277
278 int main(int argc, char *argv[]) {
279 _cleanup_udev_unref_ struct udev *udev = NULL;
280 _cleanup_udev_device_unref_ struct udev_device *device = NULL;
281 _cleanup_free_ char *escaped_ss = NULL, *escaped_sysname = NULL, *escaped_path_id = NULL;
282 const char *sysname, *path_id, *ss, *saved;
283 unsigned max_brightness;
284 int r;
285
286 if (argc != 3) {
287 log_error("This program requires two arguments.");
288 return EXIT_FAILURE;
289 }
290
291 log_set_target(LOG_TARGET_AUTO);
292 log_parse_environment();
293 log_open();
294
295 umask(0022);
296
297 r = mkdir_p("/var/lib/systemd/backlight", 0755);
298 if (r < 0) {
299 log_error_errno(r, "Failed to create backlight directory /var/lib/systemd/backlight: %m");
300 return EXIT_FAILURE;
301 }
302
303 udev = udev_new();
304 if (!udev) {
305 log_oom();
306 return EXIT_FAILURE;
307 }
308
309 sysname = strchr(argv[2], ':');
310 if (!sysname) {
311 log_error("Requires a subsystem and sysname pair specifying a backlight device.");
312 return EXIT_FAILURE;
313 }
314
315 ss = strndupa(argv[2], sysname - argv[2]);
316
317 sysname++;
318
319 if (!STR_IN_SET(ss, "backlight", "leds")) {
320 log_error("Not a backlight or LED device: '%s:%s'", ss, sysname);
321 return EXIT_FAILURE;
322 }
323
324 errno = 0;
325 device = udev_device_new_from_subsystem_sysname(udev, ss, sysname);
326 if (!device) {
327 if (errno > 0)
328 log_error_errno(errno, "Failed to get backlight or LED device '%s:%s': %m", ss, sysname);
329 else
330 log_oom();
331
332 return EXIT_FAILURE;
333 }
334
335 /* If max_brightness is 0, then there is no actual backlight
336 * device. This happens on desktops with Asus mainboards
337 * that load the eeepc-wmi module.
338 */
339 max_brightness = get_max_brightness(device);
340 if (max_brightness == 0)
341 return EXIT_SUCCESS;
342
343 escaped_ss = cescape(ss);
344 if (!escaped_ss) {
345 log_oom();
346 return EXIT_FAILURE;
347 }
348
349 escaped_sysname = cescape(sysname);
350 if (!escaped_sysname) {
351 log_oom();
352 return EXIT_FAILURE;
353 }
354
355 path_id = udev_device_get_property_value(device, "ID_PATH");
356 if (path_id) {
357 escaped_path_id = cescape(path_id);
358 if (!escaped_path_id) {
359 log_oom();
360 return EXIT_FAILURE;
361 }
362
363 saved = strjoina("/var/lib/systemd/backlight/", escaped_path_id, ":", escaped_ss, ":", escaped_sysname);
364 } else
365 saved = strjoina("/var/lib/systemd/backlight/", escaped_ss, ":", escaped_sysname);
366
367 /* If there are multiple conflicting backlight devices, then
368 * their probing at boot-time might happen in any order. This
369 * means the validity checking of the device then is not
370 * reliable, since it might not see other devices conflicting
371 * with a specific backlight. To deal with this, we will
372 * actively delete backlight state files at shutdown (where
373 * device probing should be complete), so that the validity
374 * check at boot time doesn't have to be reliable. */
375
376 if (streq(argv[1], "load")) {
377 _cleanup_free_ char *value = NULL;
378 bool clamp;
379
380 if (shall_restore_state() == 0)
381 return EXIT_SUCCESS;
382
383 if (!validate_device(udev, device))
384 return EXIT_SUCCESS;
385
386 clamp = shall_clamp(device);
387
388 r = read_one_line_file(saved, &value);
389 if (r == -ENOENT) {
390 const char *curval;
391
392 /* Fallback to clamping current brightness or exit early if
393 * clamping is not supported/enabled. */
394 if (!clamp)
395 return EXIT_SUCCESS;
396
397 curval = udev_device_get_sysattr_value(device, "brightness");
398 if (!curval) {
399 log_warning("Failed to read 'brightness' attribute.");
400 return EXIT_FAILURE;
401 }
402
403 value = strdup(curval);
404 if (!value) {
405 log_oom();
406 return EXIT_FAILURE;
407 }
408 } else if (r < 0) {
409 log_error_errno(r, "Failed to read %s: %m", saved);
410 return EXIT_FAILURE;
411 }
412
413 if (clamp)
414 clamp_brightness(device, &value, max_brightness);
415
416 r = udev_device_set_sysattr_value(device, "brightness", value);
417 if (r < 0) {
418 log_error_errno(r, "Failed to write system 'brightness' attribute: %m");
419 return EXIT_FAILURE;
420 }
421
422 } else if (streq(argv[1], "save")) {
423 const char *value;
424
425 if (!validate_device(udev, device)) {
426 unlink(saved);
427 return EXIT_SUCCESS;
428 }
429
430 value = udev_device_get_sysattr_value(device, "brightness");
431 if (!value) {
432 log_error("Failed to read system 'brightness' attribute");
433 return EXIT_FAILURE;
434 }
435
436 r = write_string_file(saved, value, WRITE_STRING_FILE_CREATE);
437 if (r < 0) {
438 log_error_errno(r, "Failed to write %s: %m", saved);
439 return EXIT_FAILURE;
440 }
441
442 } else {
443 log_error("Unknown verb %s.", argv[1]);
444 return EXIT_FAILURE;
445 }
446
447 return EXIT_SUCCESS;
448 }