Skip to contentSkip to conversation

futex/requeue: Fix requeue PI races

PATCH In review Yao Kai 3 participants 8 messages Jul 22 – Aug 25

Subsystems (3)
lore
Share & tools
lore

Yao Kai

author
#0 lore raw

v2 cover futex/requeue: Fix requeue PI races

Hi,

This series fixes two independent issues in the requeue PI wait path.

Patch 1 restores rtmutex scheduling preparation when the temporary removal of futex_q during requeue causes futex_do_wait() to skip schedule(), while the proxy waiter still has to block on the target rtmutex.

Patch 2 prevents the requeue side from accessing the waiter's stack-based futex_q after publishing Q_REQUEUE_PI_LOCKED. The saved-task wakeup in requeue_pi_wake_futex() also covers a waiter blocked in the rcuwait synchronization path.

Changes since v1:
- Replace the scheduler helper split in patch 1 with rt_mutex_pre_schedule()/rt_mutex_post_schedule() directly around rt_mutex_wait_proxy_lock().
- Expand patch 2's comment and changelog to explain why the saved-task wakeup covers rcuwait without losing a wakeup.

Thanks to Sebastian for the review and for suggesting the simpler fix for patch 1.

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

Testing:
- Build-tested with non-RT and PREEMPT_RT configurations.
- The original rt_mutex_schedule() warning reproducer no longer triggers the warning.
- The original PREEMPT_RT KASAN reproducer no longer reports an invalid access.
- The futex requeue PI selftests and stress tests pass.

Yao

Yao Kai (2):
futex/requeue: Fix rtmutex schedule preparation for requeue PI futex/requeue: Prevent rcuwait use-after-free during requeue PI

 kernel/futex/requeue.c | 20 ++++++++++++++++++--
 1 file changed, 18 insertions(+), 2 deletions(-)
Signature · 1 line
2.43.0
author
#1 lore raw

PATCH v2 1/2 futex/requeue: Fix rtmutex schedule preparation for requeue PI

A waiter requeued onto a PI futex can reach rt_mutex_wait_proxy_lock() without rtmutex schedule preparation:

  WARNING: CPU: 0 PID: 293 at kernel/sched/core.c:7606
  RIP: rt_mutex_schedule+0x43/0x50
  Call Trace:
   rt_mutex_slowlock_block.constprop.0+0x5b/0x320
   rt_mutex_wait_proxy_lock+0x3e/0x80
   futex_wait_requeue_pi+0x3ba/0x590
   do_futex+0x171/0x1f0

rt_mutex_schedule() requires current->sched_rt_mutex to be set. Normally, rt_mutex_pre_schedule() sets it before an rtmutex waiter can schedule. With requeue PI, another task can enqueue the waiter after its futex_q becomes visible:

waiter requeue task
------ ------------
futex_wait_requeue_pi()
futex_wait_setup()

    futex_queue(&q)
                                        futex_requeue()
                                          rt_mutex_start_proxy_lock()
                                            enqueue rt_waiter
                                            install pi_blocked_on
                                          requeue_futex()
                                            plist_del(&q->list)
  futex_do_wait()
    plist_node_empty(&q->list)
    skip schedule()
                                            plist_add(&q->list)
                                          futex_requeue_pi_complete()
                                            IN_PROGRESS -> DONE

futex_requeue_pi_wakeup_sync() // DONE
rt_mutex_wait_proxy_lock()
rt_mutex_schedule()

futex_do_wait() mistakes the temporary removal for a wakeup and skips schedule(). The proxy waiter can nevertheless remain blocked on the target rtmutex and subsequently enter rt_mutex_schedule() with current->sched_rt_mutex clear.

Call rt_mutex_pre_schedule() and rt_mutex_post_schedule() directly around rt_mutex_wait_proxy_lock() so this second blocking point has the required scheduler preparation.

Fixes d14f9e930b90 ("locking/rtmutex: Use rt_mutex specific scheduler helpers")
---
 kernel/futex/requeue.c | 8 ++++++++
 1 file changed, 8 insertions(+)
