]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/backlight/backlight.c
Merge pull request #16821 from cgzones/selinux_status
[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 = 0;
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, char **value, unsigned max_brightness) {
265 unsigned brightness, new_brightness, min_brightness;
266 const char *subsystem;
267 int r;
268
269 assert(value);
270 assert(*value);
271
272 r = safe_atou(*value, &brightness);
273 if (r < 0)
274 return log_device_warning_errno(device, r, "Failed to parse brightness \"%s\": %m", *value);
275
276 r = sd_device_get_subsystem(device, &subsystem);
277 if (r < 0)
278 return log_device_warning_errno(device, r, "Failed to get device subsystem: %m");
279
280 if (streq(subsystem, "backlight"))
281 min_brightness = MAX(1U, max_brightness/20);
282 else
283 min_brightness = 0;
284
285 new_brightness = CLAMP(brightness, min_brightness, max_brightness);
286 if (new_brightness != brightness) {
287 char *new_value;
288
289 r = asprintf(&new_value, "%u", new_brightness);
290 if (r < 0)
291 return log_oom();
292
293 log_device_info(device, "Saved brightness %s %s to %s.", *value,
294 new_brightness > brightness ?
295 "too low; increasing" : "too high; decreasing",
296 new_value);
297
298 free_and_replace(*value, new_value);
299 }
300
301 return 0;
302 }
303
304 static bool shall_clamp(sd_device *d) {
305 const char *s;
306 int r;
307
308 assert(d);
309
310 r = sd_device_get_property_value(d, "ID_BACKLIGHT_CLAMP", &s);
311 if (r < 0) {
312 log_device_debug_errno(d, r, "Failed to get ID_BACKLIGHT_CLAMP property, ignoring: %m");
313 return true;
314 }
315
316 r = parse_boolean(s);
317 if (r < 0) {
318 log_device_debug_errno(d, r, "Failed to parse ID_BACKLIGHT_CLAMP property, ignoring: %m");
319 return true;
320 }
321
322 return r;
323 }
324
325 static int read_brightness(sd_device *device, const char **ret) {
326 const char *subsystem;
327 int r;
328
329 assert(device);
330 assert(ret);
331
332 r = sd_device_get_subsystem(device, &subsystem);
333 if (r < 0)
334 return log_device_debug_errno(device, r, "Failed to get subsystem: %m");
335
336 if (streq(subsystem, "backlight")) {
337 r = sd_device_get_sysattr_value(device, "actual_brightness", ret);
338 if (r >= 0)
339 return 0;
340 if (r != -ENOENT)
341 return log_device_debug_errno(device, r, "Failed to read 'actual_brightness' attribute: %m");
342
343 log_device_debug_errno(device, r, "Failed to read 'actual_brightness' attribute, fall back to use 'brightness' attribute: %m");
344 }
345
346 r = sd_device_get_sysattr_value(device, "brightness", ret);
347 if (r < 0)
348 return log_device_debug_errno(device, r, "Failed to read 'brightness' attribute: %m");
349
350 return 0;
351 }
352
353 static int run(int argc, char *argv[]) {
354 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
355 _cleanup_free_ char *escaped_ss = NULL, *escaped_sysname = NULL, *escaped_path_id = NULL;
356 const char *sysname, *path_id, *ss, *saved;
357 unsigned max_brightness;
358 int r;
359
360 log_setup_service();
361
362 if (strv_contains(strv_skip(argv, 1), "--help"))
363 return help();
364
365 if (argc != 3)
366 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires two arguments.");
367
368 umask(0022);
369
370 r = mkdir_p("/var/lib/systemd/backlight", 0755);
371 if (r < 0)
372 return log_error_errno(r, "Failed to create backlight directory /var/lib/systemd/backlight: %m");
373
374 sysname = strchr(argv[2], ':');
375 if (!sysname)
376 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Requires a subsystem and sysname pair specifying a backlight device.");
377
378 ss = strndupa(argv[2], sysname - argv[2]);
379
380 sysname++;
381
382 if (!STR_IN_SET(ss, "backlight", "leds"))
383 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a backlight or LED device: '%s:%s'", ss, sysname);
384
385 r = sd_device_new_from_subsystem_sysname(&device, ss, sysname);
386 if (r < 0)
387 return log_error_errno(r, "Failed to get backlight or LED device '%s:%s': %m", ss, sysname);
388
389 /* If max_brightness is 0, then there is no actual backlight
390 * device. This happens on desktops with Asus mainboards
391 * that load the eeepc-wmi module. */
392 if (get_max_brightness(device, &max_brightness) < 0)
393 return 0;
394
395 escaped_ss = cescape(ss);
396 if (!escaped_ss)
397 return log_oom();
398
399 escaped_sysname = cescape(sysname);
400 if (!escaped_sysname)
401 return log_oom();
402
403 if (sd_device_get_property_value(device, "ID_PATH", &path_id) >= 0) {
404 escaped_path_id = cescape(path_id);
405 if (!escaped_path_id)
406 return log_oom();
407
408 saved = strjoina("/var/lib/systemd/backlight/", escaped_path_id, ":", escaped_ss, ":", escaped_sysname);
409 } else
410 saved = strjoina("/var/lib/systemd/backlight/", escaped_ss, ":", escaped_sysname);
411
412 /* If there are multiple conflicting backlight devices, then
413 * their probing at boot-time might happen in any order. This
414 * means the validity checking of the device then is not
415 * reliable, since it might not see other devices conflicting
416 * with a specific backlight. To deal with this, we will
417 * actively delete backlight state files at shutdown (where
418 * device probing should be complete), so that the validity
419 * check at boot time doesn't have to be reliable. */
420
421 if (streq(argv[1], "load")) {
422 _cleanup_free_ char *value = NULL;
423 bool clamp;
424
425 if (shall_restore_state() == 0)
426 return 0;
427
428 if (validate_device(device) == 0)
429 return 0;
430
431 clamp = shall_clamp(device);
432
433 r = read_one_line_file(saved, &value);
434 if (IN_SET(r, -ENOENT, 0)) {
435 const char *curval;
436
437 /* Fallback to clamping current brightness or exit early if
438 * clamping is not supported/enabled. */
439 if (!clamp)
440 return 0;
441
442 r = read_brightness(device, &curval);
443 if (r < 0)
444 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
445
446 value = strdup(curval);
447 if (!value)
448 return log_oom();
449 } else if (r < 0)
450 return log_error_errno(r, "Failed to read %s: %m", saved);
451
452 if (clamp)
453 (void) clamp_brightness(device, &value, max_brightness);
454
455 r = sd_device_set_sysattr_value(device, "brightness", value);
456 if (r < 0)
457 return log_device_error_errno(device, r, "Failed to write system 'brightness' attribute: %m");
458
459 } else if (streq(argv[1], "save")) {
460 const char *value;
461
462 if (validate_device(device) == 0) {
463 (void) unlink(saved);
464 return 0;
465 }
466
467 r = read_brightness(device, &value);
468 if (r < 0)
469 return log_device_error_errno(device, r, "Failed to read current brightness: %m");
470
471 r = write_string_file(saved, value, WRITE_STRING_FILE_CREATE);
472 if (r < 0)
473 return log_device_error_errno(device, r, "Failed to write %s: %m", saved);
474
475 } else
476 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", argv[1]);
477
478 return 0;
479 }
480
481 DEFINE_MAIN_FUNCTION(run);