Skip to contentSkip to conversation

locking/rtmutex: priority inheritance fixes and tests

PATCH In review Mathieu Desnoyers 2 participants 24 messages Nov 8 – Nov 18

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

v2 cover locking/rtmutex: priority inheritance fixes and tests

Hi Peter, Thomas,

This series fixes three rt_mutex priority inheritance bugs on v7.4-rc1, and adds two tests that catch them. The bugs came out of the work on "sched/deadline: bandwidth accounting fixes and selftests". Its v5, posted after this series, applies on top of it. Its patch 8 takes a deadline boost from the waiter's rt_mutex node, and needs patch 3 here to keep that node current.

The fixes
=========

1 Stop spinning on a running owner once the waiter is woken, so that
timeouts and signals are no longer delayed.
2 Initialize the ww_mutex context of a waiter, so that PREEMPT_RT
reports PI futex deadlocks again.
3 Clone a waiter's sort keys as it enters pi_waiters, so that the
owner inherits the right priority.

Patch 4 adds futex_lock_pi_inherit to the futex selftests. It checks the priority an owner runs at, and the EDEADLK of FUTEX_LOCK_PI. It also checks how late a timeout or a signal ends a wait behind a running owner. Patch 5 adds an ABBA with both owners running to test-ww_mutex. v7.4-rc1 fails the cases of each fix. The series passes them, with and without PREEMPT_RT. So do the locking API selftests, the ww_mutex selftest, locktorture's rtmutex_lock and the futex selftests.

How this was developed
======================

An LLM coding assistant wrote these patches, their messages and the tests, under my direction and review. Patch 1 came out of a stress test of the deadline boost. Patch 3 came out of a review of the deadline fix by a second model. Patch 2 came out of futex_lock_pi_inherit, on its first run with PREEMPT_RT. A local run of the Sashiko AI review checked each patch before posting.

Changes since v1
================

- Commit messages and comments rewritten to read more easily, after Peter's and Steven's reviews.
- Patch 1: Steven's wording, with the two paragraphs on the impact added. It carries his Reviewed-by.
- Patch 3: new subject, "locking/rtmutex: Clone the sort keys in rt_mutex_enqueue_pi()". The message shows the sequence that leaves stale keys, and the comment is one line.
- Patch 5: the stage handoff of the ABBA test uses release and acquire, as the Sashiko review of v1 found. On a weakly ordered CPU, the test could fail falsely with EDEADLK.
- No change to the kernel code.

Based on v7.4-rc1, 6628e7d4c6b2. It also applies as is to tip sched/urgent (006991aa8997), which the deadline series is based on.

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

Mathieu Desnoyers (5):
locking/rtmutex: Stop spinning on the owner when the waiter is woken locking/rtmutex: Initialize the ww_mutex context of a waiter locking/rtmutex: Clone the sort keys in rt_mutex_enqueue_pi() selftests/futex: Test priority inheritance on PI futexes locking/ww_mutex/test: Time an ABBA with both owners running

 kernel/locking/rtmutex.c                      |   9 +-
 kernel/locking/rtmutex_common.h               |   1 +
 kernel/locking/test-ww_mutex.c                | 235 ++++++
 .../selftests/futex/functional/.gitignore     |   1 +
 .../selftests/futex/functional/Makefile       |   3 +-
 .../futex/functional/futex_lock_pi_inherit.c  | 773 ++++++++++++++++++
 .../testing/selftests/futex/functional/run.sh |   3 +
 7 files changed, 1021 insertions(+), 4 deletions(-)
 create mode 100644 tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c

base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4

Signature · 1 line
2.47.3
#1 lore raw

PATCH v2 1/5 locking/rtmutex: Stop spinning on the owner when the waiter is woken

The top waiter of an rt_mutex sets its sleep state. Then it spins in rtmutex_spin_on_owner() as long as the owner is running. A wakeup sets the waiter back to TASK_RUNNING. The spin loop does not check for this. So a timeout or a signal is only handled when the owner blocks, or when the waiter has to reschedule.

The rtmutex_spin_on_owner() is just an optimization with the idea that if the owner is still running on a CPU, it will likely release it soon. If the owner gets preempted or schedules out on its own, the spinning will stop and the waiter will sleep. This came from PREEMPT_RT adaptive spinning for rt_spin_locks that allowed them to behave more like normal spin locks and speed up PREEMPT_RT performance.

The problem is that when this was implemented for futex and normal mutexes it did not account for timeouts or other mechanisms where the owner releasing the lock wasn't the only way for the spinning task to exit the mutex acquire. The spinning currently does not account for anything else but the lock being released or the owner sleeping.

The owner of a PI futex is a user task. It can run for a long time. With an owner spinning in userspace, a 1ms pthread_mutex_timedlock() returned up to 1.4s late in testing. The timeout signal or any signal to the waiter will not stop it from spinning, and the signal will be delayed until it exits the spin.

With PREEMPT_RT, two contexts that take two ww_mutexes in opposite order spin on each other. Only something else that needs one of the two CPUs stops them. By default, the fair server does it after 950ms, to run SCHED_OTHER tasks.

Luckily, when the spinning task needs to exit the mutex lock code, its state is set to TASK_RUNNING. By having the spin check the spinning task's state to see if it switches to running, it can exit the spin appropriately.

Fixes 992caf7f1724 ("locking/rtmutex: Add adaptive spinwait mechanism")
---
 kernel/locking/rtmutex.c | 4 ++++
 1 file changed, 4 insertions(+)
kernel/locking/rtmutex.c +4 -0
index 5a9534c715b8..323973be2074 100644
@@ -1516,9 +1516,13 @@ static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 		 *  - current is not longer the top waiter
 		 *  - current is requested to reschedule (redundant
 		 *    for CONFIG_PREEMPT_RCU=y)
