Skip to contentSkip to conversation

drivers/base: Introduce revocable

PATCH New Tzung-Bi Shih 2 participants 7 messages Dec 1

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

v16 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.

- Patch 4 transitions the reset controller framework to use the "revocable" mechanism.

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

[1] https://lpc.events/event/17/contributions/1627/
[2] https://lpc.events/event/19/contributions/2262/
---
v16:
- Rebase onto next-20261130.

v15: https://lore.kernel.org/all/[email protected]
- Rebase onto v7.4-rc1.
- Fix resource and kthread cleanup on error paths in KUnit tests.
- Rename revocable struct members in GPIO and reset subsystems.
- Separate patch 4 (KUnit tests for reset controller) out.

v14: https://lore.kernel.org/all/[email protected]
- Rebase onto next-20261009.
- See changelogs in [PATCH v14 1/5] and [PATCH v14 2/5] for revocable API and KUnit test updates.
- Add patches 4 and 5 for the reset controller framework.

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

v12: https://lore.kernel.org/all/[email protected]
- 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 (4):
revocable: Revocable resource management
revocable: Add KUnit test cases
gpio: Leverage revocable for accessing struct gpio_chip
reset: Leverage revocable for accessing struct reset_controller_dev

 .../driver-api/driver-model/index.rst         |   1 +
 .../driver-api/driver-model/revocable.rst     | 440 +++++++++++++
 MAINTAINERS                                   |  11 +
 drivers/base/Makefile                         |   2 +-
 drivers/base/revocable.c                      | 305 +++++++++
 drivers/base/test/Kconfig                     |   5 +
 drivers/base/test/Makefile                    |   2 +
 drivers/base/test/revocable-test.c            | 607 ++++++++++++++++++
 drivers/gpio/gpiolib-cdev.c                   |  70 +-
 drivers/gpio/gpiolib-sysfs.c                  |  32 +-
 drivers/gpio/gpiolib.c                        | 268 ++++----
 drivers/gpio/gpiolib.h                        |  29 +-
 drivers/reset/core.c                          | 119 ++--
 include/linux/reset-controller.h              |   3 +
 include/linux/revocable.h                     | 220 +++++++
 15 files changed, 1789 insertions(+), 325 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 v16 1/4 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, initializes a struct revocable with a pointer to the resource. The provider handle can either be embedded in another structure or dynamically allocated on the heap.

- 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/
---
v16:
- No changes.

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

v14: https://lore.kernel.org/all/[email protected]
- Add Tested-by tag.
- Rename:
- revocable_deinit() -> revocable_destroy().
- revocable_handle_deinit() -> revocable_handle_destroy().
- revocable_alloc() now holds 1 initial reference instead of 2.
- revocable_revoke() only invalidates the resource; it doesn't drop the reference count now. An explicit revocable_put() is required if the handle is dynamically allocated.

v13: https://lore.kernel.org/all/[email protected]
- Invert flag "embedded" -> "dynamic" so that "embedded" looks like default one since it has concrete user.
- Embedded allocation:
- Don't work with kref as it's meaningless to embedded provider handle.
- Introduce revocable_deinit() to clean up.
- Cache 'dynamic' flag in struct revocable_handle so that it doesn't rely on the memory from the container of struct revocable.
- Dynamic allocation:
- Defer cleanup to a workqueue to prevent sleeping-in-atomic panics.

v12: https://lore.kernel.org/all/[email protected]
- 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     | 440 ++++++++++++++++++
 MAINTAINERS                                   |  10 +
 drivers/base/Makefile                         |   2 +-
 drivers/base/revocable.c                      | 305 ++++++++++++
 include/linux/revocable.h                     | 220 +++++++++
 6 files changed, 977 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 +440 -0

440 lines not on this page · raw message

MAINTAINERS +10 -0
index e7652ab2061a..6955c2c2a7a7 100644
@@ -8240,6 +8240,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
@@ -24299,6 +24300,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 +305 -0

305 lines not on this page · raw message

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

220 lines not on this page · raw message

Signature · 1 line
2.53.0
#3 lore raw

PATCH v16 2/4 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
---
v16:
- Verify that revocable_revoke() blocks until active consumers exit in
  concurrent access tests.