kernel/futex/requeue.c +8 -0
index 79823ad13683..f7889fb2fce4 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0-or-later
 
 #include <linux/plist.h>
+#include <linux/sched/rt.h>
 #include <linux/sched/signal.h>
 
 #include "futex.h"
@@ -865,7 +866,14 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
 	case Q_REQUEUE_PI_DONE:
 		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
 		pi_mutex = &q.pi_state->pi_mutex;
+		/*
+		 * Requeue temporarily removes q from the hash bucket, so
+		 * futex_do_wait() may skip schedule() even though the proxy
+		 * waiter still has to block on the rtmutex.
+		 */
+		rt_mutex_pre_schedule();
 		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
+		rt_mutex_post_schedule();
 
 		/*
 		 * See futex_unlock_pi()'s cleanup: comment.
Signature · 1 line
2.43.0
maintainer
#2 lore raw

Re: [PATCH v2 1/2] futex/requeue: Fix rtmutex schedule preparation for requeue PI

Quoted 68 lines · Yao Kai

A waiter requeued onto a PI futex can reach rt_mutex_wait_proxy_lock() without rtmutex schedule preparation:

  WARNING: CPU: 0 PID: 293 at kernel/sched/core.c:7606
  RIP: rt_mutex_schedule+0x43/0x50
  Call Trace:
   rt_mutex_slowlock_block.constprop.0+0x5b/0x320
   rt_mutex_wait_proxy_lock+0x3e/0x80
   futex_wait_requeue_pi+0x3ba/0x590
   do_futex+0x171/0x1f0

rt_mutex_schedule() requires current->sched_rt_mutex to be set. Normally, rt_mutex_pre_schedule() sets it before an rtmutex waiter can schedule. With requeue PI, another task can enqueue the waiter after its futex_q becomes visible:

waiter requeue task
------ ------------
futex_wait_requeue_pi()
futex_wait_setup()

    futex_queue(&q)
                                        futex_requeue()
                                          rt_mutex_start_proxy_lock()
                                            enqueue rt_waiter
                                            install pi_blocked_on
                                          requeue_futex()
                                            plist_del(&q->list)
  futex_do_wait()
    plist_node_empty(&q->list)
    skip schedule()
                                            plist_add(&q->list)
                                          futex_requeue_pi_complete()
                                            IN_PROGRESS -> DONE

futex_requeue_pi_wakeup_sync() // DONE
rt_mutex_wait_proxy_lock()
rt_mutex_schedule()

futex_do_wait() mistakes the temporary removal for a wakeup and skips schedule(). The proxy waiter can nevertheless remain blocked on the target rtmutex and subsequently enter rt_mutex_schedule() with current->sched_rt_mutex clear.

Call rt_mutex_pre_schedule() and rt_mutex_post_schedule() directly around rt_mutex_wait_proxy_lock() so this second blocking point has the required scheduler preparation.

Fixes d14f9e930b90 ("locking/rtmutex: Use rt_mutex specific scheduler helpers")
---
 kernel/futex/requeue.c | 8 ++++++++
 1 file changed, 8 insertions(+)
kernel/futex/requeue.c +1 -0
index 79823ad13683..f7889fb2fce4 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0-or-later
 
 #include <linux/plist.h>
+#include <linux/sched/rt.h>
 #include <linux/sched/signal.h>
 
 #include "futex.h"
@@ -865,7 +866,14 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
 	case Q_REQUEUE_PI_DONE:

kernel/futex/requeue.c int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, · line 876

Quoted 10 lines
kernel/futex/requeue.c +7 -0
 		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
 		pi_mutex = &q.pi_state->pi_mutex;
+		/*
+		 * Requeue temporarily removes q from the hash bucket, so
+		 * futex_do_wait() may skip schedule() even though the proxy
+		 * waiter still has to block on the rtmutex.
+		 */
+		rt_mutex_pre_schedule();
 		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