+		 *  - current is woken, by its timeout, a signal or
+		 *    whatever else would end the sleep the spin
+		 *    stands in for
 		 *  - the VCPU on which owner runs is preempted
 		 */
 		if (!owner_on_cpu(owner) || need_resched() ||
+		    task_is_running(current) ||
 		    !data_race(rt_mutex_waiter_is_top_waiter(lock, waiter))) {
 			res = false;
 			break;
Signature · 1 line
2.47.3
#2 lore raw

Re: [PATCH v2 1/5] locking/rtmutex: Stop spinning on the owner when the waiter is woken

Quoted 13 lines · Mathieu Desnoyers
Fixes 992caf7f1724 ("locking/rtmutex: Add adaptive spinwait mechanism")
---
 kernel/locking/rtmutex.c | 4 ++++
 1 file changed, 4 insertions(+)
kernel/locking/rtmutex.c +0 -0
index 5a9534c715b8..323973be2074 100644

kernel/locking/rtmutex.c static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock, · line 1525

Quoted 10 lines
kernel/locking/rtmutex.c +4 -0
@@ -1516,9 +1516,13 @@ static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 		 *  - current is not longer the top waiter
 		 *  - current is requested to reschedule (redundant
 		 *    for CONFIG_PREEMPT_RCU=y)
+		 *  - current is woken, by its timeout, a signal or
+		 *    whatever else would end the sleep the spin
+		 *    stands in for
 		 *  - the VCPU on which owner runs is preempted
 		 */
 		if (!owner_on_cpu(owner) || need_resched() ||
+		    task_is_running(current) ||

Wouldn't it make sense to return true in this case so it can re-evaluate the situation for timeout/ signal rather than visit the scheduler for no reason?
Also, wouldn't it make sense to restrict this to rt_mutex_slowlock_block() (and maybe there to the !TASK_UNINTERRUPTIBLE case but this might result in too much code) rather than have it also available rtlock_slowlock_locked() where it makes no difference? That file is included so having rtlock_slowlock_locked() pass an argument would remove that branch from code generation.

kernel/locking/rtmutex.c static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock, · line 1528

Quoted 3 lines
kernel/locking/rtmutex.c +0 -0
 		    !data_race(rt_mutex_waiter_is_top_waiter(lock, waiter))) {
 			res = false;
 			break;

Sebastian

#3 lore raw

Re: [PATCH v2 1/5] locking/rtmutex: Stop spinning on the owner when the waiter is woken

Hi Sebastian,

Quoted 3 lines

Wouldn't it make sense to return true in this case so it can re-evaluate the situation for timeout/ signal rather than visit the scheduler for no reason?

Yes. With true, rt_mutex_slowlock_block() takes the wait lock again and sets the sleep state. Then it tries the lock, and checks the timeout, the signal and the ww_mutex wound. A wakeup that is none of these cannot make it spin forever: the sleep state is set again before the next spin.

Quoted 4 lines

Also, wouldn't it make sense to restrict this to rt_mutex_slowlock_block() (and maybe there to the !TASK_UNINTERRUPTIBLE case but this might result in too much code) rather than have it also available rtlock_slowlock_locked() where it makes no difference?

Agreed for the rtlock side. An rtlock waiter is in TASK_RTLOCK_WAIT. The lock handoff alone makes it running, and the handoff changes the owner, which already ends the spin. Any other wakeup goes to saved_state. I added a bool argument, as you suggest.

I kept the check for TASK_UNINTERRUPTIBLE on the rt_mutex side. A ww_mutex wound also wakes an uninterruptible waiter, and the ABBA case of patch 5 needs the spin to stop there.

With both changes, the futex and ww_mutex selftests pass, with and without PREEMPT_RT. That includes the PI cases of patch 4.

Steven, the code changed after your Reviewed-by, so I dropped the tag in the version below. Is it still fine with you?

The planned next version of the patch follows.

Thanks,

Mathieu

-- >8 --
From: Mathieu Desnoyers <[email protected]>
Date: Fri, 6 Nov 2026 13:56:54 -0500
Subject: [PATCH] locking/rtmutex: Stop spinning on the owner when the waiter
is woken

The top waiter of an rt_mutex sets its sleep state. Then it spins in rtmutex_spin_on_owner() as long as the owner is running. A wakeup sets the waiter back to TASK_RUNNING. The spin loop does not check for this.

The rtmutex_spin_on_owner() is just an optimization with the idea that if the owner is still running on a CPU, it will likely release it soon. If the owner gets preempted or schedules out on its own, the spinning will stop and the waiter will sleep. This came from PREEMPT_RT adaptive spinning for rt_spin_locks that allowed them to behave more like normal spin locks and speed up PREEMPT_RT performance.

The problem is that when this was implemented for futex and normal mutexes it did not account for timeouts or other mechanisms where the owner releasing the lock wasn't the only way for the spinning task to exit the mutex acquire. The spinning currently does not account for anything else but the lock being released or the owner sleeping.

The owner of a PI futex is a user task. It can run for a long time. With an owner spinning in userspace, a 1ms pthread_mutex_timedlock() returned up to 1.4s late in testing. The timeout signal or any signal to the waiter will not stop it from spinning, and the signal will be delayed until it exits the spin.

With PREEMPT_RT, two contexts that take two ww_mutexes in opposite order spin on each other. The wound that resolves this wakes up the younger one, but it keeps spinning. Only something else that needs one of the two CPUs stops them. By default, the fair server does it after 950ms, to run SCHED_OTHER tasks.

Luckily, when the spinning task needs to exit the mutex lock code, its state is set to TASK_RUNNING. By having the spin check the spinning task's state to see if it switches to running, it can exit the spin appropriately.

On a wakeup, the spin returns true. The caller then takes the wait lock again and checks why it was woken, with no call to the scheduler. Only rt_mutex_slowlock_block() asks for the check. An rtlock waiter is made running by the lock handoff alone, and the handoff changes the owner, which already ends the spin. Sebastian Andrzej Siewior suggested both.

Fixes 992caf7f1724 ("locking/rtmutex: Add adaptive spinwait mechanism")
---
 kernel/locking/rtmutex.c | 22 ++++++++++++++++++----
 1 file changed, 18 insertions(+), 4 deletions(-)
kernel/locking/rtmutex.c +18 -4
index 5a9534c715b8..93014df90eef 100644
@@ -1494,7 +1494,8 @@ static __always_inline void __rt_mutex_unlock(struct rt_mutex_base *lock)
 #ifdef CONFIG_SMP
 static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 				  struct rt_mutex_waiter *waiter,
-				  struct task_struct *owner)
+				  struct task_struct *owner,
+				  bool check_wakeup)
 {
 	bool res = true;
 
@@ -1510,6 +1511,13 @@ static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 		 * the rcu_read_lock() ensures the memory stays valid.
 		 */
 		barrier();
+		/*
+		 * Stop spinning when current is woken, for example by a
+		 * timeout or a signal. Return true: the caller checks why,
+		 * with no call to the scheduler.
+		 */
+		if (check_wakeup && task_is_running(current))
+			break;
 		/*
 		 * Stop spinning when:
 		 *  - the lock owner has been scheduled out
@@ -1531,7 +1539,8 @@ static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 #else
 static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 				  struct rt_mutex_waiter *waiter,
-				  struct task_struct *owner)
+				  struct task_struct *owner,
+				  bool check_wakeup)
 {
 	return false;
 }
@@ -1665,7 +1674,7 @@ static int __sched rt_mutex_slowlock_block(struct rt_mutex_base *lock,
 			owner = NULL;
 		raw_spin_unlock_irq_wake(&lock->wait_lock, wake_q);
 
-		if (!owner || !rtmutex_spin_on_owner(lock, waiter, owner)) {
+		if (!owner || !rtmutex_spin_on_owner(lock, waiter, owner, true)) {
 			lockevent_inc(rtmutex_slow_sleep);
 			rt_mutex_schedule();
 		}
@@ -1890,7 +1899,12 @@ static void __sched rtlock_slowlock_locked(struct rt_mutex_base *lock,
 			owner = NULL;
 		raw_spin_unlock_irq_wake(&lock->wait_lock, wake_q);
 
-		if (!owner || !rtmutex_spin_on_owner(lock, &waiter, owner)) {
+		/*
+		 * Only the lock handoff makes an rtlock waiter running,
+		 * and it changes the owner. Any other wakeup goes to
+		 * saved_state. So the spin need not check for a wakeup.
+		 */
+		if (!owner || !rtmutex_spin_on_owner(lock, &waiter, owner, false)) {
 			lockevent_inc(rtlock_slow_sleep);
 			schedule_rtlock();
 		}
Signature · 7 lines
2.47.3


-- 
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer Reviewed-by
#4 lore raw

Re: [PATCH v2 1/5] locking/rtmutex: Stop spinning on the owner when the waiter is woken

Quoted 1 line · Mathieu Desnoyers

Hi Sebastian,

Hi,

…

Quoted 3 lines

I kept the check for TASK_UNINTERRUPTIBLE on the rt_mutex side. A ww_mutex wound also wakes an uninterruptible waiter, and the ABBA case of patch 5 needs the spin to stop there.

Not sure what is related to. I don't see this in this patch. TASK_UNINTERRUPTIBLE vs TASK_INTERRUPTIBLE would make a difference for signals here.

…

Quoted 40 lines

From: Mathieu Desnoyers <[email protected]>
Date: Fri, 6 Nov 2026 13:56:54 -0500
Subject: [PATCH] locking/rtmutex: Stop spinning on the owner when the waiter
is woken

The top waiter of an rt_mutex sets its sleep state. Then it spins in rtmutex_spin_on_owner() as long as the owner is running. A wakeup sets the waiter back to TASK_RUNNING. The spin loop does not check for this.

The rtmutex_spin_on_owner() is just an optimization with the idea that if the owner is still running on a CPU, it will likely release it soon. If the owner gets preempted or schedules out on its own, the spinning will stop and the waiter will sleep. This came from PREEMPT_RT adaptive spinning for rt_spin_locks that allowed them to behave more like normal spin locks and speed up PREEMPT_RT performance.

The problem is that when this was implemented for futex and normal mutexes it did not account for timeouts or other mechanisms where the owner releasing the lock wasn't the only way for the spinning task to exit the mutex acquire. The spinning currently does not account for anything else but the lock being released or the owner sleeping.

The owner of a PI futex is a user task. It can run for a long time. With an owner spinning in userspace, a 1ms pthread_mutex_timedlock() returned up to 1.4s late in testing. The timeout signal or any signal to the waiter will not stop it from spinning, and the signal will be delayed until it exits the spin.

With PREEMPT_RT, two contexts that take two ww_mutexes in opposite order spin on each other. The wound that resolves this wakes up the younger one, but it keeps spinning. Only something else that needs one of the two CPUs stops them. By default, the fair server does it after 950ms, to run SCHED_OTHER tasks.

Luckily, when the spinning task needs to exit the mutex lock code, its state is set to TASK_RUNNING. By having the spin check the spinning task's state to see if it switches to running, it can exit the spin appropriately.

Quoted 5 lines

On a wakeup, the spin returns true. The caller then takes the wait lock again and checks why it was woken, with no call to the scheduler. Only rt_mutex_slowlock_block() asks for the check. An rtlock waiter is made running by the lock handoff alone, and the handoff changes the owner, which already ends the spin. Sebastian Andrzej Siewior suggested both.

For my taste this is overly verbose. In the spirit of "ain't nobody got time for that" what about

rtmutex_spin_on_owner() does not abort spinning if the task state returns to TASK_RUNNING. This can happen if the task receives a signal or timeout. It will continue to spin on the lock as long as the owner is on the CPU and so delaying the processing of the signal or timeout condition.

This affects PI futex users in general and ww_mutexes users on PREEMPT_RT.

Stop spinning when the task state changes to TASK_RUNNING. Return true to let the caller check condition again instead going to the scheduler. Skip this in rtlock_slowlock_locked() which can not be interrupted and always needs to acquire the lock.

Quoted 3 lines
Fixes 992caf7f1724 ("locking/rtmutex: Add adaptive spinwait mechanism")

I agree with the change as-is so

but the text here is too verbose.

kernel/locking/rtmutex.c static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock, · line 1518

Quoted 11 lines
kernel/locking/rtmutex.c +5 -0
@@ -1510,6 +1511,13 @@ static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
 		 * the rcu_read_lock() ensures the memory stays valid.
 		 */
 		barrier();
+		/*
+		 * Stop spinning when current is woken, for example by a
+		 * timeout or a signal. Return true: the caller checks why,
+		 * with no call to the scheduler.
+		 */
		/* If became running, trylock again or abort (signal/
		 * timeout)
		 */
Quoted 6 lines
kernel/locking/rtmutex.c +2 -0
+		if (check_wakeup && task_is_running(current))
+			break;
 		/*
 		 * Stop spinning when:
 		 *  - the lock owner has been scheduled out

kernel/locking/rtmutex.c static void __sched rtlock_slowlock_locked(struct rt_mutex_base *lock, · line 1905

Quoted 8 lines
kernel/locking/rtmutex.c +5 -1
@@ -1890,7 +1899,12 @@ static void __sched rtlock_slowlock_locked(struct rt_mutex_base *lock,
 			owner = NULL;
 		raw_spin_unlock_irq_wake(&lock->wait_lock, wake_q);
-		if (!owner || !rtmutex_spin_on_owner(lock, &waiter, owner)) {
+		/*
+		 * Only the lock handoff makes an rtlock waiter running,
+		 * and it changes the owner. Any other wakeup goes to
+		 * saved_state. So the spin need not check for a wakeup.
+		 */

I would drop this entirely. It says below that the check is for signal/ timeout which is something we don't have here. So I don't think this is required.

kernel/locking/rtmutex.c static void __sched rtlock_slowlock_locked(struct rt_mutex_base *lock, · line 1910

Quoted 4 lines
kernel/locking/rtmutex.c +1 -0
+		if (!owner || !rtmutex_spin_on_owner(lock, &waiter, owner, false)) {
 			lockevent_inc(rtlock_slow_sleep);
 			schedule_rtlock();
 		}

Sebastian

#5 lore raw

Re: [PATCH v2 1/5] locking/rtmutex: Stop spinning on the owner when the waiter is woken

Hi Sebastian,

Quoted 7 lines
Quoted 3 lines

I kept the check for TASK_UNINTERRUPTIBLE on the rt_mutex side. A ww_mutex wound also wakes an uninterruptible waiter, and the ABBA case of patch 5 needs the spin to stop there.

Not sure what is related to. I don't see this in this patch. TASK_UNINTERRUPTIBLE vs TASK_INTERRUPTIBLE would make a difference for signals here.

Sorry, that was unclear. The patch tests no state. You had suggested to limit the check to !TASK_UNINTERRUPTIBLE. I did not do that. A ww_mutex waiter sleeps in TASK_UNINTERRUPTIBLE, and the wound wakes it. That is the ABBA case of patch 5. So the spin must stop for an uninterruptible waiter too.

Quoted 2 lines

For my taste this is overly verbose. In the spirit of "ain't nobody got time for that" what about

[...]

I will take your text in the next version.

Quoted 2 lines

I agree with the change as-is so

Thanks!

Quoted 3 lines
              /* If became running, trylock again or abort (signal/
               * timeout)
               */

I will take this comment.

Quoted 3 lines

I would drop this entirely. It says below that the check is for signal/ timeout which is something we don't have here. So I don't think this is required.

I will drop it.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#6 lore raw

Re: [PATCH v2 1/5] locking/rtmutex: Stop spinning on the owner when the waiter is woken

Quoted 1 line · Mathieu Desnoyers

Hi Sebastian,

Hi Mathieu,

Quoted 8 lines
Quoted 7 lines
Quoted 3 lines

I kept the check for TASK_UNINTERRUPTIBLE on the rt_mutex side. A ww_mutex wound also wakes an uninterruptible waiter, and the ABBA case of patch 5 needs the spin to stop there.

Not sure what is related to. I don't see this in this patch. TASK_UNINTERRUPTIBLE vs TASK_INTERRUPTIBLE would make a difference for signals here.

Quoted 5 lines

Sorry, that was unclear. The patch tests no state. You had suggested to limit the check to !TASK_UNINTERRUPTIBLE. I did not do that. A ww_mutex waiter sleeps in TASK_UNINTERRUPTIBLE, and the wound wakes it. That is the ABBA case of patch 5. So the spin must stop for an uninterruptible waiter too.

Ah okay, that makes sense. Sorry for the confusion then :).

Sebastian

#7 lore raw

PATCH v2 2/5 locking/rtmutex: Initialize the ww_mutex context of a waiter

In reply to Mathieu Desnoyers

With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, FUTEX_LOCK_PI reports no deadlock. Two threads that each block on a PI futex the other holds sleep forever. Without PREEMPT_RT, the second one gets EDEADLK. A chain deeper than max_lock_depth is also admitted.

With PREEMPT_RT, ww_mutexes are built on rtmutexes. They can create a cycle in the lock graph legitimately, and the wound/die logic resolves it. So the PREEMPT_RT chain walk turns deadlock detection off when it finds a waiter with a ww_mutex context, waiter->ww_ctx. It also drops the -EDEADLK of a walk that started from such a waiter.

But rt_mutex_init_waiter() does not set waiter->ww_ctx. Only __rt_mutex_slowlock_locked() sets it. So the waiters of PI futexes and rtlocks keep the 0x11 poison of CONFIG_DEBUG_RT_MUTEXES. Without that option, they keep what was on the stack, unless the compiler zeroes it. The chain walk then takes them for ww_mutex waiters.

The ww_mutex build of the chain walk can also requeue such waiters. On two of them with equal priority, __waiter_less() would dereference the poison.

Fix this by clearing waiter->ww_ctx in rt_mutex_init_waiter().

With this patch, the ABBA and the deep chain both get EDEADLK. The futex_lock_pi_inherit selftest added later in this series found this. Its deadlock and max_lock_depth cases cover it.

Fixes 6467822b8cc9 ("locking/rtmutex: Prevent spurious EDEADLK return caused by ww_mutexes")
---
 kernel/locking/rtmutex_common.h | 1 +
 1 file changed, 1 insertion(+)
kernel/locking/rtmutex_common.h +1 -0
index c38b7bdea7b3..1f56d40c3e66 100644
@@ -218,6 +218,7 @@ static inline void rt_mutex_init_waiter(struct rt_mutex_waiter *waiter)
 	RB_CLEAR_NODE(&waiter->tree.entry);
 	waiter->wake_state = TASK_NORMAL;
 	waiter->task = NULL;
+	waiter->ww_ctx = NULL;
 }
 
 static inline void rt_mutex_init_rtlock_waiter(struct rt_mutex_waiter *waiter)