v15: https://lore.kernel.org/all/[email protected]
- Clean up kthreads and revocable handles on error paths in concurrent access tests.

v14: https://lore.kernel.org/all/[email protected]
- Add Tested-by tag.
- Change revocable API usages accordingly:
- revocable_deinit() -> revocable_destroy().
- revocable_handle_deinit() -> revocable_handle_destroy().
- Adjust expected refcounts as revocable_alloc() holds 1 initial reference and revocable_revoke() no longer drops a reference.
- Refactor embedded test cases and concurrent access setup to reduce code duplication.
- Replace msleep() with completion/polling in concurrent access tests.
- Hold task_struct references with get_task_struct() and stop threads with kthread_stop_put() to prevent Use-After-Free.

v13: https://lore.kernel.org/all/[email protected]
- Explicitly indicate "dynamic" vs. "embedded" in test case names.
- Embedded allocation
- Add tests and separate "stack" vs. "heap".
- Add tests on macros and concurrent access.

v12: https://lore.kernel.org/all/[email protected]
- 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         |   2 +
 drivers/base/test/revocable-test.c | 607 +++++++++++++++++++++++++++++
 4 files changed, 615 insertions(+)
 create mode 100644 drivers/base/test/revocable-test.c
MAINTAINERS +1 -0
index 6955c2c2a7a7..b3693510fe29 100644
@@ -24307,6 +24307,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 +2 -0
index 9ced7bbd569f..cb74d3fff1ae 100644
@@ -8,3 +8,5 @@ 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 +607 -0

607 lines not on this page · raw message

Signature · 1 line
2.53.0
#4 lore raw

PATCH v16 3/4 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
---
v16:
- Rebase onto next-20261130.
  - Fix conflicts mainly with a3a1dbaf7460 ("gpiolib: cdev: don't sleep in
    the SRCU read section in read()").
- Remove leftover @chip kernel-doc line in struct gpio_device.

v15: https://lore.kernel.org/all/[email protected]
- Rename "chip_rev" -> "gc_revocable" in struct gpio_device.
- Destroy gc_revocable before desc_srcu in gpiodev_release() to match the reverse initialization order.
- Rebase onto v7.4-rc1.
- Fix conflicts with c28846ca1ac6 ("gpiolib: fix memory leak in gpiod_set_array_value_complex() on error paths") and 8381e1f15e27 ("gpiolib: Free chip resources when allocating the label fails").

v14: https://lore.kernel.org/all/[email protected]
- Add Tested-by tag.
- Rebase onto next-20261009.
- Fix conflicts with 1feb5d39b05a ("gpio: cdev: fix kernel stack leak to user-space in error path").
- Change revocable API usages accordingly:
- revocable_deinit() -> revocable_destroy().

v13: https://lore.kernel.org/all/[email protected]
- Call revocable_deinit() instead of revocable_put() as it uses embedded allocation.

v12: https://lore.kernel.org/all/[email protected]
- 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  |  70 ++++-----
 drivers/gpio/gpiolib-sysfs.c |  32 ++---
 drivers/gpio/gpiolib.c       | 268 +++++++++++++++--------------------
 drivers/gpio/gpiolib.h       |  29 +---
 4 files changed, 158 insertions(+), 241 deletions(-)
drivers/gpio/gpiolib-cdev.c +29 -41
index c4b49fbc145f..841a6b85d978 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>
@@ -211,11 +212,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->gc_revocable, gc);
 
 	switch (cmd) {
 	case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
@@ -1467,11 +1466,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->gc_revocable, gc);
 
 	switch (cmd) {
 	case GPIO_V2_LINE_GET_VALUES_IOCTL:
@@ -1498,10 +1495,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->gc_revocable, gc);
+	if (!gc)
 		return EPOLLHUP | EPOLLERR;
 
 	poll_wait(file, &lr->wait, wait);
