From ebb5827689a8c533893d94722515da8cf50b243c Mon Sep 17 00:00:00 2001 From: Simon Guinot Date: Tue, 11 Feb 2025 11:45:21 +0100 Subject: [PATCH] drivers: led: lp50xx: check the number of LED colors The current code assumes (especially in the lp50xx_set_color function) that the number of LED colors defined in DT is not greater than 3. But since this is not checked, then this is not necessarily the case... This patch consolidates the initialization of the lp50xx LED driver by checking the number of colors for each LED found in DT. Signed-off-by: Simon Guinot (cherry picked from commit ffbb8f981ad5640627bac6bdfc2e84f154a25370) --- drivers/led/lp50xx.c | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/drivers/led/lp50xx.c b/drivers/led/lp50xx.c index 82333d6b14c4..069ddc9ab05c 100644 --- a/drivers/led/lp50xx.c +++ b/drivers/led/lp50xx.c @@ -153,7 +153,8 @@ static int lp50xx_set_color(const struct device *dev, uint32_t led, { const struct lp50xx_config *config = dev->config; const struct led_info *led_info = lp50xx_led_to_info(config, led); - uint8_t buf[4]; + uint8_t buf[LP50XX_COLORS_PER_LED + 1]; + uint8_t i; if (!led_info) { return -ENODEV; @@ -170,11 +171,11 @@ static int lp50xx_set_color(const struct device *dev, uint32_t led, buf[0] = LP50XX_OUT0_COLOR(config->num_modules); buf[0] += LP50XX_COLORS_PER_LED * led_info->index; - buf[1] = color[0]; - buf[2] = color[1]; - buf[3] = color[2]; + for (i = 0; i < led_info->num_colors; i++) { + buf[1 + i] = color[i]; + } - return i2c_write_dt(&config->bus, buf, sizeof(buf)); + return i2c_write_dt(&config->bus, buf, led_info->num_colors + 1); } static int lp50xx_write_channels(const struct device *dev, @@ -266,6 +267,7 @@ static int lp50xx_enable(const struct device *dev, bool enable) static int lp50xx_init(const struct device *dev) { const struct lp50xx_config *config = dev->config; + uint8_t led; int err; if (!i2c_is_ready_dt(&config->bus)) { @@ -273,6 +275,7 @@ static int lp50xx_init(const struct device *dev) return -ENODEV; } + /* Check LED configuration found in DT */ if (config->num_leds > config->max_leds) { LOG_ERR("%s: invalid number of LEDs %d (max %d)", dev->name, @@ -280,6 +283,16 @@ static int lp50xx_init(const struct device *dev) config->max_leds); return -EINVAL; } + for (led = 0; led < config->num_leds; led++) { + const struct led_info *led_info = + lp50xx_led_to_info(config, led); + + if (led_info->num_colors > LP50XX_COLORS_PER_LED) { + LOG_ERR("%s: LED %d: invalid number of colors (max %d)", + dev->name, led, LP50XX_COLORS_PER_LED); + return -EINVAL; + } + } /* Configure GPIO if present */ if (config->gpio_enable.port != NULL) {