RCU pseudo-transactions
Mathieu Desnoyers
reviewercover RCU pseudo-transactions
Hi,
Earlier this year, I came up with a neat trick which reduces the mental challenge of adapting data structures to RCU. It turns out that it also widens the applicability of RCU to additional classes of data structures.
This is done by a low-overhead abstraction which I'm naming "RCU Pseudo-Transactions" [1, 2]. I name this "pseudo" because unlike classic transactions, the writers exclude each other, readers get no snapshot, and there is no abort.
How it works:
- Reader (rcu_txn_dereference()):
- Load (rcu_dereference()) pointer from slot.
- Fast path (no proxy installed): unlikely low-bit tag test and conditional branch (not taken).
- Slow path (proxy installed): low-bit tag test, taken branch, the proxy points at the slot's record, select old or new via the group selector word (0/1) (load-acquire). Still wait-free.
- Pointer constraint: Slots must hold pointers which are at least 2-byte aligned when using the low bit as tag and must not use the low bit for anything else. NULL is handled as a plain value.
- Updater (caller provides mutual exclusion):
- Allocate a transaction descriptor (gfp flags provided by the caller).
- Append records to the descriptor. (each slot appears at most once per transaction)
- Commit (works in atomic context):
- Install proxy pointers into each slot. (store-release)
- Commit (flip group selector from 0 to 1). (store-release)
- Settle (each slot loses the proxy, gets the new pointer value). (store-release)
- kfree_rcu the transaction descriptor.
Here are the key highlights:
- It enables atomic publication of multiple pointers observed by concurrent RCU readers. It removes the tricky "but what if a reader observes this intermediate state" conundrum typically present when porting a data structure to RCU. A reader that loads one slot before the commit and another after it sees old then new values, never the reverse along a chain of dependent loads (or with an acquire between them).
- It allows composing data structures: a node can be published atomically into many data structures (e.g. hash bucket list and LRU list).
- It removes ordering requirements on multiple object publication with respect to RCU traversal order.
- Can be used as a building block for fine-grained data structure locking (see the second example in this series).
- It enables RCU traversals of cyclic graphs with arbitrary traversal order.
- It allows replacing sequence locks and reader-writer locks in many use-cases, providing read-side wait-free progress guarantees, in scenarios where readers need a coherent walk rather than a snapshot of several fields.
- It removes the need to copy data structure nodes for updates:
multiple pointer (and data field) updates can be performed in-place on memory that cannot be reallocated.
I have presented it at LPC [1] and uploaded an article [2] detailing the idea as a defensive publication. There are no patent claims on this work.
In this RFC, I'm presenting a port of rcu_txn to the Linux kernel, along with a list and hlist API built on top of it. You will also find composed hash bucket list and LRU list examples near the end of the series. I've implemented one example with a single mutex, and the other using RCU for neighborhood lookup and fine-grained per-node locking.
I considered various alternatives such as Paul McKenney's "existence guarantees" work (2015), seqlock, rwlocks, RLU, MV-RLU, and k-CAS (all discussed in the paper), but RCU pseudo-transactions performed better than the alternatives in my benchmarks due to smaller cache footprint and fewer read-side fast path instructions. I have applied this to a partial port of the dentry cache to userspace; compared to a straight userspace port of the current kernel scheme, the rcu_txn variant shows up to 6.75x speedup for reverse walk under concurrent renames, and up to 21.56x speedup on writer throughput when scaling to 8 writers with 184 concurrent readers under a leaf name exchange workload (see LPC slides).
About the development process of this feature: I have used an LLM coding assistant (Claude) throughout the development of this feature. The novel ideas are my own, and I have carefully followed its progress, guided it towards acceptable solutions when it was hitting walls, and reviewed the resulting code.
Origin story: I came up with this idea while working on a userspace RCU trie data structure which I named Fractal Trie (still in development), and I needed to be able to atomically publish parent/child pointer updates on nodes which were controlled by the application (therefore not mine to reallocate).
The series is based on v7.3-rc7.
- Patch 1: rcu_txn core API.
- Patch 2: KUnit tests for the core API.
- Patch 3: Bloom filter so appending a record to a large transaction does not require an O(n) scan for an existing record for that slot (O(n^2) overall).
- Patch 4: rcu_txn_adopt, debug config option for internal consistency checks.
- Patches 5-6: composable singly and doubly linked lists on top of rcu_txn.
- Patch 7: documentation.
- Patch 8: litmus tests.
- Patch 9: list writer stress test.
- Patch 10: test of commit in atomic context.
- Patches 11-12: usage example for composed data structures: a cache whose nodes are present in both a bucket hlist and an LRU list, one variant with a single mutex, the other with RCU neighborhood lookup and per-node locking.
There are a few areas where I suspect this abstraction could help in the Linux kernel, namely the VFS layer and mm_struct VMA tree / per-VMA locking. I'm interested to hear whether this is useful in other subsystems.
I'd specifically like feedback on:
- Where this should live (kernel/rcu/, lib/?),
- Naming and API shape (descriptor + records),
- Whether the Bloom filter threshold should be a config knob,
- Subsystems where this could apply.
Enjoy!
Mathieu
References:
[1] "RCU Pseudo-Transactions: Bridging the gap between RCU and STM", Mathieu Desnoyers,
Linux Plumbers Conference 2026 Refereed Track, October 2026.
https://lpc.events/event/20/contributions/2348/
[2] "RCU Pseudo-Transactions and the Single-Writer Flip-Latch:
Atomic Multi-Slot Publication for Read-Copy-Update Data Structures", Mathieu Desnoyers, October 2026.
https://www.efficios.com/pub/rcu-txn/mathieu-desnoyers-rcu-pseudo-transactions.pdf
Mathieu Desnoyers (12):
rcu_txn: Add single-writer RCU pseudo-transactions
rcu_txn: Add KUnit tests
rcu_txn: Skip the record lookup with a Bloom filter
rcu_txn: Add CONFIG_DEBUG_RCU_TXN
rcu_txn: Add an hlist edited through transactions
rcu_txn: Add a doubly-linked list coherent in both directions Documentation/RCU: Describe RCU pseudo-transactions Documentation/litmus-tests: Add RCU pseudo-transaction tests
rcu_txn: Test a list writer against concurrent readers
rcu_txn: Test a commit from atomic context
samples: Add a cache on RCU pseudo-transactions under one mutex
samples: Add a cache on RCU pseudo-transactions with a lock per node
Documentation/RCU/index.rst | 1 + Documentation/RCU/rcu_txn.rst | 255 ++ Documentation/litmus-tests/README | 37 + .../rcu/RCU-txn+install+once-install.litmus | 55 + .../litmus-tests/rcu/RCU-txn+install.litmus | 66 + .../RCU-txn+list+step-back+once-flip.litmus | 78 + .../RCU-txn+list+step-back+once-settle.litmus | 78 + .../rcu/RCU-txn+list+step-back.litmus | 85 + ...-txn+monotonic+acquire+once-resolve.litmus | 79 + .../rcu/RCU-txn+monotonic+acquire.litmus | 81 + .../RCU-txn+monotonic+dep+once-flip.litmus | 77 + .../RCU-txn+monotonic+dep+once-settle.litmus | 77 + .../rcu/RCU-txn+monotonic+dep.litmus | 83 + .../rcu/RCU-txn+monotonic+unordered.litmus | 84 + .../rcu/RCU-txn+publish+once-install.litmus | 60 + .../rcu/RCU-txn+publish+once-settle.litmus | 60 + .../litmus-tests/rcu/RCU-txn+publish.litmus | 71 + .../rcu/RCU-txn+remove+nolock.litmus | 64 + .../rcu/RCU-txn+remove+nosync.litmus | 64 + .../rcu/RCU-txn+remove+once-install.litmus | 65 + .../litmus-tests/rcu/RCU-txn+remove.litmus | 72 + .../rcu/RCU-txn+sync+free+nolock.litmus | 55 + .../rcu/RCU-txn+sync+free+nosync.litmus | 55 + .../litmus-tests/rcu/RCU-txn+sync+free.litmus | 60 + MAINTAINERS | 11 + include/linux/rcu_txn.h | 1036 ++++++++ include/linux/rcu_txn_bloom.h | 110 + include/linux/rcu_txn_hlist.h | 486 ++++ include/linux/rcu_txn_list.h | 544 +++++ kernel/rcu/Kconfig.debug | 16 + lib/Kconfig | 3 + lib/Kconfig.debug | 13 + lib/Makefile | 2 + lib/rcu_txn.c | 142 ++ lib/rcu_txn_internal.h | 129 + lib/tests/Makefile | 1 + lib/tests/rcu_txn_kunit.c | 2150 +++++++++++++++++ samples/Kconfig | 13 + samples/Makefile | 1 + samples/rcu_txn/Makefile | 2 + samples/rcu_txn/rcu_txn_cache_mutex.c | 354 +++ samples/rcu_txn/rcu_txn_cache_node_lock.c | 713 ++++++ 42 files changed, 7488 insertions(+) create mode 100644 Documentation/RCU/rcu_txn.rst create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+install+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-flip.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire+once-resolve.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-flip.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+unordered.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+nolock.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+nosync.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free+nolock.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free+nosync.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free.litmus create mode 100644 include/linux/rcu_txn.h create mode 100644 include/linux/rcu_txn_bloom.h create mode 100644 include/linux/rcu_txn_hlist.h create mode 100644 include/linux/rcu_txn_list.h create mode 100644 lib/rcu_txn.c create mode 100644 lib/rcu_txn_internal.h create mode 100644 lib/tests/rcu_txn_kunit.c create mode 100644 samples/rcu_txn/Makefile create mode 100644 samples/rcu_txn/rcu_txn_cache_mutex.c create mode 100644 samples/rcu_txn/rcu_txn_cache_node_lock.c
base-commit: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907
Signature · 1 line
2.47.3
Mathieu Desnoyers
reviewerRFC PATCH 1/12 rcu_txn: Add single-writer RCU pseudo-transactions
rcu_assign_pointer() publishes one pointer atomically. An update that re-points several pointers exposes its intermediate states to RCU
readers: a reader that loads two of them may see the new value of one and then the old value of the other. Moving an object between two hash buckets and editing a doubly-linked list are such updates.
Add RCU pseudo-transactions, which switch a set of RCU-protected pointers from their old to their new values with a single store, as observed by readers. The writer records one {slot, old, new} triple per pointer, then commits:
1. Install: each slot is made to point at its record, tagged so that readers recognise a proxy. A proxy resolves through a selector shared by the records of the transaction, to its old target.
2. Commit: one store to the selector makes every proxy resolve to its new target.
3. Settle: each slot is overwritten with its new target, and the records are freed after a grace period.
Readers use rcu_txn_dereference() in place of rcu_dereference(). On a slot that holds no proxy, it adds a test of the tag bits.
Writers of a slot are excluded by the caller, as for any RCU update. The transaction has no read set, no conflict detection and no abort, and readers get no snapshot, hence "pseudo".
A transaction of a single record installs no proxy and commits with one rcu_assign_pointer(). A writer that may write the same slot twice reads it back with rcu_txn_load() and records with rcu_txn_record_chain(), which keeps one record per slot. The lookup is a linear scan of the records, which rcu_txn_declare_disjoint() turns off.
The records and the selector live in one descriptor, allocated with the gfp_t given to rcu_txn_init() and freed with kfree_rcu() after a commit that installed proxies. A descriptor that installed none, after a commit of one record or a cancel, owes no grace period: it is freed with kfree() or, on PREEMPT_RT, with kfree_rcu(): rcu_txn_commit() and rcu_txn_cancel() may then be called under a raw or a bit spinlock on every kernel, as a hash table with hlist_bl buckets does. An allocation failure is sticky and reported by rcu_txn_commit(), which then publishes nothing. Slots are __rcu pointers, handed over as void __rcu ** through rcu_txn_slot() so that sparse checks the annotation.
The inline paths are in <linux/rcu_txn.h>. What allocates or frees a descriptor, and the commit of two records or more, are in lib/rcu_txn.c, built with the hidden CONFIG_RCU_TXN that users select; the header does not include <linux/slab.h>.
Add a MAINTAINERS entry for the new files.
--- MAINTAINERS | 7 + include/linux/rcu_txn.h | 765 ++++++++++++++++++++++++++++++++++++++++ lib/Kconfig | 3 + lib/Makefile | 2 + lib/rcu_txn.c | 105 ++++++ lib/rcu_txn_internal.h | 50 +++ 6 files changed, 932 insertions(+) create mode 100644 include/linux/rcu_txn.h create mode 100644 lib/rcu_txn.c create mode 100644 lib/rcu_txn_internal.h
MAINTAINERS +7 -0
@@ -22853,6 +22853,13 @@ M: Patrick Lerda <[email protected]> S: Maintained F: drivers/media/rc/ir-rcmm-decoder.c +RCU PSEUDO-TRANSACTIONS +M: Mathieu Desnoyers <[email protected]> +L: [email protected] +S: Maintained +F: include/linux/rcu_txn*.h +F: lib/rcu_txn* + RCUTORTURE TEST FRAMEWORK M: "Paul E. McKenney" <[email protected]> M: Josh Triplett <[email protected]>
include/linux/rcu_txn.h new file +765 -0
765 lines not on this page · raw message
lib/Kconfig +3 -0
@@ -366,6 +366,9 @@ config ASSOCIATIVE_ARRAY config CLOSURES bool +config RCU_TXN + bool + config HAS_IOMEM bool depends on !NO_IOMEM
lib/Makefile +2 -0
@@ -223,6 +223,8 @@ obj-$(CONFIG_CPU_RMAP) += cpu_rmap.o obj-$(CONFIG_CLOSURES) += closure.o +obj-$(CONFIG_RCU_TXN) += rcu_txn.o + obj-$(CONFIG_DQL) += dynamic_queue_limits.o obj-$(CONFIG_GLOB) += glob.o
lib/rcu_txn.c new file +105 -0
105 lines not on this page · raw message
lib/rcu_txn_internal.h new file +50 -0
50 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 01/12] rcu_txn: Add single-writer RCU pseudo-transactions
On Fri, Oct 16, 2026 at 09:33:08AM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 7 lines
The records and the selector live in one descriptor, allocated with the
gfp_tgiven torcu_txn_init()and freed withkfree_rcu()after a commit that installed proxies. A descriptor that installed none, after a commit of one record or a cancel, owes no grace period: it is freed withkfree()or, onPREEMPT_RT, withkfree_rcu():rcu_txn_commit()andrcu_txn_cancel()may then be called under a raw or a bit spinlock on every kernel, as a hash table withhlist_blbuckets does. An allocation
This isn't quite true on !PREEMPT_RT. As far as lockdep is concerned, kfree() can't be called under a raw_spinlock_t on any kernel: once the per-CPU sheaf is full, SLUB takes barn->lock, a spinlock_t, and PROVE_RAW_LOCK_NESTING flags that whether or not PREEMPT_RT is set. kfree_rcu() gets away with it because mm/slub.c annotates its sheaf path for exactly this case (kfree_rcu_sheaf_map); kfree() has no such annotation.
[...]
Review
Quoted 11 lines
(quoted diff) +11
-0+/* + * Free a descriptor that installed no proxy, which owes no grace period. + * commit() and cancel() may run under a raw or a bit spinlock, where + * PREEMPT_RT does not allow kfree(). It does allow kfree_rcu(). + */ +void __rcu_txn_free_desc(struct rcu_txn_desc *desc) +{ + if (IS_ENABLED(CONFIG_PREEMPT_RT)) + kfree_rcu(desc, rcu_head); + else + kfree(desc);
A single commit rarely trips it, since barn->lock is only taken once the sheaf is full, and lockdep skips the wait-context check for the fast path's trylock. 4096 reserved one-record commits under one raw spinlock do trip it. This is the series as posted, on arm64 with PROVE_LOCKING and PROVE_RAW_LOCK_NESTING:
[ BUG: Invalid wait context ]
kunit_try_catch/44 is trying to lock:ffff000001804318 (&barn->lock){....}-{3:3}, at: __pcs_replace_full_main+0x4b4/0x514 locks held by kunit_try_catch/44: 2, last CPU#1:
#0: ffff80008080c120 (exp_raw_lock){....}-{2:2}, at: exp_bulk+0x1cc/0x2fc
#1: ffff00003fda37a0 ((local_lock_t *)&pcs->lock){+.+.}-{3:3}, at: local_trylock_acquire+0x14/0x8c
[...]
Call trace: _raw_spin_lock_irqsave+0x60/0x88 __pcs_replace_full_main+0x4b4/0x514 kfree+0x400/0x43c __rcu_txn_free_desc+0x10/0x1c rcu_txn_commit+0x54/0x11c exp_bulk+0x250/0x2fc rcu_txn_test_exp_bulk_commit_raw+0x14/0x20
Cancels give the same splat, and so does a loop doing one commit per raw-lock section once the sheaf fills up.
Using kfree_rcu() unconditionally fixes it, and the rest of the suite still passes (against the top of the series):
lib/rcu_txn.c +1 -4
@@ -73,9 +73,6 @@ static struct rcu_txn_desc *rcu_txn_desc_alloc(unsigned int cap, gfp_t gfp)*/ void __rcu_txn_free_desc (struct rcu_txn_desc *desc) { -if (IS_ENABLED (CONFIG_PREEMPT_RT )) -kfree_rcu (desc, rcu_head); -else -kfree (desc); +kfree_rcu (desc, rcu_head); }EXPORT_SYMBOL_GPL (__rcu_txn_free_desc);
The cost is a grace period of delay before freeing descriptors that never installed a proxy. I'd take that over a wait-type override around the !PREEMPT_RT kfree(), since it also removes the RT/!RT split.
This makes a few comments stale: the kerneldoc of rcu_txn_cancel(), the comment above __rcu_txn_free_desc(), the two "no proxy: free now" comments, the comment above rcu_txn_test_single_record() in patch 2 and the one above rcu_txn_test_commit_atomic() in patch 10, plus the commit messages of patches 1 and 10. On the other hand, the "Readers and reclaim" comment, which says commit reclaims with kfree_rcu(), and the raw spinlock paragraph in rcu_txn.rst only become true with it.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 01/12] rcu_txn: Add single-writer RCU pseudo-transactions
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 4 lines
This isn't quite true on !PREEMPT_RT. As far as lockdep is concerned,
kfree()can't be called under araw_spinlock_ton any kernel: once the per-CPU sheaf is full, SLUB takesbarn->lock, aspinlock_t, andPROVE_RAW_LOCK_NESTINGflags that whether or notPREEMPT_RTis set.
You are right. Thanks for tracking it down to barn->lock.
[...]
Quoted 3 lines
The cost is a grace period of delay before freeing descriptors that never installed a proxy. I'd take that over a wait-type override around the !PREEMPT_RT
kfree(), since it also removes the RT/!RT split.
Agreed. The next version will free every heap descriptor with kfree_rcu(). This includes the old descriptor that a grow replaces. A grow can run with GFP_ATOMIC under a raw spinlock too.
The descriptors of the per-CPU pool, which the list operations will use, never go back to the slab allocator. One that installed no proxy returns to its pool at once, without the grace period.
Updating the comments and commit messages you listed is planned too. The atomic-context test (patch 10) will reproduce your splat when kfree() is put back. See my reply there.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 2/12 rcu_txn: Add KUnit tests
In reply to Mathieu DesnoyersTest the RCU pseudo-transactions: commits of one and of several records, the three steps of a commit as a reader observes them, typed slots, growth and reservation of a transaction, cancellation, the sticky allocation failure, reading back one's own writes, and misuse of a handle.
The steps of a commit are staged by hand through lib/rcu_txn_internal.h, since rcu_txn_commit() runs them back to back.
A misuse reports through WARN_ON_ONCE(), which the tests suppress and count. Where the architecture does not keep a WARN_ON_ONCE()'s once state in its bug table (no __WARN_FLAGS), it fires once per boot whether it is suppressed or not, so the count is only checked to be at most one there.
--- MAINTAINERS | 1 + lib/Kconfig.debug | 13 ++ lib/tests/Makefile | 1 + lib/tests/rcu_txn_kunit.c | 463 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 478 insertions(+) create mode 100644 lib/tests/rcu_txn_kunit.c
MAINTAINERS +1 -0
@@ -22859,6 +22859,7 @@ L: [email protected] S: Maintained F: include/linux/rcu_txn*.h F: lib/rcu_txn* +F: lib/tests/rcu_txn_kunit.c RCUTORTURE TEST FRAMEWORK M: "Paul E. McKenney" <[email protected]>
lib/Kconfig.debug +13 -0
@@ -2844,6 +2844,19 @@ config LIST_PRIVATE_KUNIT_TEST If unsure, say N. +config RCU_TXN_KUNIT_TEST + tristate "KUnit Test for single-writer RCU pseudo-transactions" if !KUNIT_ALL_TESTS + depends on KUNIT + select RCU_TXN + default KUNIT_ALL_TESTS + help + This builds the KUnit test suite of the single-writer RCU + pseudo-transactions defined in include/linux/rcu_txn.h. It tests + the commit of a transaction as readers observe it, and the + lifecycle of a transaction handle, including its misuse. + + If unsure, say N. + config HASHTABLE_KUNIT_TEST tristate "KUnit Test for Kernel Hashtable structures" if !KUNIT_ALL_TESTS depends on KUNIT
lib/tests/Makefile +1 -0
@@ -44,6 +44,7 @@ obj-$(CONFIG_OVERFLOW_KUNIT_TEST) += overflow_kunit.o obj-$(CONFIG_PRANDOM_KUNIT_TEST) += random32_kunit.o obj-$(CONFIG_PRINTF_KUNIT_TEST) += printf_kunit.o obj-$(CONFIG_RANDSTRUCT_KUNIT_TEST) += randstruct_kunit.o +obj-$(CONFIG_RCU_TXN_KUNIT_TEST) += rcu_txn_kunit.o obj-$(CONFIG_SCANF_KUNIT_TEST) += scanf_kunit.o obj-$(CONFIG_SEQ_BUF_KUNIT_TEST) += seq_buf_kunit.o obj-$(CONFIG_SIPHASH_KUNIT_TEST) += siphash_kunit.o
lib/tests/rcu_txn_kunit.c new file +463 -0
463 lines not on this page · raw message
Signature · 1 line
2.47.3
Mathieu Desnoyers
reviewerRFC PATCH 3/12 rcu_txn: Skip the record lookup with a Bloom filter
In reply to Mathieu Desnoyersrcu_txn_load() and rcu_txn_record_chain() look the slot up among the records of the transaction with a linear scan, so a transaction of n records costs O(n) per access and O(n^2) to build. Most lookups miss.
Answer the miss from a Bloom filter: a clear bit means the slot is not recorded, and the scan is skipped. A hit still goes to the scan, so the filter never changes an answer.
The filter is armed by the first lookup that faces RCU_TXN_BLOOM_MIN records, and is not even zeroed before that. Most transactions hold a record or two, for which the scan is cheaper than hashing.
The filter takes 128 bytes, which the handle does not carry, as it lives on the stack: the filter lives in the descriptor, past the records. A descriptor of RCU_TXN_BLOOM_MIN records or more has room for it among the slots of its records array, which the array's __counted_by() covers, and a resize carries an armed filter over to the new descriptor.
--- include/linux/rcu_txn.h | 89 ++++++++++++++++++-- include/linux/rcu_txn_bloom.h | 110 +++++++++++++++++++++++++ lib/rcu_txn.c | 36 ++++++++- lib/tests/rcu_txn_kunit.c | 147 ++++++++++++++++++++++++++++++++++ 4 files changed, 373 insertions(+), 9 deletions(-) create mode 100644 include/linux/rcu_txn_bloom.h
include/linux/rcu_txn.h +82 -7
@@ -102,6 +102,7 @@#include <linux/errno.h> #include <linux/gfp_types.h> #include <linux/rcupdate.h> +#include <linux/rcu_txn_bloom.h> /* read-your-own-writes filter */ #include <linux/stddef.h> #include <linux/string.h> #include <linux/types.h>
@@ -197,7 +198,13 @@ struct rcu_txn_desc {struct rcu_txn_group group;/* read by installed proxies */ struct rcu_head rcu_head;/* deferred-free handle */ unsigned int cap;/* records it can hold */ - struct rcu_txn_record records[] __counted_by(cap); +/* +* Record-sized slots of the allocation: the @cap records and, in a +* descriptor of RCU_TXN_BLOOM_MIN records or more, past them, the +* read-your-own-writes filter (__rcu_txn_bloom()). +*/ +unsigned int slots; + struct rcu_txn_record records[] __counted_by(slots); };/*
@@ -218,6 +225,7 @@ struct rcu_txn {gfp_t gfp;/* for the descriptor */ enum rcu_txn_state state;bool disjoint;/* declared slot-disjoint */ +bool bloom_live;/* the descriptor's filter is armed */ };/*
@@ -463,9 +471,10 @@ static inline void __rcu_txn_done(struct rcu_txn *t)/* * Scan this transaction's records for @slot, or NULL. Linear, so O(nr) per -* call and O(nr^2) to build a write set. The returned pointer is invalidated -* by the next record() (a grow may move the records), so use it before -* recording again. +* call and O(nr^2) to build a write set -- __rcu_txn_find_ryw() below is what +* keeps that off the hot path. The returned pointer is invalidated by the +* next record() (a grow may move the records), so use it before recording +* again. */ static inline struct rcu_txn_record *__rcu_txn_scan (const struct rcu_txn *t,void __rcu **slot)
@@ -478,6 +487,69 @@ static inline struct rcu_txn_record *__rcu_txn_scan(const struct rcu_txn *t,return NULL ; } +/* +* RCU_TXN_BLOOM_MIN: the record count from which the read-your-own-writes +* filter (<linux/rcu_txn_bloom.h>) is used. Below it the filter is never +* armed, nor even zeroed. +* +* rcu_txn_load() is only called on a slot about to be recorded, so loads +* track records one for one, and most transactions are tiny: one edge for an +* hlist operation, two for a list operation. Scanning that many records is +* cheaper than hashing. +* +* The filter is built and armed by the first __rcu_txn_find_ryw() that faces +* at least this many records, then kept current by every record(). Arming on +* the record that crosses the threshold instead would make a transaction of +* exactly RCU_TXN_BLOOM_MIN records build a filter it never tests. +* +* The filter lives in the descriptor, past the records, so that the handle on +* the stack does not carry it. A descriptor of this many records or more has +* room for it (rcu_txn_desc_alloc()). +*/ +#define RCU_TXN_BLOOM_MIN 8 + +static_assert (RCU_TXN_BLOOM_MIN >1 ); + +/* The filter of the handle's descriptor: see RCU_TXN_BLOOM_MIN. */ +static inline u64 *__rcu_txn_bloom (const struct rcu_txn *t) +{ +return (u64 *)&t->desc->records[t->desc->cap]; +} + +/* +* Build the filter from the records so far and arm it. See +* RCU_TXN_BLOOM_MIN. +*/ +static inline void __rcu_txn_bloom_arm (struct rcu_txn *t) +{ +u64 *bloom =__rcu_txn_bloom (t); +unsigned int i; + +memset (bloom,0 ,RCU_TXN_BLOOM_SIZE ); +for (i =0 ; i < t->nr; i++) +rcu_txn_bloom_set (bloom, t->records[i].slot); + t->bloom_live = true; +} + +/* +* __rcu_txn_scan() behind the filter: a clear bit means the slot is not +* recorded, and the scan is skipped. All k bits set leaves the answer to the +* scan, which rules out a false positive. The filter never changes the answer. +*/ +static inline struct rcu_txn_record *__rcu_txn_find_ryw (struct rcu_txn *t, +void __rcu **slot) +{ +if (unlikely (!t->bloom_live)) { +/* Armed on first use: see RCU_TXN_BLOOM_MIN. */ +if (t->nr <RCU_TXN_BLOOM_MIN ) +return __rcu_txn_scan (t, slot); +__rcu_txn_bloom_arm (t); + } +if (!rcu_txn_bloom_test (__rcu_txn_bloom (t), slot)) +return NULL ;/* definitely absent */ +return __rcu_txn_scan (t, slot); +} +/* * Grow a full handle: double its capacity, or give an unreserved handle its * first RCU_TXN_CAP records. Returns false if it cannot allocate.
@@ -531,6 +603,8 @@ static inline bool rcu_txn_record(struct rcu_txn *t, void __rcu **slot,return false;/* OOM, now sticky */ r = &t->records[t->nr++];__rcu_txn_record_set (r, slot, old_ptr, new_ptr, tag); +if (unlikely (t->bloom_live))/* armed: keep it current */ +rcu_txn_bloom_set (__rcu_txn_bloom (t), slot);return true; }
@@ -579,7 +653,8 @@ static inline bool rcu_txn_record(struct rcu_txn *t, void __rcu **slot,* a list, may write the same slot. * * This skips the lookup among the records so far on every load and record, a -* scan: a small saving from the second record on. +* scan or, past RCU_TXN_BLOOM_MIN records, a Bloom filter test: a small saving +* from the second record on. * * Recording a slot twice on such a handle breaks the rule of rcu_txn_record(), * with the consequence stated there.
@@ -619,7 +694,7 @@ static inline void *rcu_txn_load(struct rcu_txn *t, void __rcu **slot,/* A consumed handle has no record left: it reads committed values. */ WARN_ON_ONCE (t->state ==RCU_TXN_DONE );if (!t->disjoint) { - r =__rcu_txn_scan (t, slot); + r =__rcu_txn_find_ryw (t, slot);if (r)return r->ptr[1 ];/* our own pending write */ }
@@ -637,7 +712,7 @@ static inline bool __rcu_txn_chain(struct rcu_txn *t, void __rcu **slot, {struct rcu_txn_record *r; - r =__rcu_txn_scan (t, slot); + r =__rcu_txn_find_ryw (t, slot);if (!r)return rcu_txn_record (t, slot, old_ptr, new_ptr, tag); r->ptr[1 ] = new_ptr;/* committed old preserved */
include/linux/rcu_txn_bloom.h new file +110 -0
110 lines not on this page · raw message
lib/rcu_txn.c +34 -2
@@ -9,6 +9,8 @@*/ #include <linux/export.h> +#include <linux/math.h> +#include <linux/minmax.h> #include <linux/overflow.h> #include <linux/rcu_txn.h> #include <linux/rcupdate.h>
@@ -17,6 +19,24 @@#include "rcu_txn_internal.h" +/* Record-sized slots that the filter takes, past the records. */ +#define RCU_TXN_BLOOM_SLOTS \ + DIV_ROUND_UP(RCU_TXN_BLOOM_SIZE, sizeof(struct rcu_txn_record)) + +/* +* The records that a descriptor of @slots record-sized slots holds. Once they +* are RCU_TXN_BLOOM_MIN or more, the filter takes the slots past them: a +* descriptor with slots for that many records but not for the filter as well +* holds RCU_TXN_BLOOM_MIN - 1 records. +*/ +static unsigned int rcu_txn_desc_cap (unsigned int slots) +{ +if (slots <RCU_TXN_BLOOM_MIN ) +return slots; + return max_t(unsigned int, slots - RCU_TXN_BLOOM_SLOTS, +RCU_TXN_BLOOM_MIN -1 ); +} +/* * Allocate a transaction descriptor for at least @cap records, with its flip * group initialized. Its capacity is what the allocation holds, which may be
@@ -32,12 +52,17 @@ static struct rcu_txn_desc *rcu_txn_desc_alloc(unsigned int cap, gfp_t gfp)struct rcu_txn_desc *desc;size_t size; - size =kmalloc_size_roundup (struct_size (desc, records, cap)); + size =struct_size (desc, records, cap); +if (cap >=RCU_TXN_BLOOM_MIN ) + size =size_add (size,RCU_TXN_BLOOM_SLOTS * +sizeof (struct rcu_txn_record )); + size =kmalloc_size_roundup (size); desc =kmalloc (size, gfp);if (!desc)return NULL ;__rcu_txn_group_init (&desc->group); - desc->cap = (size -sizeof (*desc)) /sizeof (desc->records[0 ]); + desc->slots = (size -sizeof (*desc)) /sizeof (desc->records[0 ]); + desc->cap =rcu_txn_desc_cap (desc->slots);return desc; }
@@ -66,6 +91,13 @@ bool __rcu_txn_resize(struct rcu_txn *t, unsigned int cap)if (t->nr)/* @records is NULL until first allocated */ memcpy (desc->records, t->records, (size_t )t->nr *sizeof (*desc->records)); +/* +* An armed filter moves too: both descriptors hold RCU_TXN_BLOOM_MIN +* records or more, so both have room for it. +*/ +if (t->bloom_live) +memcpy (&desc->records[desc->cap],__rcu_txn_bloom (t), +RCU_TXN_BLOOM_SIZE );kfree (t->desc);/* NULL if it had none */ t->desc = desc; t->records = desc->records;
lib/tests/rcu_txn_kunit.c +147 -0
159 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 03/12] rcu_txn: Skip the record lookup with a Bloom filter
On Fri, Oct 16, 2026 at 09:33:10AM -0400, Mathieu Desnoyers wrote:
[...]
Review
Quoted 7 lines
(quoted diff) +1
-1/* A consumed handle has no record left: it reads committed values. */ WARN_ON_ONCE(t->state == RCU_TXN_DONE); if (!t->disjoint) { - r = __rcu_txn_scan(t, slot); + r = __rcu_txn_find_ryw(t, slot); if (r) return r->ptr[1]; /* our own pending write */
This patch adds t->bloom_live, but __rcu_txn_done() never clears it. So on a committed or cancelled handle that had armed its filter, rcu_txn_load() warns about the DONE state and then dereferences the now-NULL t->desc in __rcu_txn_bloom(). Recording 16 slots through rcu_txn_load() and rcu_txn_record_chain(), committing, and then calling rcu_txn_load() again gives:
# rcu_txn_test_exp_consumed_bloom: after commit: desc 0000000000000000 bloom_live 1 Unable to handle kernel NULL pointer dereference at virtual address 0000000000000018 [...] pc : rcu_txn_load.constprop.0+0xfc/0x284
Patch 7 says misuse of a handle warns in every build, so this should only warn. Clearing the flag in __rcu_txn_done() does that:
include/linux/rcu_txn.h +1 -0
@@ -615,5 +615,6 @@ static inline void __rcu_txn_done(struct rcu_txn *t) t->desc =NULL ; t->records =NULL ; t->nr =0 ; + t->bloom_live = false; t->state =RCU_TXN_DONE ; }
[...]
Review
Quoted 5 lines
(quoted diff) +4
-1- size = kmalloc_size_roundup(struct_size(desc, records, cap)); + size = struct_size(desc, records, cap); + if (cap >= RCU_TXN_BLOOM_MIN) + size = size_add(size, RCU_TXN_BLOOM_SLOTS * + sizeof(struct rcu_txn_record));
The room for the filter costs more than the filter itself. ksize() after rcu_txn_reserve(n) on arm64, against what patch 1 alone gives:
n this series patch 1 6, 7 512 bytes, cap 7 512 bytes, cap 10 8..10 1024 bytes, cap 17 512 bytes, cap 10
So transactions of 8 to 10 records now take 1024 bytes, even on a handle declared disjoint that never arms the filter, and an unreserved handle gets there on its fifth record.
[...]
Review
Quoted 5 lines
(quoted diff) +5
-0+ for (i = 0; i < 64; i++) + rcu_txn_bloom_set(bloom, &bloom_slots[i]); + for (i = 64; i-- > 0; ) + rcu_txn_bloom_set(rebuilt, &bloom_slots[i]); + KUNIT_EXPECT_MEMEQ(test, bloom, rebuilt, sizeof(bloom));
This can't fail, since OR doesn't care about order, and it doesn't exercise __rcu_txn_bloom_arm(); rcu_txn_test_bloom_arming() already does. I'd drop it.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 03/12] rcu_txn: Skip the record lookup with a Bloom filter
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 1 line
This patch adds
t->bloom_live, but__rcu_txn_done()never clears it.
Good catch. Dropping this patch is planned for the next version, as you suggested in your reply to the cover letter. The NULL dereference will go with it, and so will the order test.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 4/12 rcu_txn: Add CONFIG_DEBUG_RCU_TXN
In reply to Mathieu DesnoyersA pseudo-transaction relies on its caller to exclude other writers, and has no way to notice when it does not: two writers racing on a slot corrupt it silently. Add an option that checks the contract.
It validates the proxy tags, warns about a slot recorded twice in one transaction, and validates the single-writer contract:
- a handle must be driven by the task that initialized it;
- a slot being recorded or installed to must not hold a proxy, which would be another writer's;
- at install, and at the commit of a single record, a slot must still hold the old value that was recorded;
- at settle, a slot must still hold the proxy that was installed.
An embedder may get a transaction ready in one task, initializing it and reserving its records where an allocation failure can still be handled, then record and commit it in another task, such as the one that completes an asynchronous request. Nothing is recorded in between, so nothing is mid-flight when the handle changes hands. rcu_txn_adopt() is what the task that takes over calls first: it makes that task the one the checks expect, and warns if the handle already holds records. Without the option it does nothing.
These checks report every occurrence, with WARN(). A once-only report would be consumed by the first user to trip it, and hide the others.
The tests stage each violation deterministically, by installing the other writer's proxy in the slot by hand.
--- include/linux/rcu_txn.h | 195 ++++++++++++++++++++- kernel/rcu/Kconfig.debug | 16 ++ lib/rcu_txn.c | 9 +- lib/rcu_txn_internal.h | 79 +++++++++ lib/tests/rcu_txn_kunit.c | 350 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 643 insertions(+), 6 deletions(-)
include/linux/rcu_txn.h +191 -4
@@ -107,6 +107,21 @@#include <linux/string.h> #include <linux/types.h> +#ifdef CONFIG_DEBUG_RCU_TXN +#include <asm/current.h> +#endif + +/* +* Contract checks that cost more than a test of the handle's state are built +* with CONFIG_DEBUG_RCU_TXN only. They report every occurrence: a once-only +* report would hide the violations of every embedder but the first. +*/ +#ifdef CONFIG_DEBUG_RCU_TXN +# define RCU_TXN_WARN_ON (cond) WARN_ON(cond) +#else +# define RCU_TXN_WARN_ON (cond) BUILD_BUG_ON_INVALID(cond) +#endif +/* * First capacity of an unreserved handle: with its header, such a descriptor * fits a 256-byte allocation. A transaction that records more should
@@ -226,6 +241,10 @@ struct rcu_txn {enum rcu_txn_state state;bool disjoint;/* declared slot-disjoint */ bool bloom_live;/* the descriptor's filter is armed */ +#ifdef CONFIG_DEBUG_RCU_TXN +/* Task that initialized or adopted the handle, and drives it. */ +struct task_struct *owner; +#endif };/*
@@ -251,6 +270,17 @@ static inline bool rcu_txn_is_proxy(const void *v, unsigned long tag)return ((unsigned long )v & tag) == tag; } +/* +* Does @v, loaded from a slot transacted under @tag, hold an installed proxy? +* Unlike rcu_txn_is_proxy(), this answers false under a zero tag, which every +* value matches and which marks no proxy. A zero tag is legal for a +* transaction that installs none. +*/ +static inline bool __rcu_txn_holds_proxy (const void *v,unsigned long tag) +{ +return tag &&rcu_txn_is_proxy (v, tag); +} +/* * Recover the record's address from a slot value that holds an installed proxy. *
@@ -261,6 +291,7 @@ static inline bool rcu_txn_is_proxy(const void *v, unsigned long tag)*/ static inline struct rcu_txn_record *__rcu_txn_untag (void *v,unsigned long tag) { +RCU_TXN_WARN_ON (!rcu_txn_is_proxy (v, tag));return (struct rcu_txn_record *)((unsigned long )v - tag); }
@@ -383,6 +414,96 @@ static inline void __rcu_txn_record_settle(struct rcu_txn_record *r)rcu_assign_pointer (*r->slot, r->ptr[1 ]); } +/* +* CONFIG_DEBUG_RCU_TXN: runtime validation of the single-writer contract. +* +* This engine requires writer mutual exclusion -- it has no install-time CAS, +* no conflict detection and no abort, so two writers racing on one slot simply +* corrupt it, and a default build does not detect it. With +* CONFIG_DEBUG_RCU_TXN a violation warns, with a report identifying the +* violated handle or slot. Without it there is no check, and the handle does +* not carry the owner field. +* +* There is no per-structure object to claim an owner on, so the +* validator claims the two things that do exist: +* +* - the handle. Its owner is the task that initialized it, or the one +* that adopted it before anything was recorded, and reserve / record / +* load / commit / cancel must all run in that task. Catches a +* transaction handed between tasks mid-flight. +* +* - the slot, which is what two racing writers actually share, and so is +* where the real violation is visible. In a correct single-writer +* program a slot being recorded or installed to cannot already hold an +* installed proxy. A proxy sitting there therefore means another +* writer is mid-transaction on that very slot right now. +* Symmetrically, at settle each slot must still hold this writer's +* proxy; anything else means a concurrent writer overwrote it. +*/ + +#ifdef CONFIG_DEBUG_RCU_TXN + +static inline void __rcu_txn_excl_claim (struct rcu_txn *t) +{ + t->owner = current; +} + +static inline void __rcu_txn_excl_owner (const struct rcu_txn *t, +const char *what) +{ +WARN (t->owner != current, +"rcu_txn %p: %s in a task other than the one that initialized or adopted the handle -- one transaction is driven end to end by one task\n" , + t, what); +} + +/* @slot must hold no proxy: it would be another writer's. */ +static inline void __rcu_txn_excl_slot_free (void __rcu **slot, +unsigned long tag,const char *what) +{ +void *v =rcu_access_pointer (*slot); + +WARN (__rcu_txn_holds_proxy (v, tag), +"rcu_txn: slot %p already holds an installed proxy (%p) at %s: another writer is mid-transaction on it\n" , + slot, v, what); +} + +/* +* @r's slot must still hold the recorded old. This is the only witness of a +* single-record commit, which installs no proxy. +*/ +static inline void __rcu_txn_excl_slot_unchanged (struct rcu_txn_record *r, +const char *what) +{ +void *v =rcu_access_pointer (*r->slot); + +WARN (v != r->ptr[0 ], +"rcu_txn: slot %p holds %p at %s, but %p was recorded as its old: a concurrent writer changed it\n" , + r->slot, v, what, r->ptr[0 ]); +} + +#else /* !CONFIG_DEBUG_RCU_TXN */ + +static inline void __rcu_txn_excl_claim (struct rcu_txn *t) +{ +} + +static inline void __rcu_txn_excl_owner (const struct rcu_txn *t, +const char *what) +{ +} + +static inline void __rcu_txn_excl_slot_free (void __rcu **slot, +unsigned long tag,const char *what) +{ +} + +static inline void __rcu_txn_excl_slot_unchanged (struct rcu_txn_record *r, +const char *what) +{ +} + +#endif /* CONFIG_DEBUG_RCU_TXN */ +/* * Writer side * ===========
@@ -403,6 +524,7 @@ static inline void rcu_txn_init(struct rcu_txn *t, gfp_t gfp)memset (t,0 ,sizeof (*t)); t->state =RCU_TXN_PREPARE ; t->gfp = gfp; +__rcu_txn_excl_claim (t); }/*
@@ -439,11 +561,29 @@ static inline bool rcu_txn_reserve(struct rcu_txn *t, unsigned int cap)WARN_ON_ONCE (t->state !=RCU_TXN_OOM );return false; } +__rcu_txn_excl_owner (t,"reserve()" );if (t->records && cap <= t->cap)return true;/* already large enough */ return __rcu_txn_resize (t, cap); } +/** +* rcu_txn_adopt() - take over a handle that another task got ready +* @t: the handle, initialized and holding no record yet +* +* One task drives a transaction end to end. An embedder may still get a +* handle ready in one task, where it can sleep and fail, with rcu_txn_init() +* and rcu_txn_reserve(), and have another record and commit, or cancel. The +* task that takes over calls this first. The embedder makes sure that the +* task which got the handle ready is done with it. +*/ +static inline void rcu_txn_adopt (struct rcu_txn *t) +{ +/* A handle that changes hands with records in it is mid-flight. */ +RCU_TXN_WARN_ON (t->nr); +__rcu_txn_excl_claim (t); +} +/* Free a descriptor that installed no proxy: see lib/rcu_txn.c. */ void __rcu_txn_free_desc (struct rcu_txn_desc *desc);
@@ -581,8 +721,8 @@ bool __rcu_txn_grow(struct rcu_txn *t);* Records must target pairwise-distinct slots. record() appends without * looking for an earlier record of the same slot; recording a slot twice * installs two proxies on it and settles both in record order, so the earlier -* edit is lost. Use rcu_txn_record_chain() when the same slot may be written -* twice. +* edit is lost. CONFIG_DEBUG_RCU_TXN warns about it at commit. Use +* rcu_txn_record_chain() when the same slot may be written twice. * * Context: The caller excludes other writers of @slot. May sleep if the * handle is full and its gfp_t allows it.
@@ -599,6 +739,15 @@ static inline bool rcu_txn_record(struct rcu_txn *t, void __rcu **slot,WARN_ON_ONCE (t->state !=RCU_TXN_OOM );return false; } +/* +* Neither value may look like a proxy under @tag. After settle the +* slot holds @new_ptr directly: were it tagged, every later reader +* would resolve it as a proxy and dereference garbage. +*/ +RCU_TXN_WARN_ON (__rcu_txn_holds_proxy (old_ptr, tag)); +RCU_TXN_WARN_ON (__rcu_txn_holds_proxy (new_ptr, tag)); +__rcu_txn_excl_owner (t,"record()" ); +__rcu_txn_excl_slot_free (slot, tag,"record()" );if (unlikely (t->nr == t->cap) && !__rcu_txn_grow (t))return false;/* OOM, now sticky */ r = &t->records[t->nr++];
@@ -657,7 +806,8 @@ static inline bool rcu_txn_record(struct rcu_txn *t, void __rcu **slot,* from the second record on. * * Recording a slot twice on such a handle breaks the rule of rcu_txn_record(), -* with the consequence stated there. +* with the consequence stated there. CONFIG_DEBUG_RCU_TXN warns about it at +* the offending rcu_txn_load() or rcu_txn_record_chain(). * * Call after init and before the first record(). On a handle whose reserve() * failed it does nothing: the failure is sticky, and commit() reports it.
@@ -672,6 +822,27 @@ static inline void rcu_txn_declare_disjoint(struct rcu_txn *t) t->disjoint = true; } +/* +* On a handle declared disjoint, warn when a load or a record targets a slot +* that the transaction has already recorded. The load would return the +* committed value where its caller expects the pending one, and the record +* would install a second proxy on the slot. +*/ +#ifdef CONFIG_DEBUG_RCU_TXN +static inline void __rcu_txn_disjoint_check (const struct rcu_txn *t, +void __rcu **slot,const char *what) +{ +WARN (t->disjoint &&__rcu_txn_scan (t, slot), +"rcu_txn %p: slot %p is already recorded at %s, on a handle declared disjoint\n" , + t, slot, what); +} +#else +static inline void __rcu_txn_disjoint_check (const struct rcu_txn *t, +void __rcu **slot,const char *what) +{ +} +#endif +/** * rcu_txn_load() - load a slot as the transaction will leave it * @t: the handle
@@ -681,6 +852,10 @@ static inline void rcu_txn_declare_disjoint(struct rcu_txn *t)* On a handle declared disjoint, this returns the committed value without * looking for a pending one. * +* CONFIG_DEBUG_RCU_TXN checks that an unrecorded slot holds no proxy under +* @tag: this writer owns every store to the slot, and its earlier transactions +* settled before commit() returned. +* * Context: The caller excludes other writers of @slot. * Return: the pending new value of the transaction's record for @slot if it * has one, else the slot's current value.
@@ -691,6 +866,7 @@ static inline void *rcu_txn_load(struct rcu_txn *t, void __rcu **slot,struct rcu_txn_record *r;void *v; +__rcu_txn_excl_owner (t,"load()" );/* A consumed handle has no record left: it reads committed values. */ WARN_ON_ONCE (t->state ==RCU_TXN_DONE );if (!t->disjoint) {
@@ -698,7 +874,9 @@ static inline void *rcu_txn_load(struct rcu_txn *t, void __rcu **slot,if (r)return r->ptr[1 ];/* our own pending write */ } +__rcu_txn_disjoint_check (t, slot,"load()" ); v =rcu_dereference_protected (*slot,1 ); +RCU_TXN_WARN_ON (__rcu_txn_holds_proxy (v, tag));return v; }
@@ -715,6 +893,9 @@ static inline bool __rcu_txn_chain(struct rcu_txn *t, void __rcu **slot, r =__rcu_txn_find_ryw (t, slot);if (!r)return rcu_txn_record (t, slot, old_ptr, new_ptr, tag); +RCU_TXN_WARN_ON (r->tag != tag); +/* The caller must have read its own write. */ +RCU_TXN_WARN_ON (r->ptr[1 ] != old_ptr); r->ptr[1 ] = new_ptr;/* committed old preserved */ return true; }
@@ -733,7 +914,8 @@ static inline bool __rcu_txn_chain(struct rcu_txn *t, void __rcu **slot,* rcu_txn_record() does. See the pair's contract above. * * On the chain path @old_ptr is the record's pending value, and a different -* @old_ptr means the caller computed @new_ptr from a stale read. +* @old_ptr means the caller computed @new_ptr from a stale read, which +* CONFIG_DEBUG_RCU_TXN warns about. * * Context: As rcu_txn_record(). * Return: As rcu_txn_record().
@@ -747,7 +929,9 @@ static inline bool rcu_txn_record_chain(struct rcu_txn *t, void __rcu **slot,WARN_ON_ONCE (t->state !=RCU_TXN_OOM );return false; } +__rcu_txn_excl_owner (t,"record_chain()" );if (t->disjoint) {/* no slot repeats: skip the lookup */ +__rcu_txn_disjoint_check (t, slot,"record_chain()" );return rcu_txn_record (t, slot, old_ptr, new_ptr, tag); }return __rcu_txn_chain (t, slot, old_ptr, new_ptr, tag);
@@ -770,6 +954,7 @@ static inline bool rcu_txn_record_chain(struct rcu_txn *t, void __rcu **slot,*/ static inline void rcu_txn_cancel (struct rcu_txn *t) { +__rcu_txn_excl_owner (t,"cancel()" );/* A consumed handle must be initialized again before reuse. */ if (WARN_ON_ONCE (t->state ==RCU_TXN_DONE ))return ;
@@ -811,6 +996,7 @@ static inline int rcu_txn_commit(struct rcu_txn *t) {const unsigned int nr = t->nr; +__rcu_txn_excl_owner (t,"commit()" );/* A consumed handle must be initialized again before reuse. */ if (WARN_ON_ONCE (t->state ==RCU_TXN_DONE ))return -EINVAL ;
@@ -823,6 +1009,7 @@ static inline int rcu_txn_commit(struct rcu_txn *t)struct rcu_txn_record *r = &t->records[0 ];/* One record: its settle store is the whole commit. */ +__rcu_txn_excl_slot_unchanged (r,"commit" );__rcu_txn_record_settle (r); }__rcu_txn_release_desc (t);/* no proxy: free now */
kernel/rcu/Kconfig.debug +16 -0
@@ -239,4 +239,20 @@ config TRIVIAL_PREEMPT_RCU This has no value for production and is only for testing. +config DEBUG_RCU_TXN + bool "Debug checks for single-writer RCU pseudo-transactions" + depends on DEBUG_KERNEL && RCU_TXN + help + Enable the costlier contract checks of <linux/rcu_txn.h>: validity + of the proxy tags, pairwise-distinct recorded slots, and a validator + of the single-writer contract. The validator warns when a + transaction is driven by two tasks, and when a slot it records, + installs to or settles was touched by another writer in the + meantime. + + This adds an owner field to every transaction handle and a pairwise + scan of the records to every commit of two records or more. + + Say N unless you are debugging a user of RCU pseudo-transactions. + endmenu # "RCU Debugging"
lib/rcu_txn.c +7 -2
@@ -123,14 +123,19 @@ void __rcu_txn_commit_desc(struct rcu_txn_desc *desc, unsigned int nr)struct rcu_txn_record *records = desc->records;unsigned int i; +__rcu_txn_assert_distinct_slots (records, nr);/* Install: readers still resolve to old, the selector being 0. */ -for (i =0 ; i < nr; i++) +for (i =0 ; i < nr; i++) { +__rcu_txn_excl_slot_installable (&records[i]);__rcu_txn_record_install (&desc->group, &records[i]); + }/* Flip: every proxy resolves to new. */ __rcu_txn_group_commit (&desc->group);/* Settle. */ -for (i =0 ; i < nr; i++) +for (i =0 ; i < nr; i++) { +__rcu_txn_excl_slot_ours (&records[i]);__rcu_txn_record_settle (&records[i]); + }/* A reader may still hold a proxy, which lives in the descriptor. */ kfree_rcu (desc, rcu_head); }
lib/rcu_txn_internal.h +79 -0
88 lines not on this page · raw message
lib/tests/rcu_txn_kunit.c +350 -0
368 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 04/12] rcu_txn: Add CONFIG_DEBUG_RCU_TXN
On Fri, Oct 16, 2026 at 09:33:11AM -0400, Mathieu Desnoyers wrote:
[...]
Review static inline bool rcu_txn_is_proxy(const void *v, unsigned long tag) · line 296
Quoted 7 lines
(quoted diff) +1
-0@@ -261,6 +291,7 @@ static inline bool rcu_txn_is_proxy(const void *v, unsigned long tag) */ static inline struct rcu_txn_record *__rcu_txn_untag(void *v, unsigned long tag) { + RCU_TXN_WARN_ON(!rcu_txn_is_proxy(v, tag)); return (struct rcu_txn_record *)((unsigned long)v - tag); }
This can never fire: the only caller, rcu_txn_resolve(), has just checked rcu_txn_is_proxy(v, tag). I'd drop it.
[...]
Quoted 2 lines
(quoted diff) +2
-0+ RCU_TXN_WARN_ON(__rcu_txn_holds_proxy(old_ptr, tag)); + RCU_TXN_WARN_ON(__rcu_txn_holds_proxy(new_ptr, tag));
[...]
Review static inline bool __rcu_txn_chain(struct rcu_txn *t, void __rcu **slot, · line 901
Quoted 10 lines
(quoted diff) +3
-0@@ -715,6 +893,9 @@ static inline bool __rcu_txn_chain(struct rcu_txn *t, void __rcu **slot, r = __rcu_txn_find_ryw(t, slot); if (!r) return rcu_txn_record(t, slot, old_ptr, new_ptr, tag); + RCU_TXN_WARN_ON(r->tag != tag); + /* The caller must have read its own write. */ + RCU_TXN_WARN_ON(r->ptr[1] != old_ptr); r->ptr[1] = new_ptr; /* committed old preserved */ return true; }
The append path checks new_ptr for the tag, but the chain path doesn't. With CONFIG_DEBUG_RCU_TXN, chaining a tagged value onto an already-recorded slot of a non-disjoint handle and committing gives no warning, and leaves the tagged value in the slot, where every later reader treats it as a proxy. Passing the same slot, value and tag through the append path warns once:
# rcu_txn_test_exp_chain_tagged: append path: 1 warnings
# rcu_txn_test_exp_chain_tagged: chain path + commit: 0 warnings, slot now 0000000000000301 (tagged: 1)
The same check in the chain path catches it:
include/linux/rcu_txn.h +1 -0
@@ -905,6 +905,7 @@ static inline bool __rcu_txn_chain(struct rcu_txn *t, void __rcu **slot,RCU_TXN_WARN_ON (r->tag != tag);/* The caller must have read its own write. */ RCU_TXN_WARN_ON (r->ptr[1 ] != old_ptr); +RCU_TXN_WARN_ON (__rcu_txn_holds_proxy (new_ptr, tag)); r->ptr[1 ] = new_ptr;/* committed old preserved */ return true; }
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 04/12] rcu_txn: Add CONFIG_DEBUG_RCU_TXN
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 2 lines
This can never fire: the only caller,
rcu_txn_resolve(), has just checkedrcu_txn_is_proxy(v, tag). I'd drop it.
Dropping it is planned for the next version.
[...]
Quoted 1 line
The append path checks
new_ptrfor the tag, but the chain path doesn't.
Good catch. Adding your check to the chain path is planned for the next version.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 5/12 rcu_txn: Add an hlist edited through transactions
In reply to Mathieu DesnoyersAdd rcu_txn_hlist, a list with a single-pointer head shaped like hlist, whose edits are recorded into an RCU pseudo-transaction. Its commit makes all of them, on one list or on many, visible to readers at once:
an entry can move between two hash buckets, through a copy, and be in exactly one of them at any instant.
Readers walk forward only and never load pprev, so a single update has one reader-visible edge. The _rcu forms make such an update outside of any transaction, as hlist_add_head_rcu() does: they publish that edge with rcu_assign_pointer(), then write pprev with a plain store, which no other writer reads in between. Every transaction settles its slots before its commit returns, and the writers are excluded, so the slots they read hold no proxy. They allocate nothing and cannot fail.
The _prepare forms record into a transaction of the caller's, and transact pprev too, as a slot of its own. A later operation of the same transaction then loads its neighbour's pprev as the transaction leaves it, which lets edits of one bucket compose, and a transaction that fails or is cancelled leaves every pprev as it was. An update with a successor thus records two edges there, and takes the descriptor path at commit even alone.
A writer that excludes the others walks a chain with the same iterators as readers, outside of an RCU read-side critical section, by passing them a lockdep condition for that exclusion, such as lockdep_is_held() of its lock, as with hlist_for_each_entry_rcu(). rcu_txn_hlist_empty() takes the same condition: unlike hlist_empty(), it may have to resolve a proxy, which reads the descriptor of a commit in flight. Add __rcu_txn_cond() to the engine, which picks that optional condition.
--- include/linux/rcu_txn.h | 7 + include/linux/rcu_txn_hlist.h | 483 ++++++++++++++++++++++++++++++++++ lib/tests/rcu_txn_kunit.c | 396 ++++++++++++++++++++++++++++ 3 files changed, 886 insertions(+) create mode 100644 include/linux/rcu_txn_hlist.h
include/linux/rcu_txn.h +7 -0
@@ -363,6 +363,13 @@ static inline void *rcu_txn_resolve(void *v, unsigned long tag)*/ #define rcu_txn_dereference (p, tag) rcu_txn_dereference_check(p, tag, 0) +/* +* The optional lockdep condition of an iterator, as for +* list_for_each_entry_rcu(): the condition if one was given, else 0. +*/ +#define __rcu_txn_cond(cond...) ___rcu_txn_cond(0, ## cond, 0) +#define ___rcu_txn_cond(zero, cond, extra...) ((zero) || (cond)) +/** * rcu_txn_slot() - the engine's view of an RCU-protected pointer's address * @pp: address of an __rcu pointer, of any type
include/linux/rcu_txn_hlist.h new file +483 -0
483 lines not on this page · raw message
lib/tests/rcu_txn_kunit.c +396 -0
414 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 05/12] rcu_txn: Add an hlist edited through transactions
On Fri, Oct 16, 2026 at 09:33:12AM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 3 lines
+ * - Every node an operation is anchored on must still be in the list as the
+ * transaction leaves it. A single-writer delete leaves no deletion mark:
+ * nothing in a deleted anchor distinguishes it from a live one.
[...]
include/linux/rcu_txn_hlist.h line 439
Quoted 9 lines
include/linux/rcu_txn_hlist.h new file +9
-0+static inline void rcu_txn_hlist_del_rcu (struct rcu_txn_hlist_node *elem) +{ +struct rcu_txn_hlist_node __rcu **ppv =__rcu_txn_hlist_pprev (elem); +struct rcu_txn_hlist_node *next =__rcu_txn_hlist_load (&elem->next); + +rcu_assign_pointer (*ppv, next); +if (next) +RCU_INIT_POINTER (next->pprev, ppv); +}
hlist_del_rcu() poisons pprev, so a double delete faults straight away. Here pprev keeps pointing at the old slot, so a second del_rcu() quietly overwrites whatever that slot holds now with the node's stale ->next. For example, 1 -> 2 -> 3, del_rcu(2), add_behind_rcu(4, 1), del_rcu(2) leaves 1 -> 3 with node 4 gone, and nothing warns, even with CONFIG_DEBUG_RCU_TXN. Had 3 been deleted and freed in between, the second delete would link it back in and write to it.
dcache relies on d_unhashed(), i.e. a NULL pprev, which __d_drop() sets. Could the _rcu delete and replace clear pprev the way hlist_del_init_rcu() does, and could there be an rcu_txn_hlist_unhashed()? For the _prepare forms, del_prepare and replace_prepare could record pprev -> NULL through __rcu_txn_hlist_record_pprev(). That costs at most one record, though a lone delete or replace of a bucket's last node would no longer be a one-record commit.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 05/12] rcu_txn: Add an hlist edited through transactions
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 6 lines
dcache relies on
d_unhashed(), i.e. a NULL pprev, which__d_drop()sets. Could the_rcudelete and replace clear pprev the wayhlist_del_init_rcu()does, and could there be anrcu_txn_hlist_unhashed()? For the_prepareforms,del_prepareandreplace_preparecould record pprev -> NULL through__rcu_txn_hlist_record_pprev().
Yes. Readers never load pprev, so clearing it is safe for them. What you suggest is planned for the next version:
- The _rcu forms of delete and replace will set the removed node's pprev to NULL.
- The _prepare forms will record pprev -> NULL. A cancel then leaves the node as it was.
- rcu_txn_hlist_unhashed() will test the state. rcu_txn_hlist_node_init() will initialize a node as unhashed.
A second delete will then fault on the NULL pprev, as hlist_del_rcu() does on its poison. With CONFIG_DEBUG_RCU_TXN, an edit anchored on an unhashed node will warn.
Quoted 3 lines
That costs at most one record, though a
lone delete or replace of a bucket's last node would no longer be a one-record commit.
Yes. The samples will reserve five records for an unlink.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 6/12 rcu_txn: Add a doubly-linked list coherent in both directions
In reply to Mathieu DesnoyersAn update of a doubly-linked list re-points a forward and a backward edge. The RCU list does it with two stores, so a reader that walks in both directions (list_bidir_prev_rcu()) can find the new forward edge and then the old backward edge: having stepped forward over a node just inserted, a step back can skip it.
Add rcu_txn_list, a circular doubly-linked list that commits both edges of each operation as one RCU pseudo-transaction. At every instant, a->next == b implies b->prev == a for the nodes of the list, and a reader walking from node to node never finds the new value of an edge and then the old value of the other.
Every operation switches two slots, so it installs proxies and allocates a descriptor: the _rcu forms take a gfp_t and may return -ENOMEM, leaving the list unchanged. The _prepare forms record into a transaction of the caller's, which can be reserved beforehand and can compose several operations, on this list or with other structures.
A node moves with rcu_txn_list_move_after_prepare() and _before_prepare(), and the _rcu forms move_after, move_before, move (to the front) and move_tail. A move records six edges: the two that unlink the node, the two that link it at its new place, and the node's own next and prev, which a reader standing on the node follows. The add forms cannot move a node, as they build its links with plain stores. A move to where the node already is records nothing.
Its iterators and rcu_txn_list_empty() take the same optional lockdep condition as those of rcu_txn_hlist, and rcu_txn_list_next_check() and _prev_check() are the accessors that take one.
--- include/linux/rcu_txn_hlist.h | 7 +- include/linux/rcu_txn_list.h | 544 ++++++++++++++++++++++++++++++++++ lib/tests/rcu_txn_kunit.c | 402 +++++++++++++++++++++++++ 3 files changed, 951 insertions(+), 2 deletions(-) create mode 100644 include/linux/rcu_txn_list.h
include/linux/rcu_txn_hlist.h +5 -2
@@ -11,7 +11,9 @@* rcu_txn_hlist: an RCU list with a single-pointer head, shaped like hlist, for * a single writer (writers mutually excluded, as with hlist_add_head_rcu()). * Its edits are recorded into a transaction of <linux/rcu_txn.h>, whose commit -* makes all of them, on one bucket or on many, visible to readers at once. +* makes all of them, on one bucket or on many, visible to readers at once. It +* is the hash-bucket sibling of the circular <linux/rcu_txn_list.h>: its head +* is one pointer, half the footprint of a sentinel-node head. * * Forward-only readers, and pprev * -------------------------------
@@ -23,7 +25,8 @@* struct rcu_txn_hlist_node **pprev; (slot ptr; writer-only) } * * Readers walk forward only and never load pprev, so each operation has exactly -* one reader-visible edge: the next slot it re-points. +* one reader-visible edge: the next slot it re-points. This is where the hlist +* differs from <linux/rcu_txn_list.h>, whose prev is reader-visible. * * Single updates and transactions * -------------------------------
include/linux/rcu_txn_list.h new file +544 -0
544 lines not on this page · raw message
lib/tests/rcu_txn_kunit.c +402 -0
420 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 06/12] rcu_txn: Add a doubly-linked list coherent in both directions
On Fri, Oct 16, 2026 at 09:33:13AM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 6 lines
+/*
+ *rcu_txn_list: a circular doubly-linked list whose forward and backward
+ * chains stay mutually coherent under concurrent RCU readers. A reader may
+ * iterate in either direction, or reverse direction mid-traversal, and never
+ * observe the two directions disagree.
+ *
This overstates it a bit: a reader can read P->next == N and then, once an insertion of E between them commits, read N->prev == E. The commit message puts it accurately ("never finds the new value of an edge and then the old value of the other"), so I'd use that wording here too.
[...]
Quoted 4 lines
+ * See
rcu_txn_list_add_after_prepare(). Six edges switch together: the two
+ * that unlink @elem, the two that link it after @pos, and @elem's own next and
+ * prev, so that a reader standing on @elem leaves it by its old neighbours
+ * until the commit and by its new ones from then on. The add forms cannot
That has a consequence for iterators, which should be documented: a reader standing on the moved node can skip or revisit nodes that never moved. With H -> A -> B -> C, a reader on A when A moves after C steps straight to H and never sees B or C, and a reader on C when C moves to the front walks A and B again. I checked both with sequential KUnit cases. LRU second chances are exactly this pattern.
[...]
include/linux/rcu_txn_list.h line 487
Quoted 7 lines
include/linux/rcu_txn_list.h new file +7
-0+/* Move @elem to the head of the list (just after @head). */ +static inline int rcu_txn_list_move_rcu (struct rcu_txn_list_node *elem, +struct rcu_txn_list_head *head, +gfp_t gfp) +{ +return rcu_txn_list_move_after_rcu (elem, &head->node, gfp); +}
This looks like list_move(), whose kerneldoc is literally "delete from one list and add as another's head", and nothing here says @head has to be @elem's own list. If it isn't, a reader standing on @elem follows its new ->next into the other list and never gets back to its own head, so rcu_txn_list_for_each_entry_rcu() never terminates and treats the other list's head as an entry. Either document on every move form that the destination must be in the same list, or give readers a way to detect it, like hlist_nulls does.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 06/12] rcu_txn: Add a doubly-linked list coherent in both directions
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 4 lines
This overstates it a bit: a reader can read
P->next== N and then, once an insertion of E between them commits, readN->prev== E. The commit message puts it accurately ("never finds the new value of an edge and then the old value of the other"), so I'd use that wording here too.
Agreed. The next version will use the wording of the commit message in the header.
Your points show two levels of coherence, and the header should name both:
- Per-node coherence: a reader never finds the new value of an edge, then the old value of the other. Every operation of rcu_txn_list gives it.
- Per-walk coherence: a walk visits every node that is not moved exactly once, and ends at its own head. A move does not give it, as your examples show.
[...]
Quoted 3 lines
That has a consequence for iterators, which should be documented: a reader standing on the moved node can skip or revisit nodes that never moved.
Agreed. The next version will document it on the iterators and on the move forms.
So the next version will present two ways to move a node, and the caller picks by what its readers need.
The move itself never fails, never sleeps, and never waits for a grace period. Its descriptor goes back to the per-CPU pool through call_rcu_hurry(). It keeps per-node coherence, which an RCU list cannot give for a move: a delete then an add are two updates that readers observe separately. The move fits:
- readers that take the first or last entry, or that reach a node through another index, then read its neighbours;
- walkers that tolerate a skipped or repeated node, like an LRU scan, when the node moves within the same list. A walker standing on a node moved to another list would never reach its own head;
- writers that cannot sleep, like a second chance under a spinlock;
- moves composed with other edits in one commit, through rcu_txn_list_move_after_prepare().
A writer whose readers need per-walk coherence can instead delete the node, wait for a grace period, then add it back. A deleted node keeps its next and prev, so a reader standing on it leaves in the old order. The add comes after every reader that saw the node at its old place. So a walk sees every other node exactly once, and the moved node at most once. The cost is a writer that sleeps for a grace period, and a node that readers do not find during that time.
With this sequence, your reader on A walks H -> A -> B -> C -> H. So does your reader on C.
[...]
Quoted 3 lines
Either document on every move form that the destination must be in the same list, or give readers a way to detect it, like
hlist_nullsdoes.
The next version will document it on every move form, with the reason. A move to another list can use the same sequence. A reader standing on the node finishes its own list, and ends at its own head.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 7/12 Documentation/RCU: Describe RCU pseudo-transactions
In reply to Mathieu DesnoyersAdd a page on the RCU pseudo-transactions to the RCU handbook: when they apply and what they cost, how a commit proceeds, what readers and writers call, how a transaction allocates, and the two data structures built on them. It ends with the API reference extracted from the headers. The overview at the top of <linux/rcu_txn.h> points to it.
--- Documentation/RCU/index.rst | 1 + Documentation/RCU/rcu_txn.rst | 230 ++++++++++++++++++++++++++++++++++ MAINTAINERS | 1 + include/linux/rcu_txn.h | 2 + 4 files changed, 234 insertions(+) create mode 100644 Documentation/RCU/rcu_txn.rst
Documentation/RCU/index.rst +1 -0
@@ -18,6 +18,7 @@ RCU Handbook rcu rculist_nulls rcuref + rcu_txn torture stallwarn listRCU
Documentation/RCU/rcu_txn.rst new file +230 -0
230 lines not on this page · raw message
MAINTAINERS +1 -0
@@ -22857,6 +22857,7 @@ RCU PSEUDO-TRANSACTIONS M: Mathieu Desnoyers <[email protected]> L: [email protected] S: Maintained +F: Documentation/RCU/rcu_txn.rst F: include/linux/rcu_txn*.h F: lib/rcu_txn* F: lib/tests/rcu_txn_kunit.c
include/linux/rcu_txn.h +2 -0
@@ -12,6 +12,8 @@* the slots, from their old to their new targets with a single store, as * observed by concurrent RCU readers: at any instant, every slot of the set * resolves to its old target, or every slot to its new one. +* Documentation/RCU/rcu_txn.rst says when to use them, and describes the data +* structures built on them. * * The slots are the edges of the data structure that an update re-points; the * writer records each edge as its slot with the slot's old and new targets.
Signature · 1 line
2.47.3
Mathieu Desnoyers
reviewerRFC PATCH 8/12 Documentation/litmus-tests: Add RCU pseudo-transaction tests
In reply to Mathieu DesnoyersModel the memory ordering of RCU pseudo-transactions with the Linux kernel memory model: the store-release / load-acquire pairs that <linux/rcu_txn.h> documents, and the guarantee they give readers.
- RCU-txn+install: a reader that finds a proxy reads its record initialized.
- RCU-txn+monotonic+dep and +acquire: the slots of one transaction resolve old, then new, never new then old, along a chain of dependent loads or with a load-acquire between the loads.
- RCU-txn+list+step-back: a reader of an rcu_txn_list that steps forward onto a node being inserted, then back, never skips it.
- RCU-txn+sync+free: a reader never reads a record freed after a grace period.
- RCU-txn+publish and RCU-txn+remove: a transaction end to end, with the writer doing every step. A reader of a transaction that publishes an object sees the record initialized and the object built. A reader of one that removes an object, which the writer frees with the descriptor after a grace period, sees the record initialized, and reads neither of them freed.
Each test checks an outcome that the code forbids, and herd7 finds that it never happens. Error-injection variants validate that the model catches a missing ordering: each drops one ordering that its test relies on, and herd7 then finds the outcome possible. A store-release or a load-acquire becomes a plain access, the grace period or the read-side critical section goes, or, in RCU-txn+monotonic+unordered, the reader's two loads are left with neither a dependency nor a load-acquire between them.
herd7 can express neither a structure nor a tagged pointer: a record is a few variables, and the reader's tag test compares the loaded value with the record's address. Nor does it have arrays: where the code indexes the record's targets with the selector, an address dependency, the reader branches on the selector, and a branch orders no later load. The model thus orders less than the code, and an outcome that it forbids, the code forbids as well. For the same reason, the selector's load-acquire is dropped only in RCU-txn+monotonic+acquire+once-resolve, whose reader loads slot b independently of slot a: for a reader whose next load depends on the target it resolved, the code's address dependency still orders that load.
--- Documentation/RCU/rcu_txn.rst | 12 +++ Documentation/litmus-tests/README | 37 ++++++++ .../rcu/RCU-txn+install+once-install.litmus | 55 ++++++++++++ .../litmus-tests/rcu/RCU-txn+install.litmus | 66 ++++++++++++++ .../RCU-txn+list+step-back+once-flip.litmus | 78 +++++++++++++++++ .../RCU-txn+list+step-back+once-settle.litmus | 78 +++++++++++++++++ .../rcu/RCU-txn+list+step-back.litmus | 85 +++++++++++++++++++ ...-txn+monotonic+acquire+once-resolve.litmus | 79 +++++++++++++++++ .../rcu/RCU-txn+monotonic+acquire.litmus | 81 ++++++++++++++++++ .../RCU-txn+monotonic+dep+once-flip.litmus | 77 +++++++++++++++++ .../RCU-txn+monotonic+dep+once-settle.litmus | 77 +++++++++++++++++ .../rcu/RCU-txn+monotonic+dep.litmus | 83 ++++++++++++++++++ .../rcu/RCU-txn+monotonic+unordered.litmus | 84 ++++++++++++++++++ .../rcu/RCU-txn+publish+once-install.litmus | 60 +++++++++++++ .../rcu/RCU-txn+publish+once-settle.litmus | 60 +++++++++++++ .../litmus-tests/rcu/RCU-txn+publish.litmus | 71 ++++++++++++++++ .../rcu/RCU-txn+remove+nolock.litmus | 64 ++++++++++++++ .../rcu/RCU-txn+remove+nosync.litmus | 64 ++++++++++++++ .../rcu/RCU-txn+remove+once-install.litmus | 65 ++++++++++++++ .../litmus-tests/rcu/RCU-txn+remove.litmus | 72 ++++++++++++++++ .../rcu/RCU-txn+sync+free+nolock.litmus | 55 ++++++++++++ .../rcu/RCU-txn+sync+free+nosync.litmus | 55 ++++++++++++ .../litmus-tests/rcu/RCU-txn+sync+free.litmus | 60 +++++++++++++ MAINTAINERS | 1 + 24 files changed, 1519 insertions(+) create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+install+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-flip.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire+once-resolve.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-flip.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+unordered.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+nolock.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+nosync.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free+nolock.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free+nosync.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free.litmus
Documentation/RCU/rcu_txn.rst +12 -0
@@ -220,6 +220,18 @@ the engine, both data structures and the debug checks:: --kconfig_add CONFIG_DEBUG_RCU_TXN=y \ 'rcu_txn*' +The litmus tests ``Documentation/litmus-tests/rcu/RCU-txn+*.litmus`` model the +memory ordering of the engine and of ``rcu_txn_list`` with the Linux kernel +memory model. Each test checks an outcome that the code forbids, and herd7 +finds that it never happens. Error-injection variants validate that the model +catches a missing ordering: each drops one ordering that its test relies on, and +herd7 then finds the outcome possible. With herd7 installed as +``tools/memory-model/README`` says:: + + cd tools/memory-model + scripts/checktheselitmus.sh --timeout 1h -- \ + ../../Documentation/litmus-tests/rcu/RCU-txn+*.litmus + API ===
Documentation/litmus-tests/README +37 -0
@@ -78,3 +78,40 @@ RCU+sync+read.litmus RCU+sync+free.litmus Both the above litmus tests demonstrate the RCU grace period guarantee that an RCU read-side critical section can never span a grace period. + +RCU-txn+install.litmus + Demonstrates that the install of an RCU pseudo-transaction + (include/linux/rcu_txn.h) publishes its record: a reader that finds a + proxy reads the record initialized. + +RCU-txn+monotonic+dep.litmus +RCU-txn+monotonic+acquire.litmus + Demonstrate that the slots of one RCU pseudo-transaction resolve old, + then new, never new then old, along a chain of dependent loads or with + a load-acquire between the loads. + +RCU-txn+list+step-back.litmus + Demonstrates that a reader of an rcu_txn_list that steps forward onto + a node being inserted, then back, never skips it. + NOTE: herd7 takes about half an hour on it, and on its variants. + +RCU-txn+sync+free.litmus + Demonstrates that a reader never reads the record of an RCU + pseudo-transaction once it is freed after a grace period. + +RCU-txn+publish.litmus +RCU-txn+remove.litmus + Demonstrate RCU pseudo-transactions end to end, the writer doing every + step: a reader sees the record initialized and a published object + built, and never reads a removed object, nor the record, once they are + freed after a grace period. + +RCU-txn+*+once-*.litmus +RCU-txn+monotonic+unordered.litmus +RCU-txn+remove+nolock.litmus +RCU-txn+remove+nosync.litmus +RCU-txn+sync+free+nolock.litmus +RCU-txn+sync+free+nosync.litmus + Error injection into the above RCU-txn tests. Each variant drops one + ordering that its test relies on, and herd7 then finds the outcome + possible, which validates that the model catches the missing ordering.
Documentation/litmus-tests/rcu/RCU-txn+install+once-install.litmus new file +55 -0
55 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+install.litmus new file +66 -0
66 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-flip.litmus new file +78 -0
78 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-settle.litmus new file +78 -0
78 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+list+step-back.litmus new file +85 -0
85 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire+once-resolve.litmus new file +79 -0
79 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire.litmus new file +81 -0
81 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-flip.litmus new file +77 -0
77 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-settle.litmus new file +77 -0
77 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep.litmus new file +83 -0
83 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+monotonic+unordered.litmus new file +84 -0
84 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+publish+once-install.litmus new file +60 -0
60 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+publish+once-settle.litmus new file +60 -0
60 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+publish.litmus new file +71 -0
71 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+remove+nolock.litmus new file +64 -0
64 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+remove+nosync.litmus new file +64 -0
64 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+remove+once-install.litmus new file +65 -0
65 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+remove.litmus new file +72 -0
72 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+sync+free+nolock.litmus new file +55 -0
55 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+sync+free+nosync.litmus new file +55 -0
55 lines not on this page · raw message
Documentation/litmus-tests/rcu/RCU-txn+sync+free.litmus new file +60 -0
60 lines not on this page · raw message
MAINTAINERS +1 -0
@@ -22858,6 +22858,7 @@ M: Mathieu Desnoyers <[email protected]> L: [email protected] S: Maintained F: Documentation/RCU/rcu_txn.rst +F: Documentation/litmus-tests/rcu/RCU-txn+* F: include/linux/rcu_txn*.h F: lib/rcu_txn* F: lib/tests/rcu_txn_kunit.c
Signature · 1 line
2.47.3
Mathieu Desnoyers
reviewerRFC PATCH 9/12 rcu_txn: Test a list writer against concurrent readers
In reply to Mathieu DesnoyersRun one writer on a key-sorted rcu_txn_list while kthreads walk it forward and backward.
Each walk must see sorted keys. That alone cannot catch an operation whose two edges are published separately, since such a list is still sorted in each direction taken alone. So, during phases where the writer only inserts, each forward step p -> q also loads the prev of q and requires its key to be at least that of p. That catches an insert that publishes its forward edge before its backward one, as list_add_rcu() does; the other order cannot be told from a completed insert by key.
The test is marked slow. It needs more than one CPU to exercise real concurrency.
--- Documentation/RCU/rcu_txn.rst | 4 +- lib/tests/rcu_txn_kunit.c | 307 ++++++++++++++++++++++++++++++++++ 2 files changed, 310 insertions(+), 1 deletion(-)
Documentation/RCU/rcu_txn.rst +3 -1
@@ -212,9 +212,11 @@ Testing ======= ``CONFIG_RCU_TXN_KUNIT_TEST`` builds the KUnit suite ``rcu_txn``, which covers -the engine, both data structures and the debug checks:: +the engine, both data structures and the debug checks, and runs one writer +against concurrent readers of a list:: ./tools/testing/kunit/kunit.py run --arch=x86_64 \ + --qemu_args="-smp 4" \ --kconfig_add CONFIG_RCU_TXN_KUNIT_TEST=y \ --kconfig_add CONFIG_DEBUG_KERNEL=y \ --kconfig_add CONFIG_DEBUG_RCU_TXN=y \
lib/tests/rcu_txn_kunit.c +307 -0
330 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 09/12] rcu_txn: Test a list writer against concurrent readers
On Fri, Oct 16, 2026 at 09:33:16AM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 4 lines
lib/tests/rcu_txn_kunit.c +4
-0+/* +* Invariant (2). Skipped for the first step, whose +* predecessor is the head. +*/
lib/tests/rcu_txn_kunit.c static void rcu_txn_test_list_debug_disjoint_compose(struct kunit *test) · line 1804
Quoted 10 lines
lib/tests/rcu_txn_kunit.c +10
-0+if (insert_only && prev_key) { +struct rcu_txn_list_node *back = +rcu_txn_list_prev_rcu (p); + + r->cross_checks++; +if (back != &head->node && + container_of(back, struct cn, + node)->key < prev_key) + r->cross_violations++; + }
In an insert-only phase, once a reader has stepped from A to p, A stays before p, so p's prev can only be A or a node inserted between them, never the head. The back != &head->node exemption can therefore only hide failures, and it hides exactly the tear this check is for when the insertion is at the front: head->next == E, E->next == F, then F->prev == head. prev_key already skips the first step, so I'd count back == &head->node as a violation.
[...]
lib/tests/rcu_txn_kunit.c static void rcu_txn_test_list_debug_disjoint_compose(struct kunit *test) · line 1908
Quoted 9 lines
lib/tests/rcu_txn_kunit.c +9
-0+for (i =0 ; i <CONC_READERS ; i++) { + readers[i].conc = c; + readers[i].task =kthread_run (conc_reader_fn, &readers[i], +"rcu_txn_reader/%d" , i); +if (IS_ERR (readers[i].task)) { + readers[i].task =NULL ; + ok = false; + } + }
If the writer oopses, KUnit fails the test and frees c and the readers array while these threads are still walking the list. Registering the stop with kunit_add_action_or_reset(), and calling kunit_release_action() where they're stopped now, would avoid the use-after-free.
[...]
lib/tests/rcu_txn_kunit.c static void rcu_txn_test_list_debug_disjoint_compose(struct kunit *test) · line 1982
Quoted 3 lines
lib/tests/rcu_txn_kunit.c +3
-0+for (key =1 ; key <=CONC_KEY_MAX ; key++) +if (c->live[key]) +conc_del (c, key);
A failed conc_del() here leaks the node without anyone noticing. The readers are already stopped at this point, so the leftovers could just be kfree()d.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 09/12] rcu_txn: Test a list writer against concurrent readers
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 1 line
prev_keyalready skips the first step, so I'd count back ==&head->nodeas a violation.
Agreed. Counting it is planned for the next version.
[...]
Quoted 5 lines
If the writer oopses, KUnit fails the test and frees c and the readers array while these threads are still walking the list. Registering the stop with
kunit_add_action_or_reset(), and callingkunit_release_action()where they're stopped now, would avoid the use-after-free.
Planned for the next version, as you describe.
[...]
Quoted 3 lines
A failed
conc_del()here leaks the node without anyone noticing. The readers are already stopped at this point, so the leftovers could just be kfree()d.
In the next version, a delete will no longer fail. The test will unlink and free the leftovers directly, without a grace period.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 10/12 rcu_txn: Test a commit from atomic context
In reply to Mathieu DesnoyersA hash table with hlist_bl buckets excludes its writers with a bit spinlock. On PREEMPT_RT a bit spinlock keeps the semantics of a raw
spinlock: nothing under it may take a sleeping lock, which rules out the memory allocator.
Commit a transaction of two records under a bit spinlock, another under a raw spinlock with interrupts off, and a single record and a cancel under the bit spinlock, and check that neither lockdep nor the might_sleep() checks report anything. The transactions reserve their records before they take the lock, so recording and committing allocate nothing, and the descriptor of a commit that installed proxies goes to kfree_rcu(), which is allowed there. Each commit's return value is checked once the lock is released, since a failed expectation allocates.
The test is only meaningful on a PREEMPT_RT kernel with lockdep, PROVE_RAW_LOCK_NESTING and DEBUG_ATOMIC_SLEEP. It passes there, and fails as expected when a spinlock_t is taken under the bit spinlock.
The last two cases release a descriptor that installed no proxy, which has to be kfree_rcu() on PREEMPT_RT. They would pass with a kfree() as
well: a kfree() under a bit spinlock on PREEMPT_RT was reported by neither lockdep nor the might_sleep() checks when tried.
--- lib/tests/rcu_txn_kunit.c | 85 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+)
lib/tests/rcu_txn_kunit.c +85 -0
@@ -7,8 +7,11 @@#include <kunit/test.h> #include <linux/bug.h> +#include <linux/debug_locks.h> #include <linux/kthread.h> +#include <linux/list_bl.h> #include <linux/minmax.h> +#include <linux/panic.h> #include <linux/rcu_txn.h> #include <linux/rcu_txn_hlist.h> #include <linux/rcu_txn_list.h>
@@ -1992,6 +1995,87 @@ static void rcu_txn_test_list_concurrent(struct kunit *test)KUNIT_EXPECT_EQ (test, cross_violations,0 ); } +/* Did the kernel report something since @tainted and @locks were sampled? */ +static void expect_no_report (struct kunit *test,bool tainted,int locks) +{ +KUNIT_EXPECT_EQ (test,test_taint (TAINT_WARN ), tainted); +KUNIT_EXPECT_EQ (test, debug_locks, locks); +} + +/* +* A commit from atomic context: under a bit spinlock, which is how a hash +* table with hlist_bl buckets excludes its writers, and under a raw spinlock. +* On PREEMPT_RT neither may take a sleeping lock, which lockdep and the +* might_sleep() checks would report. +* +* The transaction reserves its records before it takes the lock, so recording +* and committing allocate nothing, and the descriptor of a commit that +* installed proxies is handed to kfree_rcu(). +* +* A descriptor that installed none is released under the lock as well, by a +* commit of one record or by a cancel. On PREEMPT_RT that has to be +* kfree_rcu() too, but these checks did not report a kfree() there when +* tried: those two cases only exercise the path. +*/ +static void rcu_txn_test_commit_atomic (struct kunit *test) +{ +static DEFINE_RAW_SPINLOCK (raw_lock); +void __rcu *s1 =RCU_INITIALIZER (T (0 )); +void __rcu *s2 =RCU_INITIALIZER (T (1 )); +bool tainted =test_taint (TAINT_WARN ); +struct hlist_bl_head bucket; +int locks = debug_locks; +unsigned long flags; +struct rcu_txn txn; +int err; + +INIT_HLIST_BL_HEAD (&bucket); + +/* Two records, under a bit spinlock. */ +rcu_txn_init (&txn,GFP_KERNEL ); +KUNIT_ASSERT_TRUE (test,rcu_txn_reserve (&txn,2 )); +hlist_bl_lock (&bucket); +rcu_txn_record (&txn, &s1,T (0 ),T (10 ),TAG ); +rcu_txn_record (&txn, &s2,T (1 ),T (11 ),TAG ); + err =rcu_txn_commit (&txn); +hlist_bl_unlock (&bucket); +KUNIT_EXPECT_EQ (test, err,0 ); +expect_no_report (test, tainted, locks); + +/* Two records, under a raw spinlock with interrupts off. */ +rcu_txn_init (&txn,GFP_KERNEL ); +KUNIT_ASSERT_TRUE (test,rcu_txn_reserve (&txn,2 )); +raw_spin_lock_irqsave (&raw_lock, flags); +rcu_txn_record (&txn, &s1,T (10 ),T (20 ),TAG ); +rcu_txn_record (&txn, &s2,T (11 ),T (21 ),TAG ); + err =rcu_txn_commit (&txn); +raw_spin_unlock_irqrestore (&raw_lock, flags); +KUNIT_EXPECT_EQ (test, err,0 ); +expect_no_report (test, tainted, locks); + +/* One record. */ +rcu_txn_init (&txn,GFP_KERNEL ); +KUNIT_ASSERT_TRUE (test,rcu_txn_reserve (&txn,2 )); +hlist_bl_lock (&bucket); +rcu_txn_record (&txn, &s1,T (20 ),T (40 ),TAG ); + err =rcu_txn_commit (&txn); +hlist_bl_unlock (&bucket); +KUNIT_EXPECT_EQ (test, err,0 ); +expect_no_report (test, tainted, locks); + +/* A cancel of such a handle. */ +rcu_txn_init (&txn,GFP_KERNEL ); +KUNIT_ASSERT_TRUE (test,rcu_txn_reserve (&txn,2 )); +hlist_bl_lock (&bucket); +rcu_txn_record (&txn, &s1,T (40 ),T (50 ),TAG ); +rcu_txn_cancel (&txn); +hlist_bl_unlock (&bucket); +expect_no_report (test, tainted, locks); + +KUNIT_EXPECT_PTR_EQ (test,rcu_access_pointer (s1),T (40 )); +KUNIT_EXPECT_PTR_EQ (test,rcu_access_pointer (s2),T (21 )); +} +static struct kunit_case rcu_txn_test_cases[] = {KUNIT_CASE (rcu_txn_test_single_record),KUNIT_CASE (rcu_txn_test_multi_record),
@@ -2051,6 +2135,7 @@ static struct kunit_case rcu_txn_test_cases[] = {KUNIT_CASE (rcu_txn_test_list_compose_moves),KUNIT_CASE (rcu_txn_test_list_debug_disjoint_compose),KUNIT_CASE_SLOW (rcu_txn_test_list_concurrent), + KUNIT_CASE(rcu_txn_test_commit_atomic), {} };
Signature · 1 line
2.47.3
Re: [RFC PATCH 10/12] rcu_txn: Test a commit from atomic context
On Fri, Oct 16, 2026 at 09:33:17AM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 8 lines
The test is only meaningful on a
PREEMPT_RTkernel with lockdep,PROVE_RAW_LOCK_NESTINGandDEBUG_ATOMIC_SLEEP. It passes there, and fails as expected when aspinlock_tis taken under the bit spinlock.The last two cases release a descriptor that installed no proxy, which has to be
kfree_rcu()onPREEMPT_RT. They would pass with akfree()as
well: akfree()under a bit spinlock onPREEMPT_RTwas reported by neither lockdep nor themight_sleep()checks when tried.
This matters on !PREEMPT_RT too: there, a one-record commit or a cancel under a raw spinlock calls kfree(), which lockdep can flag (see my reply to patch 1). The test can't catch that as written.
[...]
lib/tests/rcu_txn_kunit.c static void rcu_txn_test_list_concurrent(struct kunit *test) · line 2062
Quoted 7 lines
lib/tests/rcu_txn_kunit.c +7
-0+/* One record. */ +rcu_txn_init (&txn,GFP_KERNEL ); +KUNIT_ASSERT_TRUE (test,rcu_txn_reserve (&txn,2 )); +hlist_bl_lock (&bucket); +rcu_txn_record (&txn, &s1,T (20 ),T (40 ),TAG ); + err =rcu_txn_commit (&txn); +hlist_bl_unlock (&bucket);
On !PREEMPT_RT, this case and the cancel after it are the two that reach kfree(), and they only run under the bit spinlock, which lockdep doesn't track. The raw spinlock case only commits two records, which go through kfree_rcu(). Even under a raw spinlock, a single call rarely trips it, because lockdep only sees barn->lock once the per-CPU sheaf is full. Running the one-record and cancel cases under raw_spin_lock_irqsave() in a loop would catch it. That is probably also why the kfree() you tried on PREEMPT_RT went unreported, though I haven't checked RT.
[...]
lib/tests/rcu_txn_kunit.c static void rcu_txn_test_list_concurrent(struct kunit *test) · line 2003
Quoted 6 lines
lib/tests/rcu_txn_kunit.c +6
-0+/* Did the kernel report something since @tainted and @locks were sampled? */ +static void expect_no_report (struct kunit *test,bool tainted,int locks) +{ +KUNIT_EXPECT_EQ (test,test_taint (TAINT_WARN ), tainted); +KUNIT_EXPECT_EQ (test, debug_locks, locks); +}
These compare against the state at the start of the test, so if lockdep is already off, or TAINT_WARN already set, the matching check can't fail. I ran into that: once one of my raw-spinlock cases splatted, the two bulk cases after it passed even though each splats when run alone. A kunit_skip() when PROVE_RAW_LOCK_NESTING is off, or debug_locks is already 0, or TAINT_WARN is already set, would make that visible.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 10/12] rcu_txn: Test a commit from atomic context
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 3 lines
This matters on !PREEMPT_RT too: there, a one-record commit or a cancel under a raw spinlock calls
kfree(), which lockdep can flag (see my reply to patch 1). The test can't catch that as written.
Agreed. The next version will fix the free in patch 1, and this test will catch it.
[...]
Quoted 2 lines
Running the one-record and cancel cases under
raw_spin_lock_irqsave()in a loop would catch it.
My first try reserved and committed one handle at a time. It did not catch it: each kfree() gave back the object that the reserve had just taken, so the sheaf never filled. As in your reproducer, the next version reserves 4096 one-record handles first. Then it commits them all under one raw spinlock, and does the same for cancels. On x86_64, this gives your barn->lock splat with kfree() put back, and passes with kfree_rcu().
[...]
Quoted 3 lines
A
kunit_skip()whenPROVE_RAW_LOCK_NESTINGis off, ordebug_locksis already 0, orTAINT_WARNis already set, would make that visible.
Planned for the next version, with these three conditions.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerRFC PATCH 11/12 samples: Add a cache on RCU pseudo-transactions under one mutex
In reply to Mathieu DesnoyersShow the hlist and the list of RCU pseudo-transactions together: a cache whose entries are found by key in a hash table of rcu_txn_hlist buckets, and kept in an rcu_txn_list as their LRU.
Lookup threads find entries under RCU alone, and mark the ones they find referenced. Writer threads insert, update and delete entries under one mutex. An insertion into a full cache evicts the oldest entry, after moving to the front of the list the referenced entries it finds at its tail, as a second chance. Each change is one transaction over both
structures: an insertion that evicts links the new entry into its bucket and at the front of the list, makes the moves, and unlinks the victim from both, and at any instant the cache holds all of it or none of it. Its records are reserved before the writer takes the mutex, which keeps the allocation out of the critical section.
The module runs for duration_ms when it is loaded, then checks that the hash table and the list hold the same entries, and reports what it did. An allocation failure stops the writers there.
--- Documentation/RCU/rcu_txn.rst | 9 + MAINTAINERS | 1 + samples/Kconfig | 13 + samples/Makefile | 1 + samples/rcu_txn/Makefile | 2 + samples/rcu_txn/rcu_txn_cache_mutex.c | 354 ++++++++++++++++++++++++++ 6 files changed, 380 insertions(+) create mode 100644 samples/rcu_txn/Makefile create mode 100644 samples/rcu_txn/rcu_txn_cache_mutex.c
Documentation/RCU/rcu_txn.rst +9 -0
@@ -193,6 +193,15 @@ section, if it passes them a lockdep condition for that exclusion, such as backward edge, and a move six, the moved node's own included: each allocates a descriptor. +Samples +======= + +``samples/rcu_txn/`` holds a cache whose entries are found by key in a hash +table of ``rcu_txn_hlist`` buckets, and kept in an ``rcu_txn_list`` as their +LRU. Its lookups run under RCU alone, and each of its changes is one +transaction over both structures. ``rcu_txn_cache_mutex`` excludes its +writers with a single mutex. ``CONFIG_SAMPLE_RCU_TXN`` builds it. + Debugging =========
MAINTAINERS +1 -0
@@ -22862,6 +22862,7 @@ F: Documentation/litmus-tests/rcu/RCU-txn+* F: include/linux/rcu_txn*.h F: lib/rcu_txn* F: lib/tests/rcu_txn_kunit.c +F: samples/rcu_txn/ RCUTORTURE TEST FRAMEWORK M: "Paul E. McKenney" <[email protected]>
samples/Kconfig +13 -0
@@ -103,6 +103,19 @@ config SAMPLE_KFIFO If in doubt, say "N" here. +config SAMPLE_RCU_TXN + tristate "Build RCU pseudo-transaction examples -- loadable modules only" + depends on m + select RCU_TXN + help + Build sample modules of a cache on RCU pseudo-transactions: a hash + table of rcu_txn_hlist buckets, with an rcu_txn_list as its LRU, + that threads look entries up in under RCU alone while other threads + insert, update, delete and evict them. Each module runs for a while + when it is loaded, then reports what it did. + + If in doubt, say "N" here. + config SAMPLE_KDB tristate "Build kdb command example -- loadable modules only" depends on KGDB_KDB && m
samples/Makefile +1 -0
@@ -18,6 +18,7 @@ subdir-$(CONFIG_SAMPLE_LANDLOCK) += landlock obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch/ subdir-$(CONFIG_SAMPLE_PIDFD) += pidfd obj-$(CONFIG_SAMPLE_QMI_CLIENT) += qmi/ +obj-$(CONFIG_SAMPLE_RCU_TXN) += rcu_txn/ obj-$(CONFIG_SAMPLE_RPMSG_CLIENT) += rpmsg/ subdir-$(CONFIG_SAMPLE_SECCOMP) += seccomp subdir-$(CONFIG_SAMPLE_TIMER) += timers
samples/rcu_txn/Makefile new file +2 -0
@@ -0,0 +1,2 @@ +# SPDX-License-Identifier: GPL-2.0-only +obj-$(CONFIG_SAMPLE_RCU_TXN) += rcu_txn_cache_mutex.o
samples/rcu_txn/rcu_txn_cache_mutex.c new file +354 -0
354 lines not on this page · raw message
Signature · 1 line
2.47.3
Mathieu Desnoyers
reviewerRFC PATCH 12/12 samples: Add a cache on RCU pseudo-transactions with a lock per node
In reply to Mathieu DesnoyersShow RCU pseudo-transactions under fine-grained locking: the same cache as the mutex sample, with writers that exclude each other per node rather than under one mutex, so that writers updating distinct entries run in parallel. Every entry, every bucket and the head of the list has a spinlock, and a writer holds the lock of every node updated by its transaction.
A writer plans under RCU, with no lock held: it finds the entry by walking its bucket, and reads the other nodes around it from its links. It then takes the locks of those nodes, in the order of the locks' addresses, and validates the plan: no planned node is dead, and the planned links are in place, in the entry and in its neighbours. If not, it releases the locks and plans again. The dead flag is an entry's tombstone, set by the writer that unlinks it, since an unlinked entry keeps its links for the readers standing on it.
The operation is one RCU read-side critical section from the plan to the commit, which keeps every node it found allocated; its records are reserved before that section. The locks are of one lockdep class, with a comparison function that gives lockdep their order.
As in the mutex sample, lookup threads find entries under RCU alone, and each insertion, update, deletion or eviction is one transaction over the hash table and the list; a second chance moves a referenced entry from the tail of the list to its front. The module runs and reports as the mutex sample does, with its writers' retries and lost races in the report.
--- Documentation/RCU/rcu_txn.rst | 4 +- samples/rcu_txn/Makefile | 2 +- samples/rcu_txn/rcu_txn_cache_node_lock.c | 713 ++++++++++++++++++++++ 3 files changed, 717 insertions(+), 2 deletions(-) create mode 100644 samples/rcu_txn/rcu_txn_cache_node_lock.c
Documentation/RCU/rcu_txn.rst +3 -1
@@ -200,7 +200,9 @@ Samples table of ``rcu_txn_hlist`` buckets, and kept in an ``rcu_txn_list`` as their LRU. Its lookups run under RCU alone, and each of its changes is one transaction over both structures. ``rcu_txn_cache_mutex`` excludes its -writers with a single mutex. ``CONFIG_SAMPLE_RCU_TXN`` builds it. +writers with a single mutex; ``rcu_txn_cache_node_lock`` with a spinlock in +every node, taken in the order of their addresses, so that its writers run in +parallel. ``CONFIG_SAMPLE_RCU_TXN`` builds them. Debugging =========
samples/rcu_txn/Makefile +1 -1
@@ -1,2 +1,2 @@ # SPDX-License-Identifier: GPL-2.0-only -obj-$(CONFIG_SAMPLE_RCU_TXN) += rcu_txn_cache_mutex.o +obj-$(CONFIG_SAMPLE_RCU_TXN) += rcu_txn_cache_mutex.o rcu_txn_cache_node_lock.o
samples/rcu_txn/rcu_txn_cache_node_lock.c new file +713 -0
713 lines not on this page · raw message
Signature · 1 line
2.47.3
Re: [RFC PATCH 12/12] samples: Add a cache on RCU pseudo-transactions with a lock per node
On Fri, Oct 16, 2026 at 09:33:19AM -0400, Mathieu Desnoyers wrote:
[...]
samples/rcu_txn/rcu_txn_cache_node_lock.c line 461
Quoted 13 lines
samples/rcu_txn/rcu_txn_cache_node_lock.c new file +13
-0+rcu_read_lock (); + e =lru_entry (rcu_txn_list_prev_rcu (&cache_lru.head.node)); +if (!e) { +rcu_read_unlock (); +rcu_txn_cancel (&txn); +break ; + } +if (chances <CACHE_CHANCES &&READ_ONCE (e->referenced)) { +WRITE_ONCE (e->referenced, false); +cache_move_front (&txn, e); + chances++; + }else { + evicted =__cache_unlink (&txn, e->key, e,NULL );
I think there's an eviction race here. cache_lock_entry() re-plans from e's current links, but doesn't check that e is still the tail. If W1 gives e a second chance (clears referenced, moves it to the front) while W2 has already read e as the tail, W2 then sees referenced cleared, locks e at the front and evicts the entry W1 just saved. Only the policy suffers. Checking p->next == &cache_lru.head.node for evictions would close it, but then cache_lock_entry() has to return false when the check fails rather than retry, or the writer spins until e is back at the tail.
[...]
samples/rcu_txn/rcu_txn_cache_node_lock.c line 558
Quoted 2 lines
samples/rcu_txn/rcu_txn_cache_node_lock.c new file +2
-0+atomic_long_inc (&nr_lost);/* another writer was first */ +kfree (new);
Nit: an allocation failure in cache_unlink() or cache_link() also ends up here, so it's counted as a lost race as well as a failure.
Two more small things, which apply to the mutex sample in patch 11 as
well: a bad lookup (nr_bad) prints the same "the hash table and the list disagree" as a cache_check() failure, and a kthread_run() failure is skipped silently, so a run in which no thread started reports no error.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerRe: [RFC PATCH 12/12] samples: Add a cache on RCU pseudo-transactions with a lock per node
On 2026-10-23 14:22, Puranjay Mohan wrote:
[...]
Quoted 2 lines
I think there's an eviction race here.
cache_lock_entry()re-plans from e's current links, but doesn't check that e is still the tail.
[...]
Quoted 4 lines
Checking
p->next== &cache_lru.head.node for
evictions would close it, but thencache_lock_entry()has to return false when the check fails rather than retry, or the writer spins until e is back at the tail.
Yes, this is a race. The next version will add a CACHE_EVICT mode to cache_lock_entry(). It checks that the entry is still the tail, and returns false when it is not. The writer then reads the new tail.
[...]
Quoted 2 lines
Nit: an allocation failure in
cache_unlink()orcache_link()also ends up here, so it's counted as a lost race as well as a failure.
A fix is planned for the next version. Link and unlink will return an errno. An allocation failure will be counted in nr_nomem only.
Quoted 4 lines
Two more small things, which apply to the mutex sample in patch 11 as
well: a bad lookup (nr_bad) prints the same "the hash table and the list disagree" as acache_check()failure, and akthread_run()failure is skipped silently, so a run in which no thread started reports no error.
Fixes are planned for the next version, in both samples. A bad lookup will have its own message. A thread that fails to start will fail the module load.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Joel Fernandes
maintainerQuoted 11 lines · Mathieu Desnoyers
Hi,
Earlier this year, I came up with a neat trick which reduces the mental challenge of adapting data structures to RCU. It turns out that it also widens the applicability of RCU to additional classes of data structures.
This is done by a low-overhead abstraction which I'm naming "RCU Pseudo-Transactions" [1, 2]. I name this "pseudo" because unlike classic transactions, the writers exclude each other, readers get no snapshot, and there is no abort.
Cool idea! Instead of tagging the pointer, perhaps alternatively the proxy object can be allocated in specific dedicated parts of kernel address space? Might be slower to test against though. But perhaps will make it usable by any users who use lower bits for other purposes.
Btw, Pseudo-Transactions sounds long and weird, maybe "RCU proxy"? :-)
thanks,
Joel Fernandes
Quoted 235 lines
How it works:
- Reader (
rcu_txn_dereference()):
- Load (rcu_dereference()) pointer from slot.
- Fast path (no proxy installed): unlikely low-bit tag test and conditional branch (not taken).
- Slow path (proxy installed): low-bit tag test, taken branch, the proxy points at the slot's record, select old or new via the group selector word (0/1) (load-acquire). Still wait-free.
- Pointer constraint: Slots must hold pointers which are at least 2-byte aligned when using the low bit as tag and must not use the low bit for anything else. NULL is handled as a plain value.- Updater (caller provides mutual exclusion):
- Allocate a transaction descriptor (gfp flags provided by the caller).
- Append records to the descriptor. (each slot appears at most once per transaction)
- Commit (works in atomic context):
- Install proxy pointers into each slot. (store-release)
- Commit (flip group selector from 0 to 1). (store-release)
- Settle (each slot loses the proxy, gets the new pointer value). (store-release)
-kfree_rcuthe transaction descriptor.Here are the key highlights:
- It enables atomic publication of multiple pointers observed by concurrent RCU readers. It removes the tricky "but what if a reader observes this intermediate state" conundrum typically present when porting a data structure to RCU. A reader that loads one slot before the commit and another after it sees old then new values, never the reverse along a chain of dependent loads (or with an acquire between them).
- It allows composing data structures: a node can be published atomically into many data structures (e.g. hash bucket list and LRU list).
- It removes ordering requirements on multiple object publication with respect to RCU traversal order.
- Can be used as a building block for fine-grained data structure locking (see the second example in this series).
- It enables RCU traversals of cyclic graphs with arbitrary traversal order.
- It allows replacing sequence locks and reader-writer locks in many use-cases, providing read-side wait-free progress guarantees, in scenarios where readers need a coherent walk rather than a snapshot of several fields.
- It removes the need to copy data structure nodes for updates:
multiple pointer (and data field) updates can be performed in-place on memory that cannot be reallocated.I have presented it at LPC [1] and uploaded an article [2] detailing the idea as a defensive publication. There are no patent claims on this work.
In this RFC, I'm presenting a port of
rcu_txnto the Linux kernel, along with a list and hlist API built on top of it. You will also find composed hash bucket list and LRU list examples near the end of the series. I've implemented one example with a single mutex, and the other using RCU for neighborhood lookup and fine-grained per-node locking.I considered various alternatives such as Paul McKenney's "existence guarantees" work (2015), seqlock, rwlocks, RLU, MV-RLU, and k-CAS (all discussed in the paper), but RCU pseudo-transactions performed better than the alternatives in my benchmarks due to smaller cache footprint and fewer read-side fast path instructions. I have applied this to a partial port of the dentry cache to userspace; compared to a straight userspace port of the current kernel scheme, the
rcu_txnvariant shows up to 6.75x speedup for reverse walk under concurrent renames, and up to 21.56x speedup on writer throughput when scaling to 8 writers with 184 concurrent readers under a leaf name exchange workload (see LPC slides).About the development process of this feature: I have used an LLM coding assistant (Claude) throughout the development of this feature. The novel ideas are my own, and I have carefully followed its progress, guided it towards acceptable solutions when it was hitting walls, and reviewed the resulting code.
Origin story: I came up with this idea while working on a userspace RCU trie data structure which I named Fractal Trie (still in development), and I needed to be able to atomically publish parent/child pointer updates on nodes which were controlled by the application (therefore not mine to reallocate).
The series is based on v7.3-rc7.
- Patch 1:
rcu_txncore API.
- Patch 2: KUnit tests for the core API.
- Patch 3: Bloom filter so appending a record to a large transaction does not require an O(n) scan for an existing record for that slot (O(n^2) overall).
- Patch 4:rcu_txn_adopt, debug config option for internal consistency checks.
- Patches 5-6: composable singly and doubly linked lists on top ofrcu_txn.
- Patch 7: documentation.
- Patch 8: litmus tests.
- Patch 9: list writer stress test.
- Patch 10: test of commit in atomic context.
- Patches 11-12: usage example for composed data structures: a cache whose nodes are present in both a bucket hlist and an LRU list, one variant with a single mutex, the other with RCU neighborhood lookup and per-node locking.There are a few areas where I suspect this abstraction could help in the Linux kernel, namely the VFS layer and
mm_structVMA tree / per-VMA locking. I'm interested to hear whether this is useful in other subsystems.I'd specifically like feedback on:
- Where this should live (
kernel/rcu/,lib/?),- Naming and API shape (descriptor + records),
- Whether the Bloom filter threshold should be a config knob,
- Subsystems where this could apply.
Enjoy!
Mathieu
References:
[1] "RCU Pseudo-Transactions: Bridging the gap between RCU and STM", Mathieu Desnoyers,
Linux Plumbers Conference 2026 Refereed Track, October 2026.
https://lpc.events/event/20/contributions/2348/[2] "RCU Pseudo-Transactions and the Single-Writer Flip-Latch:
Atomic Multi-Slot Publication for Read-Copy-Update Data Structures", Mathieu Desnoyers, October 2026.
https://www.efficios.com/pub/rcu-txn/mathieu-desnoyers-rcu-pseudo-transactions.pdfMathieu Desnoyers (12):
rcu_txn: Add single-writer RCU pseudo-transactions
rcu_txn: Add KUnit tests
rcu_txn: Skip the record lookup with a Bloom filter
rcu_txn: AddCONFIG_DEBUG_RCU_TXN
rcu_txn: Add an hlist edited through transactions
rcu_txn: Add a doubly-linked list coherent in both directionsDocumentation/RCU: Describe RCU pseudo-transactionsDocumentation/litmus-tests: Add RCU pseudo-transaction tests
rcu_txn: Test a list writer against concurrent readers
rcu_txn: Test a commit from atomic context
samples: Add a cache on RCU pseudo-transactions under one mutex
samples: Add a cache on RCU pseudo-transactions with a lock per nodeDocumentation/RCU/index.rst | 1 + Documentation/RCU/rcu_txn.rst | 255 ++ Documentation/litmus-tests/README | 37 + .../rcu/RCU-txn+install+once-install.litmus | 55 + .../litmus-tests/rcu/RCU-txn+install.litmus | 66 + .../RCU-txn+list+step-back+once-flip.litmus | 78 + .../RCU-txn+list+step-back+once-settle.litmus | 78 + .../rcu/RCU-txn+list+step-back.litmus | 85 + ...-txn+monotonic+acquire+once-resolve.litmus | 79 + .../rcu/RCU-txn+monotonic+acquire.litmus | 81 + .../RCU-txn+monotonic+dep+once-flip.litmus | 77 + .../RCU-txn+monotonic+dep+once-settle.litmus | 77 + .../rcu/RCU-txn+monotonic+dep.litmus | 83 + .../rcu/RCU-txn+monotonic+unordered.litmus | 84 + .../rcu/RCU-txn+publish+once-install.litmus | 60 + .../rcu/RCU-txn+publish+once-settle.litmus | 60 + .../litmus-tests/rcu/RCU-txn+publish.litmus | 71 + .../rcu/RCU-txn+remove+nolock.litmus | 64 + .../rcu/RCU-txn+remove+nosync.litmus | 64 + .../rcu/RCU-txn+remove+once-install.litmus | 65 + .../litmus-tests/rcu/RCU-txn+remove.litmus | 72 + .../rcu/RCU-txn+sync+free+nolock.litmus | 55 + .../rcu/RCU-txn+sync+free+nosync.litmus | 55 + .../litmus-tests/rcu/RCU-txn+sync+free.litmus | 60 + MAINTAINERS | 11 + include/linux/rcu_txn.h | 1036 ++++++++ include/linux/rcu_txn_bloom.h | 110 + include/linux/rcu_txn_hlist.h | 486 ++++ include/linux/rcu_txn_list.h | 544 +++++ kernel/rcu/Kconfig.debug | 16 + lib/Kconfig | 3 + lib/Kconfig.debug | 13 + lib/Makefile | 2 + lib/rcu_txn.c | 142 ++ lib/rcu_txn_internal.h | 129 + lib/tests/Makefile | 1 + lib/tests/rcu_txn_kunit.c | 2150 +++++++++++++++++ samples/Kconfig | 13 + samples/Makefile | 1 + samples/rcu_txn/Makefile | 2 + samples/rcu_txn/rcu_txn_cache_mutex.c | 354 +++ samples/rcu_txn/rcu_txn_cache_node_lock.c | 713 ++++++ 42 files changed, 7488 insertions(+) create mode 100644 Documentation/RCU/rcu_txn.rst create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+install+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-flip.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+list+step-back.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire+once-resolve.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+acquire.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-flip.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+dep.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+monotonic+unordered.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish+once-settle.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+publish.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+nolock.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+nosync.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove+once-install.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+remove.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free+nolock.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free+nosync.litmus create mode 100644 Documentation/litmus-tests/rcu/RCU-txn+sync+free.litmus create mode 100644 include/linux/rcu_txn.h create mode 100644 include/linux/rcu_txn_bloom.h create mode 100644 include/linux/rcu_txn_hlist.h create mode 100644 include/linux/rcu_txn_list.h create mode 100644 lib/rcu_txn.c create mode 100644 lib/rcu_txn_internal.h create mode 100644 lib/tests/rcu_txn_kunit.c create mode 100644 samples/rcu_txn/Makefile create mode 100644 samples/rcu_txn/rcu_txn_cache_mutex.c create mode 100644 samples/rcu_txn/rcu_txn_cache_node_lock.cbase-commit:
24a19b953e2a3d0ea5a8c4951a0ab8f32720c907Signature · 1 line
2.47.3
Mathieu Desnoyers
reviewerQuoted 13 lines · Joel Fernandes
Quoted 11 lines · Mathieu Desnoyers
Hi,
Earlier this year, I came up with a neat trick which reduces the mental challenge of adapting data structures to RCU. It turns out that it also widens the applicability of RCU to additional classes of data structures.
This is done by a low-overhead abstraction which I'm naming "RCU Pseudo-Transactions" [1, 2]. I name this "pseudo" because unlike classic transactions, the writers exclude each other, readers get no snapshot, and there is no abort.
Quoted 4 lines
Cool idea! Instead of tagging the pointer, perhaps alternatively the proxy object can be allocated in specific dedicated parts of kernel address space? Might be slower to test against though. But perhaps will make it usable by any users who use lower bits for other purposes.
A range check is possible, but it costs more on the read-side fast path than a single-bit test, and with variable bounds it adds memory loads. On x86-64, roughly:
1) Low-bit tag: ptr & 0x1
test $0x1, %al
jnz slow2) Range, constant bounds: ptr >= BEGIN && ptr < END
sub $BEGIN, %rax
cmp $(END - BEGIN), %rax
jb slow3) Range, variable bounds: ptr >= begin && ptr < end
cmp begin(%rip), %rax
jb fast
cmp end(%rip), %rax
jb slowUsers that already need a low bit for other purposes can align their objects on 16 bytes and use any of the other low bits as the tag, still with a single test. A multi-bit pattern within the low 4 bits can also be used as the tag, at the cost of and + cmp + jne on the fast path, if more flexibility is needed.
One alternative I've considered (suggested by Paul McKenney) was to use a trap (page fault) to handle the proxy case. The idea would be to make sure the proxy address range triggers a read fault, and handle the proxy resolution within a page fault handler.
This is a tradeoff: we'd skip the test-and-branch on the fast path, but we would then have to make readers take page faults (orders of magnitude slower) whenever they run concurrently with an ongoing transaction. This would favor a workload with very infrequent updates at a large cost for workloads where updates are not *so* infrequent.
Therefore I went for an approach which would keep read-side overhead in the same order of magnitude whether or not a transaction is in progress, hence the low-bit tag check.
Quoted 1 line
Btw, Pseudo-Transactions sounds long and weird, maybe "RCU proxy"? :-)
I initially called it "RCU flip-latch proxy", but ended up going for a name that better describes what this really is: a transaction in the filesystem (journaling) sense.
Note that I use "proxy" in my definitions and code to describe pointers that are re-routed to the transaction descriptor records.
Thank you for the feedback!
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Hi Mathieu,
Quoted 9 lines · Mathieu Desnoyers
I'd specifically like feedback on:
- Where this should live (
kernel/rcu/,lib/?),- Naming and API shape (descriptor + records),
- Whether the Bloom filter threshold should be a config knob,
- Subsystems where this could apply.
I went through the series and ran the KUnit suite on arm64 (QEMU/KVM) with PROVE_LOCKING, PROVE_RAW_LOCK_NESTING and DEBUG_RCU_TXN. All 59 cases pass, and herd7 agrees with all 21 litmus tests. The install/flip/settle ordering and the descriptor lifetime look right to me.
I found two bugs, details in the replies to the patches:
- patch 1: a one-record commit or a cancel frees the descriptor with kfree() on !PREEMPT_RT, which lockdep can flag as an invalid wait context under a raw spinlock;
- patch 3: rcu_txn_load() on a consumed handle with an armed Bloom filter dereferences a NULL descriptor.
Moves in patch 6 can also make a reader skip or revisit nodes, or loop in another list instead of terminating if the node moves there. In patch 5, deleting a node twice can silently corrupt the bucket.
On your questions:
Location: either works for me, but CONFIG_RCU_TXN is in lib/Kconfig and CONFIG_DEBUG_RCU_TXN in kernel/rcu/Kconfig.debug; I'd keep them together.
Naming: no strong opinion.
Bloom filter knob: I wouldn't add one. Outside the KUnit tests, the only transactions that reach eight records are the mutex sample's evicting insertions, which reserve 32 records anyway. Meanwhile the room reserved for the filter pushes descriptors of 8 to 10 records from 512 to 1024 bytes. I'd drop patch 3 until something needs it.
API shape: every rcu_txn_list add, delete and replace allocates a descriptor and frees it with kfree_rcu(), so all of them can fail with -ENOMEM, delete included. That is hard to use on teardown paths, and reserving first only moves the failure. Since a descriptor can be reused a grace period after its commit, have you considered a small cache of them, tagged with start_poll_synchronize_rcu() and checked with poll_state_synchronize_rcu()? Separately, a one-record transaction never installs a proxy but still allocates a descriptor, 256 bytes unless reserved smaller; keeping the first record inline in struct rcu_txn would avoid that.
Subsystems: in dcache the hash buckets are hlist_bl, with bit 0 of the head as the lock, and d_unhashed() tests for a NULL pprev. rcu_txn_hlist hard-codes bit 0 as its tag and has no unhashed state, so I'm curious how your userspace port deals with both. Also, the only in-tree user of list_bidir_prev_rcu(), kernel/nstree.c, walks either way but never forward and then back in one walk, so a user that needs that guarantee would help make the case for patch 6.
I can send my KUnit reproducers as patches if they're useful.
Thanks,
Puranjay
Mathieu Desnoyers
reviewerQuoted 11 lines · Puranjay Mohan
Hi Mathieu,
Quoted 8 lines · Mathieu Desnoyers
I'd specifically like feedback on:
- Where this should live (
kernel/rcu/,lib/?),- Naming and API shape (descriptor + records),
- Whether the Bloom filter threshold should be a config knob,
Quoted 7 lines
Quoted 1 line
- Subsystems where this could apply.
I went through the series and ran the KUnit suite on arm64 (QEMU/KVM) with
PROVE_LOCKING,PROVE_RAW_LOCK_NESTINGandDEBUG_RCU_TXN. All 59 cases pass, and herd7 agrees with all 21 litmus tests. The install/flip/settle ordering and the descriptor lifetime look right to me.
Thank you for the review and testing!
[...]
Quoted 7 lines
API shape: every
rcu_txn_listadd, delete and replace allocates a descriptor and frees it withkfree_rcu(), so all of them can fail with-ENOMEM, delete included. That is hard to use on teardown paths, and reserving first only moves the failure. Since a descriptor can be reused a grace period after its commit, have you considered a small cache of them, tagged withstart_poll_synchronize_rcu()and checked withpoll_state_synchronize_rcu()?
This question is really the crux of your feedback. There are many options to explore here, and it all depends on the user expectations. Let's focus on this one and keep your other questions for separate replies.
First, I suspect that the "add" and "replace" cases could fail with -ENOMEM without too much problem, which really leaves "remove" as problematic.
The problem with the cache of descriptors (which I've done in my userspace implementation already, a per-cpu "txn slab cache") is that it does not fully address your concern: a thread doing a batch list removal in a huge linked list can run out of pre-allocated descriptors before the grace period ends and the descriptors are freed. How should we handle that ?
We should consider the way struct rcu_head is designed for call_rcu as a precedent here. The tradeoff is to accept a waste of 16 bytes within objects to make sure there is no memory allocation needed when call_rcu is invoked. This ensures there is no situation where the caller may need to block and wait for memory to be freed when invoking call_rcu, e.g. in teardown scenarios.
The basic question is whether there is a _hard_ requirement on making sure a list removal operation *never* sleeps due to memory allocation.
Another open question is whether what we want to prevent here is only memory allocation, or do we also want to prevent blocking that waits for a RCU grace period to complete ? Or RCU deferral the culprit of the issue here ?
Here are a few takes on what the user requirement could look like:
A) Allocate on object creation, no allocation on removal (hard requirement)
If there is a hard requirement on never allocating memory on list removal (not even GFP_ATOMIC), here is one possible option:
We could embed 2x struct rcu_txn_record into each list node, so it's already available for the eventual removal. We could then change the txn descriptor from a flat array into a piecewise scattered set of 2 entries records (one pair of records per pre-planned removal operation).
This wastes memory during the entire object lifetime. This could sit on cache lines separate from the hot object cache lines. These objects would need to plan space for the rcu_txn_group (the selector) so there is really no rcu-reclaimed memory allocated for the transaction descriptor on removal.
The space overhead would be 4x larger than for rcu_head though, we're talking about roughly one cache line (64 bytes) per object for list removal (2 records).
B) Use a preallocated per-cpu rcu-txn slab, allocate GFP_ATOMIC when slab is empty
Another option is to consider using a per-cpu slab of preallocated txn descriptors. This suffers from the basic problem that if a user pushes hard and depletes the reserve, we end up in a scenario where we still need to allocate from that context.
Relying on GFP_ATOMIC allocation could help, up to a point, but this is not bulletproof, as a user could also theoretically empty the atomic emergency reserve as well.
C) Require user to pre-reserve txn descriptors in contexts able to handle allocation error
I've actually used that approach in my userspace fractal trie implementation to facilitate error handling: each mutation operation first reserves all the memory it needs for the rcu txns it will need to perform throughout the entire operation (e.g. insertion, removal, rekey, graft...) so ENOMEM can be handled early before any externally observable side-effect is done. This requires to carefully design the data structure mutations so they are split into a planning, allocation and commit stages.
I find that this approach was a good fit for userspace, but it does require to allow "removal" operations to fail with ENOMEM if there is no memory available, so I'm not sure how applicable it is for the kernel.
D) Use a preallocated per-cpu rcu-txn slab, synchronize_rcu when slab is empty (sleepable caller)
I would expect users to remove list items from within RCU read-side critical sections, so calling synchronize_rcu() on the same RCU grace period "domain" would break this.
One alternative there is to consider having a different RCU grace period "domain" for RCU txn, and wrap all accesses to the txn descriptors within that RCU domain read-side. This way we could handle OOM by enqueuing the thread hitting OOM on a waitqueue associated with the rcu-txn slab, which would necessarily be woken up when RCU readers of that rcu-txn domain complete (typically in a short time frame), and the call-rcu worker moves the memory back to the rcu-txn slab, and issues the wakeup.
E) Use a preallocated per-cpu rcu-txn slab, synchronize txn descriptor reclaim with RCU (steady state) and hazard pointers (OOM)
This is basically just pushing idea (D) further to remove the need for sleepable callers. We surround the rcu txn proxy pointer resolve with both a RCU read-side critical section and a hazard pointer slab address guard, thus protecting the use of the txn descriptor with two types of critical sections. The resolve would run with interrupts disabled. The "resolve" path of txn proxy is not a fast path, so we don't mind the extra overhead too much.
On the "remove" side, we typically have plenty of preallocated rcu-txn from the slab. In the common case, we keep using RCU deferral to free the rcu-txn in batches. This would implement a custom per-cpu pending list to enable the following "stealing" scheme.
In the rare cases where a user empties the slab, we move to a more aggressive mechanism based on synchronize_hazptr: we "steal" the batched in-flight RCU txn reclaims so we can fast-track their reclaim after a hazptr synchronize. This would all be using busy-wait and the only contexts we'd wait against have irqs disabled.
The motivation for handling the steady-state with RCU is throughput (no synchronize_hazptr on the typical "remove" case). Hazard pointers then handle the OOM corner case without requiring sleepable callers.
Thoughts ?
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Mathieu Desnoyers
reviewerOn 2026-10-27 15:57, Mathieu Desnoyers wrote:
[...]
Quoted 16 lines
E) Use a preallocated per-cpu rcu-txn slab, synchronize txn descriptor reclaim with RCU (steady state) and hazard pointers (OOM)
This is basically just pushing idea (D) further to remove the need for sleepable callers. We surround the rcu txn proxy pointer resolve with both a RCU read-side critical section and a hazard pointer slab address guard, thus protecting the use of the txn descriptor with two types of critical sections. The resolve would run with interrupts disabled. The "resolve" path of txn proxy is not a fast path, so we don't mind the extra overhead too much.
On the "remove" side, we typically have plenty of preallocated rcu-txn from the slab. In the common case, we keep using RCU deferral to free the rcu-txn in batches. This would implement a custom per-cpu pending list to enable the following "stealing" scheme.
Quoted 8 lines
In the rare cases where a user empties the slab, we move to a more aggressive mechanism based on
synchronize_hazptr: we "steal" the batched in-flight RCU txn reclaims so we can fast-track their reclaim after a hazptr synchronize. This would all be using busy-wait and the only contexts we'd wait against have irqs disabled.The motivation for handling the steady-state with RCU is throughput (no
synchronize_hazptron the typical "remove" case). Hazard pointers then handle the OOM corner case without requiring sleepable callers.
Well it turns out that this approach has potential, but the hazard pointer machinery is way overkill for this. We can replace my use of hazptr above by a very simple RCU domain with the following characteristics:
- All RCU txn proxy resolves are RCU readers running with irqoff, protected by a per-cpu counter (incremented on read lock and again on unlock),
- There is at most one reader per cpu at any time,
- We use a synchronize RCU on that domain on OOM for the pending slab reclaim "steal" to do reclaim synchronously. This domain's synchronize RCU waits for each CPU until it observes either an even counter or a counter transition.
- We disable preemption across rcu txn (e.g. list insert, remove).
So we'd keep using call_rcu to handle the steady-state reclaim of rcu txn, but use this specialized irqoff RCU domain for the empty slab case.
Thoughts ?
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Paul E. McKenney
maintainerQuoted 39 lines · Mathieu Desnoyers
On 2026-10-27 15:57, Mathieu Desnoyers wrote:
[...]Quoted 16 lines
E) Use a preallocated per-cpu rcu-txn slab, synchronize txn descriptor reclaim with RCU (steady state) and hazard pointers (OOM)
This is basically just pushing idea (D) further to remove the need for sleepable callers. We surround the rcu txn proxy pointer resolve with both a RCU read-side critical section and a hazard pointer slab address guard, thus protecting the use of the txn descriptor with two types of critical sections. The resolve would run with interrupts disabled. The "resolve" path of txn proxy is not a fast path, so we don't mind the extra overhead too much.
On the "remove" side, we typically have plenty of preallocated rcu-txn from the slab. In the common case, we keep using RCU deferral to free the rcu-txn in batches. This would implement a custom per-cpu pending list to enable the following "stealing" scheme.
Quoted 8 lines
In the rare cases where a user empties the slab, we move to a more aggressive mechanism based on
synchronize_hazptr: we "steal" the batched in-flight RCU txn reclaims so we can fast-track their reclaim after a hazptr synchronize. This would all be using busy-wait and the only contexts we'd wait against have irqs disabled.The motivation for handling the steady-state with RCU is throughput (no
synchronize_hazptron the typical "remove" case). Hazard pointers then handle the OOM corner case without requiring sleepable callers.Well it turns out that this approach has potential, but the hazard pointer machinery is way overkill for this. We can replace my use of hazptr above by a very simple RCU domain with the following characteristics:
- All RCU txn proxy resolves are RCU readers running with irqoff, protected by a per-cpu counter (incremented on read lock and again on unlock),
- There is at most one reader per cpu at any time,
- We use a synchronize RCU on that domain on OOM for the pending slab reclaim "steal" to do reclaim synchronously. This domain's synchronize RCU waits for each CPU until it observes either an even counter or a counter transition.
- We disable preemption across rcu txn (e.g. list insert, remove).
Quoted 4 lines
So we'd keep using
call_rcuto handle the steady-state reclaim of rcu txn, but use this specialized irqoff RCU domain for the empty slab case.Thoughts ?
Atomic SRCU within interrupts-disabled regions seems to fit this bill: synchronize_srcu_atomic(), srcu_read_lock_atomic(), and srcu_read_unlock_atomic(), which interrupts disabled across the latter two. Maybe srcu_read_lock_atomic_irqsave() and srcu_read_lock_atomic_irqrestore() if that helps.
Or am I missing a turn in your requirements?
Thanx, Paul
Mathieu Desnoyers
reviewerQuoted 1 line · Paul E. McKenney
On Tue, Oct 27, 2026 at 09:13:17PM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 5 lines
Quoted 4 lines
So we'd keep using
call_rcuto handle the steady-state reclaim of rcu txn, but use this specialized irqoff RCU domain for the empty slab case.Thoughts ?
Quoted 7 lines
Atomic SRCU within interrupts-disabled regions seems to fit this bill:
synchronize_srcu_atomic(),srcu_read_lock_atomic(), andsrcu_read_unlock_atomic(), which interrupts disabled across the latter two. Maybesrcu_read_lock_atomic_irqsave()andsrcu_read_lock_atomic_irqrestore()if that helps.Or am I missing a turn in your requirements?
It fits well, thanks! It would replace the per-CPU counters I wrote for this domain. The steady state stays on call_rcu(), so the srcu_struct would only see synchronize_srcu_atomic(), never call_srcu(). I see two gaps between my requirements and your proposal:
First, NMI readers. rcu_txn_dereference() should work in any context, NMI included, as rcu_dereference() does. A tracer or a BPF program can walk an rcu_txn list from NMI. The atomic flavor uses __srcu_read_lock(). Its this_cpu_inc() is not NMI-safe on every architecture. And one srcu_struct cannot mix the atomic flavor with the nmisafe one.
Could the atomic flavor count its readers as srcu_read_lock_nmisafe() does? Then a reader could also enter from NMI. The code I have for the next version keeps one counter per NMI nesting level for this. With SRCU, the sums of locks and unlocks handle the nesting already.
Second, interrupts off. The wait for readers can run with interrupts disabled, for example in a list delete under a raw spinlock. The kerneldoc of synchronize_srcu_atomic() then requires the readers to disable interrupts too. So yes, the irqsave and irqrestore variants would help. The readers would use them instead of preemption off.
Would you prefer to add these two variants on the SRCU side, or should I prototype them with the next version of this series?
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Paul E. McKenney
maintainerQuoted 30 lines · Mathieu Desnoyers
Quoted 1 line · Paul E. McKenney
On Tue, Oct 27, 2026 at 09:13:17PM -0400, Mathieu Desnoyers wrote:
[...]
Quoted 1 line
Quoted 1 line
So we'd keep using
call_rcuto handle the steady-state reclaim of rcutxn,
Quoted 11 lines
Quoted 3 lines
but use this specialized irqoff RCU domain for the empty slab case.
Thoughts ?
Atomic SRCU within interrupts-disabled regions seems to fit this bill:
synchronize_srcu_atomic(),srcu_read_lock_atomic(), andsrcu_read_unlock_atomic(), which interrupts disabled across the latter two. Maybesrcu_read_lock_atomic_irqsave()andsrcu_read_lock_atomic_irqrestore()if that helps.Or am I missing a turn in your requirements?
It fits well, thanks! It would replace the per-CPU counters I wrote for this domain. The steady state stays on
call_rcu(), so thesrcu_structwould only seesynchronize_srcu_atomic(), nevercall_srcu(). I see two gaps between my requirements and your proposal:First, NMI readers.
rcu_txn_dereference()should work in any context, NMI included, asrcu_dereference()does. A tracer or a BPF program can walk anrcu_txnlist from NMI. The atomic flavor uses__srcu_read_lock(). Itsthis_cpu_inc()is not NMI-safe on every architecture. And onesrcu_structcannot mix the atomic flavor with the nmisafe one.
Quoted 4 lines
Could the atomic flavor count its readers as
srcu_read_lock_nmisafe()does? Then a reader could also enter from NMI. The code I have for the next version keeps one counter per NMI nesting level for this. With SRCU, the sums of locks and unlocks handle the nesting already.
The other user that I know of is David Woodhouse, now CCed.
David, would you be OK with srcu_read_lock_atomic() using NMI-safe counters, similar to __srcu_read_lock_fast()?
(Yes, I *could* make only your _irqsave() and _irqrestore() variants NMI-safe, but then we have to enforce different srcu_struct structures for _irqsave() and not.)
Quoted 8 lines
Second, interrupts off. The wait for readers can run with interrupts disabled, for example in a list delete under a raw spinlock. The kerneldoc of
synchronize_srcu_atomic()then requires the readers to disable interrupts too. So yes, the irqsave and irqrestore variants would help. The readers would use them instead of preemption off.Would you prefer to add these two variants on the SRCU side, or should I prototype them with the next version of this series?
Your choice!
If you would like to do it, the trick is to make srcu_read_lock_atomic() and srcu_read_unlock_atomic() invoke __srcu_read_lock_fast() and __srcu_read_unlock_fast(), respectively, instead of __srcu_read_lock() and __srcu_read_unlock(), again respectively.
Then there would need to be an srcu_read_lock_atomic_irqsafe() and srcu_read_unlock_irqrestore(), which would (as you say), replace preempt_disable() with local_irq_save() and preempt_enable() with local_irq_restore(). There would be a flags argument that as far as I know requires srcu_read_lock_atomic_irqsafe() and srcu_read_unlock_irqrestore() be macros. It would be good to share code with srcu_read_lock_atomic() and srcu_read_unlock_atomic().
And kernel/rcu/rcutorture.c would need a bit of tweaking to test this new interface, which should be discoverable by looking for the code that tests srcu_read_{,un}lock_atomic(). Maybe just make srcu_torture_read_lock() randomly decide between srcu_read_lock_atomic() and srcu_read_lock_atomic_irqsave(), and have srcu_torture_read_unlock() follow that decision.
One potentially tricky part here is that rcutorture is not set up to pass a flags variable from a read-lock to the corresponding read-unlock.
Thanx, Paul
Mathieu Desnoyers
reviewerOn 2026-11-09 20:34, Paul E. McKenney wrote:
[...]
Quoted 4 lines
Quoted 2 lines
Would you prefer to add these two variants on the SRCU side, or should I prototype them with the next version of this series?
Your choice!
I'll do it. Adapting atomic SRCU to these needs is much more maintainable than keeping my own copy of nearly the same mechanism.
Quoted 4 lines
If you would like to do it, the trick is to make
srcu_read_lock_atomic()andsrcu_read_unlock_atomic()invoke__srcu_read_lock_fast()and__srcu_read_unlock_fast(), respectively, instead of__srcu_read_lock()and__srcu_read_unlock(), again respectively.
I'll start by making every atomic reader NMI-safe this way, as you suggest. If David objects, we can still change it based on his feedback.
Quoted 7 lines
Then there would need to be an
srcu_read_lock_atomic_irqsafe()andsrcu_read_unlock_irqrestore(), which would (as you say), replacepreempt_disable()withlocal_irq_save()andpreempt_enable()withlocal_irq_restore(). There would be a flags argument that as far as I know requiressrcu_read_lock_atomic_irqsafe()andsrcu_read_unlock_irqrestore()be macros. It would be good to share code withsrcu_read_lock_atomic()andsrcu_read_unlock_atomic().
Agreed. I plan to name them srcu_read_lock_atomic_irqsave() and srcu_read_unlock_atomic_irqrestore(), as macros sharing code with the current pair.
Quoted 9 lines
And
kernel/rcu/rcutorture.cwould need a bit of tweaking to test this new interface, which should be discoverable by looking for the code that tests srcu_read_{,un}lock_atomic(). Maybe just makesrcu_torture_read_lock()randomly decide betweensrcu_read_lock_atomic()andsrcu_read_lock_atomic_irqsave(), and havesrcu_torture_read_unlock()follow that decision.One potentially tricky part here is that rcutorture is not set up to pass a flags variable from a read-lock to the corresponding read-unlock.
I'll look at the rcutorture side as part of it.
A later version of rcu_txn will then use these readers, instead of its own per-CPU counters.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Paul E. McKenney
maintainerQuoted 38 lines · Mathieu Desnoyers
On 2026-11-09 20:34, Paul E. McKenney wrote:
[...]Quoted 4 lines
Quoted 2 lines
Would you prefer to add these two variants on the SRCU side, or should I prototype them with the next version of this series?
Your choice!
I'll do it. Adapting atomic SRCU to these needs is much more maintainable than keeping my own copy of nearly the same mechanism.
Quoted 4 lines
If you would like to do it, the trick is to make
srcu_read_lock_atomic()andsrcu_read_unlock_atomic()invoke__srcu_read_lock_fast()and__srcu_read_unlock_fast(), respectively, instead of__srcu_read_lock()and__srcu_read_unlock(), again respectively.I'll start by making every atomic reader NMI-safe this way, as you suggest. If David objects, we can still change it based on his feedback.
Quoted 7 lines
Then there would need to be an
srcu_read_lock_atomic_irqsafe()andsrcu_read_unlock_irqrestore(), which would (as you say), replacepreempt_disable()withlocal_irq_save()andpreempt_enable()withlocal_irq_restore(). There would be a flags argument that as far as I know requiressrcu_read_lock_atomic_irqsafe()andsrcu_read_unlock_irqrestore()be macros. It would be good to share code withsrcu_read_lock_atomic()andsrcu_read_unlock_atomic().Agreed. I plan to name them
srcu_read_lock_atomic_irqsave()andsrcu_read_unlock_atomic_irqrestore(), as macros sharing code with the current pair.Quoted 7 lines
And
kernel/rcu/rcutorture.cwould need a bit of tweaking to test this new interface, which should be discoverable by looking for the code that tests srcu_read_{,un}lock_atomic(). Maybe just makesrcu_torture_read_lock()randomly decide betweensrcu_read_lock_atomic()andsrcu_read_lock_atomic_irqsave(), and havesrcu_torture_read_unlock()follow that decision.
Quoted 7 lines
Quoted 2 lines
One potentially tricky part here is that rcutorture is not set up to pass a flags variable from a read-lock to the corresponding read-unlock.
I'll look at the rcutorture side as part of it.
A later version of
rcu_txnwill then use these readers, instead of its own per-CPU counters.
Sounds good, and looking forward to seeing what you come up with!
Thanx, Paul
Quoted 9 lines · Paul E. McKenney
Quoted 4 lines
Could the atomic flavor count its readers as
srcu_read_lock_nmisafe()does? Then a reader could also enter from NMI. The code I have for the next version keeps one counter per NMI nesting level for this. With SRCU, the sums of locks and unlocks handle the nesting already.The other user that I know of is David Woodhouse, now CCed.
David, would you be OK with
srcu_read_lock_atomic()using NMI-safe counters, similar to__srcu_read_lock_fast()?
I can't see any reason why I should object to that, as long as the synchronize_srcu_atomic() stays in the 4-16µs bracket which was our major criterion for this approach.
I'm still iterating on the KVM GPC use case¹, as sashiko-bot keeps finding things that my own local sashiko runs don't.
¹ https://git.infradead.org/users/dwmw2/linux.git/shortlog/refs/heads/gpc-srcu-v3
Paul E. McKenney
maintainerQuoted 6 lines · David Woodhouse
Quoted 5 lines · Paul E. McKenney
Quoted 4 lines
Could the atomic flavor count its readers as
srcu_read_lock_nmisafe()does? Then a reader could also enter from NMI. The code I have for the next version keeps one counter per NMI nesting level for this. With SRCU, the sums of locks and unlocks handle the nesting already.
Quoted 8 lines
Quoted 4 lines
The other user that I know of is David Woodhouse, now CCed.
David, would you be OK with
srcu_read_lock_atomic()using NMI-safe counters, similar to__srcu_read_lock_fast()?I can't see any reason why I should object to that, as long as the
synchronize_srcu_atomic()stays in the 4-16µs bracket which was our major criterion for this approach.
Then full speed ahead! ;-)
Quoted 4 lines
I'm still iterating on the KVM GPC use case¹, as sashiko-bot keeps finding things that my own local sashiko runs don't.
¹ https://git.infradead.org/users/dwmw2/linux.git/shortlog/refs/heads/gpc-srcu-v3
I know that feeling...
Thanx, Paul
Mathieu Desnoyers
reviewerHi Puranjay,
On 2026-10-23 14:19, Puranjay Mohan wrote:
[...]
Quoted 1 line
I found two bugs, details in the replies to the patches:
Thanks for finding them, and for the reproducers. Fixes for both bugs are planned for the next version. I answered each point of your patch replies in its own thread. Here are the answers to the rest of this mail.
Quoted 3 lines
Location: either works for me, but
CONFIG_RCU_TXNis in lib/Kconfig andCONFIG_DEBUG_RCU_TXNinkernel/rcu/Kconfig.debug; I'd keep them together.
Planned for the next version. DEBUG_RCU_TXN will move to lib/Kconfig.debug, next to RCU_TXN_KUNIT_TEST.
Quoted 1 line
Bloom filter knob: I wouldn't add one.
[...]
Quoted 1 line
I'd drop patch 3 until something needs it.
Agreed. Dropping patch 3 is planned for the next version. Your size table settled it.
Quoted 7 lines
API shape: every
rcu_txn_listadd, delete and replace allocates a descriptor and frees it withkfree_rcu(), so all of them can fail with-ENOMEM, delete included. That is hard to use on teardown paths, and reserving first only moves the failure. Since a descriptor can be reused a grace period after its commit, have you considered a small cache of them, tagged withstart_poll_synchronize_rcu()and checked withpoll_state_synchronize_rcu()?
The next version will implement the design of my second reply. It is planned as three new patches:
- Readers resolve a proxy only within a resolve section. This is a short section with interrupts off, counted per CPU. A writer can wait for the sections in flight without sleeping.
- A local transaction takes its descriptor from a per-CPU pool. The pool holds 16 descriptors of 6 records, 5920 bytes per CPU. Preemption stays off from init to commit.
- The _rcu forms of rcu_txn_list run a local transaction. They take no gfp_t and return nothing.
A cache alone does not cover a burst. A CPU can run more operations within a grace period than its pool holds. When its pool is empty, the CPU steals its own descriptors back. It waits for the resolve sections in flight, then reuses them. So a delete never fails and never sleeps.
In the steady state, descriptors go back to the pool through call_rcu_hurry(), with one rcu_head per batch. With CONFIG_RCU_LAZY, call_rcu() can hold a callback back for up to 10 seconds. The descriptors would stay out of the pool that long, and the CPU would steal more often. I chose a callback over start_poll_synchronize_rcu() because start_poll takes the leaf rcu_node lock on every call.
Quoted 4 lines
Separately, a one-record transaction
never installs a proxy but still allocates a descriptor, 256 bytes unless reserved smaller; keeping the first record inline in structrcu_txnwould avoid that.
I would rather handle this in the users than in rcu_txn. A user knows which of the pointers it writes are followed by readers. An update that re-points a single such slot needs no transaction. The writers are excluded, and every commit settles its slots before it returns, so the slot holds no proxy. rcu_assign_pointer() then publishes the update.
This covers more than one-record transactions. Each _rcu operation of rcu_txn_hlist writes several pointers, but readers follow only one edge. That edge is published with rcu_assign_pointer(), and pprev and the new node's links take plain stores. So none of them creates a transaction. Recorded through rcu_txn, the same update would take two or three records, and an inline first record would not cover it. Patch 7 documents this in Documentation/RCU/rcu_txn.rst.
The rcu_txn_list operations change at least two slots that readers follow, so they need a descriptor. With the pool, they will allocate nothing either.
Quoted 4 lines
Subsystems: in dcache the hash buckets are
hlist_bl, with bit 0 of the head as the lock, andd_unhashed()tests for a NULL pprev.rcu_txn_hlisthard-codes bit 0 as its tag and has no unhashed state, so I'm curious how your userspace port deals with both.
The hlist of this series is for tables locked some other way, as in the samples. A bucket with a bit lock gets an rcu_txn_hlist_bl:
- The lock keeps bit 0, as in list_bl.h.
- The proxy tag takes bit 1.
- A record of the head carries the lock bit in its tag and in both of its values. So the head stays locked from install to settle.
- Readers strip the lock bit. The engine is unchanged.
It is not part of this series. It exists on my branch that converts the dentry cache to rcu_txn. The userspace port does the same with other bits: tag in bit 0, lock in bit 2.
For d_unhashed(), the unhashed state you asked for in patch 5 is planned for the next version. A removed node will have a NULL pprev.
Quoted 4 lines
Also, the only
in-tree user oflist_bidir_prev_rcu(),kernel/nstree.c, walks either way but never forward and then back in one walk, so a user that needs that guarantee would help make the case for patch 6.
The node-lock sample (patch 12) is such a user. An eviction walks back from the head to the tail. Then cache_lock_entry() reads the tail's prev and next, to lock its neighbours. cache_plan_holds() re-checks the four edges in both directions. If the backward chain disagreed with the forward one, the writer would lock the wrong nodes. Your reply to patch 6 makes the same point about LRU second chances.
Quoted 1 line
I can send my KUnit reproducers as patches if they're useful.
Yes, please. They can go on top of the next version.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com