@@ -1519,10 +1516,9 @@ static __poll_t linereq_poll(struct file *file,
  */
 static int gpiodev_check_chip(struct gpio_device *gdev)
 {
-	guard(srcu)(&gdev->srcu);
+	struct gpio_chip *gc;
 
-	if (!rcu_access_pointer(gdev->chip))
-		return -ENODEV;
+	revocable_try_access_or_return(&gdev->gc_revocable, gc);
 
 	return 0;
 }
@@ -1553,7 +1549,7 @@ static ssize_t linereq_read(struct file *file, char __user *buf,
 
 				ret = wait_event_interruptible_locked(lr->wait,
 						!kfifo_is_empty(&lr->events) ||
-						!rcu_access_pointer(lr->gdev->chip));
+						gpiodev_check_chip(lr->gdev));
 				if (ret)
 					return ret;
 				if (kfifo_is_empty(&lr->events))
@@ -1821,10 +1817,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->gc_revocable, gc);
+	if (!gc)
 		return EPOLLHUP | EPOLLERR;
 
 	poll_wait(file, &le->wait, wait);
@@ -1896,7 +1892,7 @@ static ssize_t lineevent_read(struct file *file, char __user *buf,
 
 				ret = wait_event_interruptible_locked(le->wait,
 						!kfifo_is_empty(&le->events) ||
-						!rcu_access_pointer(le->gdev->chip));
+						gpiodev_check_chip(le->gdev));
 				if (ret)
 					return ret;
 				if (kfifo_is_empty(&le->events))
@@ -1951,11 +1947,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->gc_revocable, gc);
 
 	/*
 	 * We can get the value for an event line but not set it,
@@ -2241,12 +2235,11 @@ static int gpio_desc_to_lineinfo(struct gpio_desc *desc,
 	u32 debounce_period_us;
 	unsigned long dflags;
 	const char *label;
+	struct gpio_chip *gc;
 
 	memset(info, 0, sizeof(*info));
 
-	CLASS(gpio_chip_guard, guard)(desc);
-	if (!guard.gc)
-		return -ENODEV;
+	revocable_try_access_or_return(&desc->gdev->gc_revocable, gc);
 
 	info->offset = gpiod_hwgpio(desc);
 
@@ -2278,10 +2271,10 @@ static int 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;
 	}
 
@@ -2472,12 +2465,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->gc_revocable, gc);
 
 	/* Fill in the struct and pass to userspace */
 	switch (cmd) {
@@ -2535,12 +2526,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->gc_revocable, 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,
@@ -2628,10 +2616,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->gc_revocable, gc);
+	if (!gc)
 		return EPOLLHUP | EPOLLERR;
 
 	poll_wait(file, &cdev->wait, pollt);
@@ -2673,7 +2661,7 @@ static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
 
 				ret = wait_event_interruptible_locked(cdev->wait,
 						!kfifo_is_empty(&cdev->events) ||
-						!rcu_access_pointer(cdev->gdev->chip));
+						gpiodev_check_chip(cdev->gdev));
 				if (ret)
 					return ret;
 				if (kfifo_is_empty(&cdev->events))
drivers/gpio/gpiolib-sysfs.c +14 -18
index 08f514992569..7ed60faf2723 100644
@@ -10,9 +10,9 @@
 #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>
 #include <linux/sysfs.h>
 #include <linux/types.h>
 
@@ -215,10 +215,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->gc_revocable, gc);
 
 	data->irq = gpiod_to_irq(desc);
 	if (data->irq < 0)
@@ -244,7 +243,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 +257,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 +272,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->gc_revocable, 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 +471,12 @@ static const 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->gc_revocable, 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;
@@ -731,6 +728,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)) {
@@ -743,9 +741,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->gc_revocable, gc);
 
 	if (test_and_set_bit(GPIOD_FLAG_EXPORT, &desc->flags))
 		return -EPERM;
@@ -768,7 +764,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 +112 -156

689 lines not on this page · raw message

drivers/gpio/gpiolib.h +3 -26
index d5eb47e5c517..ebeb72f719b2 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,8 +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
  * used from the chip.