+		rt_mutex_post_schedule();

As per always, I'm totally confused about everything. I mean, futexes suck, but requeue sucks worse.

So the purpose of rt_mutex_pre_schedule() was to avoid the double waiter enqueue for rt_mutex on RT, where sched_submit_work() will hit a spinlock-nee-rtlock.

So rt_mutex_pre_schedule() must happen before the rt_mutex is added as a waiter. However, AFAICT we're already a waiter at the above spot, no? So this cannot be right.

The changelogs doesn't at all explain why this is correct. Please help?

author
#3 lore raw

Re: [PATCH v2 1/2] futex/requeue: Fix rtmutex schedule preparation for requeue PI

Quoted 87 lines · Peter Zijlstra
Quoted 68 lines · Yao Kai

A waiter requeued onto a PI futex can reach rt_mutex_wait_proxy_lock() without rtmutex schedule preparation:

   WARNING: CPU: 0 PID: 293 at kernel/sched/core.c:7606
   RIP: rt_mutex_schedule+0x43/0x50
   Call Trace:
    rt_mutex_slowlock_block.constprop.0+0x5b/0x320
    rt_mutex_wait_proxy_lock+0x3e/0x80
    futex_wait_requeue_pi+0x3ba/0x590
    do_futex+0x171/0x1f0

rt_mutex_schedule() requires current->sched_rt_mutex to be set. Normally, rt_mutex_pre_schedule() sets it before an rtmutex waiter can schedule. With requeue PI, another task can enqueue the waiter after its futex_q becomes visible:

waiter requeue task
------ ------------
futex_wait_requeue_pi()
futex_wait_setup()

     futex_queue(&q)
                                         futex_requeue()
                                           rt_mutex_start_proxy_lock()
                                             enqueue rt_waiter
                                             install pi_blocked_on
                                           requeue_futex()
                                             plist_del(&q->list)
   futex_do_wait()
     plist_node_empty(&q->list)
     skip schedule()
                                             plist_add(&q->list)
                                           futex_requeue_pi_complete()
                                             IN_PROGRESS -> DONE

futex_requeue_pi_wakeup_sync() // DONE
rt_mutex_wait_proxy_lock()
rt_mutex_schedule()

futex_do_wait() mistakes the temporary removal for a wakeup and skips schedule(). The proxy waiter can nevertheless remain blocked on the target rtmutex and subsequently enter rt_mutex_schedule() with current->sched_rt_mutex clear.

Call rt_mutex_pre_schedule() and rt_mutex_post_schedule() directly around rt_mutex_wait_proxy_lock() so this second blocking point has the required scheduler preparation.

Fixes d14f9e930b90 ("locking/rtmutex: Use rt_mutex specific scheduler helpers")
---
  kernel/futex/requeue.c | 8 ++++++++
  1 file changed, 8 insertions(+)
kernel/futex/requeue.c +1 -0
index 79823ad13683..f7889fb2fce4 100644
@@ -1,6 +1,7 @@
  // SPDX-License-Identifier: GPL-2.0-or-later
 
  #include <linux/plist.h>
+#include <linux/sched/rt.h>
  #include <linux/sched/signal.h>
 
  #include "futex.h"
@@ -865,7 +866,14 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
  	case Q_REQUEUE_PI_DONE:

kernel/futex/requeue.c int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, · line 876

Quoted 10 lines
kernel/futex/requeue.c +7 -0
  		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
  		pi_mutex = &q.pi_state->pi_mutex;
+		/*
+		 * Requeue temporarily removes q from the hash bucket, so
+		 * futex_do_wait() may skip schedule() even though the proxy
+		 * waiter still has to block on the rtmutex.
+		 */
+		rt_mutex_pre_schedule();
  		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
+		rt_mutex_post_schedule();

As per always, I'm totally confused about everything. I mean, futexes suck, but requeue sucks worse.