Signature · 1 line
2.47.3
#8 lore raw

Re: [PATCH v2 2/5] locking/rtmutex: Initialize the ww_mutex context of a waiter

Quoted 10 lines · Mathieu Desnoyers

With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, FUTEX_LOCK_PI reports no deadlock. Two threads that each block on a PI futex the other holds sleep forever. Without PREEMPT_RT, the second one gets EDEADLK. A chain deeper than max_lock_depth is also admitted.

With PREEMPT_RT, ww_mutexes are built on rtmutexes. They can create a cycle in the lock graph legitimately, and the wound/die logic resolves it. So the PREEMPT_RT chain walk turns deadlock detection off when it finds a waiter with a ww_mutex context, waiter->ww_ctx. It also drops the -EDEADLK of a walk that started from such a waiter.

I *think* this is unrelated because the futex caller shouldn't end up here. The __rt_mutex_slowlock() -> rt_mutex_handle_deadlock() should be different for the futex and ww_mutex case.

Quoted 5 lines

But rt_mutex_init_waiter() does not set waiter->ww_ctx. Only __rt_mutex_slowlock_locked() sets it. So the waiters of PI futexes and rtlocks keep the 0x11 poison of CONFIG_DEBUG_RT_MUTEXES. Without that option, they keep what was on the stack, unless the compiler zeroes it. The chain walk then takes them for ww_mutex waiters.