@@ -55,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
+ * @gc_revocable: 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
@@ -68,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;
@@ -83,7 +81,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	gc_revocable;
 
 #ifdef CONFIG_PINCTRL
 	/*
@@ -227,27 +225,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
#5 lore raw

PATCH v16 4/4 reset: Leverage revocable for accessing struct reset_controller_dev

In reply to Tzung-Bi Shih

Commit 78ebbff6d1a0 ("reset: handle removing supplier before consumers") protected the rcdev pointer in struct reset_control with SRCU so that the reset core can handle suppliers unbinding while consumers still hold reset control handles.

Because struct reset_control handles can outlive rcdev, each of the N handles had to embed its own srcu_struct and call synchronize_srcu() on release, and reset_controller_unregister() had to call synchronize_srcu() N times in a loop.

Leverage dynamic revocable to allocate a single reference-counted struct revocable for rcdev shared across all N struct reset_control handles (1-to-N). This reduces N srcu_struct instances per controller to 1, drops synchronize_srcu() from reset_control_put_internal(), and replaces the N synchronize_srcu() calls on unregistration with a single revocable_revoke().

---
Test:

$ ./tools/testing/kunit/kunit.py run \
        --kconfig_add CONFIG_RESET_CONTROLLER=y \
        --kconfig_add CONFIG_RESET_KUNIT_TEST=y \
        reset_test
$ ./tools/testing/kunit/kunit.py run \
        --kconfig_add CONFIG_RESET_CONTROLLER=y \
        --kconfig_add CONFIG_RESET_KUNIT_TEST=y \
        --kconfig_add CONFIG_PROVE_LOCKING=y \
        --kconfig_add CONFIG_DEBUG_KERNEL=y \
        --kconfig_add CONFIG_KASAN=y \
        --arch=x86_64 \
        --raw_output=all \
        reset_test
---
v16:
- Rebase onto next-20261130.
  - Fix conflicts mainly with bd357ffa1145 ("reset: core: Serialize concurrent
    deassert/reset of shared resets").
- Drop __reset_control_free() as it was a 1-line function.
- Reorder in reset_controller_unregister().
  - Move rstc to the local list (with kref_get()) before revocable_revoke().
  - reset_controller_remove() can only be called once (either in
    reset_controller_unregister() or reset_control_put_internal()).
  - Drop the list_empty() guard in reset_controller_remove().

v15: https://lore.kernel.org/all/[email protected]
- Rename:
- "rev" -> "revocable" in struct reset_controller_dev.
- "rev" -> "rcdev_revocable" in struct reset_control.

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

---
 drivers/reset/core.c             | 119 ++++++++++---------------------
 include/linux/reset-controller.h |   3 +
 2 files changed, 39 insertions(+), 83 deletions(-)
drivers/reset/core.c +36 -83
index 0bff49d9b558..afc17a3c698a 100644
@@ -24,8 +24,8 @@
 #include <linux/property.h>
 #include <linux/reset.h>
 #include <linux/reset-controller.h>
+#include <linux/revocable.h>
 #include <linux/slab.h>
-#include <linux/srcu.h>
 
 static DEFINE_MUTEX(reset_list_mutex);
 static LIST_HEAD(reset_controller_list);
@@ -37,9 +37,7 @@ static DEFINE_IDA(reset_gpio_ida);
 
 /**
  * struct reset_control - a reset control
- * @rcdev: a pointer to the reset controller device
- *         this reset control belongs to
- * @srcu: protects the rcdev pointer from removal during consumer access
+ * @rcdev_revocable: revocable handle for accessing the reset controller device
  * @list: list entry for the rcdev's reset controller list
  * @id: ID of the reset controller in the reset
  *      controller device
@@ -53,11 +51,10 @@ static DEFINE_IDA(reset_gpio_ida);
  *                   will be either 0 or 1.
  * @shared_lock: serializes the shared refcount update and the hardware op for
  *               controllers whose ops may sleep (rcdev->can_sleep); taken only
- *               inside the SRCU read-side critical section
+ *               with revocable access
  */
 struct reset_control {
-	struct reset_controller_dev __rcu *rcdev;
-	struct srcu_struct srcu;
+	struct revocable *rcdev_revocable;
 	struct list_head list;
 	unsigned int id;
 	struct kref refcnt;
@@ -144,6 +141,10 @@ int reset_controller_register(struct reset_controller_dev *rcdev)
 			return -EINVAL;
 	}
 
+	rcdev->revocable = revocable_alloc(rcdev);
+	if (!rcdev->revocable)
+		return -ENOMEM;
+
 	if (rcdev->of_xlate)
 		rcdev->fwnode_reset_n_cells = rcdev->of_reset_n_cells;
 
