Skip to contentSkip to conversation

drivers/base: Introduce revocable

PATCH Superseded Tzung-Bi Shih 2 participants 6 messages Sep 8 – Sep 12

Subsystems (4)

v12 of 15 Superseded Latest is v15 →

lore
Share & tools
lore
#0 lore raw

v12 cover drivers/base: Introduce revocable

This series introduces the "revocable" mechanism, a synchronization primitive designed to prevent Use-After-Free errors.

- Patch 1 introduces the revocable which is an implementation of ideas from the talk [1][2].

- Patch 2 adds KUnit test cases.

- Patch 3 transitions the UAF prevention logic within the GPIO core (gpiolib) to use the "revocable" mechanism.

The existing code aims to prevent UAF issues when the underlying GPIO chip is removed. The patch replaces that custom logic with the generic "revocable" API, which is designed to handle such lifecycle dependencies. There should be no changes in behavior.

Since v9, there are two ways to manage the resource provider handle.
- Embedded allocation: patch 3 is the user.
- Dynamic allocation: no user yet.

[1] https://lpc.events/event/17/contributions/1627/
[2] https://lpc.events/event/19/contributions/2262/
---
v12:
- Rebase onto next-20260907.
- Drop patch 4 and 5.

v11: https://lore.kernel.org/all/[email protected]
- Rebase onto v7.1-rc3.
- Squash patches 4 to 7 into patch 3. A single patch for GPIO.

v10: https://lore.kernel.org/all/[email protected]
- Unify handling of embedded and dynamic allocation.

v9: https://lore.kernel.org/all/[email protected]
- Rebase onto v7.1-rc1.
- Remove the selftests patch as it makes less sense to test revocable APIs via kselftests.
- Merge patches 7 to 11 from
https://lore.kernel.org/all/[email protected]
into the series.
- Merge patch from
https://lore.kernel.org/all/[email protected]
- Merge patch from
https://lore.kernel.org/all/[email protected]

v8: https://lore.kernel.org/all/[email protected]
- Rework on the revocable APIs. See changelog in [PATCH v8 1/3] for details.

v7: https://lore.kernel.org/all/[email protected]
- Rebase onto next-20260115.

v6: https://lore.kernel.org/all/[email protected]
- Rebase onto next-20251106.
- Separate revocable core and use cases.

v5: https://lore.kernel.org/all/[email protected]
- Rebase onto next-20251015.
- Add more context about the PoC.
- Support multiple revocable providers in the PoC.

v4: https://lore.kernel.org/all/[email protected]
- Rebase onto next-20250922.
- Remove the 5th patch from v3.
- Add fops replacement PoC in 5th - 7th patches.

v3: https://lore.kernel.org/all/[email protected]
- Rebase onto https://lore.kernel.org/all/[email protected]
and next-20250912.
- The 4th patch changed accordingly.

v2: https://lore.kernel.org/all/[email protected]
- Rename "ref_proxy" -> "revocable".
- Add test cases in Kunit and selftest.

v1: https://lore.kernel.org/all/[email protected]

Tzung-Bi Shih (3):
revocable: Revocable resource management
revocable: Add KUnit test cases
gpio: Leverage revocable for accessing struct gpio_chip

 .../driver-api/driver-model/index.rst         |   1 +
 .../driver-api/driver-model/revocable.rst     | 384 +++++++++++++++++
 MAINTAINERS                                   |  11 +
 drivers/base/Makefile                         |   2 +-
 drivers/base/revocable.c                      | 267 ++++++++++++
 drivers/base/test/Kconfig                     |   5 +
 drivers/base/test/Makefile                    |   4 +
 drivers/base/test/revocable-test.c            | 406 ++++++++++++++++++
 drivers/gpio/gpiolib-cdev.c                   |  77 ++--
 drivers/gpio/gpiolib-sysfs.c                  |  31 +-
 drivers/gpio/gpiolib.c                        | 259 +++++------
 drivers/gpio/gpiolib.h                        |  28 +-
 include/linux/revocable.h                     | 204 +++++++++
 13 files changed, 1438 insertions(+), 241 deletions(-)
 create mode 100644 Documentation/driver-api/driver-model/revocable.rst
 create mode 100644 drivers/base/revocable.c
 create mode 100644 drivers/base/test/revocable-test.c
 create mode 100644 include/linux/revocable.h
Signature · 1 line
2.53.0
#1 lore raw

PATCH v12 1/3 revocable: Revocable resource management

The "revocable" mechanism is a synchronization primitive designed to manage safe access to resources that can be asynchronously removed or invalidated. Its primary purpose is to prevent Use-After-Free (UAF) errors when interacting with resources whose lifetimes are not guaranteed to outlast their consumers.

This is particularly useful in systems where resources can disappear unexpectedly, such as those provided by hot-pluggable devices like USB. When a consumer holds a reference to such a resource, the underlying device might be removed, causing the resource's memory to be freed. Subsequent access attempts by the consumer would then lead to UAF errors.

Revocable addresses this by providing a form of "weak reference" and a controlled access method. It allows a resource consumer to safely attempt to access the resource. The mechanism guarantees that any access granted is valid for the duration of its use. If the resource has already been revoked (i.e., freed), the access attempt will fail safely, typically by returning NULL, instead of causing a crash.