So the purpose of rt_mutex_pre_schedule() was to avoid the double waiter enqueue for rt_mutex on RT, where sched_submit_work() will hit a spinlock-nee-rtlock.

Quoted 5 lines

So rt_mutex_pre_schedule() must happen before the rt_mutex is added as a waiter. However, AFAICT we're already a waiter at the above spot, no? So this cannot be right.

The changelogs doesn't at all explain why this is correct. Please help?

You are right that rt_mutex_pre_schedule() is normally required before the rtmutex waiter is enqueued.

The v2 placement relies on a property of this particular call path that I failed to explain in the changelog: futex_wait_requeue_pi() is reachable only via the FUTEX_WAIT_REQUEUE_PI syscall from userspace. Therefore, 'current' cannot be a workqueue/io-wq worker, nor can it carry a live block plug across the syscall boundary.

Consequently, sched_submit_work() inside rt_mutex_pre_schedule() has no pending plugged I/O or worker notifications to process here, so it cannot recurse into an rtlock after the proxy waiter has been installed. In this specific path, calling rt_mutex_pre_schedule() here effectively only sets current->sched_rt_mutex before rt_mutex_wait_proxy_lock() calls rt_mutex_schedule(), without executing any blocking submit_work after enqueue.

This was the rationale for adopting Sebastian's simpler suggestion from the v1 discussion, but this essential invariant was omitted from the v2 changelog and code comments.

Thanks,
Yao Kai

author
#4 lore raw

Re: [PATCH v2 1/2] futex/requeue: Fix rtmutex schedule preparation for requeue PI

Quoted 110 lines · Yao Kai
Quoted 85 lines · Peter Zijlstra
Quoted 68 lines · Yao Kai

A waiter requeued onto a PI futex can reach rt_mutex_wait_proxy_lock() without rtmutex schedule preparation:

   WARNING: CPU: 0 PID: 293 at kernel/sched/core.c:7606
   RIP: rt_mutex_schedule+0x43/0x50
   Call Trace:
    rt_mutex_slowlock_block.constprop.0+0x5b/0x320
    rt_mutex_wait_proxy_lock+0x3e/0x80
    futex_wait_requeue_pi+0x3ba/0x590
    do_futex+0x171/0x1f0

rt_mutex_schedule() requires current->sched_rt_mutex to be set. Normally, rt_mutex_pre_schedule() sets it before an rtmutex waiter can schedule. With requeue PI, another task can enqueue the waiter after its futex_q becomes visible:

         waiter                          requeue task ------                          ------------ futex_wait_requeue_pi()
   futex_wait_setup()
     futex_queue(&q)
                                         futex_requeue() rt_mutex_start_proxy_lock() enqueue rt_waiter install pi_blocked_on requeue_futex() plist_del(&q->list) futex_do_wait()
     plist_node_empty(&q->list)
     skip schedule()
                                             plist_add(&q->list) futex_requeue_pi_complete() IN_PROGRESS -> DONE futex_requeue_pi_wakeup_sync() // DONE rt_mutex_wait_proxy_lock()
     rt_mutex_schedule()

futex_do_wait() mistakes the temporary removal for a wakeup and skips schedule(). The proxy waiter can nevertheless remain blocked on the target rtmutex and subsequently enter rt_mutex_schedule() with current->sched_rt_mutex clear.

Call rt_mutex_pre_schedule() and rt_mutex_post_schedule() directly around rt_mutex_wait_proxy_lock() so this second blocking point has the required scheduler preparation.

Fixes d14f9e930b90 ("locking/rtmutex: Use rt_mutex specific scheduler helpers")

---
  kernel/futex/requeue.c | 8 ++++++++

  1 file changed, 8 insertions(+)
kernel/futex/requeue.c +1 -0
index 79823ad13683..f7889fb2fce4 100644
@@ -1,6 +1,7 @@
   // SPDX-License-Identifier: GPL-2.0-or-later
   #include <linux/plist.h>