@@ -164,7 +165,6 @@ int reset_controller_register(struct reset_controller_dev *rcdev)
 EXPORT_SYMBOL_GPL(reset_controller_register);
 
 static void __reset_control_release(struct kref *kref);
-static void __reset_control_free(struct reset_control *rstc);
 
 /*
  * Removes rstc from its list and drops the references on rcdev's owner module
@@ -197,27 +197,29 @@ void reset_controller_unregister(struct reset_controller_dev *rcdev)
 		 * Numb but don't free the remaining reset control handles that are
 		 * still held by consumers.
 		 *
-		 * Hold a temporary reference on rstc before clearing rstc->rcdev:
-		 * once rstc->rcdev is NULL, a concurrent reset_control_put_internal()
-		 * will not acquire rcdev->lock and could otherwise free rstc.
+		 * Hold a temporary reference on rstc before revocable_revoke():
+		 * once revocable_revoke() clears the resource pointer, a concurrent
+		 * reset_control_put_internal() will not acquire rcdev->lock and
+		 * could otherwise free rstc.
 		 */
 		list_for_each_entry_safe(rstc, pos, &rcdev->reset_control_head, list) {
 			kref_get(&rstc->refcnt);
-			rcu_assign_pointer(rstc->rcdev, NULL);
 			list_move(&rstc->list, &reset_control_head);
 		}
 	}
 
 	/*
-	 * Run synchronize_srcu() outside rcdev->lock to avoid a circular
+	 * Run revocable_revoke() outside rcdev->lock to avoid a circular
 	 * locking dependency with paths that acquire rcdev->lock inside
-	 * the rstc->srcu read-side critical section.
+	 * the revocable access critical section.
 	 */
+	revocable_revoke(rcdev->revocable);
+	revocable_put(rcdev->revocable);
+
 	list_for_each_entry_safe(rstc, pos, &reset_control_head, list) {
-		synchronize_srcu(&rstc->srcu);
 		reset_controller_remove(rcdev, rstc);
 		if (kref_put(&rstc->refcnt, __reset_control_release))
-			__reset_control_free(rstc);
+			kfree(rstc);
 	}
 
 	mutex_destroy(&rcdev->lock);
@@ -438,11 +440,7 @@ int reset_control_reset(struct reset_control *rstc)
 	if (reset_control_is_array(rstc))
 		return reset_control_array_reset(rstc_to_array(rstc));
 
