From e623c4303ed112a1fc20aec8427ba8407e2842e6 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Mon, 10 Feb 2025 11:52:02 +0100 Subject: [PATCH] gpiolib: sanitize the return value of gpio_chip::get_direction() As per the API contract, the get_direction() callback can only return 0, 1 or a negative error number. Add a wrapper around the callback calls that filters out anything else. Reviewed-by: Linus Walleij Link: https://lore.kernel.org/r/20250210-gpio-sanitize-retvals-v1-8-12ea88506cb2@linaro.org Signed-off-by: Bartosz Golaszewski --- drivers/gpio/gpiolib.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index e720a1d2f343..9103384f4a5e 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -342,6 +342,22 @@ static int gpiochip_find_base_unlocked(u16 ngpio) } } +static int gpiochip_get_direction(struct gpio_chip *gc, unsigned int offset) +{ + int ret; + + lockdep_assert_held(&gc->gpiodev->srcu); + + if (WARN_ON(!gc->get_direction)) + return -EOPNOTSUPP; + + ret = gc->get_direction(gc, offset); + if (ret > 1) + ret = -EBADE; + + return ret; +} + /** * gpiod_get_direction - return the current direction of a GPIO * @desc: GPIO to get the direction of @@ -382,7 +398,7 @@ int gpiod_get_direction(struct gpio_desc *desc) if (!guard.gc->get_direction) return -ENOTSUPP; - ret = guard.gc->get_direction(guard.gc, offset); + ret = gpiochip_get_direction(guard.gc, offset); if (ret < 0) return ret; @@ -1067,7 +1083,7 @@ int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data, desc->gdev = gdev; if (gc->get_direction && gpiochip_line_is_valid(gc, desc_index)) { - ret = gc->get_direction(gc, desc_index); + ret = gpiochip_get_direction(gc, desc_index); if (ret < 0) /* * FIXME: Bail-out here once all GPIO drivers @@ -2788,8 +2804,7 @@ int gpiod_direction_input_nonotify(struct gpio_desc *desc) ret = gpiochip_direction_input(guard.gc, gpio_chip_hwgpio(desc)); } else if (guard.gc->get_direction) { - ret = guard.gc->get_direction(guard.gc, - gpio_chip_hwgpio(desc)); + ret = gpiochip_get_direction(guard.gc, gpio_chip_hwgpio(desc)); if (ret < 0) return ret; @@ -2836,8 +2851,8 @@ static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value) } else { /* Check that we are in output mode if we can */ if (guard.gc->get_direction) { - ret = guard.gc->get_direction(guard.gc, - gpio_chip_hwgpio(desc)); + ret = gpiochip_get_direction(guard.gc, + gpio_chip_hwgpio(desc)); if (ret < 0) return ret; -- 2.50.1