+#include <linux/sched/rt.h>
   #include <linux/sched/signal.h>
   #include "futex.h"
@@ -865,7 +866,14 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,

      case Q_REQUEUE_PI_DONE:
          /* Requeue completed. Current is 'pi_blocked_on' the rtmutex */ pi_mutex = &q.pi_state->pi_mutex;

Quoted 8 lines

+        /*
+         * Requeue temporarily removes q from the hash bucket, so +         * futex_do_wait() may skip schedule() even though the proxy +         * waiter still has to block on the rtmutex.
+         */
+        rt_mutex_pre_schedule();
          ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter); +        rt_mutex_post_schedule();

As per always, I'm totally confused about everything. I mean, futexes suck, but requeue sucks worse.

So the purpose of rt_mutex_pre_schedule() was to avoid the double waiter enqueue for rt_mutex on RT, where sched_submit_work() will hit a spinlock-nee-rtlock.

Quoted 5 lines

So rt_mutex_pre_schedule() must happen before the rt_mutex is added as a waiter. However, AFAICT we're already a waiter at the above spot, no? So this cannot be right.

The changelogs doesn't at all explain why this is correct. Please help?

You are right that rt_mutex_pre_schedule() is normally required before the rtmutex waiter is enqueued.

The v2 placement relies on a property of this particular call path that I failed to explain in the changelog: futex_wait_requeue_pi() is reachable only via the FUTEX_WAIT_REQUEUE_PI syscall from userspace. Therefore, 'current' cannot be a workqueue/io-wq worker, nor can it carry a live block plug across the syscall boundary.

Consequently, sched_submit_work() inside rt_mutex_pre_schedule() has no pending plugged I/O or worker notifications to process here, so it cannot recurse into an rtlock after the proxy waiter has been installed. In this specific path, calling rt_mutex_pre_schedule() here effectively only sets current->sched_rt_mutex before rt_mutex_wait_proxy_lock() calls rt_mutex_schedule(), without executing any blocking submit_work after enqueue.

Quoted 8 lines

This was the rationale for adopting Sebastian's simpler suggestion from the v1 discussion, but this essential invariant was omitted from the v2 changelog and code comments.

Thanks,
Yao Kai

Gentle ping. If the v2 approach is not acceptable, would the v1 approach be preferable instead?

https://lore.kernel.org/r/[email protected]

Thanks,
Yao Kai

#5 lore raw

Re: [PATCH v2 1/2] futex/requeue: Fix rtmutex schedule preparation for requeue PI

In reply to Peter Zijlstra
Quoted 13 lines · Peter Zijlstra
Quoted 12 lines
kernel/futex/requeue.c +7 -0
@@ -865,7 +866,14 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
 	case Q_REQUEUE_PI_DONE:
 		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
 		pi_mutex = &q.pi_state->pi_mutex;
+		/*
+		 * Requeue temporarily removes q from the hash bucket, so
+		 * futex_do_wait() may skip schedule() even though the proxy
+		 * waiter still has to block on the rtmutex.
+		 */
+		rt_mutex_pre_schedule();
 		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
+		rt_mutex_post_schedule();

…

Quoted 7 lines

So the purpose of rt_mutex_pre_schedule() was to avoid the double waiter enqueue for rt_mutex on RT, where sched_submit_work() will hit a spinlock-nee-rtlock.

So rt_mutex_pre_schedule() must happen before the rt_mutex is added as a waiter. However, AFAICT we're already a waiter at the above spot, no? So this cannot be right.

Urgh. So I missed this part entirely while reading it.
Isn't the usage of this in futex_lock_pi() just to keep the assert quiet?
We do add a waiter there (futex_lock_pi()) and this (rt_mutex_pre_schedule()) must be done before a waiter is enqueued so we can acquire the lock (mutex) during the blk_flush_plug() which is in general part of schedule().
While doing all this, we moved the flush outside for mutex_t locking (mutex_lock() and others like it) and use rt_mutex_schedule() instead of schedule().
We do rt_mutex_pre_schedule() to flush the possible plug to avoid a deadlock in case we didn't flush it and someone waits for it. But need to do it before we add a waiter because we can be only have on one pi_waiter.
spinlock_t doesn't flush it so we use schedule_rtlock() there instead because as per definition this kind of lock can't have any dependency so we don't flush the plug.