-	guard(srcu)(&rstc->srcu);
-
-	rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu);
-	if (!rcdev)
-		return -ENODEV;
+	revocable_try_access_or_return(rstc->rcdev_revocable, rcdev);
 
 	/*
 	 * For a shared reset only the first caller runs the hardware op while
@@ -590,11 +588,7 @@ int reset_control_assert(struct reset_control *rstc)
 	if (reset_control_is_array(rstc))
 		return reset_control_array_assert(rstc_to_array(rstc));
 
-	guard(srcu)(&rstc->srcu);
-
-	rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu);
-	if (!rcdev)
-		return -ENODEV;
+	revocable_try_access_or_return(rstc->rcdev_revocable, rcdev);
 
 	/*
 	 * For a shared reset the last caller runs the hardware op while the
@@ -695,11 +689,7 @@ int reset_control_deassert(struct reset_control *rstc)
 	if (reset_control_is_array(rstc))
 		return reset_control_array_deassert(rstc_to_array(rstc));
 
-	guard(srcu)(&rstc->srcu);
-
-	rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu);
-	if (!rcdev)
-		return -ENODEV;
+	revocable_try_access_or_return(rstc->rcdev_revocable, rcdev);
 
 	/*
 	 * For a shared reset only the first caller runs the hardware op while
@@ -762,11 +752,7 @@ int reset_control_status(struct reset_control *rstc)
 	if (WARN_ON(IS_ERR(rstc)) || reset_control_is_array(rstc))
 		return -EINVAL;
 
-	guard(srcu)(&rstc->srcu);
-
-	rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu);
-	if (!rcdev)
-		return -ENODEV;
+	revocable_try_access_or_return(rstc->rcdev_revocable, rcdev);
 
 	if (rcdev->ops->status)
 		return rcdev->ops->status(rcdev, rstc->id);
@@ -812,11 +798,7 @@ int reset_control_acquire(struct reset_control *rstc)
 	if (rstc->acquired)
 		return 0;
 
-	guard(srcu)(&rstc->srcu);
-
-	rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu);
-	if (!rcdev)
-		return -ENODEV;
+	revocable_try_access_or_return(rstc->rcdev_revocable, rcdev);
 
 	scoped_guard(mutex, &rcdev->lock) {
 		list_for_each_entry(rc, &rcdev->reset_control_head, list) {
@@ -912,7 +894,6 @@ __reset_control_get_internal(struct reset_controller_dev *rcdev,
 	bool shared = flags & RESET_CONTROL_FLAGS_BIT_SHARED;
 	bool acquired = flags & RESET_CONTROL_FLAGS_BIT_ACQUIRED;
 	struct reset_control *rstc;
-	int ret;
 
 	lockdep_assert_held(&rcdev->lock);
 
@@ -943,19 +924,13 @@ __reset_control_get_internal(struct reset_controller_dev *rcdev,
 	if (!rstc)
 		return ERR_PTR(-ENOMEM);
 
-	ret = init_srcu_struct(&rstc->srcu);
-	if (ret) {
-		kfree(rstc);
-		return ERR_PTR(ret);
-	}
-
 	if (!try_module_get(rcdev->owner)) {
-		cleanup_srcu_struct(&rstc->srcu);
 		kfree(rstc);
 		return ERR_PTR(-ENODEV);
 	}
 
-	rcu_assign_pointer(rstc->rcdev, rcdev);
+	revocable_get(rcdev->revocable);
+	rstc->rcdev_revocable = rcdev->revocable;
 	list_add(&rstc->list, &rcdev->reset_control_head);
 	rstc->id = index;
 	kref_init(&rstc->refcnt);
@@ -967,34 +942,12 @@ __reset_control_get_internal(struct reset_controller_dev *rcdev,
 	return rstc;
 }
 
-/*
- * Detaches rstc from rcdev (if still attached) when refcnt reaches 0.
- * If rstc is still attached, the caller must hold rcdev->lock.
- */
 static void __reset_control_release(struct kref *kref)
 {
 	struct reset_control *rstc = container_of(kref, struct reset_control,
 						  refcnt);
-	struct reset_controller_dev *rcdev;
-
-	rcdev = rcu_replace_pointer(rstc->rcdev, NULL, true);
-	if (rcdev) {
-		lockdep_assert_held(&rcdev->lock);
-		reset_controller_remove(rcdev, rstc);
-	}
-
 	mutex_destroy(&rstc->shared_lock);
-}
-
-/*
- * Must be called outside the rstc->srcu read-side critical section after
- * kref_put(..., __reset_control_release) returns true.
- */
-static void __reset_control_free(struct reset_control *rstc)
-{
-	synchronize_srcu(&rstc->srcu);
-	cleanup_srcu_struct(&rstc->srcu);
-	kfree(rstc);
+	revocable_put(rstc->rcdev_revocable);
 }
 
 static void reset_control_put_internal(struct reset_control *rstc)
@@ -1005,19 +958,19 @@ static void reset_control_put_internal(struct reset_control *rstc)
 	if (IS_ERR_OR_NULL(rstc))
 		return;
 
-	scoped_guard(srcu, &rstc->srcu) {
-		rcdev = srcu_dereference(rstc->rcdev, &rstc->srcu);
-		if (rcdev) {
-			guard(mutex)(&rcdev->lock);
-			ret = kref_put(&rstc->refcnt, __reset_control_release);
-		} else {
-			/* Already detached from rcdev. */
-			ret = kref_put(&rstc->refcnt, __reset_control_release);
-		}
+	revocable_try_access_with(rstc->rcdev_revocable, rcdev);
+	if (rcdev) {
+		guard(mutex)(&rcdev->lock);
+		ret = kref_put(&rstc->refcnt, __reset_control_release);
+		if (ret)
+			reset_controller_remove(rcdev, rstc);
+	} else {
+		/* Already detached from rcdev. */
+		ret = kref_put(&rstc->refcnt, __reset_control_release);
 	}
 
 	if (ret)
-		__reset_control_free(rstc);
+		kfree(rstc);
 }
 
 static void reset_gpio_aux_device_release(struct device *dev)