Is this really the case?
You have a lock chain where the ww_mutex and a regular rtmutex interact? This doesn't sound too crazy. __waiter_less() expects it to be NULL for those.

Quoted 4 lines

The ww_mutex build of the chain walk can also requeue such waiters. On two of them with equal priority, __waiter_less() would dereference the poison.

I *think* the enqueue part is only affected if a regular rtmutex already exists. Because the rtmutex enqueue would ignore ww_mutex/ treat it as equals.
This will affect rt_mutex_adjust_prio_chain(), the futex interface which is the only user of the chainwalk.

Quoted 10 lines

Fix this by clearing waiter->ww_ctx in rt_mutex_init_waiter().

With this patch, the ABBA and the deep chain both get EDEADLK. The futex_lock_pi_inherit selftest added later in this series found this. Its deadlock and max_lock_depth cases cover it.

Fixes 6467822b8cc9 ("locking/rtmutex: Prevent spurious EDEADLK return caused by ww_mutexes")

This is the right thing to do. Either my analysis is wrong or the changelog confusing. I would argue that the full-chainwalk depends now on a random stack value _and_ __waiter_less() might access the random value if ww_mutex is enqueued and a regular mutex exists in the lock chain.

Sebastian

#9 lore raw

Re: [PATCH v2 2/5] locking/rtmutex: Initialize the ww_mutex context of a waiter

Hi Sebastian,

Quoted 3 lines

I *think* this is unrelated because the futex caller shouldn't end up here. The __rt_mutex_slowlock() -> rt_mutex_handle_deadlock() should be different for the futex and ww_mutex case.

The futex caller does not go through __rt_mutex_slowlock(). It gets to the chain walk through the proxy lock:

futex_lock_pi()

    rt_mutex_init_waiter(&rt_waiter)
    __rt_mutex_start_proxy_lock()
      task_blocks_on_rt_mutex(..., RT_MUTEX_FULL_CHAINWALK)
        rt_mutex_adjust_prio_chain()

rt_mutex_adjust_prio_chain() reads waiter->ww_ctx in two places:

	if (IS_ENABLED(CONFIG_PREEMPT_RT) && waiter->ww_ctx && detect_deadlock)
		detect_deadlock = false;
	[...]
		if (IS_ENABLED(CONFIG_PREEMPT_RT) && orig_waiter && orig_waiter->ww_ctx)
			ret = 0;

Both tests are under IS_ENABLED(CONFIG_PREEMPT_RT), not under build_ww_mutex(). So the futex build of the chain walk has them too.

Quoted 2 lines

Is this really the case?
You have a lock chain where the ww_mutex and a regular rtmutex interact?

No ww_mutex is needed. Two PI futexes are enough. Both waiters come from rt_mutex_init_waiter() in futex_lock_pi(), so both hold the 0x11 poison in ww_ctx with CONFIG_DEBUG_RT_MUTEXES. The chain walk takes them for ww_mutex waiters.

The deadlock case of futex_lock_pi_inherit (patch 4) is that ABBA. With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, it fails without this patch: the second FUTEX_LOCK_PI blocks. It passes with it.

Quoted 4 lines

I would argue that the full-chainwalk depends now
on a random stack value _and_ __waiter_less() might access the random value if ww_mutex is enqueued and a regular mutex exists in the lock chain.

Yes, those are the two effects. I reproduced the first one only. The second one is from reading the code, which is why the changelog says "would dereference".

You are right that the changelog is confusing. It starts with the futex symptom, and only then says where the value is read. In the planned next version, I would put the mechanism first, with the call path above. Does this read better?

rt_mutex_init_waiter() does not set waiter->ww_ctx. Only __rt_mutex_slowlock_locked() sets it. So the waiters of PI futexes and rtlocks keep the 0x11 poison of CONFIG_DEBUG_RT_MUTEXES. Without that option, they keep what was on the stack, unless the compiler zeroes it.

With PREEMPT_RT, ww_mutexes are built on rtmutexes. They can create a cycle in the lock graph legitimately, and the wound/die logic resolves it. So rt_mutex_adjust_prio_chain() turns deadlock detection off when it finds a waiter with a ww_ctx. It also drops the -EDEADLK of a walk that started from such a waiter. Both tests are under IS_ENABLED(CONFIG_PREEMPT_RT), so every build of the chain walk has them.

FUTEX_LOCK_PI gets there with no ww_mutex in the chain:

futex_lock_pi()
rt_mutex_init_waiter()
__rt_mutex_start_proxy_lock()
task_blocks_on_rt_mutex()
rt_mutex_adjust_prio_chain()

The chain walk takes its waiters for ww_mutex waiters. With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, FUTEX_LOCK_PI then reports no deadlock. Two threads that each block on a PI futex the other holds sleep forever. Without PREEMPT_RT, the second one gets EDEADLK. FUTEX_LOCK_PI also blocks on a chain deeper than max_lock_depth, instead of returning EDEADLK.

The ww_mutex build of the chain walk can also requeue such waiters. On two of them with equal priority, __waiter_less() would dereference the poison.

Fix this by clearing waiter->ww_ctx in rt_mutex_init_waiter().

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer Reviewed-by
#10 lore raw

Re: [PATCH v2 2/5] locking/rtmutex: Initialize the ww_mutex context of a waiter

Quoted 1 line · Mathieu Desnoyers

Hi Sebastian,

Hi Mathieu,

Quoted 15 lines
Quoted 3 lines

I *think* this is unrelated because the futex caller shouldn't end up here. The __rt_mutex_slowlock() -> rt_mutex_handle_deadlock() should be different for the futex and ww_mutex case.

The futex caller does not go through __rt_mutex_slowlock(). It gets to the chain walk through the proxy lock:

futex_lock_pi()

    rt_mutex_init_waiter(&rt_waiter)
    __rt_mutex_start_proxy_lock()
      task_blocks_on_rt_mutex(..., RT_MUTEX_FULL_CHAINWALK)
        rt_mutex_adjust_prio_chain()

rt_mutex_adjust_prio_chain() reads waiter->ww_ctx in two places:

Quoted 8 lines
	if (IS_ENABLED(CONFIG_PREEMPT_RT) && waiter->ww_ctx && detect_deadlock)
		detect_deadlock = false;
	[...]
		if (IS_ENABLED(CONFIG_PREEMPT_RT) && orig_waiter && orig_waiter->ww_ctx)
			ret = 0;

Both tests are under IS_ENABLED(CONFIG_PREEMPT_RT), not under build_ww_mutex(). So the futex build of the chain walk has them too.

Yes, this part. I realised this later…

Quoted 11 lines
Quoted 2 lines

Is this really the case?
You have a lock chain where the ww_mutex and a regular rtmutex interact?

No ww_mutex is needed. Two PI futexes are enough. Both waiters come from rt_mutex_init_waiter() in futex_lock_pi(), so both hold the 0x11 poison in ww_ctx with CONFIG_DEBUG_RT_MUTEXES. The chain walk takes them for ww_mutex waiters.

The deadlock case of futex_lock_pi_inherit (patch 4) is that ABBA. With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, it fails without this patch: the second FUTEX_LOCK_PI blocks. It passes with it.

right. That is an issue.

Quoted 8 lines
Quoted 4 lines

I would argue that the full-chainwalk depends now
on a random stack value _and_ __waiter_less() might access the random value if ww_mutex is enqueued and a regular mutex exists in the lock chain.

Yes, those are the two effects. I reproduced the first one only. The second one is from reading the code, which is why the changelog says "would dereference".

The deference _shouldn't_ happen because those two a different. However, we could have a mix of those two and which point it becomes relevant.

Quoted 6 lines

You are right that the changelog is confusing. It starts with the futex symptom, and only then says where the value is read. In the planned next version, I would put the mechanism first, with the call path above. Does this read better?

    rt_mutex_init_waiter() does not set waiter->ww_ctx. Only

rt_mutex_waiter::ww_ctx please

Quoted 2 lines

__rt_mutex_slowlock_locked() sets it. So the waiters of PI futexes and rtlocks keep the 0x11 poison of CONFIG_DEBUG_RT_MUTEXES. Without

or random garbage which.

Quoted 10 lines

that option, they keep what was on the stack, unless the compiler zeroes it.

