[PATCH v2 3/3] gpiolib: release user space's lines when adding the chip fails late

From: Adrian Ambrozewicz

Date: Fri Nov 27 2026 - 02:49:54 EST


gpiochip_setup_dev() registers the character device and then the sysfs
interface. If the latter fails, the error path removes the irqchip and
returns, but user space may already hold a line request with edge
detection. Unlike gpiochip_remove(), the error path neither clears
gdev->chip nor has the character device free its IRQs, so the request
keeps calling into a chip the driver may already have freed, and its
IRQ outlives the irqchip.

Unwind as gpiochip_remove() does: release the lines the chip owns,
numb the device and free what user space left.

Reproduced with a test-only gpio-sim setup failure after the chardev is
added: reading a line requested then hit a KASAN use-after-free in
gpiod_get_array_value_complex(); with this change, reads return -ENODEV.

This depends on "gpiolib: release the chip's own lines before numbing
it on removal".

Fixes: d7c51b47ac11 ("gpio: userspace ABI for reading/writing GPIO lines")
Reported-by: Sashiko <sashiko-bot@xxxxxxxxxx>
Closes: https://sashiko.dev/#/patchset/20261016-gpiolib-chip-removal-v2-0-aambrozewicz@xxxxxxxxxx?part=6
Signed-off-by: Adrian Ambrozewicz <aambrozewicz@xxxxxxxxxx>
---
A backport of this patch to 6.12.y or 6.18.y also needs 16fdabe143fc
("gpio: Fix resource leaks on errors in gpiochip_add_data_with_key()"),
which is in 6.12.95 and 6.18.22.

drivers/gpio/gpiolib.c | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c
index 1b92ace14a5a..6d3531f5833e 100644
--- a/drivers/gpio/gpiolib.c
+++ b/drivers/gpio/gpiolib.c
@@ -1419,13 +1419,19 @@ int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data,
if (gpiolib_initialized) {
ret = gpiochip_setup_dev(gc);
if (ret)
- goto err_teardown_shared;
+ goto err_release_lines;
}

return 0;

-err_teardown_shared:
- gpio_device_teardown_shared(gdev);
+err_release_lines:
+ /* The character device may have been live: user space may hold lines. */
+ gpiochip_free_own_lines(gc);
+ gpiochip_numb_device(gc);
+ gpiochip_irqchip_remove(gc);
+ gpiochip_remove_pin_ranges(gc);
+ /* What the labels down to err_remove_of_chip undo is done above. */
+ goto err_remove_of_chip;
err_remove_irqchip:
gpiochip_irqchip_remove(gc);
err_remove_irqchip_mask:
--
2.43.0