include/linux/reset-controller.h +3 -0
index 587fb57c2c52..4fe6c8a49e05 100644
@@ -28,6 +28,7 @@ struct reset_control_ops {
 struct module;
 struct device_node;
 struct of_phandle_args;
+struct revocable;
 
 /**
  * struct reset_controller_dev - reset controller entity that might
@@ -51,6 +52,7 @@ struct of_phandle_args;
  *             serialize the shared reset, assert and deassert paths under a
  *             mutex
  * @lock: protects the reset control list from concurrent access
+ * @revocable: revocable provider handle for itself
  */
 struct reset_controller_dev {
 	const struct reset_control_ops *ops;
@@ -69,6 +71,7 @@ struct reset_controller_dev {
 	unsigned int nr_resets;
 	bool can_sleep;
 	struct mutex lock;
+	struct revocable *revocable;
 };
 
 #if IS_ENABLED(CONFIG_RESET_CONTROLLER)
Signature · 1 line
2.53.0
#6 lore raw

Re: [PATCH v16 4/4] reset: Leverage revocable for accessing struct reset_controller_dev

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] reset: race in reset_controller_unregister() breaks reset_control_acquire() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] reset: race in reset_controller_unregister() breaks reset_control_acquire()
--

commit 898d975d7b1e8a5978d7e104db12ced65e4b60a4
Author: Tzung-Bi Shih <[email protected]>

reset: Leverage revocable for accessing struct reset_controller_dev

This commit replaces the per-handle SRCU instances in struct reset_control with a single reference-counted struct revocable allocated per reset_controller_dev.

Quoted 4 lines
drivers/reset/core.c +0 -0
index 0bff49d9b5586..afc17a3c698af 100644

[ ... ]

Quoted 18 lines
drivers/reset/core.c +4 -4
@@ -197,27 +197,29 @@ void reset_controller_unregister(struct reset_controller_dev *rcdev)
 		 * Numb but don't free the remaining reset control handles that are
 		 * still held by consumers.
 		 *
-		 * Hold a temporary reference on rstc before clearing rstc->rcdev:
-		 * once rstc->rcdev is NULL, a concurrent reset_control_put_internal()
-		 * will not acquire rcdev->lock and could otherwise free rstc.
+		 * Hold a temporary reference on rstc before revocable_revoke():
+		 * once revocable_revoke() clears the resource pointer, a concurrent
+		 * reset_control_put_internal() will not acquire rcdev->lock and
+		 * could otherwise free rstc.
 		 */
 		list_for_each_entry_safe(rstc, pos, &rcdev->reset_control_head, list) {
 			kref_get(&rstc->refcnt);
-			rcu_assign_pointer(rstc->rcdev, NULL);
 			list_move(&rstc->list, &reset_control_head);
 		}
 	}

drivers/reset/core.c void reset_controller_unregister(struct reset_controller_dev *rcdev) · line 217

Quoted 10 lines
drivers/reset/core.c +4 -2
 
 	/*
-	 * Run synchronize_srcu() outside rcdev->lock to avoid a circular
+	 * Run revocable_revoke() outside rcdev->lock to avoid a circular
 	 * locking dependency with paths that acquire rcdev->lock inside
-	 * the rstc->srcu read-side critical section.
+	 * the revocable access critical section.
 	 */
+	revocable_revoke(rcdev->revocable);
+	revocable_put(rcdev->revocable);

[Severity: Medium]
Can moving all handles off rcdev->reset_control_head before revocable_revoke() allow a concurrent reset_control_acquire() to succeed on an already-acquired exclusive reset line?

Previously, rcu_assign_pointer(rstc->rcdev, NULL) was executed under rcdev->lock alongside list_move(). Now the resource pointer is not cleared until revocable_revoke() runs after rcdev->lock is dropped:

