mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v2] locking/rwsem: don't let readers retain the lock past a queued writer
@ 2026-11-26 22:14 Lorenzo Stoakes (ARM)
  2026-12-01 16:27 ` Waiman Long
  0 siblings, 1 reply; 2+ messages in thread
From: Lorenzo Stoakes (ARM) @ 2026-11-26 22:14 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng,
	Waiman Long, Nick Terrell, David Sterba, Nathan Chancellor,
	Nick Desaulniers, Bill Wendling, Justin Stitt
  Cc: linux-kernel, David Hildenbrand (Arm), llvm, ljs

Since commit 1a728dff855a ("locking/rwsem: Enable reader optimistic lock
stealing"), a racing read lock can steal an rwsem from under a queued
writer whose handoff timeout hasn't expired yet.

This is most problematic when an rwsem read lock is released then
reacquired in order to relieve lock contention, as instead it will simply
have the lock handed right back to it ahead of the intended beneficiary.

Naturally, this behaviour rather defeats the object of doing this kind of
thing, so this is less than ideal.

Fix this by updating the optimistic read lock stealing code in
rwsem_down_read_slowpath() to explicitly check whether the first queued
lock is a waiting writer and the rwsem was last held by a reader, and to
not allow the theft if so.

This still permits reader stealing if a writer last held the lock, as
failing to do so can starve readers in favour of writers. This maintains
fairness.

When a steal is disallowed, keep the existing sem->wait_lock held when
jumping to the queue code to avoid useless lock acquisition/release.

Also update the comment describing optimistic read lock acquisition
conditions to include this newly introduced behaviour.

Care is taken to ensure correct ordering of lock acquisition, lock waking
and marking the lock reader-owned.

Signed-off-by: Lorenzo Stoakes (ARM) <ljs@kernel.org>
---
Testing:

All on an AMD threadripper 9980X with 64 cores, one thread per core (SMT off),
bare metal testing.

Correctness
-----------
locktorture: RWSEM01-08 all pass, 30 minutes each, 0 read/write failures,
no splats.
Bare metal: no dmesg splats on any boot.

Writer latency (microbenchmark, bare metal, p99)
------------------------------------------------
readers          base      patched
2             3813 us        17 us
4             3868 us        29 us
16            5369 us      4008 us  (within expected stddev)
62            4612 us      3835 us  (ditto)
2, one CCD    3865 us        17 us
7, one CCD    3951 us        35 us

Writer throughput +35-54% at 2 and 4 readers and in both one-CCD cases.
Reader steals in this test: 4.8M -> 8.

stress-ng (bare metal, 64 instances, 2 boots each, alternating)
---------------------------------------------------------------
vma        59.9k -> 67.1k bogo-ops/s   +12.0%
msg                                     +9.5%
madvise                                 +5.0%

vma in guests: 64.2k-66.7k vs 58.8k-61.0k base.

will-it-scale (t=8 and t=64)
----------------------------
mmap1, mmap2, brk1, open1, page_fault1/2/3, unlink1: within noise.

Real workloads
--------------
                              base     patched
kernel build, LLVM (guest)    28.33 s  28.51 s   +0.6%
kernel build (bare metal)     26.86 s  27.03 s   +0.6%
relink with lld               6.136 s  6.154 s   +0.3%
zstd                          0.617 s  0.610 s   -1.1%
ripgrep                       0.154 s  0.153 s   flat
Go std build                  3.718 s  3.707 s   flat

I.e. all within noise levels.

v2:
* Update to allow reader stealing if a writer last held the lock to avoid a
  spinning writer from starving readers.
* Simplified the code.
* Ran a full suite of tests and benchmarks on bare metal to ensure
  correctness and avoid performance regressions.

v1:
https://lore.kernel.org/r/20261105-rwsem-dont-steal-from-queued-writer-v1-1-275e070f426f@kernel.org
---
 kernel/locking/rwsem.c | 44 +++++++++++++++++++++++++++-----------------
 1 file changed, 27 insertions(+), 17 deletions(-)

diff --git a/kernel/locking/rwsem.c b/kernel/locking/rwsem.c
index b9c180ac1eee..c49e518f1b2c 100644
--- a/kernel/locking/rwsem.c
+++ b/kernel/locking/rwsem.c
@@ -59,7 +59,9 @@
  * A fast path reader optimistic lock stealing is supported when the rwsem
  * is previously owned by a writer and the following conditions are met:
  *  - rwsem is not currently writer owned
- *  - the handoff isn't set.
+ *  - the handoff isn't set
+ *  - a writer isn't at the head of the wait queue while the rwsem was last
+ *    held by a reader.
  */
 #define RWSEM_READER_OWNED	(1UL << 0)
 #define RWSEM_NONSPINNABLE	(1UL << 1)
@@ -1018,47 +1020,55 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
 {
 	long adjustment = -RWSEM_READER_BIAS;
 	long rcnt = (count >> RWSEM_READER_SHIFT);
+	bool reader_owned = atomic_long_read(&sem->owner) & RWSEM_READER_OWNED;
 	struct rwsem_waiter waiter, *first;
 	DEFINE_WAKE_Q(wake_q);
 
-	/*
-	 * To prevent a constant stream of readers from starving a sleeping
-	 * writer, don't attempt optimistic lock stealing if the lock is
-	 * very likely owned by readers.
-	 */
-	if ((atomic_long_read(&sem->owner) & RWSEM_READER_OWNED) &&
-	    (rcnt > 1) && !(count & RWSEM_WRITER_LOCKED))
-		goto queue;
-
 	/*
 	 * Reader optimistic lock stealing.
 	 */
 	if (!(count & (RWSEM_WRITER_LOCKED | RWSEM_FLAG_HANDOFF))) {
-		rwsem_set_reader_owned(sem);
-		lockevent_inc(rwsem_rlock_steal);
-
 		/*
-		 * Wake up other readers in the wait queue if it is
-		 * the first reader.
+		 * To prevent a constant stream of readers from starving a
+		 * sleeping writer, don't attempt optimistic lock stealing if
+		 * the lock is very likely owned by readers.
 		 */
+		if (reader_owned && rcnt > 1)
+			goto queue;
+
 		if ((rcnt == 1) && (count & RWSEM_FLAG_WAITERS)) {
 			raw_spin_lock_irq(&sem->wait_lock);
-			if (sem->first_waiter)
+			first = sem->first_waiter;
+			/*
+			 * If a reader last held this lock, let a queued writer
+			 * take precedence to avoid writer starvation.
+			 */
+			if (reader_owned && first &&
+			    first->type == RWSEM_WAITING_FOR_WRITE)
+				goto queue_locked;
+			rwsem_set_reader_owned(sem);
+			/* If first reader, wake other readers in queue. */
+			if (first)
 				rwsem_mark_wake(sem, RWSEM_WAKE_READ_OWNED,
 						&wake_q);
 			raw_spin_unlock_irq(&sem->wait_lock);
 			wake_up_q(&wake_q);
+		} else {
+			rwsem_set_reader_owned(sem);
 		}
+
+		lockevent_inc(rwsem_rlock_steal);
 		return sem;
 	}
 
 queue:
+	raw_spin_lock_irq(&sem->wait_lock);
+queue_locked:
 	waiter.task = current;
 	waiter.type = RWSEM_WAITING_FOR_READ;
 	waiter.timeout = jiffies + RWSEM_WAIT_TIMEOUT;
 	waiter.handoff_set = false;
 
-	raw_spin_lock_irq(&sem->wait_lock);
 	first = sem->first_waiter;
 	if (!first) {
 		/*

---
base-commit: 05441d697f7f9a927264f4058cbbc6a03dfcac9d
change-id: 20261105-rwsem-dont-steal-from-queued-writer-04b11d9d406b

Cheers,
-- 
Lorenzo Stoakes (ARM) <ljs@kernel.org>


^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: [PATCH v2] locking/rwsem: don't let readers retain the lock past a queued writer
  2026-11-26 22:14 [PATCH v2] locking/rwsem: don't let readers retain the lock past a queued writer Lorenzo Stoakes (ARM)
@ 2026-12-01 16:27 ` Waiman Long
  0 siblings, 0 replies; 2+ messages in thread