It uses a provider/consumer model built on Sleepable RCU (SRCU) to guarantee safe memory access:

- A resource provider, such as a driver for a hot-pluggable device, allocates a struct revocable and initializes it with a pointer to the resource.

- A resource consumer that wants to access the resource allocates a struct revocable_handle containing a reference to the provider.

- To access the resource, the consumer uses revocable_try_access(). This function enters an SRCU read-side critical section and returns the pointer to the resource. If the provider has already freed the resource, it returns NULL. After use, the consumer calls revocable_withdraw_access() to exit the SRCU critical section. There are some macro level helpers for doing that.

The API provides the following contract:

- revocable_try_access() can be safely called from both process and atomic contexts.
- It is permitted to sleep within the critical section established between revocable_try_access() and revocable_withdraw_access().
- revocable_try_access() and the matching revocable_withdraw_access() must occur in the same context. For example, it is illegal to invoke revocable_withdraw_access() in an irq handler if the matching revocable_try_access() was invoked in process context.

- When the provider needs to remove the resource, it calls revocable_revoke(). This function sets the internal resource pointer to NULL and then calls synchronize_srcu() to wait for all current readers to finish before the resource can be completely torn down.

---
Test:

$ make O=build SPHINXDIRS=driver-api/driver-model/ htmldocs
$ python3 -m http.server --directory \
        build/Documentation/output/driver-api/driver-model/
---
v12:
- Rebase onto next-20260907.
- Fix "struct revocable_consumer" -> "struct revocable_handle" in the
  commit message.
- Add "Documentation/driver-api/driver-model/revocable.rst" to
  MAINTAINERS.

v11: https://lore.kernel.org/all/[email protected]
- Add Reviewed-by and Tested-by tags.

v10: https://lore.kernel.org/all/[email protected]
- Drop unused header.
- Unify handling of embedded and dynamic allocation.
- Rename:
- struct revocable_consumer -> struct revocable_handle.
- revocable_init() -> revocable_handle_init().
- revocable_deinit() -> revocable_handle_deinit().
- revocable_embed_init() -> revocable_init().

v9: https://lore.kernel.org/all/[email protected]
- Add revocable_embed_init() and revocable_embed_destroy() for embedded resource provider per
https://lore.kernel.org/all/CAMRc=MehkJc-js=Wk9vBAcXOpazqjtYDLPUEhmbN8U7Wu2YpgA@mail.gmail.com

v8: https://lore.kernel.org/all/[email protected]
- Squash:
- fdeb3ca3cca8 revocable: Remove redundant synchronize_srcu() call
- 4d7dc4d1a62d revocable: Fix races in revocable_alloc() using RCU
- 377563ce0653 revocable: fix SRCU index corruption by requiring caller-provided storage
- Rename macro names:
- REVOCABLE_TRY_ACCESS_WITH() -> revocable_try_access_with().
- REVOCABLE_TRY_ACCESS_SCOPED() -> revocable_try_access_with_scoped().
- Rename terminologies as now normal users should only "see" provider handles, using a shorter name for provider handle to echo the main concept.
- struct revocable -> struct revocable_consumer.
- struct revocable_provider -> struct revocable.
- revocable_provider_alloc() -> revocable_alloc().
- revocable_provider_revoke() -> revocable_revoke().
- New APIs:
- revocable_get().
- revocable_put().
- revocable_try_access_or_return_err().
- revocable_try_access_or_return().
- revocable_try_access_or_return_void().
- revocable_try_access_or_return_err_scoped().
- revocable_try_access_or_return_scoped().
- revocable_try_access_or_void_scoped().
- revocable_try_access_or_skip_scoped().
- Add API contract that revocable_try_access() works from process and atomic context while also allowing sleeping inside the critical
sections.
- Add revocable.h to the DRIVER CORE entry in MAINTAINERS.

v7: https://lore.kernel.org/all/[email protected]
- "2025" -> "2026" in copyright.
- Documentation/
- Rephrase section "Revocable vs. Devres (devm)".
- Include sections for struct revocable_provider and struct revocable.
- Minor rename: "revocable" -> "access_rev" for DEFINE_FREE().
- Add Acked-by tag.

v6: https://lore.kernel.org/all/[email protected]
- Rename REVOCABLE_TRY_ACCESS_WITH() -> REVOCABLE_TRY_ACCESS_SCOPED().
- Add new REVOCABLE_TRY_ACCESS_WITH().
- Remove Acked-by tags as the API names changed a bit.

v5: https://lore.kernel.org/all/[email protected]
- No changes.

v4: https://lore.kernel.org/all/[email protected]
- Rename:
- revocable_provider_free() -> revocable_provider_revoke().
- REVOCABLE() -> REVOCABLE_TRY_ACCESS_WITH().
- revocable_release() -> revocable_withdraw_access().
- rcu_dereference() -> srcu_dereference() to fix a warning from lock debugging.
- Move most docs to kernel-doc, include them in Documentation/, and modify the commit message accordingly.
- Fix some doc errors.
- Add Acked-by tags.

v3: https://lore.kernel.org/all/[email protected]
- No changes.