CPU0 CPU1
reset_controller_unregister() reset_control_acquire(rstc)

                                        revocable_try_access_or_return()
                                          // gets valid rcdev
  lock(&rcdev->lock)
  list_move(&rstc->list, ...)
  unlock(&rcdev->lock)
                                        lock(&rcdev->lock)
                                        // rcdev->reset_control_head is empty
                                        rstc->acquired = true;  <-- bypasses check
                                        unlock(&rcdev->lock)

revocable_revoke(rcdev->revocable)

Because rcdev->reset_control_head has already been emptied, reset_control_acquire() does not see the other exclusive handle with rc->acquired == true and returns 0 instead of -EBUSY. If the second consumer then calls reset_control_reset(), reset_control_assert(), or reset_control_deassert() before revocable_revoke() clears the pointer, it can also manipulate the reset line while the first consumer still holds exclusive control.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#2 lore raw

Re: [PATCH v16 1/4] revocable: Revocable resource management

In reply to Tzung-Bi Shih
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] revocable: exclusive context lock annotations used for shared srcu_struct - [Low] revocable: missing…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] revocable: exclusive context lock annotations used for shared srcu_struct
- [Low] revocable: missing Return section in revocable_init() kernel-doc comment
--

commit 50e7a51b025e8180202192107f613bdccc5a9f5b
Author: Tzung-Bi Shih <[email protected]>

revocable: Revocable resource management

This commit introduces an SRCU-based revocable resource management primitive that provides safe access to resources that can be asynchronously removed.

Quoted 6 lines
drivers/base/revocable.c new file +0 -0
new file mode 100644
index 0000000000000..a7fcda012f3c6
@@ -0,0 +1,305 @@

[ ... ]

drivers/base/revocable.c line 79

Quoted 8 lines
drivers/base/revocable.c new file +8 -0
+/**
+ * revocable_init() - Initialize struct revocable.
+ * @rev: The pointer of resource provider.
+ * @res: The pointer of resource.
+ *
+ * This initializes a resource provider handle embedded within another struct.
+ */
+int revocable_init(struct revocable *rev, void *res)

[Severity: Low]
revocable_init() returns an int, but its kernel-doc comment has no Return:
section, causing scripts/kernel-doc to warn when run with -Wreturn (such as during W=2 builds).

[ ... ]

Quoted 6 lines
include/linux/revocable.h new file +0 -0
new file mode 100644
index 0000000000000..577ee1a8dc17e
@@ -0,0 +1,220 @@

[ ... ]

Quoted 6 lines
include/linux/revocable.h new file +6 -0
+void *revocable_try_access(struct revocable_handle *rh)
+	__acquires(&rh->rev->srcu);
+void revocable_withdraw_access(struct revocable_handle *rh)
+	__releases(&rh->rev->srcu);
+
+DEFINE_FREE(access_rev, struct revocable_handle *, if (_T) {

include/linux/revocable.h line 76

Quoted 10 lines
include/linux/revocable.h new file +10 -0
+	revocable_withdraw_access(_T);
+	revocable_handle_destroy(_T);
+})
+
+#define _revocable_try_access_with(_rev, _rh, _res)				\
+	struct revocable_handle _rh;						\
+	struct revocable_handle *__UNIQUE_ID(name) __free(access_rev) = &_rh;	\
+										\
+	revocable_handle_init(_rev, &_rh);					\
+	_res = revocable_try_access(&_rh)

[Severity: Low]
Should revocable_try_access() and revocable_withdraw_access() use __acquires_shared(&rh->rev->srcu) and __releases_shared(&rh->rev->srcu) here and in drivers/base/revocable.c?

srcu_read_lock() and srcu_read_unlock() acquire and release srcu_struct in shared mode (__acquires_shared / __releases_shared), so the exclusive __acquires and __releases annotations trigger Clang -Wthread-safety warnings when context analysis is enabled.

In addition, _revocable_try_access_with() and _revocable_try_access_with_scoped() call revocable_try_access(&_rh) directly in the caller's scope while relying on DEFINE_FREE(access_rev, ...) to release the SRCU read lock at scope exit. Because DEFINE_FREE() generates __free_access_rev() with __context_unsafe and no release annotation, Clang context analysis reports &_rh.rev->srcu as still held at the end of the caller scope.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1