From: Waiman Long @ 2026-12-01 16:27 UTC (permalink / raw)
  To: Lorenzo Stoakes (ARM),
	Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng,
	Nick Terrell, David Sterba, Nathan Chancellor, Nick Desaulniers,
	Bill Wendling, Justin Stitt
  Cc: linux-kernel, David Hildenbrand (Arm), llvm

On 11/26/26 5:14 PM, Lorenzo Stoakes (ARM) wrote:
> Since commit 1a728dff855a ("locking/rwsem: Enable reader optimistic lock
> stealing"), a racing read lock can steal an rwsem from under a queued
> writer whose handoff timeout hasn't expired yet.
>
> This is most problematic when an rwsem read lock is released then
> reacquired in order to relieve lock contention, as instead it will simply
> have the lock handed right back to it ahead of the intended beneficiary.
>
> Naturally, this behaviour rather defeats the object of doing this kind of
> thing, so this is less than ideal.
>
> Fix this by updating the optimistic read lock stealing code in
> rwsem_down_read_slowpath() to explicitly check whether the first queued
> lock is a waiting writer and the rwsem was last held by a reader, and to
> not allow the theft if so.
>
> This still permits reader stealing if a writer last held the lock, as
> failing to do so can starve readers in favour of writers. This maintains
> fairness.
Yes, I like this idea of maintaining some fairness.
>
> When a steal is disallowed, keep the existing sem->wait_lock held when
> jumping to the queue code to avoid useless lock acquisition/release.
>
> Also update the comment describing optimistic read lock acquisition
> conditions to include this newly introduced behaviour.
>
> Care is taken to ensure correct ordering of lock acquisition, lock waking
> and marking the lock reader-owned.
>
> Signed-off-by: Lorenzo Stoakes (ARM) <ljs@kernel.org>
> ---
> Testing:
>
> All on an AMD threadripper 9980X with 64 cores, one thread per core (SMT off),
> bare metal testing.
>
> Correctness
> -----------
> locktorture: RWSEM01-08 all pass, 30 minutes each, 0 read/write failures,
> no splats.
> Bare metal: no dmesg splats on any boot.
>
> Writer latency (microbenchmark, bare metal, p99)
> ------------------------------------------------
> readers          base      patched
> 2             3813 us        17 us
> 4             3868 us        29 us
> 16            5369 us      4008 us  (within expected stddev)
> 62            4612 us      3835 us  (ditto)
> 2, one CCD    3865 us        17 us
> 7, one CCD    3951 us        35 us
>
> Writer throughput +35-54% at 2 and 4 readers and in both one-CCD cases.
> Reader steals in this test: 4.8M -> 8.
Just to confirm if the reader steals had dropped from 4.8M to just 8. 
That is really low. What is the test duration?
>
> stress-ng (bare metal, 64 instances, 2 boots each, alternating)
> ---------------------------------------------------------------
> vma        59.9k -> 67.1k bogo-ops/s   +12.0%
> msg                                     +9.5%
> madvise                                 +5.0%
>
> vma in guests: 64.2k-66.7k vs 58.8k-61.0k base.
>
> will-it-scale (t=8 and t=64)
> ----------------------------
> mmap1, mmap2, brk1, open1, page_fault1/2/3, unlink1: within noise.
>
> Real workloads
> --------------
>                                base     patched
> kernel build, LLVM (guest)    28.33 s  28.51 s   +0.6%
> kernel build (bare metal)     26.86 s  27.03 s   +0.6%
> relink with lld               6.136 s  6.154 s   +0.3%
> zstd                          0.617 s  0.610 s   -1.1%
> ripgrep                       0.154 s  0.153 s   flat
> Go std build                  3.718 s  3.707 s   flat
>
> I.e. all within noise levels.
>
> v2:
> * Update to allow reader stealing if a writer last held the lock to avoid a
>    spinning writer from starving readers.
> * Simplified the code.
> * Ran a full suite of tests and benchmarks on bare metal to ensure
>    correctness and avoid performance regressions.
>
> v1:
> https://lore.kernel.org/r/20261105-rwsem-dont-steal-from-queued-writer-v1-1-275e070f426f@kernel.org
> ---
>   kernel/locking/rwsem.c | 44 +++++++++++++++++++++++++++-----------------
>   1 file changed, 27 insertions(+), 17 deletions(-)
>
> diff --git a/kernel/locking/rwsem.c b/kernel/locking/rwsem.c
> index b9c180ac1eee..c49e518f1b2c 100644
> --- a/kernel/locking/rwsem.c
> +++ b/kernel/locking/rwsem.c
> @@ -59,7 +59,9 @@
>    * A fast path reader optimistic lock stealing is supported when the rwsem
>    * is previously owned by a writer and the following conditions are met:
>    *  - rwsem is not currently writer owned
> - *  - the handoff isn't set.
> + *  - the handoff isn't set
> + *  - a writer isn't at the head of the wait queue while the rwsem was last
> + *    held by a reader.
>    */
>   #define RWSEM_READER_OWNED	(1UL << 0)
>   #define RWSEM_NONSPINNABLE	(1UL << 1)
> @@ -1018,47 +1020,55 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
>   {
>   	long adjustment = -RWSEM_READER_BIAS;
>   	long rcnt = (count >> RWSEM_READER_SHIFT);
> +	bool reader_owned = atomic_long_read(&sem->owner) & RWSEM_READER_OWNED;
>   	struct rwsem_waiter waiter, *first;
>   	DEFINE_WAKE_Q(wake_q);
>   
> -	/*
> -	 * To prevent a constant stream of readers from starving a sleeping
> -	 * writer, don't attempt optimistic lock stealing if the lock is
> -	 * very likely owned by readers.
> -	 */
> -	if ((atomic_long_read(&sem->owner) & RWSEM_READER_OWNED) &&
> -	    (rcnt > 1) && !(count & RWSEM_WRITER_LOCKED))
> -		goto queue;
> -
>   	/*
>   	 * Reader optimistic lock stealing.
>   	 */
>   	if (!(count & (RWSEM_WRITER_LOCKED | RWSEM_FLAG_HANDOFF))) {
> -		rwsem_set_reader_owned(sem);
> -		lockevent_inc(rwsem_rlock_steal);
> -
>   		/*
> -		 * Wake up other readers in the wait queue if it is
> -		 * the first reader.
> +		 * To prevent a constant stream of readers from starving a
> +		 * sleeping writer, don't attempt optimistic lock stealing if
> +		 * the lock is very likely owned by readers.
>   		 */
> +		if (reader_owned && rcnt > 1)
> +			goto queue;
> +
>   		if ((rcnt == 1) && (count & RWSEM_FLAG_WAITERS)) {
>   			raw_spin_lock_irq(&sem->wait_lock);
> -			if (sem->first_waiter)
> +			first = sem->first_waiter;
> +			/*
> +			 * If a reader last held this lock, let a queued writer
> +			 * take precedence to avoid writer starvation.
> +			 */
> +			if (reader_owned && first &&
> +			    first->type == RWSEM_WAITING_FOR_WRITE)
> +				goto queue_locked;
> +			rwsem_set_reader_owned(sem);
> +			/* If first reader, wake other readers in queue. */
> +			if (first)
>   				rwsem_mark_wake(sem, RWSEM_WAKE_READ_OWNED,
>   						&wake_q);
>   			raw_spin_unlock_irq(&sem->wait_lock);
>   			wake_up_q(&wake_q);
> +		} else {
> +			rwsem_set_reader_owned(sem);
>   		}
> +
> +		lockevent_inc(rwsem_rlock_steal);
>   		return sem;
>   	}
>   
>   queue:
> +	raw_spin_lock_irq(&sem->wait_lock);
> +queue_locked:
>   	waiter.task = current;
>   	waiter.type = RWSEM_WAITING_FOR_READ;
>   	waiter.timeout = jiffies + RWSEM_WAIT_TIMEOUT;
>   	waiter.handoff_set = false;
>   
> -	raw_spin_lock_irq(&sem->wait_lock);
>   	first = sem->first_waiter;
>   	if (!first) {
>   		/*
>
> ---
> base-commit: 05441d697f7f9a927264f4058cbbc6a03dfcac9d
> change-id: 20261105-rwsem-dont-steal-from-queued-writer-04b11d9d406b

Other than a question about the drop in reader stealing count, the patch 
looks reasonable to me and the benchmark results look good too.

Reviewed-by: Waiman Long <longman@redhat.com>


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-12-01 16:28 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-26 22:14 [PATCH v2] locking/rwsem: don't let readers retain the lock past a queued writer Lorenzo Stoakes (ARM)
2026-12-01 16:27 ` Waiman Long

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®