v2: https://lore.kernel.org/all/[email protected]
- Rename "ref_proxy" -> "revocable".
- Add introduction in kernel-doc format in revocable.c.
- Add MAINTAINERS entry.
- Add copyright.
- Move from lib/ to drivers/base/.
- EXPORT_SYMBOL() -> EXPORT_SYMBOL_GPL().
- Add Documentation/.
- Rename _get() -> try_access(); _put() -> release().
- Fix a sparse warning by removing the redundant __rcu annotations.
- Fix a sparse warning by adding __acquires() and __releases() annotations.

v1: https://lore.kernel.org/all/[email protected]

---
 .../driver-api/driver-model/index.rst         |   1 +
 .../driver-api/driver-model/revocable.rst     | 384 ++++++++++++++++++
 MAINTAINERS                                   |  10 +
 drivers/base/Makefile                         |   2 +-
 drivers/base/revocable.c                      | 267 ++++++++++++
 include/linux/revocable.h                     | 204 ++++++++++
 6 files changed, 867 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/driver-api/driver-model/revocable.rst
 create mode 100644 drivers/base/revocable.c
 create mode 100644 include/linux/revocable.h
Documentation/driver-api/driver-model/index.rst +1 -0
index abeb4b36636b..cc90b20bb192 100644
@@ -14,3 +14,4 @@ Driver Model
    overview
    platform
    porting
+   revocable
Documentation/driver-api/driver-model/revocable.rst new file +384 -0

384 lines not on this page · raw message

MAINTAINERS +10 -0
index 95227134bcc1..6d87bda2a8ad 100644
@@ -7997,6 +7997,7 @@ F:	include/linux/fwnode.h
 F:	include/linux/kobj*
 F:	include/linux/ksysfs.h
 F:	include/linux/property.h
+F:	include/linux/revocable.h
 F:	include/linux/sys_soc.h
 F:	include/linux/sysfs.h
 F:	kernel/ksysfs.c
@@ -23492,6 +23493,15 @@ F:	include/uapi/linux/rseq.h
 F:	kernel/rseq.c
 F:	tools/testing/selftests/rseq/
 
+REVOCABLE RESOURCE MANAGEMENT
+M:	Tzung-Bi Shih <[email protected]>
+L:	[email protected]
+S:	Maintained
+T:	git git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
+F:	Documentation/driver-api/driver-model/revocable.rst
+F:	drivers/base/revocable.c
+F:	include/linux/revocable.h
+
 RFKILL
 M:	Johannes Berg <[email protected]>
 L:	[email protected]
drivers/base/Makefile +1 -1
index 435710f643a5..43723162379e 100644
@@ -6,7 +6,7 @@ obj-y			:= component.o core.o bus.o dd.o syscore.o \
 			   cpu.o firmware.o init.o map.o devres.o \
 			   attribute_container.o transport_class.o \
 			   topology.o container.o property.o cacheinfo.o \
-			   swnode.o faux.o
+			   swnode.o faux.o revocable.o
 obj-$(CONFIG_AUXILIARY_BUS) += auxiliary.o
 obj-$(CONFIG_DEVTMPFS)	+= devtmpfs.o
 obj-y			+= power/
drivers/base/revocable.c new file +267 -0

267 lines not on this page · raw message

include/linux/revocable.h new file +204 -0

204 lines not on this page · raw message

Signature · 1 line
2.53.0
#2 lore raw

PATCH v12 2/3 revocable: Add KUnit test cases

In reply to Tzung-Bi Shih

Add KUnit test cases for the revocable API.

The test cases cover the following scenarios:

- Basic: Verifies that a consumer can successfully access the resource.
- Revocation: Verifies that after the provider revokes the resource, the consumer correctly receives a NULL pointer on a subsequent access.
- Try Access Macro: Same as "Revocation" but uses the macro level helpers.
- Concurrent Access: Verifies multiple threads can access the resource.

---
Test:

$ ./tools/testing/kunit/kunit.py run \
        --kconfig_add CONFIG_REVOCABLE_KUNIT_TEST=y \
        revocable_test
$ ./tools/testing/kunit/kunit.py run \
        --kconfig_add CONFIG_REVOCABLE_KUNIT_TEST=y \
        --kconfig_add CONFIG_PROVE_LOCKING=y \
        --kconfig_add CONFIG_DEBUG_KERNEL=y \
        --kconfig_add CONFIG_DEBUG_INFO=y \
        --kconfig_add CONFIG_DEBUG_INFO_DWARF5=y \
        --kconfig_add CONFIG_KASAN=y \
        --kconfig_add CONFIG_DETECT_HUNG_TASK=y \
        --kconfig_add CONFIG_DEFAULT_HUNG_TASK_TIMEOUT="10" \
        --arch=x86_64 \
        --make_options="C=1 W=1" \
        revocable_test
---
v12:
- Rebase onto next-20260907.
- Fix path in MAINTAINERS: "drivers/base/revocable_test.c" ->
  "drivers/base/test/revocable-test.c".

v11: https://lore.kernel.org/all/[email protected]
- Move the test to drivers/base/test/.
- Add R-b tag.