Since the futex's rt_mutex usage matches more the mutex we ended up with rt_mutex_pre_schedule() + rt_mutex_schedule() around the wait schedule.

blk_flush_plug() is not preserved across syscalls boundaries, there is usually blk_start_plug() followed by blk_finish_plug(). So the futex code shouldn't have the need to flush it at all because there shouldn't be any.

I suppose for futex's usage it should be enough to simple have a dummy to skip the assert and not flush the plug at all.

Otherwise we would have to flush the possible plug before futex_wait_setup() (since starting here the requeue code could act) and need to clear task_struct::sched_rt_mutex before futex_do_wait() again because it's schedule() usage will trigger another assert. And then we need something for rt_mutex_wait_proxy_lock().

So maybe, we have something to satisfy the assert without plug flush for futex/pi/requeue.

Quoted 1 line

The changelogs doesn't at all explain why this is correct. Please help?

I updated it for other reasons. Probably not what you have expected. Maybe the above is better reasoning but then we might want a different solution…

Sebastian

author
#6 lore raw

Re: [PATCH v2 1/2] futex/requeue: Fix rtmutex schedule preparation for requeue PI

Quoted 62 lines · Sebastian Andrzej Siewior
Quoted 13 lines · Peter Zijlstra
Quoted 12 lines
(quoted diff) +7 -0
@@ -865,7 +866,14 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
  	case Q_REQUEUE_PI_DONE:
  		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
  		pi_mutex = &q.pi_state->pi_mutex;
+		/*
+		 * Requeue temporarily removes q from the hash bucket, so
+		 * futex_do_wait() may skip schedule() even though the proxy
+		 * waiter still has to block on the rtmutex.
+		 */
+		rt_mutex_pre_schedule();
  		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
+		rt_mutex_post_schedule();

…

Quoted 7 lines

So the purpose of rt_mutex_pre_schedule() was to avoid the double waiter enqueue for rt_mutex on RT, where sched_submit_work() will hit a spinlock-nee-rtlock.

So rt_mutex_pre_schedule() must happen before the rt_mutex is added as a waiter. However, AFAICT we're already a waiter at the above spot, no? So this cannot be right.

Urgh. So I missed this part entirely while reading it.
Isn't the usage of this in futex_lock_pi() just to keep the assert quiet?
We do add a waiter there (futex_lock_pi()) and this (rt_mutex_pre_schedule()) must be done before a waiter is enqueued so we can acquire the lock (mutex) during the blk_flush_plug() which is in general part of schedule().
While doing all this, we moved the flush outside for mutex_t locking (mutex_lock() and others like it) and use rt_mutex_schedule() instead of schedule().
We do rt_mutex_pre_schedule() to flush the possible plug to avoid a deadlock in case we didn't flush it and someone waits for it. But need to do it before we add a waiter because we can be only have on one pi_waiter.
spinlock_t doesn't flush it so we use schedule_rtlock() there instead because as per definition this kind of lock can't have any dependency so we don't flush the plug.

Since the futex's rt_mutex usage matches more the mutex we ended up with rt_mutex_pre_schedule() + rt_mutex_schedule() around the wait schedule.

blk_flush_plug() is not preserved across syscalls boundaries, there is usually blk_start_plug() followed by blk_finish_plug(). So the futex code shouldn't have the need to flush it at all because there shouldn't be any.

I suppose for futex's usage it should be enough to simple have a dummy to skip the assert and not flush the plug at all.

Otherwise we would have to flush the possible plug before futex_wait_setup() (since starting here the requeue code could act) and need to clear task_struct::sched_rt_mutex before futex_do_wait() again because it's schedule() usage will trigger another assert. And then we need something for rt_mutex_wait_proxy_lock().