With PREEMPT_RT, ww_mutexes are built on rtmutexes. They can create a cycle in the lock graph legitimately, and the wound/die logic resolves it. So rt_mutex_adjust_prio_chain() turns deadlock detection off when it finds a waiter with a ww_ctx. It also drops the -EDEADLK of a walk that started from such a waiter. Both tests are under IS_ENABLED(CONFIG_PREEMPT_RT), so every build of the chain walk has them.

I would strip that paragraph because *I* think it is more important to mention the FUTEX case which no longer does proper chainwalk regardless of PREEMPT_RT. Yes, ww_mutex has

Quoted 15 lines

FUTEX_LOCK_PI gets there with no ww_mutex in the chain:

futex_lock_pi()
rt_mutex_init_waiter()
__rt_mutex_start_proxy_lock()
task_blocks_on_rt_mutex()
rt_mutex_adjust_prio_chain()

The chain walk takes its waiters for ww_mutex waiters. With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, FUTEX_LOCK_PI then reports no deadlock. Two threads that each block on a PI futex the other holds sleep forever. Without PREEMPT_RT, the second one gets EDEADLK. FUTEX_LOCK_PI also blocks on a chain deeper than max_lock_depth, instead of returning EDEADLK.

Quoted 3 lines

The ww_mutex build of the chain walk can also requeue such waiters. On two of them with equal priority, __waiter_less() would dereference the poison.

The futex code for PI_LOCK performs a RT_MUTEX_FULL_CHAINWALK during locking. rt_mutex_adjust_prio_chain() then wrongly assumes that it is a ww_mutex (due to random garbage in rt_mutex_waiter::ww_ctx) and does not report a deadlock but expects the caller to handle it.

Quoted 1 line
    Fix this by clearing waiter->ww_ctx in rt_mutex_init_waiter().

rt_mutex_waiter::ww_ctx

This, Fixes: and

Quoted 3 lines

Thanks,

Mathieu

Sebastian

#11 lore raw

Re: [PATCH v2 2/5] locking/rtmutex: Initialize the ww_mutex context of a waiter

Hi Sebastian,

Quoted 2 lines

The deference _shouldn't_ happen because those two a different. However, we could have a mix of those two and which point it becomes relevant.

Agreed. It needs a chain that mixes both. I dropped that paragraph.

Quoted 3 lines

I would strip that paragraph because *I* think it is more important to mention the FUTEX case which no longer does proper chainwalk regardless of PREEMPT_RT.

One point. The two tests of ww_ctx in rt_mutex_adjust_prio_chain() are under IS_ENABLED(CONFIG_PREEMPT_RT). Without PREEMPT_RT, futex_lock_pi_inherit gets EDEADLK in both cases, with or without this patch. So I kept the PREEMPT_RT condition in the message. Did you have another path in mind?

With your changes, the message reads:

rt_mutex_init_waiter() does not set rt_mutex_waiter::ww_ctx. Only __rt_mutex_slowlock_locked() sets it. So the waiters of PI futexes and rtlocks keep the 0x11 poison of CONFIG_DEBUG_RT_MUTEXES, or random garbage without that option.

The futex code for FUTEX_LOCK_PI performs a RT_MUTEX_FULL_CHAINWALK during locking:

futex_lock_pi()
rt_mutex_init_waiter()
__rt_mutex_start_proxy_lock()
task_blocks_on_rt_mutex()
rt_mutex_adjust_prio_chain()

With PREEMPT_RT, rt_mutex_adjust_prio_chain() then wrongly assumes that it is a ww_mutex, due to the garbage in rt_mutex_waiter::ww_ctx. It does not report a deadlock, but expects the caller to handle it. Two threads that each block on a PI futex the other holds then sleep forever. Without PREEMPT_RT, the second one gets EDEADLK. FUTEX_LOCK_PI also blocks on a chain deeper than max_lock_depth, instead of returning EDEADLK.

Fix this by clearing rt_mutex_waiter::ww_ctx in rt_mutex_init_waiter().

With this patch, FUTEX_LOCK_PI returns EDEADLK in both cases. The futex_lock_pi_inherit selftest added later in this series found this, with PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES. Its deadlock and max_lock_depth cases cover it.

Quoted 3 lines

This, Fixes: and

Thanks!

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#12 lore raw

Re: [PATCH v2 2/5] locking/rtmutex: Initialize the ww_mutex context of a waiter

Quoted 1 line · Mathieu Desnoyers

Hi Sebastian,

Hi Mathieu,

Quoted 9 lines
Quoted 3 lines

I would strip that paragraph because *I* think it is more important to mention the FUTEX case which no longer does proper chainwalk regardless of PREEMPT_RT.

One point. The two tests of ww_ctx in rt_mutex_adjust_prio_chain() are under IS_ENABLED(CONFIG_PREEMPT_RT). Without PREEMPT_RT, futex_lock_pi_inherit gets EDEADLK in both cases, with or without this patch. So I kept the PREEMPT_RT condition in the message. Did you have another path in mind?

Indeed. This supposed to be simple code…

Quoted 2 lines

With your changes, the message reads:

…

Good, works for me.

Quoted 3 lines

Thanks!

Mathieu

Sebastian

#13 lore raw

PATCH v2 3/5 locking/rtmutex: Clone the sort keys in rt_mutex_enqueue_pi()

In reply to Mathieu Desnoyers

An rt_mutex waiter has two copies of its sort keys. waiter->tree sorts the waiters of its lock. waiter->pi_tree sorts the pi_waiters of the lock owner. Only the top waiter of each lock is in pi_waiters.

When the priority of a waiter changes, the chain walk updates waiter->tree. It copies waiter->tree to waiter->pi_tree for the top waiter only. A waiter that is not the top waiter keeps its old pi_tree keys.

Such a waiter can become the top waiter later. remove_waiter() does this when the top waiter leaves. try_to_take_rt_mutex() does it when the lock changes owner. Both put the new top waiter in pi_waiters without a new copy. So pi_waiters sorts it by a priority it no longer has. The owner then inherits from the wrong waiter, at that waiter's current priority.

In this example, O is the owner, a SCHED_OTHER task. L1 and L2 are two rt_mutexes. W1, W2 and W3 are waiters. Their SCHED_FIFO priority is under their name. T is any other task. It changes the priority of W2:

  T                         O                W1                            W2           W3
                                             FIFO 80                       FIFO 70      FIFO 50

locks L1, L2
blocks on L2
blocks on L1 (timed)
blocks on L1
sched_setscheduler(W2)
W2 now at FIFO 10
rt_mutex_adjust_pi(W2)
W2->tree: FIFO 10
W2 not top: no copy
W2->pi_tree: FIFO 70
<timeout>
remove_waiter()
rt_mutex_enqueue_pi(O, W2)
W2 sorted as FIFO 70,
ahead of W3
rt_mutex_adjust_prio(O)
O inherits W2's FIFO 10
runs at FIFO 10 still waits

The owner runs at SCHED_FIFO 10 while a SCHED_FIFO 50 task waits for it. This needs no race. Each step can come long after the one before.

Fix this by copying the keys in rt_mutex_enqueue_pi(). All callers hold the wait_lock and the owner's pi_lock, as waiter_clone_prio() requires. Remove the three copies the callers made.

With this patch, the owner runs at SCHED_FIFO 50. The futex_lock_pi_inherit selftest added later in this series tests this case (promoted_waiter).

Fixes f7853c342418 ("locking/rtmutex: Fix task->pi_waiters integrity")
---
 kernel/locking/rtmutex.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
kernel/locking/rtmutex.c +2 -3
index 323973be2074..975efa1d864c 100644
@@ -517,6 +517,8 @@ rt_mutex_enqueue_pi(struct task_struct *task, struct rt_mutex_waiter *waiter)
 {
 	lockdep_assert_held(&task->pi_lock);
 
+	/* The tree keys can change while @waiter is not in pi_waiters. */
+	waiter_clone_prio(waiter, task);
 	rb_add_cached(&waiter->pi_tree.entry, &task->pi_waiters, __pi_waiter_less);
 }
 
@@ -1005,7 +1007,6 @@ static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
 		 * and adjust the priority of the owner.
 		 */
 		rt_mutex_dequeue_pi(task, prerequeue_top_waiter);
-		waiter_clone_prio(waiter, task);
 		rt_mutex_enqueue_pi(task, waiter);
 		rt_mutex_adjust_prio(lock, task);
 
@@ -1022,7 +1023,6 @@ static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
 		 */
 		rt_mutex_dequeue_pi(task, waiter);
 		waiter = rt_mutex_top_waiter(lock);