v10: https://lore.kernel.org/all/[email protected]
- Merge revocable_test_try_access_macro*() cases.
- Change revocable API usages accordingly.

v9: https://lore.kernel.org/all/[email protected]
- Add test cases for embedded resource provider.

v8: https://lore.kernel.org/all/[email protected]
- Squash:
- c259cd7ea3c9 revocable: fix missing module license and description
- a243f7fb11fe revocable: Add KUnit test for provider lifetime races
- 988357628c2c revocable: Add KUnit test for concurrent access
- Change accordingly due to its dependency "revocable: Revocable resource management" changes.

v7: https://lore.kernel.org/all/[email protected]
- "2025" -> "2026" in copyright.
- Rename the test name "macro" -> "try_access_macro".

v6: https://lore.kernel.org/all/[email protected]
- Rename REVOCABLE_TRY_ACCESS_WITH() -> REVOCABLE_TRY_ACCESS_SCOPED().
- Add tests for new REVOCABLE_TRY_ACCESS_WITH().

v5: https://lore.kernel.org/all/[email protected]
- No changes.

v4: https://lore.kernel.org/all/[email protected]
- REVOCABLE() -> REVOCABLE_TRY_ACCESS_WITH().
- revocable_release() -> revocable_withdraw_access().

v3: https://lore.kernel.org/all/[email protected]
- No changes.

v2: https://lore.kernel.org/all/[email protected]
- New in the series.

---
 MAINTAINERS                        |   1 +
 drivers/base/test/Kconfig          |   5 +
 drivers/base/test/Makefile         |   4 +
 drivers/base/test/revocable-test.c | 406 +++++++++++++++++++++++++++++
 4 files changed, 416 insertions(+)
 create mode 100644 drivers/base/test/revocable-test.c
MAINTAINERS +1 -0
index 6d87bda2a8ad..b88208e044e5 100644
@@ -23500,6 +23500,7 @@ S:	Maintained
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
 F:	Documentation/driver-api/driver-model/revocable.rst
 F:	drivers/base/revocable.c
+F:	drivers/base/test/revocable-test.c
 F:	include/linux/revocable.h
 
 RFKILL
drivers/base/test/Kconfig +5 -0
index 1ecf0791241a..80353db68a4f 100644
@@ -23,3 +23,8 @@ config DRIVER_SWNODE_KUNIT_TEST
 	tristate "KUnit Tests for software node fw_devlink links" if !KUNIT_ALL_TESTS
 	depends on KUNIT
 	default KUNIT_ALL_TESTS
+
+config REVOCABLE_KUNIT_TEST
+	tristate "KUnit tests for revocable" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	default KUNIT_ALL_TESTS
drivers/base/test/Makefile +4 -0
index 9ced7bbd569f..ddb061e12c0f 100644
@@ -8,3 +8,7 @@ obj-$(CONFIG_DRIVER_PE_KUNIT_TEST) += property-entry-test.o
 CFLAGS_property-entry-test.o += $(DISABLE_STRUCTLEAK_PLUGIN)
 
 obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-devlink-test.o
+
+obj-$(CONFIG_REVOCABLE_KUNIT_TEST) += revocable-test.o
+
+
drivers/base/test/revocable-test.c new file +406 -0

406 lines not on this page · raw message

Signature · 1 line
2.53.0
#3 lore raw

PATCH v12 3/3 gpio: Leverage revocable for accessing struct gpio_chip

In reply to Tzung-Bi Shih

The underlying chip can be removed asynchronously. gdev->srcu is used to ensure the synchronization before accessing gdev->chip.

Revocable encapsulates the details. Leverage revocable for accessing the struct gpio_chip and remove the gdev->srcu.

---
Test:

Prepare gpiod-test.
(https://libgpiod.readthedocs.io/en/master/building.html#building)

$ cd libgpiod-2.3.1
$ mkdir build && cd build
$ meson setup .. -Dtools=enabled
$ ninja

Prepare kernel.

$ cat >test_config <<EOF
CONFIG_IKCONFIG=y
CONFIG_IKCONFIG_PROC=y
CONFIG_KASAN=y
CONFIG_GPIOLIB=y
CONFIG_GPIO_SYSFS=y
CONFIG_GPIO_SIM=y
CONFIG_EXPERT=y
CONFIG_PROVE_LOCKING=y
CONFIG_PANIC_ON_OOPS=y
CONFIG_DEBUG_KERNEL=y
CONFIG_LOCKDEP=y
EOF
$ export KBUILD_OUTPUT=build
$ vng -k -f test_config && vng -b

Run gpiod-test.

$ vng
$ ./libgpiod-2.3.1/build/tests/gpiod-test
$ time ./libgpiod-2.3.1/build/tests/gpiod-test >/dev/null 2>&1
---
v12:
- Rebase onto next-20260907.
- Fix conflicts mainly with aa7e8b7ef031 ("gpio: core: fix
  const-correctness of gpio_chip_guard").
- Fix error unwinding in gpiochip_add_data_with_key() by initializing
  chip_rev before device_initialize() and ensuring both references are
  dropped on error.

v11: https://lore.kernel.org/all/[email protected]
- Add Tested-by tag.
- Squash
- https://lore.kernel.org/all/[email protected]
- https://lore.kernel.org/all/[email protected]
- https://lore.kernel.org/all/[email protected]
- https://lore.kernel.org/all/[email protected]

v10: https://lore.kernel.org/all/[email protected]
- Change revocable API usages accordingly.

v9: https://lore.kernel.org/all/[email protected]
- New to the series.
- Use static allocated resource provider.
- Rename "chip_rp" -> "chip_rev".

v4 - v8:
- Doesn't exist.

v3: https://lore.kernel.org/all/[email protected]
- Change revocable API usages accordingly.

v2: https://lore.kernel.org/all/[email protected]
- Change usages accordingly after applying
https://lore.kernel.org/all/[email protected].
- Add __rcu for chip_rp.
- Pass pointer of pointer to revocable_provider_revoke().
- Rebase accordingly after applying
https://lore.kernel.org/all/[email protected].

v1: https://lore.kernel.org/all/[email protected]

---
 drivers/gpio/gpiolib-cdev.c  |  77 ++++-------
 drivers/gpio/gpiolib-sysfs.c |  31 ++---
 drivers/gpio/gpiolib.c       | 259 +++++++++++++++--------------------
 drivers/gpio/gpiolib.h       |  28 +---
 4 files changed, 155 insertions(+), 240 deletions(-)
drivers/gpio/gpiolib-cdev.c +30 -47
index b5da6e8566dc..dc94fd1f1002 100644
@@ -22,6 +22,7 @@
 #include <linux/overflow.h>
 #include <linux/pinctrl/consumer.h>
 #include <linux/poll.h>
+#include <linux/revocable.h>
 #include <linux/seq_file.h>
 #include <linux/spinlock.h>
 #include <linux/string.h>
@@ -210,11 +211,9 @@ static long linehandle_ioctl(struct file *file, unsigned int cmd,
 	DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
 	unsigned int i;
 	int ret;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&lh->gdev->srcu);
-
-	if (!rcu_access_pointer(lh->gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&lh->gdev->chip_rev, gc);
 
 	switch (cmd) {
 	case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
@@ -1447,11 +1446,9 @@ static long linereq_ioctl(struct file *file, unsigned int cmd,
 {
 	struct linereq *lr = file->private_data;
 	void __user *ip = (void __user *)arg;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&lr->gdev->srcu);
-
-	if (!rcu_access_pointer(lr->gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&lr->gdev->chip_rev, gc);
 
 	switch (cmd) {
 	case GPIO_V2_LINE_GET_VALUES_IOCTL:
@@ -1478,10 +1475,10 @@ static __poll_t linereq_poll(struct file *file,
 {
 	struct linereq *lr = file->private_data;
 	__poll_t events = 0;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&lr->gdev->srcu);
-
-	if (!rcu_access_pointer(lr->gdev->chip))
+	revocable_try_access_with(&lr->gdev->chip_rev, gc);
+	if (!gc)
 		return EPOLLHUP | EPOLLERR;
 
 	poll_wait(file, &lr->wait, wait);
@@ -1500,11 +1497,9 @@ static ssize_t linereq_read(struct file *file, char __user *buf,
 	struct gpio_v2_line_event le;
 	ssize_t bytes_read = 0;
 	int ret;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&lr->gdev->srcu);
-
-	if (!rcu_access_pointer(lr->gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&lr->gdev->chip_rev, gc);
 
 	if (count < sizeof(le))
 		return -EINVAL;
@@ -1774,10 +1769,10 @@ static __poll_t lineevent_poll(struct file *file,
 {
 	struct lineevent_state *le = file->private_data;
 	__poll_t events = 0;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&le->gdev->srcu);
-
-	if (!rcu_access_pointer(le->gdev->chip))
+	revocable_try_access_with(&le->gdev->chip_rev, gc);
+	if (!gc)
 		return EPOLLHUP | EPOLLERR;
 
 	poll_wait(file, &le->wait, wait);
@@ -1812,11 +1807,9 @@ static ssize_t lineevent_read(struct file *file, char __user *buf,
 	ssize_t bytes_read = 0;
 	ssize_t ge_size;
 	int ret;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&le->gdev->srcu);
-
-	if (!rcu_access_pointer(le->gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&le->gdev->chip_rev, gc);
 
 	/*
 	 * When compatible system call is being used the struct gpioevent_data,
@@ -1894,11 +1887,9 @@ static long lineevent_ioctl(struct file *file, unsigned int cmd,
 	struct lineevent_state *le = file->private_data;
 	void __user *ip = (void __user *)arg;
 	struct gpiohandle_data ghd;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&le->gdev->srcu);
-
-	if (!rcu_access_pointer(le->gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&le->gdev->chip_rev, gc);
 
 	/*
 	 * We can get the value for an event line but not set it,
@@ -2180,10 +2171,9 @@ static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
 	u32 debounce_period_us;
 	unsigned long dflags;
 	const char *label;
+	struct gpio_chip *gc;
 
-	CLASS(gpio_chip_guard, guard)(desc);
-	if (!guard.gc)
-		return;
+	revocable_try_access_or_return_void(&desc->gdev->chip_rev, gc);
 
 	memset(info, 0, sizeof(*info));
 	info->offset = gpiod_hwgpio(desc);
@@ -2216,10 +2206,10 @@ static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
 	    test_bit(GPIOD_FLAG_IS_HOGGED, &dflags) ||
 	    test_bit(GPIOD_FLAG_EXPORT, &dflags) ||
 	    test_bit(GPIOD_FLAG_SYSFS, &dflags) ||
-	    !gpiochip_line_is_valid(guard.gc, info->offset)) {
+	    !gpiochip_line_is_valid(gc, info->offset)) {
 		info->flags |= GPIO_V2_LINE_FLAG_USED;
 	} else if (!atomic) {
-		if (!pinctrl_gpio_can_use_line(guard.gc, info->offset))
+		if (!pinctrl_gpio_can_use_line(gc, info->offset))
 			info->flags |= GPIO_V2_LINE_FLAG_USED;
 	}
 
@@ -2400,12 +2390,10 @@ static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	struct gpio_chardev_data *cdev = file->private_data;
 	struct gpio_device *gdev = cdev->gdev;
 	void __user *ip = (void __user *)arg;
-
-	guard(srcu)(&gdev->srcu);
+	struct gpio_chip *gc;
 
 	/* We fail any subsequent ioctl():s when the chip is gone */
-	if (!rcu_access_pointer(gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&gdev->chip_rev, gc);
 
 	/* Fill in the struct and pass to userspace */
 	switch (cmd) {
@@ -2463,12 +2451,9 @@ static void lineinfo_changed_func(struct work_struct *work)
 		 * Pin functions are in general much more static and while it's
 		 * not 100% bullet-proof, it's good enough for most cases.
 		 */
-		scoped_guard(srcu, &ctx->gdev->srcu) {
-			gc = srcu_dereference(ctx->gdev->chip, &ctx->gdev->srcu);
-			if (gc &&
-			    !pinctrl_gpio_can_use_line(gc, ctx->chg.info.offset))
+		revocable_try_access_or_skip_scoped(&ctx->gdev->chip_rev, gc)
+			if (!pinctrl_gpio_can_use_line(gc, ctx->chg.info.offset))
 				ctx->chg.info.flags |= GPIO_V2_LINE_FLAG_USED;
-		}
 	}
 
 	ret = kfifo_in_spinlocked(&ctx->cdev->events, &ctx->chg, 1,
@@ -2549,10 +2534,10 @@ static __poll_t lineinfo_watch_poll(struct file *file,
 {
 	struct gpio_chardev_data *cdev = file->private_data;
 	__poll_t events = 0;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&cdev->gdev->srcu);
-
-	if (!rcu_access_pointer(cdev->gdev->chip))
+	revocable_try_access_with(&cdev->gdev->chip_rev, gc);
+	if (!gc)
 		return EPOLLHUP | EPOLLERR;
 
 	poll_wait(file, &cdev->wait, pollt);
@@ -2572,11 +2557,9 @@ static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
 	ssize_t bytes_read = 0;
 	int ret;
 	size_t event_size;
+	struct gpio_chip *gc;
 
-	guard(srcu)(&cdev->gdev->srcu);
-
-	if (!rcu_access_pointer(cdev->gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&cdev->gdev->chip_rev, gc);
 
 #ifndef CONFIG_GPIO_CDEV_V1
 	event_size = sizeof(struct gpio_v2_line_info_changed);
drivers/gpio/gpiolib-sysfs.c +14 -17
index fc06b0c2881b..c40320433ff7 100644
@@ -10,6 +10,7 @@
 #include <linux/list.h>
 #include <linux/mutex.h>
 #include <linux/printk.h>
+#include <linux/revocable.h>
 #include <linux/slab.h>
 #include <linux/string.h>
 #include <linux/srcu.h>
@@ -215,10 +216,9 @@ static int gpio_sysfs_request_irq(struct gpiod_data *data, unsigned char flags)
 	struct gpio_desc *desc = data->desc;
 	unsigned long irq_flags;
 	int ret;
+	struct gpio_chip *gc;
 
-	CLASS(gpio_chip_guard, guard)(desc);
-	if (!guard.gc)
-		return -ENODEV;
+	revocable_try_access_or_return(&desc->gdev->chip_rev, gc);
 
 	data->irq = gpiod_to_irq(desc);
 	if (data->irq < 0)
@@ -244,7 +244,7 @@ static int gpio_sysfs_request_irq(struct gpiod_data *data, unsigned char flags)
 	 * Remove this redundant call (along with the corresponding unlock)
 	 * when those drivers have been fixed.
 	 */
-	ret = gpiochip_lock_as_irq(guard.gc, gpiod_hwgpio(desc));
+	ret = gpiochip_lock_as_irq(gc, gpiod_hwgpio(desc));
 	if (ret < 0)
 		goto err_clr_bits;
 
@@ -258,7 +258,7 @@ static int gpio_sysfs_request_irq(struct gpiod_data *data, unsigned char flags)
 	return 0;
 
 err_unlock:
-	gpiochip_unlock_as_irq(guard.gc, gpiod_hwgpio(desc));
+	gpiochip_unlock_as_irq(gc, gpiod_hwgpio(desc));
 err_clr_bits:
 	clear_bit(GPIOD_FLAG_EDGE_RISING, &desc->flags);
 	clear_bit(GPIOD_FLAG_EDGE_FALLING, &desc->flags);
@@ -273,14 +273,13 @@ static int gpio_sysfs_request_irq(struct gpiod_data *data, unsigned char flags)
 static void gpio_sysfs_free_irq(struct gpiod_data *data)
 {
 	struct gpio_desc *desc = data->desc;
+	struct gpio_chip *gc;
 
-	CLASS(gpio_chip_guard, guard)(desc);
-	if (!guard.gc)
-		return;
+	revocable_try_access_or_return_void(&desc->gdev->chip_rev, gc);
 
 	data->irq_flags = 0;
 	free_irq(data->irq, data);
-	gpiochip_unlock_as_irq(guard.gc, gpiod_hwgpio(desc));
+	gpiochip_unlock_as_irq(gc, gpiod_hwgpio(desc));
 	clear_bit(GPIOD_FLAG_EDGE_RISING, &desc->flags);
 	clear_bit(GPIOD_FLAG_EDGE_FALLING, &desc->flags);
 }
@@ -473,13 +472,12 @@ static DEVICE_ATTR_RO(ngpio);
 static int export_gpio_desc(struct gpio_desc *desc)
 {
 	int offset, ret;
+	struct gpio_chip *gc;
 
-	CLASS(gpio_chip_guard, guard)(desc);
-	if (!guard.gc)
-		return -ENODEV;
+	revocable_try_access_or_return(&desc->gdev->chip_rev, gc);
 
 	offset = gpiod_hwgpio(desc);
-	if (!gpiochip_line_is_valid(guard.gc, offset)) {
+	if (!gpiochip_line_is_valid(gc, offset)) {
 		pr_debug_ratelimited("%s: GPIO %d masked\n", __func__,
 				     gpiod_hwgpio(desc));
 		return -EINVAL;
@@ -732,6 +730,7 @@ int gpiod_export(struct gpio_desc *desc, bool direction_may_change)
 	struct gpio_device *gdev;
 	struct attribute **attrs;
 	int status;
+	struct gpio_chip *gc;
 
 	/* can't export until sysfs is available ... */
 	if (!class_is_registered(&gpio_class)) {
@@ -744,9 +743,7 @@ int gpiod_export(struct gpio_desc *desc, bool direction_may_change)
 		return -EINVAL;
 	}
 
-	CLASS(gpio_chip_guard, guard)(desc);
-	if (!guard.gc)
-		return -ENODEV;
+	revocable_try_access_or_return(&desc->gdev->chip_rev, gc);
 
 	if (test_and_set_bit(GPIOD_FLAG_EXPORT, &desc->flags))
 		return -EPERM;
@@ -769,7 +766,7 @@ int gpiod_export(struct gpio_desc *desc, bool direction_may_change)
 
 	desc_data->desc = desc;
 	mutex_init(&desc_data->mutex);
-	if (guard.gc->direction_input && guard.gc->direction_output)
+	if (gc->direction_input && gc->direction_output)
 		desc_data->direction_can_change = direction_may_change;
 	else
 		desc_data->direction_can_change = false;
drivers/gpio/gpiolib.c +108 -151

669 lines not on this page · raw message

drivers/gpio/gpiolib.h +3 -25
index 650a702741df..efbff4a1cd4e 100644
@@ -16,6 +16,7 @@
 #include <linux/gpio/driver.h>
 #include <linux/module.h>
 #include <linux/notifier.h>
+#include <linux/revocable.h>
 #include <linux/spinlock.h>
 #include <linux/string.h>
 #include <linux/srcu.h>
@@ -31,7 +32,6 @@ struct fwnode_handle;
  * @chrdev: character device for the GPIO device
  * @id: numerical ID number for the GPIO chip
  * @owner: helps prevent removal of modules exporting active GPIOs
- * @chip: pointer to the corresponding gpiochip, holding static
  * data for this device
  * @descs: array of ngpio descriptors.
  * @valid_mask: If not %NULL, holds bitmask of GPIOs which are valid to be
@@ -54,7 +54,7 @@ struct fwnode_handle;
  *                 process context
  * @device_notifier: used to notify character device wait queues about the GPIO
  *                   device being unregistered
- * @srcu: protects the pointer to the underlying GPIO chip
+ * @chip_rev: revocable provider handle for the corresponding struct gpio_chip.
  * @pin_ranges: range of pins served by the GPIO driver
  *
  * This state container holds most of the runtime variable data
@@ -67,7 +67,6 @@ struct gpio_device {
 	struct cdev		chrdev;
 	int			id;
 	struct module		*owner;
-	struct gpio_chip __rcu	*chip;
 	struct gpio_desc	*descs;
 	unsigned long		*valid_mask;
 	struct srcu_struct	desc_srcu;
@@ -81,7 +80,7 @@ struct gpio_device {
 	rwlock_t		line_state_lock;
 	struct workqueue_struct	*line_state_wq;
 	struct blocking_notifier_head device_notifier;
-	struct srcu_struct	srcu;
+	struct revocable	chip_rev;
 
 #ifdef CONFIG_PINCTRL
 	/*
@@ -225,27 +224,6 @@ struct gpio_desc {
 
 #define gpiod_not_found(desc)		(IS_ERR(desc) && PTR_ERR(desc) == -ENOENT)
 
-struct gpio_chip_guard {
-	struct gpio_device *gdev;
-	struct gpio_chip *gc;
-	int idx;
-};
-
-DEFINE_CLASS(gpio_chip_guard,
-	     struct gpio_chip_guard,
-	     srcu_read_unlock(&_T.gdev->srcu, _T.idx),
-	     ({
-		struct gpio_chip_guard _guard;
-
-		_guard.gdev = desc->gdev;
-		_guard.idx = srcu_read_lock(&_guard.gdev->srcu);
-		_guard.gc = srcu_dereference(_guard.gdev->chip,
-					     &_guard.gdev->srcu);
-
-		_guard;
-	     }),
-	     const struct gpio_desc *desc)
-
 int gpiod_request(struct gpio_desc *desc, const char *label);
 int gpiod_request_commit(struct gpio_desc *desc, const char *label);
 void gpiod_free(struct gpio_desc *desc);
Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH v12 3/3] gpio: Leverage revocable for accessing struct gpio_chip

Quoted 9 lines · Tzung-Bi Shih

The underlying chip can be removed asynchronously. gdev->srcu is used to ensure the synchronization before accessing gdev->chip.

Revocable encapsulates the details. Leverage revocable for accessing the struct gpio_chip and remove the gdev->srcu.

---

Could you address the following issue pointed out by sashiko?

Quoted 5 lines
drivers/gpio/gpiolib.c +0 -0
index 66d2325bfae87..a7d3c4d9018c8 100644

drivers/gpio/gpiolib.c static void gpiodev_release(struct device *dev) · line 905

Quoted 10 lines
drivers/gpio/gpiolib.c +1 -1
@@ -898,10 +897,10 @@ static void gpiodev_release(struct device *dev)
 	synchronize_srcu(&gdev->desc_srcu);
 	cleanup_srcu_struct(&gdev->desc_srcu);
 
+	revocable_put(&gdev->chip_rev);
 	ida_free(&gpio_ida, gdev->id);
 	kfree_const(gdev->label);
 	kfree(gdev->descs);
-	cleanup_srcu_struct(&gdev->srcu);
 	kfree(gdev);
 }

Could this cause a use-after-free crash during concurrent device removal?

The revocable object chip_rev is embedded directly in the gpio_device struct. The new access cleanup pattern drops the SRCU lock before dropping the kref on the revocable object.

During asynchronous device removal, revocable_revoke() executes synchronize_srcu() to wait for readers. Because the reader drops the SRCU lock first, revocable_revoke() will unblock, proceed to gpio_device_put(gdev), and gpiodev_release() will execute kfree(gdev) while the reader thread is still active.

The reader thread will then attempt to call kref_put() on the chip_rev that is embedded inside the now-freed gdev.

--

Thanks,
Bartosz

#5 lore raw

Re: [PATCH v12 3/3] gpio: Leverage revocable for accessing struct gpio_chip

Quoted 35 lines · Bartosz Golaszewski
Quoted 9 lines · Tzung-Bi Shih

The underlying chip can be removed asynchronously. gdev->srcu is used to ensure the synchronization before accessing gdev->chip.

Revocable encapsulates the details. Leverage revocable for accessing the struct gpio_chip and remove the gdev->srcu.

---

Could you address the following issue pointed out by sashiko?

Quoted 5 lines
drivers/gpio/gpiolib.c +0 -0
index 66d2325bfae87..a7d3c4d9018c8 100644

drivers/gpio/gpiolib.c static void gpiodev_release(struct device *dev) · line 905

Quoted 10 lines
drivers/gpio/gpiolib.c +1 -1
@@ -898,10 +897,10 @@ static void gpiodev_release(struct device *dev)
 	synchronize_srcu(&gdev->desc_srcu);
 	cleanup_srcu_struct(&gdev->desc_srcu);
 
+	revocable_put(&gdev->chip_rev);
 	ida_free(&gpio_ida, gdev->id);
 	kfree_const(gdev->label);
 	kfree(gdev->descs);
-	cleanup_srcu_struct(&gdev->srcu);
 	kfree(gdev);
 }

Could this cause a use-after-free crash during concurrent device removal?

The revocable object chip_rev is embedded directly in the gpio_device struct. The new access cleanup pattern drops the SRCU lock before dropping the kref on the revocable object.

Quoted 8 lines

During asynchronous device removal, revocable_revoke() executes synchronize_srcu() to wait for readers. Because the reader drops the SRCU lock first, revocable_revoke() will unblock, proceed to gpio_device_put(gdev), and gpiodev_release() will execute kfree(gdev) while the reader thread is still active.

The reader thread will then attempt to call kref_put() on the chip_rev that is embedded inside the now-freed gdev.

While callers who use embedded allocations should properly pin the container, the revocable primitive itself shouldn't rely on that.

I have fixed this in v13[1] by caching the flag locally inside the handle, ensuring the teardown never touches the container's memory after unlocking SRCU.

[1] https://lore.kernel.org/all/[email protected]