]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/backlight/backlight.c
man/html: fix invocation for pages which are *not* symlinks
[thirdparty/systemd.git] / src / backlight / backlight.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <sys/stat.h>
4 #include <sys/types.h>
5 #include <unistd.h>
6
7 #include "sd-device.h"
8
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 "pretty-print.h"
17 #include "terminal-util.h"
18 #include "reboot-util.h"
19 #include "string-util.h"
20 #include "strv.h"
21 #include "util.h"
22
23 static int help(void) {
24 _cleanup_free_ char *link = NULL;
25 int r;
26
27 r = terminal_urlify_man("systemd-backlight", "8", &link);
28 if (r < 0)
29 return log_oom();
30
31 printf("%s save [backlight|leds]:DEVICE\n"
32 "%s load [backlight|leds]:DEVICE\n"
33 "\n%sSave and restore backlight brightness at shutdown and boot.%s\n\n"
34 " save Save current brightness\n"
35 " load Set brightness to be the previously saved value\n"
36 "\nSee the %s for details.\n"
37 , program_invocation_short_name
38 , program_invocation_short_name
39 , ansi_highlight(), ansi_normal()
40 , link
41 );
42
43 return 0;
44 }
45
46 static int find_pci_or_platform_parent(sd_device *device, sd_device **ret) {
47 const char *subsystem, *sysname, *value;
48 sd_device *parent;
49 int r;
50
51 assert(device);
52 assert(ret);
53
54 r = sd_device_get_parent(device, &parent);
55 if (r < 0)
56 return r;
57
58 r = sd_device_get_subsystem(parent, &subsystem);
59 if (r < 0)
60 return r;
61
62 r = sd_device_get_sysname(parent, &sysname);
63 if (r < 0)
64 return r;
65
66 if (streq(subsystem, "drm")) {
67 const char *c;
68
69 c = startswith(sysname, "card");
70 if (!c)
71 return -ENODATA;
72
73 c += strspn(c, DIGITS);
74 if (*c == '-') {
75 /* A connector DRM device, let's ignore all but LVDS and eDP! */
76 if (!STARTSWITH_SET(c, "-LVDS-", "-Embedded DisplayPort-"))
77 return -EOPNOTSUPP;
78 }
79
80 } else if (streq(subsystem, "pci") &&
81 sd_device_get_sysattr_value(parent, "class", &value) >= 0) {
82 unsigned long class;
83
84 r = safe_atolu(value, &class);
85 if (r < 0)
86 return log_warning_errno(r, "Cannot parse PCI class '%s' of device %s:%s: %m",
87 value, subsystem, sysname);
88
89 /* Graphics card */
90 if (class == 0x30000) {
91 *ret = parent;
92 return 0;
93 }
94
95 } else if (streq(subsystem, "platform")) {
96 *ret = parent;
97 return 0;
98 }
99
100 return find_pci_or_platform_parent(parent, ret);
101 }
102
103 static int same_device(sd_device *a, sd_device *b) {
104 const char *a_val, *b_val;
105 int r;
106
107 assert(a);
108 assert(b);
109
110 r = sd_device_get_subsystem(a, &a_val);
111 if (r < 0)
112 return r;
113
114 r = sd_device_get_subsystem(b, &b_val);
115 if (r < 0)
116 return r;
117
118 if (!streq(a_val, b_val))
119 return false;
120
121 r = sd_device_get_sysname(a, &a_val);
122 if (r < 0)
123 return r;
124
125 r = sd_device_get_sysname(b, &b_val);
126 if (r < 0)
127 return r;
128
129 return streq(a_val, b_val);
130 }
131
132 static int validate_device(sd_device *device) {
133 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *enumerate = NULL;
134 const char *v, *subsystem;
135 sd_device *parent, *other;
136 int r;
137
138 assert(device);
139
140 /* Verify whether we should actually care for a specific
141 * backlight device. For backlight devices there might be
142 * multiple ways to access the same control: "firmware"
143 * (i.e. ACPI), "platform" (i.e. via the machine's EC) and
144 * "raw" (via the graphics card). In general we should prefer
145 * "firmware" (i.e. ACPI) or "platform" access over "raw"
146 * access, in order not to confuse the BIOS/EC, and
147 * compatibility with possible low-level hotkey handling of
148 * screen brightness. The kernel will already make sure to
149 * expose only one of "firmware" and "platform" for the same
150 * device to userspace. However, we still need to make sure
151 * that we use "raw" only if no "firmware" or "platform"
152 * device for the same device exists. */
153
154 r = sd_device_get_subsystem(device, &subsystem);
155 if (r < 0)
156 return r;
157 if (!streq(subsystem, "backlight"))
158 return true;
159
160 r = sd_device_get_sysattr_value(device, "type", &v);
161 if (r < 0)
162 return r;
163 if (!streq(v, "raw"))
164 return true;
165
166 r = find_pci_or_platform_parent(device, &parent);
167 if (r < 0)
168 return r;
169
170 r = sd_device_get_subsystem(parent, &subsystem);
171 if (r < 0)
172 return r;
173
174 r = sd_device_enumerator_new(&enumerate);
175 if (r < 0)
176 return r;
177
178 r = sd_device_enumerator_allow_uninitialized(enumerate);
179 if (r < 0)
180 return r;
181
182 r = sd_device_enumerator_add_match_subsystem(enumerate, "backlight", true);
183 if (r < 0)
184 return r;
185
186 FOREACH_DEVICE(enumerate, other) {
187 const char *other_subsystem;
188 sd_device *other_parent;
189
190 if (same_device(device, other) > 0)
191 continue;
192
193 if (sd_device_get_sysattr_value(other, "type", &v) < 0 ||
194 !STR_IN_SET(v, "platform", "firmware"))
195 continue;
196
197 /* OK, so there's another backlight device, and it's a
198 * platform or firmware device, so, let's see if we
199 * can verify it belongs to the same device as ours. */
200 if (find_pci_or_platform_parent(other, &other_parent) < 0)
201 continue;
202
203 if (same_device(parent, other_parent)) {
204 const char *device_sysname = NULL, *other_sysname = NULL;
205
206 /* Both have the same PCI parent, that means we are out. */
207
208 (void) sd_device_get_sysname(device, &device_sysname);
209 (void) sd_device_get_sysname(other, &other_sysname);
210
211 log_debug("Skipping backlight device %s, since device %s is on same PCI device and takes precedence.",
212 device_sysname, other_sysname);
213 return false;
214 }
215
216 if (sd_device_get_subsystem(other_parent, &other_subsystem) < 0)
217 continue;
218
219 if (streq(other_subsystem, "platform") && streq(subsystem, "pci")) {
220 const char *device_sysname = NULL, *other_sysname = NULL;
221
222 /* The other is connected to the platform bus and we are a PCI device, that also means we are out. */
223
224 (void) sd_device_get_sysname(device, &device_sysname);
225 (void) sd_device_get_sysname(other, &other_sysname);
226
227 log_debug("Skipping backlight device %s, since device %s is a platform device and takes precedence.",
228 device_sysname, other_sysname);
229 return false;
230 }
231 }
232
233 return true;
234 }
235
236 static int get_max_brightness(sd_device *device, unsigned *ret) {
237 const char *max_brightness_str;
238 unsigned max_brightness;
239 int r;
240
241 assert(device);
242 assert(ret);
243
244 r = sd_device_get_sysattr_value(device, "max_brightness", &max_brightness_str);
245 if (r < 0)
246 return log_device_warning_errno(device, r, "Failed to read 'max_brightness' attribute: %m");
247
248 r = safe_atou(max_brightness_str, &max_brightness);
249 if (r < 0)
250 return log_device_warning_errno(device, r, "Failed to parse 'max_brightness' \"%s\": %m", max_brightness_str);
251
252 if (max_brightness <= 0)
253 return log_device_warning_errno(device, SYNTHETIC_ERRNO(EINVAL), "Maximum brightness is 0, ignoring device.");
254
255 *ret = max_brightness;
256 return 0;
257 }
258
259 /* Some systems turn the backlight all the way off at the lowest levels.
260 * clamp_brightness clamps the saved brightness to at least 1 or 5% of
261 * max_brightness in case of 'backlight' subsystem. This avoids preserving
262 * an unreadably dim screen, which would otherwise force the user to
263 * disable state restoration. */
264 static int clamp_brightness(sd_device *device, bool saved, unsigned max_brightness, unsigned *brightness) {
265 unsigned new_brightness, min_brightness;
266 const char *subsystem;
267 int r;
268
269 assert(device);
270 assert(brightness);
271
272 r = sd_device_get_subsystem(device, &subsystem);
273 if (r < 0)
274 return log_device_warning_errno(device, r, "Failed to get device subsystem: %m");
275
276 if (streq(subsystem, "backlight"))
277 min_brightness = MAX(1U, max_brightness/20);
278 else
279 min_brightness = 0;
280
281 new_brightness = CLAMP(*brightness, min_brightness, max_brightness);
282 if (new_brightness != *brightness)
283 log_device_info(device, "%s brightness %u is %s to %u.",
284 saved ? "Saved" : "Current",
285 *brightness,
286 new_brightness > *brightness ?
287 "too low; increasing" : "too high; decreasing",
288 new_brightness);
289
290 *brightness = new_brightness;
291 return 0;
292 }
293
294 static bool shall_clamp(sd_device *d) {
295 const char *s;
296 int r;
297
298 assert(d);
299
300 r = sd_device_get_property_value(d, "ID_BACKLIGHT_CLAMP", &s);
301 if (r < 0) {
302 if (r != -ENOENT)
303 log_device_debug_errno(d, r, "Failed to get ID_BACKLIGHT_CLAMP property, ignoring: %m");
304 return true;
305 }
306
307 r = parse_boolean(s);
308 if (r < 0) {
309 log_device_debug_errno(d, r, "Failed to parse ID_BACKLIGHT_CLAMP property, ignoring: %m");
310 return true;
311 }
312
313 return r;
314 }
315
316 static int read_brightness(sd_device *device, unsigned max_brightness, unsigned *ret_brightness) {
317 const char *subsystem, *value;
318 unsigned brightness;
319 int r;
320
321 assert(device);
322 assert(ret_brightness);
323
324 r = sd_device_get_subsystem(device, &subsystem);
325 if (r < 0)
326 return log_device_debug_errno(device, r, "Failed to get subsystem: %m");
327
328 if (streq(subsystem, "backlight")) {
329 r = sd_device_get_sysattr_value(device, "actual_brightness", &value);
330 if (r == -ENOENT) {
331 log_device_debug_errno(device, r, "Failed to read 'actual_brightness' attribute, "
332 "fall back to use 'brightness' attribute: %m");
333 goto use_brightness;
334 }
335 if (r < 0)
336 return log_device_debug_errno(device, r, "Failed to read 'actual_brightness' attribute: %m");
337
338 r = safe_atou(value, &brightness);
339 if (r < 0) {
340 log_device_debug_errno(device, r, "Failed to parse 'actual_brightness' attribute, "
341 "fall back to use 'brightness' attribute: %s", value);
342 goto use_brightness;
343 }
344
345 if (brightness > max_brightness) {
346 log_device_debug(device, "actual_brightness=%u is larger than max_brightness=%u, "
347 "fall back to use 'brightness' attribute", brightness, max_brightness);
348 goto use_brightness;
349 }
350
351 *ret_brightness = brightness;
352 return 0;
353 }
354
355 use_brightness:
356 r = sd_device_get_sysattr_value(device, "brightness", &value);
357 if (r < 0)
358 return log_device_debug_errno(device, r, "Failed to read 'brightness' attribute: %m");
359
360 r = safe_atou(value, &brightness);
361 if (r < 0)
362 return log_device_debug_errno(device, r, "Failed to parse 'brightness' attribute: %s", value);
363
364 if (brightness > max_brightness)
365 return log_device_debug_errno(device, SYNTHETIC_ERRNO(EINVAL),
366 "brightness=%u is larger than max_brightness=%u",
367 brightness, max_brightness);
368
369 *ret_brightness = brightness;
370 return 0;
371 }
372
373 static int run(int argc, char *argv[]) {
374 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
375 _cleanup_free_ char *escaped_ss = NULL, *escaped_sysname = NULL, *escaped_path_id = NULL;
376 const char *sysname, *path_id, *ss, *saved;
377 unsigned max_brightness, brightness;
378 int r;
379
380 log_setup_service();
381
382 if (strv_contains(strv_skip(argv, 1), "--help"))
383 return help();
384
385 if (argc != 3)
386 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires two arguments.");
387
388 umask(0022);
389
390 r = mkdir_p("/var/lib/systemd/backlight", 0755);
391 if (r < 0)
392 return log_error_errno(r, "Failed to create backlight directory /var/lib/systemd/backlight: %m");
393
394 sysname = strchr(argv[2], ':');
395 if (!sysname)
396 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Requires a subsystem and sysname pair specifying a backlight device.");
397
398 ss = strndupa(argv[2], sysname - argv[2]);
399
400 sysname++;
401
402 if (!STR_IN_SET(ss, "backlight", "leds"))
403 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a backlight or LED device: '%s:%s'", ss, sysname);
404
405 r = sd_device_new_from_subsystem_sysname(&device, ss, sysname);
406 if (r < 0)
407 return log_error_errno(r, "Failed to get backlight or LED device '%s:%s': %m", ss, sysname);
408
409 /* If max_brightness is 0, then there is no actual backlight
410 * device. This happens on desktops with Asus mainboards
411 * that load the eeepc-wmi module. */
412 if (get_max_brightness(device, &max_brightness) < 0)
413 return 0;
414
415 escaped_ss = cescape(ss);
416 if (!escaped_ss)
417 return log_oom();
418
419 escaped_sysname = cescape(sysname);
420 if (!escaped_sysname)
421 return log_oom();
422
423 if (sd_device_get_property_value(device, "ID_PATH", &path_id) >= 0) {
424 escaped_path_id = cescape(path_id);
425 if (!escaped_path_id)
426 return log_oom();
427
428 saved = strjoina("/var/lib/systemd/backlight/", escaped_path_id, ":", escaped_ss, ":", escaped_sysname);
429 } else
430 saved = strjoina("/var/lib/systemd/backlight/", escaped_ss, ":", escaped_sysname);
431
432 /* If there are multiple conflicting backlight devices, then
433 * their probing at boot-time might happen in any order. This
434 * means the validity checking of the device then is not
435 * reliable, since it might not see other devices conflicting
436 * with a specific backlight. To deal with this, we will
437 * actively delete backlight state files at shutdown (where
438 * device probing should be complete), so that the validity
439 * check at boot time doesn't have to be reliable. */
440
441 if (streq(argv[1], "load")) {
442 _cleanup_free_ char *value = NULL;
443 bool clamp;
444
445 if (shall_restore_state() == 0)
446 return 0;
447
448 if (validate_device(device) == 0)
449 return 0;
450
451 clamp = shall_clamp(device);
452
453 r = read_one_line_file(saved, &value);
454 if (r < 0 && r != -ENOENT)
455 return log_error_errno(r, "Failed to read %s: %m", saved);
456 if (r > 0) {
457 r = safe_atou(value, &brightness);
458 if (r < 0) {
459 log_error_errno(r, "Failed to parse saved brightness '%s', removing %s.",
460 value, saved);
461 (void) unlink(saved);
462 } else {
463 if (clamp)
464 (void) clamp_brightness(device, true, max_brightness, &brightness);
465
466 /* Do not fall back to read current brightness below. */
467 r = 1;
468 }
469 }
470 if (r <= 0) {
471 /* Fallback to clamping current brightness or exit early if clamping is not
472 * supported/enabled. */
473 if (!clamp)
474 return 0;
475
476 r = read_brightness(device, max_brightness, &brightness);
477 if (r < 0)
478 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
479
480 (void) clamp_brightness(device, false, max_brightness, &brightness);
481 }
482
483 r = sd_device_set_sysattr_valuef(device, "brightness", "%u", brightness);
484 if (r < 0)
485 return log_device_error_errno(device, r, "Failed to write system 'brightness' attribute: %m");
486
487 } else if (streq(argv[1], "save")) {
488 if (validate_device(device) == 0) {
489 (void) unlink(saved);
490 return 0;
491 }
492
493 r = read_brightness(device, max_brightness, &brightness);
494 if (r < 0)
495 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
496
497 r = write_string_filef(saved, WRITE_STRING_FILE_CREATE, "%u", brightness);
498 if (r < 0)
499 return log_device_error_errno(device, r, "Failed to write %s: %m", saved);
500
501 } else
502 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", argv[1]);
503
504 return 0;
505 }
506
507 DEFINE_MAIN_FUNCTION(run);