So maybe, we have something to satisfy the assert without plug flush for futex/pi/requeue.

Quoted 7 lines
Quoted 1 line

The changelogs doesn't at all explain why this is correct. Please help?

I updated it for other reasons. Probably not what you have expected. Maybe the above is better reasoning but then we might want a different solution…

Sebastian

How about the patch below?

include/linux/sched/rt.h +2 -0
index 4e3338103654..b7c1dbc193de 100644
@@ -51,6 +51,8 @@ static inline bool rt_or_dl_task_policy(struct task_struct *tsk)
 }
 
 #ifdef CONFIG_RT_MUTEXES
+void rt_mutex_futex_pre_schedule(void);
+void rt_mutex_futex_post_schedule(void);
 extern void rt_mutex_pre_schedule(void);
 extern void rt_mutex_schedule(void);
 extern void rt_mutex_post_schedule(void);
kernel/futex/pi.c +3 -17
index 795011ea1202..169e6844cecb 100644
@@ -1,7 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0-or-later
 
 #include <linux/slab.h>
-#include <linux/sched/rt.h>
 #include <linux/sched/task.h>
 
 #include "futex.h"
@@ -1002,20 +1001,11 @@ int futex_lock_pi(u32 __user *uaddr, unsigned int flags, ktime_t *time, int tryl
 		}
 
 		/*
-		 * Caution; releasing @hb in-scope. The hb->lock is still locked
-		 * while the reference is dropped. The reference can not be dropped
-		 * after the unlock because if a user initiated resize is in progress
-		 * then we might need to wake him. This can not be done after the
-		 * rt_mutex_pre_schedule() invocation. The hb will remain valid because
-		 * the thread, performing resize, will block on hb->lock during
-		 * the requeue.
+		 * Drop the hash reference before releasing hb->lock below. If this
+		 * wakes a concurrent resize, holding hb->lock keeps the bucket valid
+		 * until the lock handoff is complete.
 		 */
 		futex_private_hash_put(no_free_ptr(hbr.fph));
-		/*
-		 * Must be done before we enqueue the waiter, here is unfortunately
-		 * under the hb lock, but that *should* work because it does nothing.
-		 */
-		rt_mutex_pre_schedule();
 
 		rt_mutex_init_waiter(&rt_waiter);
 
@@ -1081,10 +1071,6 @@ int futex_lock_pi(u32 __user *uaddr, unsigned int flags, ktime_t *time, int tryl
 		 * the
 		 */
 		futex_q_lockptr_lock(&q);
-		/*
-		 * Waiter is unqueued.
-		 */
-		rt_mutex_post_schedule();
 no_block:
 		/*
 		 * Fixup the pi_state owner and possibly acquire the lock if we
kernel/locking/rtmutex_api.c +2 -0
index 5d48d64725b1..eb18b094473c 100644
@@ -423,6 +423,7 @@ int __sched rt_mutex_wait_proxy_lock(struct rt_mutex_base *lock,
 {
 	int ret;
 
+	rt_mutex_futex_pre_schedule();
 	raw_spin_lock_irq(&lock->wait_lock);
 	/* sleep on the mutex */
 	set_current_state(TASK_INTERRUPTIBLE);
@@ -433,6 +434,7 @@ int __sched rt_mutex_wait_proxy_lock(struct rt_mutex_base *lock,
 	 */
 	fixup_rt_mutex_waiters(lock, true);
 	raw_spin_unlock_irq(&lock->wait_lock);
+	rt_mutex_futex_post_schedule();
 
 	return ret;
 }
kernel/sched/core.c +17 -0
index 96226707c2f6..eb6d7db5ad23 100644
@@ -7595,6 +7595,23 @@ const struct sched_class *__setscheduler_class(int policy, int prio)
  */
 #define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; })
 
+/*
+ * PI futex waits run only in syscall context, so current cannot be a worker
+ * or carry plugged I/O across the userspace boundary. Only establish the
+ * state required by rt_mutex_schedule().
+ */
+void rt_mutex_futex_pre_schedule(void)
+{
+	lockdep_assert(!(current->flags & (PF_WQ_WORKER | PF_IO_WORKER)));
+	lockdep_assert(!current->plug);
+	lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1));
+}
+
+void rt_mutex_futex_post_schedule(void)
+{
+	lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0));
+}
+
 void rt_mutex_pre_schedule(void)
 {
 	lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1));