-		waiter_clone_prio(waiter, task);
 		rt_mutex_enqueue_pi(task, waiter);
 		rt_mutex_adjust_prio(lock, task);
 	} else {
@@ -1243,7 +1243,6 @@ static int __sched task_blocks_on_rt_mutex(struct rt_mutex_base *lock,
 	waiter->task = task;
 	waiter->lock = lock;
 	waiter_update_prio(waiter, task);
-	waiter_clone_prio(waiter, task);
 
 	/* Get the top priority waiter on the lock */
 	if (rt_mutex_has_waiters(lock))
Signature · 1 line
2.47.3
maintainer Reviewed-by on v2 3/5
#14 lore raw

Re: [PATCH v2 3/5] locking/rtmutex: Clone the sort keys in rt_mutex_enqueue_pi()

Quoted 48 lines · Mathieu Desnoyers

An rt_mutex waiter has two copies of its sort keys. waiter->tree sorts the waiters of its lock. waiter->pi_tree sorts the pi_waiters of the lock owner. Only the top waiter of each lock is in pi_waiters.

When the priority of a waiter changes, the chain walk updates waiter->tree. It copies waiter->tree to waiter->pi_tree for the top waiter only. A waiter that is not the top waiter keeps its old pi_tree keys.

Such a waiter can become the top waiter later. remove_waiter() does this when the top waiter leaves. try_to_take_rt_mutex() does it when the lock changes owner. Both put the new top waiter in pi_waiters without a new copy. So pi_waiters sorts it by a priority it no longer has. The owner then inherits from the wrong waiter, at that waiter's current priority.

In this example, O is the owner, a SCHED_OTHER task. L1 and L2 are two rt_mutexes. W1, W2 and W3 are waiters. Their SCHED_FIFO priority is under their name. T is any other task. It changes the priority of W2:

  T                         O                W1                            W2           W3
                                             FIFO 80                       FIFO 70      FIFO 50

locks L1, L2
blocks on L2
blocks on L1 (timed)
blocks on L1
sched_setscheduler(W2)
W2 now at FIFO 10
rt_mutex_adjust_pi(W2)
W2->tree: FIFO 10
W2 not top: no copy
W2->pi_tree: FIFO 70
<timeout>
remove_waiter()
rt_mutex_enqueue_pi(O, W2)
W2 sorted as FIFO 70,
ahead of W3
rt_mutex_adjust_prio(O)
O inherits W2's FIFO 10
runs at FIFO 10 still waits

The owner runs at SCHED_FIFO 10 while a SCHED_FIFO 50 task waits for it. This needs no race. Each step can come long after the one before.

Fix this by copying the keys in rt_mutex_enqueue_pi(). All callers hold the wait_lock and the owner's pi_lock, as waiter_clone_prio() requires. Remove the three copies the callers made.

Quoted 7 lines

With this patch, the owner runs at SCHED_FIFO 50. The futex_lock_pi_inherit selftest added later in this series tests this case (promoted_waiter).

Fixes f7853c342418 ("locking/rtmutex: Fix task->pi_waiters integrity")

For this case, we miss one waiter_clone_prio() in remove_waiter(). Given how this is used, I don't see nothing wrong with moving before it is actually used. It might otherwise race in task_blocks_on_rt_mutex() since the pi-lock is dropped. I somehow assumed the adjust-prio will fix this.

Sebastian

#16 lore raw

PATCH v2 4/5 selftests/futex: Test priority inheritance on PI futexes

In reply to Mathieu Desnoyers

The PI futex selftests check what FUTEX_LOCK_PI returns. In these tests, the owner always sleeps. No test checks the priority an owner runs at. No test waits behind an owner that keeps running.

Add futex_lock_pi_inherit, with nine cases:
- The priority each owner runs at, read from /proc. It must follow the waiters as they block, time out, get a signal or change priority. This is also checked along a chain of owners, and when a waiter becomes the top waiter of its lock.
- A lock cycle, and a chain one deeper than max_lock_depth, must get EDEADLK.
- A 1ms timeout and a signal behind an owner spinning in userspace. On average, each must end the wait at most 5ms late.

The priority cases need CAP_SYS_NICE, and skip without it.

On v7.4-rc1, in 8-CPU VMs, these cases fail:
- promoted_waiter. "locking/rtmutex: Clone the sort keys in rt_mutex_enqueue_pi()" fixes it.
- timeout_owner_running and signal_owner_running. "locking/rtmutex: Stop spinning on the owner when the waiter is woken" fixes them. With PREEMPT_RT, signal_owner_running fails in one VM of two.
- With PREEMPT_RT and CONFIG_DEBUG_RT_MUTEXES, deadlock and max_lock_depth. "locking/rtmutex: Initialize the ww_mutex context of a waiter" fixes them.

With the whole series, the nine cases pass, with and without PREEMPT_RT.

---
 .../selftests/futex/functional/.gitignore     |   1 +
 .../selftests/futex/functional/Makefile       |   3 +-
 .../futex/functional/futex_lock_pi_inherit.c  | 773 ++++++++++++++++++
 .../testing/selftests/futex/functional/run.sh |   3 +
 4 files changed, 779 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c
tools/testing/selftests/futex/functional/.gitignore +1 -0
index 7c39d10b38e4..fb5bfd1387da 100644
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 futex_lock_pi_exiting
+futex_lock_pi_inherit
 futex_numa_mpol
 futex_priv_hash
 futex_requeue
tools/testing/selftests/futex/functional/Makefile +2 -1
index a03bd5acba50..f32a05fc46d6 100644
@@ -28,7 +28,8 @@ TEST_GEN_PROGS := \
 	futex_waitv \
 	futex_numa \
 	robust_list \
-	futex_lock_pi_exiting
+	futex_lock_pi_exiting \
+	futex_lock_pi_inherit
 
 TEST_PROGS := run.sh
 
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +773 -0

773 lines not on this page · raw message

tools/testing/selftests/futex/functional/run.sh +3 -0
index d1a681b798bd..ed37522af5c3 100755
@@ -54,3 +54,6 @@ echo
 
 echo
 ./futex_lock_pi_exiting
+
+echo
+./futex_lock_pi_inherit
Signature · 1 line
2.47.3
maintainer Reviewed-by on v2 4/5
#17 lore raw

Re: [PATCH v2 4/5] selftests/futex: Test priority inheritance on PI futexes

Quoted 3 lines · Mathieu Desnoyers

The PI futex selftests check what FUTEX_LOCK_PI returns. In these tests, the owner always sleeps. No test checks the priority an owner runs at. No test waits behind an owner that keeps running.

…

Quoted 1 line

I did play with this and looks it catches the errors you reported/ fixed earlier in this series.

Quoted 3 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +0 -0
@@ -0,0 +1,773 @@

…

tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c line 57

Quoted 4 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +4 -0
+static pid_t sys_gettid(void)
+{
+	return syscall(SYS_gettid);
+}

glibc-2.42+ has pthread_gettid_np(pthread_self()) but this is fine. Debian Trixie has just 2.41 which is a bit sad.

Quoted 10 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +10 -0
+static uint64_t now_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
+}
+
+/* An absolute CLOCK_REALTIME timeout @ns from now, for FUTEX_LOCK_PI. */
+static struct timespec abs_timeout(uint64_t ns)

tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c line 78

Quoted 10 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +10 -0
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_sec += ns / NSEC_PER_SEC;
+	ts.tv_nsec += ns % NSEC_PER_SEC;
+	if (ts.tv_nsec >= (long)NSEC_PER_SEC) {
+		ts.tv_nsec -= NSEC_PER_SEC;
+		ts.tv_sec++;
+	}

This breaks if your timeout is something like 1.5s and ts.nsec is already > 0.5s. We usually do

|         while (ts->tv_nsec >= NSEC_PER_SEC) {
|                 ts->tv_nsec -= NSEC_PER_SEC;
|                 ts->tv_sec++;
|         }

and in worst case gcc does a div. But other than that…

Quoted 2 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +2 -0
+	return ts;
+}

…

Quoted 5 lines

+/*
+ * Start @t and wait until it sleeps where it blocks. Return false if it
+ * could not be created, if it failed, or if it did not block within 2s.
+ * Unless it could not be created, the caller must still join it.
+ */

Could rename it to start_pi_thread() or pi_start_thread() rather than just start?

tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c line 244

