[PATCH 05/10] leds: class: Fix race condition when creating the device

From: Armin Wolf

Date: Sun Oct 18 2026 - 09:54:29 EST


Userspace applications can access the sysfs attributes as soon as
device_create_with_groups() has returned. Two of those sysfs
attributes ("brightness_hw_changed" and "max_brightness") access
fields that are not properly initialized at this point, with only
"max_brightness" guarding against this by taking the LED access lock.

Fix the race conditon affecting "brightness_hw_changed" by creating
the device after the associated fields have been properly initialized.
This also allows us to drop the LED access lock inside
max_brightness_show(), as the maximum brightness does not change after
initialization.

Signed-off-by: Armin Wolf <W_Armin@xxxxxx>
---
drivers/leds/led-class.c | 28 ++++++++++++----------------
1 file changed, 12 insertions(+), 16 deletions(-)

diff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.c
index d460f041ed86..e1f1b710536b 100644
--- a/drivers/leds/led-class.c
+++ b/drivers/leds/led-class.c
@@ -81,13 +81,8 @@ static ssize_t max_brightness_show(struct device *dev, const struct device_attri
char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
- unsigned int max_brightness;

- mutex_lock(&led_cdev->led_access);
- max_brightness = led_cdev->max_brightness;
- mutex_unlock(&led_cdev->led_access);
-
- return sysfs_emit(buf, "%u\n", max_brightness);
+ return sysfs_emit(buf, "%u\n", led_cdev->max_brightness);
}

static const DEVICE_ATTR_RO(max_brightness);
@@ -524,16 +519,6 @@ int led_classdev_register_ext(struct device *parent,
dev_warn(parent, "LED %s color identifier out of range\n", final_name);

mutex_init(&led_cdev->led_access);
- mutex_lock(&led_cdev->led_access);
- led_cdev->dev = device_create_with_groups(&leds_class, parent, 0,
- led_cdev, led_cdev->groups, "%s", final_name);
- if (IS_ERR(led_cdev->dev)) {
- mutex_unlock(&led_cdev->led_access);
- return PTR_ERR(led_cdev->dev);
- }
- if (init_data && init_data->fwnode)
- device_set_node(led_cdev->dev, init_data->fwnode);
-
led_cdev->work_flags = 0;
#ifdef CONFIG_LEDS_TRIGGERS
init_rwsem(&led_cdev->trigger_lock);
@@ -549,6 +534,17 @@ int led_classdev_register_ext(struct device *parent,
if (!led_cdev->max_brightness)
led_cdev->max_brightness = LED_FULL;

+ mutex_lock(&led_cdev->led_access);
+ led_cdev->dev = device_create_with_groups(&leds_class, parent, 0, led_cdev,
+ led_cdev->groups, "%s", final_name);
+ if (IS_ERR(led_cdev->dev)) {
+ mutex_unlock(&led_cdev->led_access);
+ return PTR_ERR(led_cdev->dev);
+ }
+
+ if (init_data && init_data->fwnode)
+ device_set_node(led_cdev->dev, init_data->fwnode);
+
led_update_brightness(led_cdev);

led_cdev->wq = leds_wq;
--
2.56.0