Thanks,
Yao

author
#7 lore raw

PATCH v2 2/2 futex/requeue: Prevent rcuwait use-after-free during requeue PI

In reply to Yao Kai

On PREEMPT_RT, FUTEX_CMP_REQUEUE_PI can trigger a KASAN report:

  BUG: KASAN: slab-out-of-bounds in _raw_spin_lock_irqsave+0x76/0xe0
  Call Trace:
   _raw_spin_lock_irqsave+0x76/0xe0
   try_to_wake_up+0xab/0x1540
   rcuwait_wake_up+0x39/0x60
   futex_requeue+0x18c3/0x1e10

The futex_q used by futex_wait_requeue_pi() is allocated on the waiter's stack. An early wakeup can race with a PI requeue as follows:

waiter requeue task
------ ------------
futex_wait_requeue_pi()
futex_do_wait()
schedule()

* timeout/signal wakes waiter *

futex_requeue_pi_wakeup_sync()

    IN_PROGRESS -> WAIT
    rcuwait_wait_event()
                                        requeue_pi_wake_futex()
                                          task = READ_ONCE(q->task)
                                          futex_requeue_pi_complete()
                                            WAIT -> LOCKED
    return LOCKED

return
// q lifetime ends
rcuwait_wake_up()

futex_requeue_pi_complete() publishes LOCKED before calling rcuwait_wake_up(). Once the waiter observes LOCKED, it can return from futex_wait_requeue_pi() and let q go out of scope before rcuwait_wake_up() reads q->requeue_wait.task and passes the stale pointer to try_to_wake_up().

Skip rcuwait_wake_up() for Q_REQUEUE_PI_LOCKED. This state is only published by requeue_pi_wake_futex(), which saves q->task before futex_requeue_pi_complete() and calls wake_up_state(task, TASK_NORMAL) afterwards. If the waiter is already blocked in rcuwait_wait_event(), TASK_NORMAL includes TASK_UNINTERRUPTIBLE and wakes it. If the wakeup runs before the waiter blocks, the waiter observes LOCKED and does not schedule. The other completion states retain their rcuwait wakeup.

Fixes 07d91ef510fb1 ("futex: Prevent requeue_pi() lock nesting issue on RT")
---
 kernel/futex/requeue.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
kernel/futex/requeue.c +10 -2
index f7889fb2fce4..9b32f19f320a 100644
@@ -155,8 +155,16 @@ static inline void futex_requeue_pi_complete(struct futex_q *q, int locked)
 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
 
 #ifdef CONFIG_PREEMPT_RT
-	/* If the waiter interleaved with the requeue let it know */
-	if (unlikely(old == Q_REQUEUE_PI_WAIT))
+	/*
+	 * If the waiter interleaved with the requeue, let it know. For LOCKED,
+	 * q may be invalid as soon as the state is published. Only
+	 * requeue_pi_wake_futex() publishes LOCKED; it saves q->task before
+	 * futex_requeue_pi_complete() and follows it with
+	 * wake_up_state(TASK_NORMAL), which also wakes the TASK_UNINTERRUPTIBLE
+	 * rcuwait waiter.
+	 */
+	if (unlikely(old == Q_REQUEUE_PI_WAIT) &&
+	    new != Q_REQUEUE_PI_LOCKED)
 		rcuwait_wake_up(&q->requeue_wait);
 #endif
 }
Signature · 1 line
2.43.0