Quoted 9 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +9 -0
+static bool start(struct pi_thread *t)
+{
+	uint64_t end = now_ns() + 2 * NSEC_PER_SEC;
+	pthread_attr_t attr;
+	char state = 0;
+	int err;
+
+	pthread_attr_init(&attr);
+	pthread_attr_setstacksize(&attr, 64 * 1024);

it makes me wonder what you did use as a template for this or who wrote this. I can't imagine why one would set a stack size 64KiB here. It shouldn't matter.

tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c line 253

Quoted 9 lines
tools/testing/selftests/futex/functional/futex_lock_pi_inherit.c new file +9 -0
+	err = pthread_create(&t->thread, &attr, pi_thread_fn, t);
+	pthread_attr_destroy(&attr);
+	if (err) {
+		t->thread = pthread_self();
+		t->err = err;
+		atomic_store(&t->done, 1);
+		ksft_print_msg("pthread_create: %s\n", strerror(err));
+		return false;
+	}

…

Sebastian

#18 lore raw

Re: [PATCH v2 4/5] selftests/futex: Test priority inheritance on PI futexes

Hi Sebastian,

Quoted 1 line

Thanks. I will add your tag in the next version.

Quoted 3 lines

This breaks if your timeout is something like 1.5s and ts.nsec is already > 0.5s. We usually do
| while (ts->tv_nsec >= NSEC_PER_SEC) {

The whole seconds of the timeout go to tv_sec first, so only the part below one second is added to tv_nsec. The sum stays below two seconds, and one subtraction is enough. I will still use the while loop, since it is the usual form.

Quoted 2 lines

Could rename it to start_pi_thread() or pi_start_thread() rather than just start?

Yes: start_pi_thread() in the next version.

Quoted 2 lines

I can't imagine why one would set a stack size 64KiB here. It shouldn't matter.

It is for the max_lock_depth case. It starts max_lock_depth + 2 threads, 1026 with the default. Small stacks keep that cheap. I will add a comment that says so.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#19 lore raw

PATCH v2 5/5 locking/ww_mutex/test: Time an ABBA with both owners running

In reply to Mathieu Desnoyers

In the ABBA cases of test-ww_mutex, an owner never keeps running while the other context blocks on it. With PREEMPT_RT, a ww_mutex waiter spins while its owner runs. The wound that resolves an ABBA reaches the waiter through a wakeup.

Add a wound-wait case where both contexts keep running. Each one runs on its own CPU at SCHED_FIFO. The younger context holds B and blocks on A. The older context holds A, then blocks on B, which wounds the younger one. The older context must get B within 10ms on average, over 10 rounds.

On v7.4-rc1 with PREEMPT_RT, the case fails every time. The two contexts spin on each other until the fair server preempts them, after 950ms by default. With "locking/rtmutex: Stop spinning on the owner when the waiter is woken", earlier in this series, the older context gets B in microseconds. Without PREEMPT_RT, the case passes with or without that fix.

---
 kernel/locking/test-ww_mutex.c | 235 +++++++++++++++++++++++++++++++++
 1 file changed, 235 insertions(+)
kernel/locking/test-ww_mutex.c +235 -0
index 838d631544ed..9f76647f6c07 100644
@@ -6,10 +6,12 @@
 #include <linux/kernel.h>
 
 #include <linux/completion.h>
+#include <linux/cpu.h>
 #include <linux/delay.h>
 #include <linux/kthread.h>
 #include <linux/module.h>
 #include <linux/prandom.h>
+#include <linux/sched/task.h>
 #include <linux/slab.h>
 #include <linux/ww_mutex.h>
 
@@ -279,6 +281,235 @@ static int test_abba(struct ww_class *class, bool trylock, bool resolve)
 	return ret;
 }
 
+/*
+ * An ABBA where both contexts keep running. Each one runs on its own CPU
+ * at SCHED_FIFO. The younger context holds B and blocks on A. The older
+ * context holds A and stays on its CPU. Then it blocks on B, which wounds
+ * the younger context.
+ *
+ * The wound reaches the younger context through a wakeup. A waiter that
+ * spins while its owner runs must stop spinning on that wakeup. If it
+ * does not, the two contexts spin on each other until something else
+ * needs one of the two CPUs.
+ *
+ * The older context must get B within 10ms on average, over 10 rounds.
+ * It takes microseconds when the spin stops on the wakeup.
+ *
+ * Wound-wait only. With wait-die, the younger context backs out as soon
+ * as it blocks on the older one.
+ */
+struct test_abba_spin {
+	struct ww_class *class;
+	struct ww_mutex a_mutex, b_mutex;
+	struct completion start, done[2];
+	struct task_struct *young;
+	atomic_t stage;
+	u64 wait_ns;
+	int err[2];
+};
+
+/*
+ * Spin until @s->stage reaches @stage. Give up after 5s. The acquire pairs
+ * with the release that sets each stage. This makes sure that:
+ * - the younger context takes its stamp after the older one;
+ * - a lock that a stage reports as taken is held before the other
+ *   context goes on.
+ */
+static bool abba_spin_until(struct test_abba_spin *s, int stage)
+{
+	u64 end = ktime_get_ns() + 5ULL * NSEC_PER_SEC;
+
+	while (atomic_read_acquire(&s->stage) < stage) {
+		if (ktime_get_ns() > end)
+			return false;
+		cpu_relax();
+	}
+	return true;
+}
+
+/*
+ * Spin until the younger context blocks on a lock. Its state is then no
+ * longer TASK_RUNNING. Give up after 5s.
+ */
+static bool abba_spin_until_waiting(struct test_abba_spin *s)
+{
+	u64 end = ktime_get_ns() + 5ULL * NSEC_PER_SEC;
+
+	while (task_is_running(s->young)) {
+		if (ktime_get_ns() > end)
+			return false;
+		cpu_relax();
+	}
+	return true;
+}
+
+static int abba_spin_old(void *arg)
+{
+	struct test_abba_spin *s = arg;
+	struct ww_acquire_ctx ctx;
+	u64 t, end;
+	int err = -ETIMEDOUT;
+
+	sched_set_fifo_low(current);
+	wait_for_completion(&s->start);
+	ww_acquire_init_noinject(&ctx, s->class);
+	atomic_set_release(&s->stage, 1);
+	if (!abba_spin_until(s, 2))
+		goto fini;
+	err = ww_mutex_lock(&s->a_mutex, &ctx);
+	if (err)
+		goto fini;
+	atomic_set_release(&s->stage, 3);
+	err = -ETIMEDOUT;
+	if (!abba_spin_until(s, 4) || !abba_spin_until_waiting(s))
+		goto unlock;
+	/* The younger context waits on A. Give it 1ms to start its spin. */
+	end = ktime_get_ns() + NSEC_PER_MSEC;
+	while (ktime_get_ns() < end)
+		cpu_relax();
+	t = ktime_get_ns();
+	err = ww_mutex_lock(&s->b_mutex, &ctx);
+	s->wait_ns = ktime_get_ns() - t;
+	if (!err)
+		ww_mutex_unlock(&s->b_mutex);
+unlock:
+	ww_mutex_unlock(&s->a_mutex);
+fini:
+	ww_acquire_fini(&ctx);
+	s->err[0] = err;
+	complete(&s->done[0]);
+	return 0;
+}
+
+static int abba_spin_young(void *arg)
+{
+	struct test_abba_spin *s = arg;
+	struct ww_acquire_ctx ctx;
+	int err = -ETIMEDOUT;
+
+	sched_set_fifo_low(current);
+	wait_for_completion(&s->start);
+	if (!abba_spin_until(s, 1))
+		goto out;
+	ww_acquire_init_noinject(&ctx, s->class);
+	err = ww_mutex_lock(&s->b_mutex, &ctx);
+	if (err)
+		goto fini;
+	atomic_set_release(&s->stage, 2);
+	if (!abba_spin_until(s, 3)) {
+		err = -ETIMEDOUT;
+		ww_mutex_unlock(&s->b_mutex);
+		goto fini;
+	}
+	atomic_set_release(&s->stage, 4);
+	err = ww_mutex_lock(&s->a_mutex, &ctx);
+	if (err == -EDEADLK) {
+		/* Wounded. Release B, wait for A, then take B again. */
+		ww_mutex_unlock(&s->b_mutex);
+		ww_mutex_lock_slow(&s->a_mutex, &ctx);
+		err = ww_mutex_lock(&s->b_mutex, &ctx);
+		if (err) {
+			ww_mutex_unlock(&s->a_mutex);
+			goto fini;
+		}
+	} else if (err) {
+		ww_mutex_unlock(&s->b_mutex);
+		goto fini;
+	}
+	ww_mutex_unlock(&s->b_mutex);
+	ww_mutex_unlock(&s->a_mutex);
+fini:
+	ww_acquire_fini(&ctx);
+out:
+	s->err[1] = err;
+	complete(&s->done[1]);
+	return 0;
+}
+
+static int test_abba_spin(struct ww_class *class)
+{
+	int (*fn[2])(void *) = { abba_spin_old, abba_spin_young };
+	unsigned int c, cpu[2] = { nr_cpu_ids, nr_cpu_ids };
+	u64 total = 0, longest = 0;
+	struct test_abba_spin s;
+	int i, round, ret = 0;
+
+	if (class->is_wait_die)
+		return 0;
+	cpus_read_lock();
+	/* Use the last two online CPUs. Boot and housekeeping use them least. */
+	for_each_online_cpu(c) {
+		cpu[0] = cpu[1];
+		cpu[1] = c;
+	}
+	for (round = 0; cpu[0] < nr_cpu_ids && round < 10 && !ret; round++) {
+		struct task_struct *t[2];
+
+		ww_mutex_init(&s.a_mutex, class);
+		ww_mutex_init(&s.b_mutex, class);
+		init_completion(&s.start);
+		atomic_set(&s.stage, 0);
+		s.class = class;
+		s.wait_ns = 0;
+		for (i = 0; i < 2; i++) {
+			init_completion(&s.done[i]);
+			s.err[i] = -EINVAL;
+		}
+		for (i = 0; i < 2; i++) {
+			t[i] = kthread_create_on_cpu(fn[i], &s, cpu[i], "ww_abba_spin/%u");
+			if (IS_ERR(t[i])) {
+				ret = PTR_ERR(t[i]);
+				if (i)
+					kthread_stop(t[0]);
+				goto unlock;
+			}
+		}
+		s.young = t[1];
+		/*
+		 * Hold a reference. kthread_stop() may run after the thread
+		 * has returned.
+		 */
+		for (i = 0; i < 2; i++) {
+			get_task_struct(t[i]);
+			wake_up_process(t[i]);
+		}
+		/*
+		 * Release both threads at once. Neither one starts spinning
+		 * before the other.
+		 */
+		complete_all(&s.start);
+		for (i = 0; i < 2; i++) {
+			int err;
+
+			wait_for_completion(&s.done[i]);
+			err = kthread_stop(t[i]);
+			put_task_struct(t[i]);
+			if (err && !ret) {
+				pr_err("%s: kthread_stop: %d\n", __func__, err);
+				ret = err;
+			}
+		}
+		if (s.err[0] || s.err[1]) {
+			pr_err("%s: ABBA with both owners running not resolved, err %d and %d\n",
+			       __func__, s.err[0], s.err[1]);
+			ret = -EINVAL;
+		}
+		total += s.wait_ns;
+		longest = max(longest, s.wait_ns);
+	}
+	if (cpu[0] >= nr_cpu_ids)
+		pr_info("%s: skipped, two online CPUs needed\n", __func__);
+	if (!ret && round && total > 10 * NSEC_PER_MSEC * round) {
+		pr_err("%s: ABBA with both owners running resolved in %llu us on average, %llu us at most\n",
+		       __func__, div_u64(total, round * NSEC_PER_USEC),
+		       div_u64(longest, NSEC_PER_USEC));
+		ret = -EINVAL;
+	}
+unlock:
+	cpus_read_unlock();
+	return ret;
+}
+
 struct test_cycle {
 	struct work_struct work;
 	struct ww_class *class;
@@ -664,6 +895,10 @@ static int run_tests(struct ww_class *class)
 			return ret;
 	}
 
+	ret = test_abba_spin(class);
+	if (ret)
+		return ret;
+
 	ret = test_cycle(class, ncpus);
 	if (ret)
 		return ret;
Signature · 1 line
2.47.3
maintainer Tested-by on v2 5/5
#20 lore raw

Re: [PATCH v2 5/5] locking/ww_mutex/test: Time an ABBA with both owners running

Quoted 11 lines · Mathieu Desnoyers

In the ABBA cases of test-ww_mutex, an owner never keeps running while the other context blocks on it. With PREEMPT_RT, a ww_mutex waiter spins while its owner runs. The wound that resolves an ABBA reaches the waiter through a wakeup.

Add a wound-wait case where both contexts keep running. Each one runs on its own CPU at SCHED_FIFO. The younger context holds B and blocks on A. The older context holds A, then blocks on B, which wounds the younger one. The older context must get B within 10ms on average, over 10 rounds.

Quoted 6 lines

On v7.4-rc1 with PREEMPT_RT, the case fails every time. The two contexts spin on each other until the fair server preempts them, after 950ms by default. With "locking/rtmutex: Stop spinning on the owner when the waiter is woken", earlier in this series, the older context gets B in microseconds. Without PREEMPT_RT, the case passes with or without that fix.

This is the ww_mutex equivalent of the futex case on PREEMPT_RT. I got lightly distracted by the -35/-EDEADLK error it always returns. Something that we might have since v5.16-rc1…

Anyway.
Since both (ww-mutex and futex) use the same code I am tempted to say that one test case might be enough.

But in case we want this,

Quoted 1 line

Sebastian

#21 lore raw

Re: [PATCH v2 5/5] locking/ww_mutex/test: Time an ABBA with both owners running

Hi Sebastian,

Quoted 3 lines

This is the ww_mutex equivalent of the futex case on PREEMPT_RT. I got lightly distracted by the -35/-EDEADLK error it always returns. Something that we might have since v5.16-rc1…

Where do you see it? In this case, the younger context gets -EDEADLK from ww_mutex_lock(A). That is the wound: it backs off and retries, and the case returns 0. In our PREEMPT_RT VMs, test-ww_mutex loads with 0. If a case of the module returns -35 on your setup, I can look into it. Which case prints it?

Quoted 2 lines

Since both (ww-mutex and futex) use the same code I am tempted to say that one test case might be enough.

The two take different wakeups through the same spin. A timeout or a signal wakes the futex waiter, and its cases fail with and without PREEMPT_RT. The wound wakes this one, and it fails only with PREEMPT_RT. I would keep it, but I can drop it if you prefer.

Quoted 2 lines

But in case we want this,

Thanks!

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#22 lore raw

Re: [PATCH v2 5/5] locking/ww_mutex/test: Time an ABBA with both owners running

Quoted 1 line · Mathieu Desnoyers

Hi Sebastian,

Hi Mathieu,

Quoted 9 lines
Quoted 3 lines

This is the ww_mutex equivalent of the futex case on PREEMPT_RT. I got lightly distracted by the -35/-EDEADLK error it always returns. Something that we might have since v5.16-rc1…

Where do you see it? In this case, the younger context gets -EDEADLK from ww_mutex_lock(A). That is the wound: it backs off and retries, and the case returns 0. In our PREEMPT_RT VMs, test-ww_mutex loads with 0. If a case of the module returns -35 on your setup, I can look into it. Which case prints it?

The timeout that was introduced in commit cfa92b6d52071 ("locking/ww_mutex/test: Make sure we bail out instead of livelock") triggers. That is not related to your patch. Increasing the timeout makes it go away. It takes ~7sec to complete. It is not related to your changes.
According to the history it hangs on real hardware and passes in kvm.

Quoted 7 lines
Quoted 2 lines

Since both (ww-mutex and futex) use the same code I am tempted to say that one test case might be enough.

The two take different wakeups through the same spin. A timeout or a signal wakes the futex waiter, and its cases fail with and without PREEMPT_RT. The wound wakes this one, and it fails only with PREEMPT_RT. I would keep it, but I can drop it if you prefer.

The testsuite changes, without the fixes I get

| [    0.810516][    T1] Beginning ww (wound) mutex selftests
| [    7.388445][  T143] stress (stress_inorder_work) failed with -35
| [    7.410548][    T1] Beginning ww (die) mutex selftests
| [   13.994648][    T1] All ww mutex selftests passed

The ww_mutex testsuite complains only on PREEMPT_RT. The route cause is the same. I don't see a difference on !PREEMPT_RT here nor do the patches touch anything.

I don't call the shots here, I just explained why I don't see this needed. We might want to cover this code path if the paths divert in future. I don't know.

Quoted 6 lines
Quoted 2 lines

But in case we want this,

Thanks!

Mathieu

Sebastian

#23 lore raw

Re: [PATCH v2 5/5] locking/ww_mutex/test: Time an ABBA with both owners running

Hi Sebastian,

Quoted 3 lines

The timeout that was introduced in commit cfa92b6d52071 ("locking/ww_mutex/test: Make sure we bail out instead of livelock") triggers. That is not related to your patch.

Thanks for tracking it down.

Quoted 3 lines

I don't call the shots here, I just explained why I don't see this needed. We might want to cover this code path if the paths divert in future. I don't know.

I would keep it. stress_inorder_work shows the bug only through its timeout, and its margin depends on the machine. This case times the ABBA itself: 950ms without the fix, microseconds with it. It would also catch a change in the ww_mutex path that the futex cases cannot see.

The next version keeps it, with your Tested-by.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com