FUTEX_PING: A stealable futex using Proxy Execution.
Subsystems (5)
cover FUTEX_PING: A stealable futex using Proxy Execution.
Hello,
This patch series adds a new type of PI futexes, PI Next Generation, or PING (name coined by Steven Rostedt) (but other name suggestions are welcome!), that differs from classic PI futexes in that they can be stolen from the top waiter, and use Proxy Execution instead of rtmutexes internally.
The reason to allow the futexes to be stolen is that with classic PI futex's strict handoff to the top waiter, new contending lockers are now forced to wait in queue, which means that any locking operation now becomes a scheduling event. With stealing, a contending locker has the chance of taking the lock without blocking. The longer wait time of blocked tasks can be mitigated by forcing the lock to be handed off to them in a way that can't be stolen, when they've been stolen from too much, to ensure they don't get starved.
The use of Proxy Execution lets us also get Priority Inheritance for for fair tasks, which PI futexes don't really allow.
PING futexes are used similarly to FUTEX_*_PI, where the owner is expected to write its TID in the futex.
The main user-visible difference with regular PI futexes is that the kernel is allowed to set the FUTEX_WAITERS bit with an empty TID. This is to allow for a new locker to steal the lock from the top waiter, which is supposed to improve performance in workloads that don't need strict RT handling.
The user is also allowed to notice that the futex is unlocked but has waiters, and steal it without going to the kernel.
An example of how they're meant to be used:
Lock:
static __thread pid_t tid = gettid();
uint32_t oldval = 0;
if (atomic_compare_exchange_strong(ftx, &oldval, tid)
return;
oldval = FUTEX_WAITERS;
// The user could also spin here a bit.
if (atomic_compare_exchange_strong(ftx, &oldval,
tid | FUTEX_WAITERS))
return;
if (futex(ftx, FUTEX_LOCK_PING, 0, NULL) != 0)
err(1, "FUTEX_LOCK_PING");Unlock:
static __thread pid_t tid = gettid();
uint32_t oldval = tid;
if (atomic_compare_exchange_strong(ftx, &oldval, 0))
return;
if (futex(ftx, FUTEX_UNLOCK_PING, 0, NULL) != 0)
err(1, "FUTEX_UNLOCK_PING");Why did we opt for a new futex type instead of making PI futexes and rtmutex use Proxy Execution?
PI futexes have strict rtmutex semantics, which while important for RT workloads, could also potentially result in performance penalties in workloads where maintaining those semantics isn't as important. Since we don't want to break existing applications, creating a new futex type seems appropriate.
Making a new futex type also lets us change the user interface a bit, to allow for userspace stealing.
We do hope to eventually enable rtmutexes to use Proxy Execution but the rtmutex wait_lock and pi_lock ordering is backwards for Proxy Execution, so a potentially complicated rework might be needed before rtmutexes can use it.
In the meantime, Proxy Execution boosting and rtmutex boosting can continue to coexist.
Some features of PING futexes:
- Uses Proxy Execution.
- Optimistic spinning (can also be done in userspace, similarly to FUTEX_WAIT futexes).
- Allows for userspace stealing.
- Starvation prevention with handoff.
Some performance numbers (lock acquisition time, in nsec, lower is better):
(The numbers were kindly gathered by John on a machine with 11th Gen Intel(R) Core(TM) i5.)
(How PING performs compared to PI and FUTEX_WAIT seems to vary a lot based on hardware and ping_bench parameters, and the results look a bit more impressive on my device :-), but I did not include them since they are based on an older kernel version.)
With all fair tasks:
"ping_bench -a -w 50000 -s 1000 -t 16"
x FUTEX_PING
+ FUTEX_PI
* glibc pthread_mutex_t (using FUTEX_WAIT)
N Mean Stddev Min 25p 50p 75p Max
x 159984 214377.3 859183.23 21 13703 15580 75343 1.15e+07
+ 159984 240690.75 23090.391 234635 237833 239962 241565 1.07e+06 Difference at 95.0% confidence
26313.4 +/- 4211.65 [22101.8 30525.1]
12.274363% +/- 1.9646%
(z 12.2454 p-val 1.77893e-34 crit val 1.95996 se 2148.84)
* 159984 203941.44 14257763 17 20 21 21 1.21e+09
No difference proven at 95.0% confidence
(z -0.292232 p-val 0.770109 crit val 1.95996 se 35710.9)With priority inversions with a RT foreground task:
"ping_bench -t 8 -b 16 -r 1 -p -w 10000 -S 500"
x FUTEX_PING
+ FUTEX_PI
* glibc pthread_mutex_t (using FUTEX_WAIT)
N Mean Stddev Min 25p 50p 75p Max
x 9999 615.55326 3387.2647 21 50 52 54 8.2e+04
+ 9999 701.18222 3450.3964 21 49 52 53 3.34e+04
No difference proven at 95.0% confidence
(z 1.77087 p-val 0.0765815 crit val 1.95996 se 48.354)
* 9999 205935.36 2881211.5 24 53 54 55 1.24e+08
Difference at 95.0% confidence
205320 +/- 56473.6 [148846 261793]
33355.327862% +/- 9174.44%
(z 7.1258 p-val 1.03486e-12 crit val 1.95996 se 28813.6)The patches apply on top of Linus' HEAD.
Any feedback is welcome!
Suleiman Souhlal (12):
sched: Abstract task_struct->blocked_on by locking primitive.
futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
futex: Add "ping" parameter to pi_state management functions and
export them.
futex: Introduce stealable PI futex, FUTEX_*_PING.
futex: Implement exit_ping_state_list().
futex: Address aborting from futex_lock_ping() while owning
ping_state.
futex: Make FUTEX_*_PING use Proxy Execution.
futex: Implement PING futex handoff.
futex: Wake up donor in PING futex unlock.
futex: Optimistic spinning for PING futexes.
futex: Allow userspace stealing for PING futexes. tools/testing/futex: Add ping_bench, a tool for benchmarking futexes.
include/linux/futex.h | 22 + include/linux/futex_types.h | 1 + include/linux/sched.h | 53 ++- include/uapi/linux/futex.h | 3 + init/init_task.c | 1 + kernel/fork.c | 3 +- kernel/futex/Makefile | 2 +- kernel/futex/core.c | 102 ++++- kernel/futex/futex.h | 27 +- kernel/futex/pi.c | 132 +++--- kernel/futex/ping.c | 707 +++++++++++++++++++++++++++++++ kernel/futex/syscalls.c | 6 + kernel/locking/mutex.c | 8 +- kernel/sched/core.c | 69 ++- kernel/sched/sched.h | 2 +- tools/testing/futex/Makefile | 13 + tools/testing/futex/ping_bench.c | 428 +++++++++++++++++++ 17 files changed, 1484 insertions(+), 95 deletions(-) create mode 100644 kernel/futex/ping.c create mode 100644 tools/testing/futex/Makefile create mode 100644 tools/testing/futex/ping_bench.c
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 1/12 sched: Abstract task_struct->blocked_on by locking primitive.
Abstract task_struct->blocked_on by type of locking primitive, so that it can be used by things other than mutexes.
--- include/linux/sched.h | 40 +++++++++++++++++++-------- kernel/fork.c | 2 +- kernel/locking/mutex.c | 8 +++--- kernel/sched/core.c | 62 ++++++++++++++++++++++++++++++++++++------ kernel/sched/sched.h | 2 +- 5 files changed, 89 insertions(+), 25 deletions(-)
include/linux/sched.h +29 -11
@@ -832,6 +832,16 @@ struct task_ipi_mask {struct task_ipi_mask { };#endif +enum blocked_on_type { +BO_T_NONE , +BO_T_MUTEX , +}; + +struct blocked_on_lock { +void *lock; +enum blocked_on_type type; +}; +struct task_struct {#ifdef CONFIG_THREAD_INFO_IN_TASK /*
@@ -1259,7 +1269,7 @@ struct task_struct {struct rt_mutex_waiter *pi_blocked_on;#endif -struct mutex *blocked_on;/* lock we're blocked on */ +struct blocked_on_lock blocked_on;/* lock we're blocked on */ raw_spinlock_t blocked_lock;/*
@@ -2221,10 +2231,15 @@ extern int __cond_resched_rwlock_write(rwlock_t *lock) __must_hold(lock);static inline struct mutex *__get_task_blocked_on (struct task_struct *p) {lockdep_assert_held_once (&p->blocked_lock); -return p->blocked_on; +return p->blocked_on.lock; } -static inline void __set_task_blocked_on (struct task_struct *p,struct mutex *m) +/* +* These helpers set and clear the task blocked_on pointer, as well +* as setting the initial blocked_on_state, or clearing it +*/ +static inline void __set_task_blocked_on (struct task_struct *p,void *m, +enum blocked_on_type type) {WARN_ON_ONCE (!m);/* The task should only be setting itself as blocked */
@@ -2236,11 +2251,12 @@ static inline void __set_task_blocked_on(struct task_struct *p, struct mutex *m)* with a different mutex. Note, setting it to the same * lock repeatedly is ok. */ -WARN_ON_ONCE (p->blocked_on && p->blocked_on != m); - p->blocked_on = m; +WARN_ON_ONCE (p->blocked_on.lock && p->blocked_on.lock != m); + p->blocked_on.lock = m; + p->blocked_on.type = type; } -static inline void __clear_task_blocked_on (struct task_struct *p,struct mutex *m) +static inline void __clear_task_blocked_on (struct task_struct *p,void *m) {/* Currently we serialize blocked_on under the task::blocked_lock */ lockdep_assert_held_once (&p->blocked_lock);
@@ -2249,21 +2265,23 @@ static inline void __clear_task_blocked_on(struct task_struct *p, struct mutex ** blocked_on relationships, but make sure we are not * clearing the relationship with a different lock. */ -WARN_ON_ONCE (m && p->blocked_on && p->blocked_on != m); - p->blocked_on = NULL; +WARN_ON_ONCE (m && p->blocked_on.lock && p->blocked_on.lock != m); + p->blocked_on.lock =NULL ; + p->blocked_on.type = BO_T_NONE; } -static inline void clear_task_blocked_on (struct task_struct *p,struct mutex *m) +static inline void clear_task_blocked_on (struct task_struct *p,void *m) {guard (raw_spinlock_irqsave)(&p->blocked_lock);__clear_task_blocked_on (p, m); } +#else -static inline void __clear_task_blocked_on (struct task_struct *p,struct rt_mutex *m) +static inline void __clear_task_blocked_on (struct task_struct *p,void *m) { } -static inline void clear_task_blocked_on (struct task_struct *p,struct rt_mutex *m) +static inline void clear_task_blocked_on (struct task_struct *p,void *m) { }#endif /* !CONFIG_PREEMPT_RT */
kernel/fork.c +1 -1
@@ -2266,7 +2266,7 @@ __latent_entropy struct task_struct *copy_process(lockdep_init_task (p); - p->blocked_on =NULL ;/* not blocked yet */ + p->blocked_on.lock =NULL ;/* not blocked yet */ p->blocked_donor =NULL ;/* nobody is boosting p yet */ #ifdef CONFIG_BCACHE
kernel/locking/mutex.c +4 -4
@@ -689,7 +689,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclas }raw_spin_lock (¤t->blocked_lock); -__set_task_blocked_on (current, lock); +__set_task_blocked_on (current, lock,BO_T_MUTEX );set_current_state (state);trace_contention_begin (lock,LCB_F_MUTEX );for (;;) {
@@ -734,7 +734,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclas* that has cleared our blocked_on state, re-set * it to the lock we are trying to acquire. */ -__set_task_blocked_on (current, lock); +__set_task_blocked_on (current, lock,BO_T_MUTEX );set_current_state (state);/* * Here we order against unlock; we must either see it change
@@ -762,7 +762,7 @@ __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclasraw_spin_lock_irqsave (&lock->wait_lock, flags);raw_spin_lock (¤t->blocked_lock); -__set_task_blocked_on (current, lock); +__set_task_blocked_on (current, lock,BO_T_MUTEX );set_current_state (state);if (opt_acquired)
@@ -1038,7 +1038,7 @@ static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigne*/ donor = current->blocked_donor;if (donor) { -struct mutex *next_lock; +void *next_lock;raw_spin_lock_nested (&donor->blocked_lock,SINGLE_DEPTH_NESTING ); next_lock =__get_task_blocked_on (donor);
kernel/sched/core.c +54 -8
107 lines not on this page · raw message
kernel/sched/sched.h +1 -1
@@ -2505,7 +2505,7 @@ static inline bool task_is_blocked(struct task_struct *p)if (!sched_proxy_exec ())return false; -return !!p->blocked_on; +return !!p->blocked_on.lock; }static inline int task_on_cpu (struct rq *rq,struct task_struct *p)
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 2/12 futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
In reply to Suleiman SouhlalSwitch PI futexes to use p->pi_futex_lock instead of p->pi_lock.
When augmenting PING futexes with proxy execution, we get lock order inversions, due to the lock order being p->pi_lock -> mutex->wait_lock in the scheduler, but wait_lock -> p->pi_lock in futex code.
So move the futex code to use a new lock, p->pi_futex_lock, to protect p->pi_state_list and pi_state->owner.
--- include/linux/sched.h | 1 + init/init_task.c | 1 + kernel/fork.c | 1 + kernel/futex/core.c | 39 ++++++++++++++++++++------------------ kernel/futex/pi.c | 44 +++++++++++++++++++++---------------------- 5 files changed, 46 insertions(+), 40 deletions(-)
include/linux/sched.h +1 -0
@@ -1257,6 +1257,7 @@ struct task_struct {/* Protection of the PI data structures: */ raw_spinlock_t pi_lock; +raw_spinlock_t pi_futex_lock;struct wake_q_node wake_q;
init/init_task.c +1 -0
@@ -181,6 +181,7 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { .journal_info = NULL,INIT_CPU_TIMERS (init_task) .pi_lock =__RAW_SPIN_LOCK_UNLOCKED (init_task.pi_lock), + .pi_futex_lock = __RAW_SPIN_LOCK_UNLOCKED(init_task.pi_futex_lock), .blocked_lock = __RAW_SPIN_LOCK_UNLOCKED(init_task.blocked_lock), .timer_slack_ns = 50000, /* 50 usec default slack */ .thread_pid = &init_struct_pid,
kernel/fork.c +1 -0
@@ -1835,6 +1835,7 @@ SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)static void rt_mutex_init_task (struct task_struct *p) {raw_spin_lock_init (&p->pi_lock); +raw_spin_lock_init (&p->pi_futex_lock);#ifdef CONFIG_RT_MUTEXES p->pi_waiters =RB_ROOT_CACHED ; p->pi_top_task =NULL ;
kernel/futex/core.c +21 -18
@@ -1354,8 +1354,8 @@ static void exit_pi_state_list(struct task_struct *curr)might_sleep ();/* * Ensure the hash remains stable (no resize) during the while loop -* below. The hb pointer is acquired under the pi_lock so we can't block -* on the mutex. +* below. The hb pointer is acquired under the pi_futex_lock so we +* can't block on the mutex. */ WARN_ON (curr != current);guard (private_hash)(current->mm);
@@ -1364,7 +1364,7 @@ static void exit_pi_state_list(struct task_struct *curr)* pi_state_list anymore, but we have to be careful * versus waiters unqueueing themselves: */ -raw_spin_lock_irq (&curr->pi_lock); +raw_spin_lock_irq (&curr->pi_futex_lock);while (!list_empty (head)) { next = head->next; pi_state = list_entry(next, struct futex_pi_state, list);
@@ -1384,22 +1384,25 @@ static void exit_pi_state_list(struct task_struct *curr)* progress and retry the loop. */ if (!refcount_inc_not_zero (&pi_state->refcount)) { -raw_spin_unlock_irq (&curr->pi_lock); +raw_spin_unlock_irq (&curr->pi_futex_lock);cpu_relax (); -raw_spin_lock_irq (&curr->pi_lock); +raw_spin_lock_irq (&curr->pi_futex_lock);continue ; } -raw_spin_unlock_irq (&curr->pi_lock); +raw_spin_unlock_irq (&curr->pi_futex_lock);spin_lock (&hb->lock);raw_spin_lock_irq (&pi_state->pi_mutex.wait_lock); -raw_spin_lock (&curr->pi_lock); +raw_spin_lock (&curr->pi_futex_lock);/* * We dropped the pi-lock, so re-check whether this * task still owns the PI-state: */ if (head->next != next) { -/* retain curr->pi_lock for the loop invariant */ +/* +* retain curr->pi_futex_lock for the loop +* invariant +*/ raw_spin_unlock (&pi_state->pi_mutex.wait_lock);spin_unlock (&hb->lock);put_pi_state (pi_state);
@@ -1411,7 +1414,7 @@ static void exit_pi_state_list(struct task_struct *curr)list_del_init (&pi_state->list); pi_state->owner =NULL ; -raw_spin_unlock (&curr->pi_lock); +raw_spin_unlock (&curr->pi_futex_lock);raw_spin_unlock_irq (&pi_state->pi_mutex.wait_lock);spin_unlock (&hb->lock); }
@@ -1419,9 +1422,9 @@ static void exit_pi_state_list(struct task_struct *curr)rt_mutex_futex_unlock (&pi_state->pi_mutex);put_pi_state (pi_state); - raw_spin_lock_irq(&curr->pi_lock); + raw_spin_lock_irq(&curr->pi_futex_lock); } -raw_spin_unlock_irq (&curr->pi_lock); +raw_spin_unlock_irq (&curr->pi_futex_lock); }#else static inline void exit_pi_state_list (struct task_struct *curr) { }
@@ -1513,25 +1516,25 @@ static void futex_cleanup_begin(struct task_struct *tsk)mutex_lock (&tsk->futex.exit_mutex);/* -* Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock. +* Switch the state to FUTEX_STATE_EXITING under tsk->pi_futex_lock. * * This ensures that all subsequent checks of tsk->futex_state in * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with -* tsk->pi_lock held. +* tsk->pi_futex_lock held. * * It guarantees also that a pi_state which was queued right before -* the state change under tsk->pi_lock by a concurrent waiter must +* the state change under tsk->pi_futex_lock by a concurrent waiter must * be observed in exit_pi_state_list(). */ -raw_spin_lock_irq (&tsk->pi_lock); +raw_spin_lock_irq (&tsk->pi_futex_lock); tsk->futex.state =FUTEX_STATE_EXITING ; -raw_spin_unlock_irq (&tsk->pi_lock); +raw_spin_unlock_irq (&tsk->pi_futex_lock); }static void futex_cleanup_end (struct task_struct *tsk) __releases(&tsk->futex.exit_mutex) { -scoped_guard (raw_spinlock_irq, &tsk->pi_lock) +scoped_guard (raw_spinlock_irq, &tsk->pi_futex_lock) tsk->futex.state = FUTEX_STATE_DEAD;/*
@@ -1579,7 +1582,7 @@ void futex_exec_done(struct task_struct *tsk)* ordering guarantee required here is that the previous store to * tsk::mm in the calling code cannot be reordered against this store. */ -guard (raw_spinlock_irq)(&tsk->pi_lock); +guard (raw_spinlock_irq)(&tsk->pi_futex_lock); tsk->futex.state =FUTEX_STATE_OK ; }
kernel/futex/pi.c +22 -22
116 lines not on this page · raw message
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
Peter Zijlstra
maintainerRe: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
Quoted 8 lines · Suleiman Souhlal
Switch PI futexes to use
p->pi_futex_lockinstead ofp->pi_lock.When augmenting PING futexes with proxy execution, we get lock order inversions, due to the lock order being
p->pi_lock->mutex->wait_lockin the scheduler, butwait_lock->p->pi_lockin futex code.So move the futex code to use a new lock,
p->pi_futex_lock, to protectp->pi_state_listandpi_state->owner.
This is of course horrible. Lets not do this.
Re: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
Quoted 4 lines · Peter Zijlstra
Quoted 2 lines · Suleiman Souhlal
Switch PI futexes to use
p->pi_futex_lockinstead ofp->pi_lock.
Quoted 8 lines
Quoted 6 lines
When augmenting PING futexes with proxy execution, we get lock order inversions, due to the lock order being
p->pi_lock->mutex->wait_lockin the scheduler, butwait_lock->p->pi_lockin futex code.So move the futex code to use a new lock,
p->pi_futex_lock, to protectp->pi_state_listandpi_state->owner.This is of course horrible. Lets not do this.
I suppose the alternatives would be to either figure out how to un-nest pi_lock from wait_lock in futex code or un-nesting the blocked_on lock from pi_lock in the scheduler.
Either of them seemed more involved than creating a new lock, but maybe I was wrong.
I will take another look.
-- Suleiman
K Prateek Nayak
reviewerRe: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
Hello Suleiman,
Quoted 9 lines · Suleiman Souhlal
Quoted 8 lines · Peter Zijlstra
Quoted 6 lines · Suleiman Souhlal
Switch PI futexes to use
p->pi_futex_lockinstead ofp->pi_lock.When augmenting PING futexes with proxy execution, we get lock order inversions, due to the lock order being
p->pi_lock->mutex->wait_lockin the scheduler, butwait_lock->p->pi_lockin futex code.
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
So move the futex code to use a new lock,
p->pi_futex_lock, to protectp->pi_state_listandpi_state->owner.This is of course horrible. Lets not do this.
I suppose the alternatives would be to either figure out how to un-nest
pi_lockfromwait_lockin futex code or un-nesting theblocked_onlock frompi_lockin the scheduler.
So the only time we try to grab pi_lock + blocked_lock is during wakeup so I think doing that should be (theoretically) possible.
The ttwu_runnable() handling is extremely painful unless we block the delayed task fully. Since we have he new p->is_blocked state, we can safely retain the p->blocked_on while running the task - it is either cleared during unlock by previosu owner or will be same as the lock on which the task blocked on.
Based on John's tree at commit 06ac43db4d8e ("[ANNOTATION] === Needs confirmation of functionality past this point ===") on proxy-exec-v31-7.2-rc4 branch:
(Lightly tested)
kernel/sched/core.c +35 -31
@@ -4008,18 +4008,14 @@ static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p)if (task_cpu (p) == p->wake_cpu)return false; - scoped_guard(raw_spinlock, &p->blocked_lock) { -/* Task is waking up; clear any blocked_on relationship */ -__clear_task_blocked_on (p,NULL ); +/* If already current, don't need to return migrate */ +if (task_current (rq, p)) +return false; -/* If already current, don't need to return migrate */ -if (task_current (rq, p)) -return false; +/* If we're return migrating the rq->donor, switch it out for idle */ +if (task_current_donor (rq, p)) +proxy_reset_donor (rq); -/* If we're return migrating the rq->donor, switch it out for idle */ -if (task_current_donor (rq, p)) -proxy_reset_donor (rq); - }block_task (rq, p,TASK_WAKING );return true; }
@@ -4106,9 +4102,10 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)update_rq_clock (rq);if (p->is_blocked) {if (p->se.sched_delayed) { -proxy_remove_from_sleeping_owner (p); -enqueue_task (rq, p,ENQUEUE_NOCLOCK |ENQUEUE_DELAYED ); +dequeue_task (rq, p,DEQUEUE_SLEEP |DEQUEUE_DELAYED ); +return 0 ; } +if (proxy_needs_return (rq, p))return 0 ; }
@@ -4305,20 +4302,6 @@ static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)return false; } -static void ttwu_queue (struct task_struct *p,int cpu,int wake_flags) -{ -struct rq *rq =cpu_rq (cpu); -struct rq_flags rf; - -if (ttwu_queue_wakelist (p, cpu, wake_flags)) -return ; - -rq_lock (rq, &rf); -update_rq_clock (rq); -ttwu_do_activate (rq, p, wake_flags, &rf); -rq_unlock (rq, &rf); -} -/* * Invoked from try_to_wake_up() to check whether the task can be woken up. *
@@ -4493,6 +4476,8 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) {guard (preempt)();int cpu, success =0 ; +unsigned long flags; +struct rq *rq; wake_flags |=WF_TTWU ;
@@ -4524,17 +4509,19 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) goto out; } +local_irq_save (flags); +/* * If we are going to wake up a thread waiting for CONDITION we * need to ensure that CONDITION=1 done by the caller can not be * reordered with p->state check below. This pairs with smp_store_mb() * in set_current_state() that the waiting thread does. */ - scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { + scoped_guard (raw_spinlock, &p->pi_lock) {smp_mb__after_spinlock ();if (!ttwu_state_match (p, state, &success)) -break ; + goto out_restore;trace_sched_waking (p);
@@ -4562,7 +4549,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)*/ smp_rmb ();if (READ_ONCE (p->on_rq) &&ttwu_runnable (p, wake_flags)) -break ; + goto out_restore;/* * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
@@ -4618,7 +4605,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)*/ if (smp_load_acquire (&p->on_cpu) &&ttwu_queue_wakelist (p,task_cpu (p), wake_flags)) -break ; + goto out_restore;/* * If the owning (remote) CPU is still in the middle of schedule() with
@@ -4653,8 +4640,25 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) p->wake_cpu = cpu; } -ttwu_queue (p, cpu, wake_flags); +if (ttwu_queue_wakelist (p, cpu, wake_flags)) + goto out_restore; + +/* +* p->__state is set to TASK_WAKING. It is safe to drop +* the p->pi_lock and wake up task outside holding +* rq_lock() similar to the wakelist approach. +*/ + } + + rq =cpu_rq (cpu); + + scoped_guard(rq_lock, rq) { +update_rq_clock (rq); +ttwu_do_activate (rq, p, wake_flags, &scope.rf); } + +out_restore: +local_irq_restore (flags); out:activate_blocked_waiters (cpu_rq (task_cpu (p)), p, wake_flags);if (success)
---
I'm not sure if PREEMPT_RT needs that activate within pi_lock since TTWU_QUEUE is disabled but I'll let Peter, John chime in.
Quoted 3 lines
Either of them seemed more involved than creating a new lock, but maybe I was wrong.
I will take another look.
Signature · 2 lines
Thanks and Regards, Prateek
Re: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
Hello,
Quoted 32 lines · K Prateek Nayak
Hello Suleiman,
Quoted 9 lines · Suleiman Souhlal
Quoted 8 lines · Peter Zijlstra
Quoted 6 lines · Suleiman Souhlal
Switch PI futexes to use
p->pi_futex_lockinstead ofp->pi_lock.When augmenting PING futexes with proxy execution, we get lock order inversions, due to the lock order being
p->pi_lock->mutex->wait_lockin the scheduler, butwait_lock->p->pi_lockin futex code.Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
So move the futex code to use a new lock,
p->pi_futex_lock, to protectp->pi_state_listandpi_state->owner.This is of course horrible. Lets not do this.
I suppose the alternatives would be to either figure out how to un-nest
pi_lockfromwait_lockin futex code or un-nesting theblocked_onlock frompi_lockin the scheduler.So the only time we try to grab
pi_lock+blocked_lockis during wakeup so I think doing that should be (theoretically) possible.The
ttwu_runnable()handling is extremely painful unless we block the delayed task fully. Since we have he newp->is_blockedstate, we can safely retain thep->blocked_onwhile running the task - it is either cleared during unlock by previosu owner or will be same as the lock on which the task blocked on.
Quoted 3 lines
Based on John's tree at commit
06ac43db4d8e("[ANNOTATION] === Needs confirmation of functionality past this point ===") on proxy-exec-v31-7.2-rc4 branch:
Sorry for the slow reply and thanks for the very quick patch.
Unfortunately, it doesn't seem like this approach works in the end, because there is still a pi_lock -> rq lock -> blocked_lock transitive relationship, which deadlocks when trying to get the pi_lock while holding the blocked_lock (when fixing up the pi_state owner in the futex code). :-(
On the other hand, Peter's suggestion of moving the scheduler's use of pi_lock to a new lock, p->sched_lock, seems to work in my testing, but is kind of a scary change to me.
Maybe an acceptable alternative would be for the new futex to use a new lock (similarly to what the original patch does), but keep regular PI futexes using pi_lock, at least as long as they are still based on rtmutexes.
Thanks,
-- Suleiman
K Prateek Nayak
reviewerRe: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
Hello Suleiman,
Quoted 18 lines · Suleiman Souhlal
Quoted 14 lines
Quoted 3 lines
I suppose the alternatives would be to either figure out how to un-nest
pi_lockfromwait_lockin futex code or un-nesting theblocked_onlock frompi_lockin the scheduler.So the only time we try to grab
pi_lock+blocked_lockis during wakeup so I think doing that should be (theoretically) possible.The
ttwu_runnable()handling is extremely painful unless we block the delayed task fully. Since we have he newp->is_blockedstate, we can safely retain thep->blocked_onwhile running the task - it is either cleared during unlock by previosu owner or will be same as the lock on which the task blocked on.Quoted 3 lines
Based on John's tree at commit
06ac43db4d8e("[ANNOTATION] === Needs confirmation of functionality past this point ===") on proxy-exec-v31-7.2-rc4 branch:
Quoted 7 lines
Sorry for the slow reply and thanks for the very quick patch.
Unfortunately, it doesn't seem like this approach works in the end, because there is still a
pi_lock-> rq lock ->blocked_locktransitive relationship, which deadlocks when trying to get thepi_lockwhile holding theblocked_lock(when fixing up thepi_stateowner in the futex code). :-(
Ah! So what you are saying is, since we have:
p->pi_lock
rq_lock /* ttwu_runnable() */
and
rq_lock
blocked_lock /* find_proxy_task() */
relations, doing a:
blocked_lock
p->pi_lock
would cause a deadlock via rq_lock. True that.
Quoted 9 lines
On the other hand, Peter's suggestion of moving the scheduler's use of
pi_lockto a new lock,p->sched_lock, seems to work in my testing, but is kind of a scary change to me.Maybe an acceptable alternative would be for the new futex to use a new lock (similarly to what the original patch does), but keep regular PI futexes using
pi_lock, at least as long as they are still based on rtmutexes.
I guess that should do too, yes.
On a different note, why do we need the p->pi_lock/p->pi_futex_lock to modify the ping_state->owner in ping_state_update_owner()? Isn't ping_state->ping_mutex.wait_lock + owner->blocked_on locks enough?
Note: I'm still wrapping my head around the PING implementation so it might take me a while to appreciate the need for the pi_futex_lock. I'm using proxy-exec-v32-7.3-rc-tip-sched-core from John's tree at the moment to jump around.
Signature · 2 lines
Thanks and Regards, Prateek
Re: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
Quoted 40 lines · K Prateek Nayak
Hello Suleiman,
Quoted 18 lines · Suleiman Souhlal
Quoted 14 lines
Quoted 3 lines
I suppose the alternatives would be to either figure out how to un-nest
pi_lockfromwait_lockin futex code or un-nesting theblocked_onlock frompi_lockin the scheduler.So the only time we try to grab
pi_lock+blocked_lockis during wakeup so I think doing that should be (theoretically) possible.The
ttwu_runnable()handling is extremely painful unless we block the delayed task fully. Since we have he newp->is_blockedstate, we can safely retain thep->blocked_onwhile running the task - it is either cleared during unlock by previosu owner or will be same as the lock on which the task blocked on.Quoted 3 lines
Based on John's tree at commit
06ac43db4d8e("[ANNOTATION] === Needs confirmation of functionality past this point ===") on proxy-exec-v31-7.2-rc4 branch:Quoted 7 lines
Sorry for the slow reply and thanks for the very quick patch.
Unfortunately, it doesn't seem like this approach works in the end, because there is still a
pi_lock-> rq lock ->blocked_locktransitive relationship, which deadlocks when trying to get thepi_lockwhile holding theblocked_lock(when fixing up thepi_stateowner in the futex code). :-(Ah! So what you are saying is, since we have:
p->pi_lockrq_lock /* ttwu_runnable() */and
rq_lock
blocked_lock/*find_proxy_task()*/
Quoted 6 lines
relations, doing a:
blocked_lockp->pi_lockwould cause a deadlock via
rq_lock. True that.
Yes, exactly that.
Quoted 11 lines
Quoted 10 lines
On the other hand, Peter's suggestion of moving the scheduler's use of
pi_lockto a new lock,p->sched_lock, seems to work in my testing, but is kind of a scary change to me.Maybe an acceptable alternative would be for the new futex to use a new lock (similarly to what the original patch does), but keep regular PI futexes using
pi_lock, at least as long as they are still based on rtmutexes.
Quoted 5 lines
I guess that should do too, yes.
On a different note, why do we need the p->pi_lock/p->pi_futex_lock to modify the
ping_state->ownerinping_state_update_owner()? Isn'tping_state->ping_mutex.wait_lock+owner->blocked_onlocks enough?
It's because ping_states need to be on a per-task list, task->futex.ping_state_list, so that when a task exits, we can walk all the ping_states it might still own and unlock/free them (this also applies to pi_states with PI futexes).
See exit_ping_state_list() in patch 5 in this series or exit_pi_state_list() for regular PI futexes. (owner->blocked_on lock is just wait_lock)
-- Suleiman
Quoted 10 lines
Note: I'm still wrapping my head around the PING implementation so it might take me a while to appreciate the need for the
pi_futex_lock. I'm using proxy-exec-v32-7.3-rc-tip-sched-core from John's tree at the moment to jump around.--
Thanks and Regards,
Prateek
Peter Zijlstra
maintainerRe: [RFC PATCH 02/12] futex: Switch PI futex to use p->pi_futex_lock instead of p->pi_lock.
In reply to Suleiman SouhlalQuoted 12 lines · Suleiman Souhlal
Quoted 11 lines · Peter Zijlstra
Quoted 8 lines · Suleiman Souhlal
Switch PI futexes to use
p->pi_futex_lockinstead ofp->pi_lock.When augmenting PING futexes with proxy execution, we get lock order inversions, due to the lock order being
p->pi_lock->mutex->wait_lockin the scheduler, butwait_lock->p->pi_lockin futex code.So move the futex code to use a new lock,
p->pi_futex_lock, to protectp->pi_state_listandpi_state->owner.
Quoted 7 lines
Quoted 1 line
This is of course horrible. Lets not do this.
I suppose the alternatives would be to either figure out how to un-nest
pi_lockfromwait_lockin futex code or un-nesting theblocked_onlock frompi_lockin the scheduler.
Either of them seemed more involved than creating a new lock, but maybe I was wrong.
So the reason I reacted was because the futex_pi code is tied into rt_mutex and it isn't at all obvious separating futex from rt_mutex doesn't completely wreck things.
The scheduler's (ab)use of pi_lock might be simpler to separate -- it was the last added. I basically used pi_lock because I needed a per-task raw_spinlock and pi_lock existed and had the right nesting properties already (rq->lock nests inside pi->lock).
Still, its been a while since I did that, so if you untangle that be very careful.
That is, doing something like s/pi_lock/sched_lock/ on kernel/sched/ *might* just work. But separating futex from rt_mutex seems very dangerous to me.
RFC PATCH 3/12 futex: Add "ping" parameter to pi_state management functions and export them.
In reply to Suleiman SouhlalIn preparation to adding FUTEX_PING, allow the pi_state management functions to use a different wait_lock, and make them non-static. Also rename handle_exit_race() to pi_handle_exit_race().
--- kernel/futex/futex.h | 10 ++++++++ kernel/futex/pi.c | 61 +++++++++++++++++++++++++------------------- 2 files changed, 45 insertions(+), 26 deletions(-)
kernel/futex/futex.h +10 -0
@@ -395,6 +395,16 @@ extern int refill_pi_state_cache(void);extern void get_pi_state (struct futex_pi_state *pi_state);extern void put_pi_state (struct futex_pi_state *pi_state);extern int fixup_pi_owner (u32 __user *uaddr,struct futex_q *q,int locked); +extern int pi_handle_exit_race (u32 __user *uaddr,u32 uval); +extern struct futex_pi_state *alloc_pi_state (void ); +extern int attach_to_pi_state (u32 __user *uaddr,u32 uval, +struct futex_pi_state *pi_state, +struct futex_pi_state **ps, +bool ping); +extern int attach_to_pi_owner (u32 __user *uaddr,u32 uval,union futex_key *key, +struct futex_pi_state **ps, +struct task_struct **exiting, +bool ping);/* * Express the locking dependencies for lockdep:
kernel/futex/pi.c +35 -26
149 lines not on this page · raw message
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 4/12 futex: Introduce stealable PI futex, FUTEX_*_PING.
In reply to Suleiman SouhlalIntroduce a New Generation of PI futexes, FUTEX_*_PING.
They are used similarly to FUTEX_*_PI, where the owner is expected to write its TID in the futex.
The main user-visible difference with regular PI futexes is that the kernel is allowed to set the FUTEX_WAITERS bit with an empty TID. This is to allow for a new locker to steal the lock from the top waiter, which is supposed to improve performance in workloads that don't need strict RT handling.
An example of how they're meant to be used:
Lock:
static __thread pid_t tid = gettid(); uint32_t oldval = 0; if (atomic_compare_exchange_strong(ftx, &oldval, tid) return; if (futex(ftx, FUTEX_LOCK_PING, 0, NULL) != 0) err(1, "FUTEX_LOCK_PING");
Unlock:
static __thread pid_t tid = gettid(); uint32_t oldval = tid; if (atomic_compare_exchange_strong(ftx, &oldval, 0)) return; if (futex(ftx, FUTEX_UNLOCK_PING, 0, NULL) != 0) err(1, "FUTEX_UNLOCK_PING");
--- include/linux/futex.h | 11 + include/linux/futex_types.h | 1 + include/uapi/linux/futex.h | 3 + kernel/futex/Makefile | 2 +- kernel/futex/futex.h | 13 +- kernel/futex/pi.c | 15 ++ kernel/futex/ping.c | 503 ++++++++++++++++++++++++++++++++++++ kernel/futex/syscalls.c | 6 + 8 files changed, 552 insertions(+), 2 deletions(-) create mode 100644 kernel/futex/ping.c
include/linux/futex.h +11 -0
@@ -66,6 +66,7 @@ static inline void futex_init_task(struct task_struct *tsk) {memset (&tsk->futex,0 ,sizeof (tsk->futex));INIT_LIST_HEAD (&tsk->futex.pi_state_list); +INIT_LIST_HEAD (&tsk->futex.ping_state_list); tsk->futex.state =FUTEX_STATE_OK ;mutex_init (&tsk->futex.exit_mutex); }
@@ -159,4 +160,14 @@ void futex_mm_init(struct mm_struct *mm);static inline void futex_mm_init (struct mm_struct *mm) { }#endif +struct ping_mutex { +raw_spinlock_t wait_lock; +struct task_struct *owner; +}; + +static inline struct task_struct *ping_mutex_owner (struct ping_mutex *ping_mutex) +{ +return READ_ONCE (ping_mutex->owner); +} +#endif /* _LINUX_FUTEX_H */
include/linux/futex_types.h +1 -0
@@ -26,6 +26,7 @@ struct futex_sched_data {struct compat_robust_list_head __user *compat_robust_list;#endif struct list_head pi_state_list; +struct list_head ping_state_list;struct futex_pi_state *pi_state_cache;struct mutex exit_mutex;unsigned int state;
include/uapi/linux/futex.h +3 -0
@@ -22,6 +22,9 @@#define FUTEX_WAIT_REQUEUE_PI 11#define FUTEX_CMP_REQUEUE_PI 12#define FUTEX_LOCK_PI2 13 +#define FUTEX_LOCK_PING 14 +#define FUTEX_UNLOCK_PING 15 +#define FUTEX_TRYLOCK_PING 16#define FUTEX_PRIVATE_FLAG 128#define FUTEX_CLOCK_REALTIME 256
kernel/futex/Makefile +1 -1
@@ -2,4 +2,4 @@ CONTEXT_ANALYSIS := y -obj-y += core.o syscalls.o pi.o requeue.o waitwake.o +obj-y += core.o syscalls.o pi.o ping.o requeue.o waitwake.o
kernel/futex/futex.h +12 -1
@@ -167,7 +167,10 @@ struct futex_pi_state {/* * The PI object: */ -struct rt_mutex_base pi_mutex; +union { +struct rt_mutex_base pi_mutex; +struct ping_mutex ping_mutex; + };struct task_struct *owner;refcount_t refcount;
@@ -214,6 +217,7 @@ struct futex_q {void *wake_data;union futex_key key;struct futex_pi_state *pi_state; +struct futex_pi_state *ping_state;struct rt_mutex_waiter *rt_waiter;union futex_key *requeue_pi_key;u32 bitset;
@@ -405,6 +409,8 @@ extern int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,struct futex_pi_state **ps, struct task_struct **exiting, bool ping); +extern void get_ping_state (struct futex_pi_state *ping_state); +extern void put_ping_state (struct futex_pi_state *ping_state);/* * Express the locking dependencies for lockdep:
@@ -488,4 +494,9 @@ extern int futex_lock_pi(u32 __user *uaddr, unsigned int flags, ktime_t *time, ibool futex_robust_list_clear_pending (void __user *pop,unsigned int flags); +extern int futex_unlock_ping (u32 __user *uaddr,unsigned int flags); + +extern int futex_lock_ping (u32 __user *uaddr,unsigned int flags,ktime_t *time, +int trylock); +#endif /* _FUTEX_H */
kernel/futex/pi.c +15 -0
@@ -287,6 +287,8 @@ int attach_to_pi_state(u32 __user *uaddr, u32 uval,*/ if (!ping)raw_spin_lock_irq (&pi_state->pi_mutex.wait_lock); +else +raw_spin_lock_irq (&pi_state->ping_mutex.wait_lock);/* * Since {uval, pi_state} is serialized by wait_lock, and our current
@@ -353,6 +355,9 @@ int attach_to_pi_state(u32 __user *uaddr, u32 uval,if (!ping) {get_pi_state (pi_state);raw_spin_unlock_irq (&pi_state->pi_mutex.wait_lock); + }else { +get_ping_state (pi_state); +raw_spin_unlock_irq (&pi_state->ping_mutex.wait_lock); } *ps = pi_state;return 0 ;
@@ -443,6 +448,16 @@ static void __attach_to_pi_owner(struct task_struct *p, union futex_key *key,rt_mutex_init_proxy_locked (&pi_state->pi_mutex, p);WARN_ON (!list_empty (&pi_state->list));list_add (&pi_state->list, &p->futex.pi_state_list); + }else { +/* +* Initialize the pi_mutex in locked state and make @p +* the owner of it: +*/ + pi_state->ping_mutex.owner = p; +raw_spin_lock_init (&pi_state->ping_mutex.wait_lock); + +WARN_ON (!list_empty (&pi_state->list)); +list_add (&pi_state->list, &p->futex.ping_state_list); }/* Store the key for possible exit cleanups: */
kernel/futex/ping.c new file +503 -0
503 lines not on this page · raw message
kernel/futex/syscalls.c +6 -0
@@ -151,6 +151,12 @@ long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,return futex_unlock_pi (uaddr, flags, uaddr2);case FUTEX_TRYLOCK_PI :return futex_lock_pi (uaddr, flags,NULL ,1 ); +case FUTEX_LOCK_PING : +return futex_lock_ping (uaddr, flags, timeout,0 ); +case FUTEX_UNLOCK_PING : +return futex_unlock_ping (uaddr, flags); +case FUTEX_TRYLOCK_PING : +return futex_lock_ping (uaddr, flags,NULL ,1 );case FUTEX_WAIT_REQUEUE_PI : val3 =FUTEX_BITSET_MATCH_ANY ; return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 5/12 futex: Implement exit_ping_state_list().
In reply to Suleiman SouhlalHandle the case when a task exits while holding some ping_states, unowning them and dropping their references.
--- kernel/futex/core.c | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+)
kernel/futex/core.c +55 -0
@@ -1430,6 +1430,58 @@ static void exit_pi_state_list(struct task_struct *curr)static inline void exit_pi_state_list (struct task_struct *curr) { }#endif +/* Similar to exit_pi_state_list() */ +static void exit_ping_state_list (struct task_struct *curr) +{ +struct list_head *next, *head = &curr->futex.ping_state_list; +struct futex_pi_state *ping_state; +union futex_key key =FUTEX_KEY_INIT ; + +might_sleep (); +WARN_ON (curr != current); +guard (private_hash)(current->mm); + +raw_spin_lock_irq (&curr->pi_futex_lock); +while (!list_empty (head)) { + next = head->next; + ping_state = list_entry(next, struct futex_pi_state, list); +if (1 ) { +CLASS (hbr, hbr)(&key); + auto hb = hbr.hb; + +if (!refcount_inc_not_zero (&ping_state->refcount)) { +raw_spin_unlock_irq (&curr->pi_futex_lock); +cpu_relax (); +raw_spin_lock_irq (&curr->pi_futex_lock); +continue ; + } +raw_spin_unlock_irq (&curr->pi_futex_lock); + +spin_lock (&hb->lock); +raw_spin_lock_irq (&ping_state->ping_mutex.wait_lock); +raw_spin_lock (&curr->pi_futex_lock); +if (head->next != next) { +raw_spin_unlock (&ping_state->ping_mutex.wait_lock); +spin_unlock (&hb->lock); +put_ping_state (ping_state); +continue ; + } + +WARN_ON (ping_state->owner != curr); +WARN_ON (list_empty (&ping_state->list)); +list_del_init (&ping_state->list); + ping_state->owner =NULL ; +raw_spin_unlock (&curr->pi_futex_lock); +raw_spin_unlock_irq (&ping_state->ping_mutex.wait_lock); +spin_unlock (&hb->lock); + } +put_ping_state (ping_state); + +raw_spin_lock_irq (&curr->pi_futex_lock); + } +raw_spin_unlock_irq (&curr->pi_futex_lock); +} +bool futex_robust_list_clear_pending (void __user *pop,unsigned int flags) {bool size32bit = !!(flags &FLAGS_ROBUST_LIST32 );
@@ -1475,6 +1527,9 @@ static void futex_cleanup(struct task_struct *tsk)if (unlikely (!list_empty (&tsk->futex.pi_state_list)))exit_pi_state_list (tsk); + +if (unlikely (!list_empty (&tsk->futex.ping_state_list))) +exit_ping_state_list (tsk); }/**
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 6/12 futex: Address aborting from futex_lock_ping() while owning ping_state.
In reply to Suleiman SouhlalIt is possible to unsuccesfully get out of the futex_lock_ping() loop while owning the ping_state. This can happen when a waiting task gets chosen by an unlocker as the top waiter, but gets a signal or its timeout expires.
When this happens, wake up the next waiter and give them the ping_state.
--- kernel/futex/ping.c | 72 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 61 insertions(+), 11 deletions(-)
kernel/futex/ping.c +61 -11
@@ -105,6 +105,43 @@ static void futex_unqueue_ping(struct futex_q *q) q->ping_state =NULL ; } +/* +* We own the ping_state but weren't able to get the futex. +* Wake up the next waiter and give them ownership. +*/ +static void give_ping_state_to_next_waiter (struct futex_hash_bucket *hb, +union futex_key *key, +struct futex_pi_state *ping_state) +{ +struct futex_q *top_waiter; +DEFINE_WAKE_Q (wake_q); + +raw_spin_lock_irq (&ping_state->ping_mutex.wait_lock); +/* +* Someone else got the futex and we don't need to do anything +* anymore, as it's their responsibility now. +*/ +if (ping_state->owner && ping_state->owner != current) + goto out; + + top_waiter =futex_top_waiter (hb, key); +/* +* There are no other waiters but we leave the WAITERS bit set +* (with no owner or ping_state) to be cleaned up at a later unlock, +* at the cost of an extra syscall at the next lock operation, to +* keep things simple. +*/ +if (!top_waiter) + goto out; +get_ping_state (ping_state); +get_task_struct (top_waiter->task); +wake_q_add_safe (&wake_q, top_waiter->task); +ping_state_update_owner (ping_state, top_waiter->task); + +out: +raw_spin_unlock_irq_wake (&ping_state->ping_mutex.wait_lock, &wake_q); +} +/* Returns >0 if lock acquired, <0 on error */ static int futex_trylock_ping_state (u32 __user *uaddr,struct futex_pi_state *ping_state)
@@ -365,18 +402,31 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, } out_unqueue: +/* +* We got a pending signal or timeout, but the futex was handed +* off to us. Fix up the return value to indicate success. +*/ +if ((ret == -EINTR || ret == -ETIMEDOUT ) && +ping_mutex_owner (&q.ping_state->ping_mutex) == current) + ret =0 ; + +/* +* We are the pi_state owner but don't own the futex. +* This can happen if we get picked by the previous +* owner but get out without acquiring the lock for +* some reason. +* Wake up the next waiter and give the ping_state to them. +*/ if (ret !=0 && q.ping_state->owner == current) { -/* -* We are pi_state owner but don't own the futex. -* This can happen if we get picked by the previous -* owner but get out without acquiring the lock for -* some reason. -* A later commit addresses this. -*/ -WARN_ON_ONCE (1 ); - } -/* This also puts the ping_state */ -futex_unqueue_ping (&q); +if (!plist_node_empty (&q.list)) +__futex_unqueue (&q); +give_ping_state_to_next_waiter (hb, &q.key, + q.ping_state); +put_ping_state (q.ping_state); + }else +/* This also puts the ping_state */ +futex_unqueue_ping (&q); + out_unlock:futex_q_unlock (hb);__release (q.lock_ptr);
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 7/12 futex: Make FUTEX_*_PING use Proxy Execution.
In reply to Suleiman SouhlalSet the locker side proxy execution bits, so that a task blocked on a PING futex can act as a donor.
--- include/linux/futex.h | 11 +++++++++++ include/linux/sched.h | 12 ++++++++++++ kernel/futex/ping.c | 7 +++++++ kernel/sched/core.c | 7 +++++++ 4 files changed, 37 insertions(+)
include/linux/futex.h +11 -0
@@ -170,4 +170,15 @@ static inline struct task_struct *ping_mutex_owner(struct ping_mutex *ping_mutex return READ_ONCE(ping_mutex->owner); } +static inline void ping_mutex_lock_wait_lock (struct ping_mutex *ping_mutex) +{ +lockdep_assert_irqs_disabled (); +raw_spin_lock (&ping_mutex->wait_lock); +} + +static inline void ping_mutex_unlock_wait_lock (struct ping_mutex *ping_mutex) +{ +raw_spin_unlock (&ping_mutex->wait_lock); +} +#endif /* _LINUX_FUTEX_H */
include/linux/sched.h +12 -0
@@ -835,6 +835,7 @@ struct task_ipi_mask { };enum blocked_on_type {BO_T_NONE ,BO_T_MUTEX , +BO_T_PING_FUTEX , };struct blocked_on_lock {
@@ -2257,6 +2258,13 @@ static inline void __set_task_blocked_on(struct task_struct *p, void *m, p->blocked_on.type = type; } +static inline void set_task_blocked_on (struct task_struct *p,void *m, +enum blocked_on_type type) +{ +guard (raw_spinlock_irqsave)(&p->blocked_lock); +__set_task_blocked_on (p, m, type); +} +static inline void __clear_task_blocked_on (struct task_struct *p,void *m) {/* Currently we serialize blocked_on under the task::blocked_lock */
@@ -2278,6 +2286,10 @@ static inline void clear_task_blocked_on(struct task_struct *p, void *m) }#else +static inline void set_task_blocked_on (struct task_struct *p,void *m, +enum blocked_on_type type) +{ +}static inline void __clear_task_blocked_on (struct task_struct *p,void *m) { }
kernel/futex/ping.c +7 -0
@@ -370,6 +370,9 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, queued = false;while (1 ) { +set_task_blocked_on (current, &q.ping_state->ping_mutex, +BO_T_PING_FUTEX ); +set_current_state (TASK_INTERRUPTIBLE |TASK_FREEZABLE );if (!queued) {futex_queue (&q, hb, current);
@@ -382,6 +385,9 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time,futex_do_wait (&q, to); +clear_task_blocked_on (current, + &q.ping_state->ping_mutex); +futex_q_lockptr_lock (&q);if (to && !to->task) { ret = -ETIMEDOUT ;
@@ -511,6 +517,7 @@ int futex_unlock_ping(u32 __user *uaddr, unsigned int flags)/* Leave it queued, it gets unqueued on the lock side */ get_task_struct (top_waiter->task);wake_q_add_safe (&wake_q, top_waiter->task); +clear_task_blocked_on (top_waiter->task, &ping_state->ping_mutex);spin_unlock (&hb->lock);/*
kernel/sched/core.c +7 -0
@@ -68,6 +68,7 @@#include <linux/wait_api.h> #include <linux/workqueue_api.h> #include <linux/livepatch_sched.h> +#include <linux/futex.h> #ifdef CONFIG_PREEMPT_DYNAMIC # ifdef CONFIG_GENERIC_IRQ_ENTRY
@@ -158,6 +159,8 @@ static inline struct task_struct *__blocked_on_owner(struct blocked_on_lock *bo)return NULL ;case BO_T_MUTEX :return __mutex_owner (bo->lock); +case BO_T_PING_FUTEX : +return ping_mutex_owner (bo->lock);default :WARN_ON_ONCE (1 );return NULL ;
@@ -6907,6 +6910,8 @@ lock_blocked_on_lock(struct blocked_on_lock *bo) {if (bo->type ==BO_T_MUTEX )raw_spin_lock (&((struct mutex *)bo->lock)->wait_lock); +else if (bo->type ==BO_T_PING_FUTEX ) +ping_mutex_lock_wait_lock (bo->lock);else WARN_ON_ONCE (1 ); }
@@ -6916,6 +6921,8 @@ unlock_blocked_on_lock(struct blocked_on_lock *bo) {if (bo->type ==BO_T_MUTEX )raw_spin_unlock (&((struct mutex *)bo->lock)->wait_lock); +else if (bo->type ==BO_T_PING_FUTEX ) +ping_mutex_unlock_wait_lock (bo->lock);else WARN_ON_ONCE (1 ); }
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
Re: [RFC PATCH 07/12] futex: Make FUTEX_*_PING use Proxy Execution.
Hi Suleiman,
Thanks for your RFC series.
Quoted 5 lines
kernel/futex/ping.c +0
-0
kernel/futex/ping.c int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, · line 378
Quoted 9 lines
kernel/futex/ping.c +3
-0@@ -370,6 +370,9 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, queued = false;while (1 ) { +set_task_blocked_on (current, &q.ping_state->ping_mutex, +BO_T_PING_FUTEX ); +set_current_state (TASK_INTERRUPTIBLE |TASK_FREEZABLE );if (!queued) {
A userspace deadlock seems to turn into a kernel lockup. Consider threads A and B on CPU0, unlocked PING futexes F1 and F2, with the following ordering:
A: CAS(F1, gettid(A))
B: CAS(F2, gettid(B))
A: futex(&F2, FUTEX_LOCK_PING) <-- T1
B: futex(&F1, FUTEX_LOCK_PING) <-- T2
Since futex_lock_ping_atomic() only checks self-lock, both tasks end up blocked on each other after T2. And task_is_blocked() is true for both tasks, try_to_block_task() would keep them on runqueue with tsk->is_blocked set. So if pick_next_task() picks A or B, find_proxy_task() will stuck walking on A -> B -> A -> ... with rq->lock.
Could we handle cycles in find_proxy_task(), or add a chain walk for deadlock detection for FUTEX_LOCK_PING like rtmutex?
Best regards,
Jihan
K Prateek Nayak
reviewerRe: [RFC PATCH 07/12] futex: Make FUTEX_*_PING use Proxy Execution.
Quoted 30 lines · Jihan LIN
[You don't often get email from [email protected]. Learn why this is important at https://aka.ms/LearnAboutSenderIdentification ]
Hi Suleiman,
Thanks for your RFC series.
Quoted 5 lines
kernel/futex/ping.c +0
-0kernel/futex/ping.c int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, · line 378
Quoted 9 lines
kernel/futex/ping.c +3
-0@@ -370,6 +370,9 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, queued = false;while (1 ) { +set_task_blocked_on (current, &q.ping_state->ping_mutex, +BO_T_PING_FUTEX ); +set_current_state (TASK_INTERRUPTIBLE |TASK_FREEZABLE );if (!queued) {A userspace deadlock seems to turn into a kernel lockup. Consider threads A and B on CPU0, unlocked PING futexes F1 and F2, with the following ordering:
A:
CAS(F1, gettid(A))
B:CAS(F2, gettid(B))
A:futex(&F2, FUTEX_LOCK_PING)<-- T1
B:futex(&F1, FUTEX_LOCK_PING)<-- T2
Quoted 8 lines
Since
futex_lock_ping_atomic()only checks self-lock, both tasks end up blocked on each other after T2. Andtask_is_blocked()is true for both tasks,try_to_block_task()would keep them on runqueue withtsk->is_blockedset. So ifpick_next_task()picks A or B,find_proxy_task()will stuck walking on A -> B -> A -> ... withrq->lock.Could we handle cycles in
find_proxy_task(), or add a chain walk for deadlock detection forFUTEX_LOCK_PINGlike rtmutex?
https://lore.kernel.org/lkml/[email protected]/
Signature · 2 lines
Thanks and Regards, Prateek
Peter Zijlstra
maintainerRe: [RFC PATCH 07/12] futex: Make FUTEX_*_PING use Proxy Execution.
Quoted 37 lines · K Prateek Nayak
Quoted 36 lines · Jihan LIN
[You don't often get email from [email protected]. Learn why this is important at https://aka.ms/LearnAboutSenderIdentification ]
Hi Suleiman,
Thanks for your RFC series.
Quoted 5 lines
kernel/futex/ping.c +0
-0kernel/futex/ping.c int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, · line 378
Quoted 9 lines
kernel/futex/ping.c +3
-0@@ -370,6 +370,9 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, queued = false;while (1 ) { +set_task_blocked_on (current, &q.ping_state->ping_mutex, +BO_T_PING_FUTEX ); +set_current_state (TASK_INTERRUPTIBLE |TASK_FREEZABLE );if (!queued) {A userspace deadlock seems to turn into a kernel lockup. Consider threads A and B on CPU0, unlocked PING futexes F1 and F2, with the following ordering:
A:
CAS(F1, gettid(A))
B:CAS(F2, gettid(B))
A:futex(&F2, FUTEX_LOCK_PING)<-- T1
B:futex(&F1, FUTEX_LOCK_PING)<-- T2Since
futex_lock_ping_atomic()only checks self-lock, both tasks end up blocked on each other after T2. Andtask_is_blocked()is true for both tasks,try_to_block_task()would keep them on runqueue withtsk->is_blockedset. So ifpick_next_task()picks A or B,find_proxy_task()will stuck walking on A -> B -> A -> ... withrq->lock.
Quoted 4 lines
Quoted 2 lines
Could we handle cycles in
find_proxy_task(), or add a chain walk for deadlock detection forFUTEX_LOCK_PINGlike rtmutex?
Ah yes, that thing. I would suggest to still have a hard-coded limit, but perhaps in addition to the sequence mark.
Without a hard-coded limit, userspace is free to create chains of arbitrary length. This should be discouraged :-)
Also, we need to be able to return -EDEADLK to userspace.
Ideally userspace gets to have an extra graph walk on block though, and not rely on pick time sanity checks.
K Prateek Nayak
reviewerRe: [RFC PATCH 07/12] futex: Make FUTEX_*_PING use Proxy Execution.
Quoted 8 lines · Peter Zijlstra
Quoted 4 lines
Quoted 2 lines
Could we handle cycles in
find_proxy_task(), or add a chain walk for deadlock detection forFUTEX_LOCK_PINGlike rtmutex?Ah yes, that thing. I would suggest to still have a hard-coded limit, but perhaps in addition to the sequence mark.
Quoted 7 lines
Without a hard-coded limit, userspace is free to create chains of arbitrary length. This should be discouraged :-)
Also, we need to be able to return
-EDEADLKto userspace.Ideally userspace gets to have an extra graph walk on block though, and not rely on pick time sanity checks.
Ack!
One way to do that is by setting the "p->blocked_on" to -1 when find_proxy_task() detects a chain and then clear the "p->is_blocked" making it runnable.
Once the task exits out of schedule_preempt_disabled() and grabs the wait_lock, we can check the "p->blocked_on" to return -EDEADLK / stop proxy and fully block the task.
Would that be acceptable?
Signature · 2 lines
Thanks and Regards, Prateek
Re: [RFC PATCH 07/12] futex: Make FUTEX_*_PING use Proxy Execution.
Quoted 16 lines · K Prateek Nayak
Quoted 6 lines · Peter Zijlstra
Quoted 3 lines
Quoted 2 lines
Could we handle cycles in
find_proxy_task(), or add a chain walk for deadlock detection forFUTEX_LOCK_PINGlike rtmutex?Ah yes, that thing. I would suggest to still have a hard-coded limit, but perhaps in addition to the sequence mark.
Quoted 7 lines
Without a hard-coded limit, userspace is free to create chains of arbitrary length. This should be discouraged :-)
Also, we need to be able to return
-EDEADLKto userspace.Ideally userspace gets to have an extra graph walk on block though, and not rely on pick time sanity checks.
Ack!
Quoted 7 lines
One way to do that is by setting the "
p->blocked_on" to -1 whenfind_proxy_task()detects a chain and then clear the "p->is_blocked" making it runnable.Once the task exits out of
schedule_preempt_disabled()and grabs thewait_lock, we can check the "p->blocked_on" to return-EDEADLK/ stop proxy and fully block the task.
This approach could reuse the owner walk, which sounds useful for avoiding an extra chain walk in the contended futex path.
That said, checking for deadlocks before sleeping would also be more similar with PI futexes, and extra walk might be worth the cost if the last lock attempt can simply return -EDEADLK to userspace.
Best regards,
Jihan
RFC PATCH 8/12 futex: Implement PING futex handoff.
In reply to Suleiman SouhlalImplement handoff for PING futexes, to prevent starvation in case of a waiter being repeatedly stolen from.
Currently engages after being stolen from once, after which the next unlocker hands off the futex such that it can't be stolen.
--- kernel/futex/futex.h | 2 ++ kernel/futex/ping.c | 45 ++++++++++++++++++++++++++++++++++---------- 2 files changed, 37 insertions(+), 10 deletions(-)
kernel/futex/futex.h +2 -0
@@ -174,6 +174,8 @@ struct futex_pi_state {struct task_struct *owner;refcount_t refcount; +bool handoff; +bool pickup;union futex_key key; } __randomize_layout;
kernel/futex/ping.c +35 -10
115 lines not on this page · raw message
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 9/12 futex: Wake up donor in PING futex unlock.
In reply to Suleiman SouhlalNow that PING blockers can act as donors, it makes sense to wake up the donor instead of the top_waiter when unlocking.
--- kernel/futex/ping.c | 56 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 10 deletions(-)
kernel/futex/ping.c +46 -10
@@ -478,10 +478,46 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time,return ret; } +#ifdef CONFIG_SCHED_PROXY_EXEC +static inline +struct task_struct *ping_current_proxy_donor (struct futex_pi_state *ping_state) +{ +struct task_struct *ret =NULL ; + +if (sched_proxy_exec ()) { +struct task_struct *donor; + +raw_spin_lock (¤t->blocked_lock); + donor = current->blocked_donor; +if (donor) { +void *ping_lock = (void *)&ping_state->ping_mutex; + +raw_spin_lock_nested (&donor->blocked_lock, +SINGLE_DEPTH_NESTING ); +if (__get_task_blocked_on (donor) == ping_lock) { + ret =get_task_struct (donor); +__clear_task_blocked_on (donor, ping_lock); + current->blocked_donor =NULL ; + } +raw_spin_unlock (&donor->blocked_lock); + } +raw_spin_unlock (¤t->blocked_lock); + } +return ret; +} +#else +static inline +struct task_struct *ping_current_proxy_donor (struct futex_pi_state *ping_state) +{ +return NULL ; +} +#endif +int futex_unlock_ping (u32 __user *uaddr,unsigned int flags) {struct futex_pi_state *ping_state;u32 new, uval, vpid =task_pid_vnr (current); +struct task_struct *next;union futex_key key =FUTEX_KEY_INIT ;struct futex_q *top_waiter;DEFINE_WAKE_Q (wake_q);
@@ -528,15 +564,15 @@ int futex_unlock_ping(u32 __user *uaddr, unsigned int flags)if (!ping_state) goto out_unlock;raw_spin_lock_irq (&ping_state->ping_mutex.wait_lock); -if (ping_state->owner != current) { -raw_spin_unlock_irq (&ping_state->ping_mutex.wait_lock); - goto out_unlock; - } + + next =ping_current_proxy_donor (ping_state);get_ping_state (ping_state);/* Leave it queued, it gets unqueued on the lock side */ -get_task_struct (top_waiter->task); -wake_q_add_safe (&wake_q, top_waiter->task); -clear_task_blocked_on (top_waiter->task, &ping_state->ping_mutex); +if (next ==NULL ) { + next =get_task_struct (top_waiter->task); +clear_task_blocked_on (next, &ping_state->ping_mutex); + } +wake_q_add_safe (&wake_q, next);spin_unlock (&hb->lock);/*
@@ -546,10 +582,10 @@ int futex_unlock_ping(u32 __user *uaddr, unsigned int flags)*/ new =FUTEX_WAITERS ;if (ping_state->handoff) { - new |=task_pid_vnr (top_waiter->task); + new |=task_pid_vnr (next); ping_state->handoff =0 ; ping_state->pickup =1 ; -WRITE_ONCE (ping_state->ping_mutex.owner, top_waiter->task); +WRITE_ONCE (ping_state->ping_mutex.owner, next); }else WRITE_ONCE (ping_state->ping_mutex.owner,NULL ); ret =lock_pi_update_atomic (uaddr, uval, new);
@@ -568,7 +604,7 @@ int futex_unlock_ping(u32 __user *uaddr, unsigned int flags) } } -ping_state_update_owner (ping_state, top_waiter->task); +ping_state_update_owner (ping_state, next);raw_spin_unlock_irq_wake (&ping_state->ping_mutex.wait_lock, &wake_q);put_ping_state (ping_state);return 0 ;
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 10/12 futex: Optimistic spinning for PING futexes.
In reply to Suleiman SouhlalThis allows a thread to spin on the owner of the futex instead of unconditionally spinning, if the owner is currently running on another CPU.
TODO: Currently allows every task to attempt to spin at the same time. In the future, spinning will probably either use an osq or only the top waiter will be allowed to wait. We've seen some long latencies when using an osq that we still need to investigate.
--- kernel/futex/ping.c | 80 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 67 insertions(+), 13 deletions(-)
kernel/futex/ping.c +67 -13
@@ -301,6 +301,50 @@ static int futex_lock_ping_atomic(u32 __user *uaddr,return attach_to_pi_owner (uaddr, newval, key, ps, exiting, true); } +/* +* Returns >0 on successfully having taken the lock, <0 on error +*/ +static int ping_spin_or_trylock (u32 __user *uaddr, +struct futex_pi_state *ping_state, +bool handoff) +{ +struct task_struct *owner =ping_mutex_owner (&ping_state->ping_mutex); +struct task_struct *new; +int ret; + +if (owner && !owner_on_cpu (owner)) +return 0 ; + +/* +* XXX We'll want to try to limit spinning either with an osq or +* by only allowing the top waiter to spin. +*/ + +while (1 ) { + new =ping_mutex_owner (&ping_state->ping_mutex); + ret =0 ; +if (!owner || !new || new == current) { + ret =futex_trylock_ping_state (uaddr, ping_state, + handoff); +if (ret !=0 ) +break ; +/* Spin on new owner if we didn't get the lock */ + owner =ping_mutex_owner (&ping_state->ping_mutex); + goto next; + } +if (new != owner) { + owner =ping_mutex_owner (&ping_state->ping_mutex); + goto next; + } +if (!owner_on_cpu (owner) ||need_resched ()) +break ; +next: +cpu_relax (); + } + +return ret; +} +/* * Return values: * < 0: error.
@@ -387,9 +431,6 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, queued = false; should_handoff = false;while (1 ) { -set_task_blocked_on (current, &q.ping_state->ping_mutex, -BO_T_PING_FUTEX ); -set_current_state (TASK_INTERRUPTIBLE |TASK_FREEZABLE );if (!queued) {futex_queue (&q, hb, current);
@@ -400,6 +441,26 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time,__release (q->lock_ptr); } +preempt_disable (); +set_current_state (TASK_INTERRUPTIBLE |TASK_FREEZABLE ); + ret =ping_spin_or_trylock (uaddr, q.ping_state, + should_handoff); +if (ret >0 ) { +/* Got the futex */ + ret =0 ; +preempt_enable (); +futex_q_lockptr_lock (&q); + goto out_unqueue; + }else if (ret <0 ) { +preempt_enable (); +futex_q_lockptr_lock (&q); + goto out_unqueue; + } +preempt_enable (); + +set_task_blocked_on (current, &q.ping_state->ping_mutex, +BO_T_PING_FUTEX ); +futex_do_wait (&q, to); clear_task_blocked_on(current,
@@ -414,19 +475,12 @@ int futex_lock_ping(u32 __user *uaddr, unsigned int flags, ktime_t *time, ret = -EINTR ; goto out_unqueue; } - - ret =futex_trylock_ping_state (uaddr, q.ping_state, - should_handoff); -if (ret >0 ) { -/* Got the futex */ - ret =0 ; - goto out_unqueue; - }else if (ret <0 ) - goto out_unqueue; should_handoff = true; } out_unqueue: +__set_current_state (TASK_RUNNING ); +/* * We got a pending signal or timeout, but the futex was handed * off to us. Fix up the return value to indicate success.
@@ -581,7 +635,7 @@ int futex_unlock_ping(u32 __user *uaddr, unsigned int flags)* no top_waiter. */ new =FUTEX_WAITERS ; -if (ping_state->handoff) { +if (ping_state->handoff) {/* Don't handoff to donor */ new |=task_pid_vnr (next); ping_state->handoff =0 ; ping_state->pickup =1 ;
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 11/12 futex: Allow userspace stealing for PING futexes.
In reply to Suleiman SouhlalSimilarly to how the kernel part of PING locking can steal the futex from the top waiter, it is also possible for userspace to also take advantage of this and try to steal without going to the kernel.
When a new (contending) locker notices that the lock has been stolen from userspace, the ownership of the ping_state and the ping_mutex are fixed up to the real owner.
TODO: Verify that the case where the ping_state owner exits with the
futex having been user stolen is handled correctly.
In other words, when ping_state->owner = task getting killed, ping_mutex.owner = NULL and uval = real owner (set by userspace). Right now, it seems like we might be doing the wrong thing in such cases. exit_ping_state_list() needs to detect such situations (by walking the uvals?) and fixup the ownerships.
--- kernel/futex/core.c | 8 ++++++++ kernel/futex/futex.h | 2 ++ kernel/futex/pi.c | 12 ++++++++++-- kernel/futex/ping.c | 38 +++++++++++++++++++++++++++++++++++--- 4 files changed, 55 insertions(+), 5 deletions(-)
kernel/futex/core.c +8 -0
@@ -1445,6 +1445,14 @@ static void exit_ping_state_list(struct task_struct *curr)while (!list_empty (head)) { next = head->next; ping_state = list_entry(next, struct futex_pi_state, list); +/* +* XXX In the case when we are ping_state owner but +* the futex is actually owned by someone who stole it +* from userspace, is setting ping_state.owner = NULL here +* enough? Probably not, otherwise the ping_state could leak +* if they also exit before unlocking or someone else +* fixing up the ownership. +*/ if (1 ) {CLASS (hbr, hbr)(&key); auto hb = hbr.hb;
kernel/futex/futex.h +2 -0
@@ -413,6 +413,8 @@ extern int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key, bool ping);extern void get_ping_state (struct futex_pi_state *ping_state);extern void put_ping_state (struct futex_pi_state *ping_state); +extern int fixup_ping_owner_after_user_steal (struct futex_pi_state *ping_state, +u32 __user *uaddr,u32 uval);/* * Express the locking dependencies for lockdep:
kernel/futex/pi.c +10 -2
@@ -348,8 +348,16 @@ int attach_to_pi_state(u32 __user *uaddr, u32 uval,* state exists then the owner TID must be the same as the * user space TID. [9/10] */ -if (pid !=task_pid_vnr (pi_state->owner)) - goto out_einval; +if (pid !=task_pid_vnr (pi_state->owner)) { +if (!ping) { + goto out_einval; + }else { + ret =fixup_ping_owner_after_user_steal (pi_state, + uaddr, uval); +if (ret) + goto out_error; + } + } out_attach:if (!ping) {
kernel/futex/ping.c +35 -3
@@ -96,6 +96,22 @@ put_ping_state(struct futex_pi_state *ping_state) } } +int fixup_ping_owner_after_user_steal (struct futex_pi_state *ping_state, +u32 __user *uaddr,u32 uval) +{ +struct task_struct *p; + + p =find_get_task_by_vpid (uval &FUTEX_TID_MASK ); +if (p ==NULL ) +return pi_handle_exit_race (uaddr, uval); +if (unlikely (p->flags &PF_KTHREAD )) +return -EPERM ; +ping_state_update_owner (ping_state, p); +WRITE_ONCE (ping_state->ping_mutex.owner, p); + +return 0 ; +} +static void futex_unqueue_ping (struct futex_q *q) {if (!plist_node_empty (&q->list))
@@ -149,6 +165,7 @@ static int futex_trylock_ping_state(u32 __user *uaddr, bool handoff) {struct task_struct *owner; +pid_t pid;u32 uval, new, newtid;int ret;
@@ -163,8 +180,17 @@ static int futex_trylock_ping_state(u32 __user *uaddr,WARN_ON_ONCE (ping_state->handoff || ping_state->pickup); -if (uval &FUTEX_TID_MASK ) { - ret = -EAGAIN ; +/* +* No owner but a userspace TID means that it got stolen +* from userspace. +* Fix up the ownership. +*/ + pid = uval &FUTEX_TID_MASK ; +if (pid) { + ret =fixup_ping_owner_after_user_steal (ping_state, + uaddr, uval); +if (ret ==0 ) + ret = -EAGAIN ; goto err; } new = newtid |FUTEX_WAITERS ;
@@ -203,7 +229,7 @@ static int futex_trylock_ping_state(u32 __user *uaddr,case -EINVAL :break ;default : -WARN_ON (1 ); +break ; }return ret; }
@@ -619,6 +645,12 @@ int futex_unlock_ping(u32 __user *uaddr, unsigned int flags) goto out_unlock;raw_spin_lock_irq (&ping_state->ping_mutex.wait_lock); +/* +* If we're unlocking a lock we stole from userspace, +* it's possible that we don't own the ping_state or the +* ping_mutex. But we'll give them to the next task here anyway. +*/ + next =ping_current_proxy_donor (ping_state);get_ping_state (ping_state);/* Leave it queued, it gets unqueued on the lock side */
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
RFC PATCH 12/12 tools/testing/futex: Add ping_bench, a tool for benchmarking futexes.
In reply to Suleiman SouhlalIt can generate metrics across a number of configurations, measuring how long locking takes.
It prints out lock call durations for the foreground thread to stdout (unless -q is passed), for analysis with other tools such as ministat or turning into histograms.
Some parameters:
-a: Print out durations for all threads instead of only for the
foreground thread.
-q: Don't print out locking durations.
-f: Type of futex ("f" FUTEX_WAIT, "p" FUTEX_LOCK_PI,
"n" FUTEX_LOCK_PING, "N" FUTEX_LOCK_PING with userspace stealing, "m" pthread_mutex_t).
-t: Number of threads acquiring/releasing the lock.
-n: Number of iterations the threads will take the lock. -s: How frequently a thread tries to take the lock.
-S: Duration in usec to sleep instead of spinning after unlocking
(use instead of -s).
-w: Lock hold time.
-b: Number of “busy” cpu spinner threads.
-r: Number of threads using RT prio.
-p: Use nice() biasing (foreground thread gets more cpu time,
background threads get less - allows for priority inversions).
--- tools/testing/futex/Makefile | 13 + tools/testing/futex/ping_bench.c | 428 +++++++++++++++++++++++++++++++ 2 files changed, 441 insertions(+) create mode 100644 tools/testing/futex/Makefile create mode 100644 tools/testing/futex/ping_bench.c
tools/testing/futex/Makefile new file +13 -0
@@ -0,0 +1,13 @@ +# SPDX-License-Identifier: GPL-2.0 + +.PHONY: clean + +TARGETS = ping_bench +CFLAGS = -O -Wall -g +OFILES = ping_bench.o +TARGETS = ping_bench + +ping_bench: $(OFILES) + +clean: + $(RM) $(TARGETS) $(OFILES)
tools/testing/futex/ping_bench.c new file +428 -0
428 lines not on this page · raw message
Signature · 1 line
2.55.0.1082.g2b9226bbc0-goog
Peter Zijlstra
maintainerQuoted 17 lines · Suleiman Souhlal
Hello,
This patch series adds a new type of PI futexes, PI Next Generation, or PING (name coined by Steven Rostedt) (but other name suggestions are welcome!), that differs from classic PI futexes in that they can be stolen from the top waiter, and use Proxy Execution instead of rtmutexes internally.
The reason to allow the futexes to be stolen is that with classic PI futex's strict handoff to the top waiter, new contending lockers are now forced to wait in queue, which means that any locking operation now becomes a scheduling event. With stealing, a contending locker has the chance of taking the lock without blocking. The longer wait time of blocked tasks can be mitigated by forcing the lock to be handed off to them in a way that can't be stolen, when they've been stolen from too much, to ensure they don't get starved.
Quoted 2 lines
The use of Proxy Execution lets us also get Priority Inheritance for for fair tasks, which PI futexes don't really allow.
https://patch.msgid.link/1490204338-1856-1-git-send-email-longman%40redhat.com
Also, the goal is to eventually delete rt_mutex and have it be the normal mutex, in which case the existing FUTEX_*_PI things will automagically work.
So I'm thinking all of this is way premature.
Quoted 17 lines · Peter Zijlstra
Quoted 16 lines · Suleiman Souhlal
This patch series adds a new type of PI futexes, PI Next Generation, or PING (name coined by Steven Rostedt) (but other name suggestions are welcome!), that differs from classic PI futexes in that they can be stolen from the top waiter, and use Proxy Execution instead of rtmutexes internally.
The reason to allow the futexes to be stolen is that with classic PI futex's strict handoff to the top waiter, new contending lockers are now forced to wait in queue, which means that any locking operation now becomes a scheduling event. With stealing, a contending locker has the chance of taking the lock without blocking. The longer wait time of blocked tasks can be mitigated by forcing the lock to be handed off to them in a way that can't be stolen, when they've been stolen from too much, to ensure they don't get starved.
Quoted 4 lines
Quoted 2 lines
The use of Proxy Execution lets us also get Priority Inheritance for for fair tasks, which PI futexes don't really allow.
https://patch.msgid.link/1490204338-1856-1-git-send-email-longman%40redhat.com
Thanks for that reference! I'm sure we can learn a lot from that series. (I do like the straightforward FUTEX_LOCK/UNLOCK over the PING name here :)
Quoted 3 lines
Also, the goal is to eventually delete
rt_mutexand have it be the normal mutex, in which case the existing FUTEX_*_PI things will automagically work.
Indeed, moving rt_mutexes to proxy is a goal. Though the performance concerns from FUTEX_*_PI have to do with the semantics it (and rt_mutex) promises: strict RT prio order handoff - esentially FIFO for SCHED_NORMAL. Not so much the mechanism it uses for boosting.
That's why it seems a new FUTEX op is needed. Since we 1) need to communicate the owner to the kernel 2) want different semantics for lock-handoff and stealing.
Even when we get to moving rt_mutexes to proxy, it seems to me we're likely going to have to keep the rt_mutex itself (even if the PI boosting is proxy based) as a distinguisher, since the users likely desire the strict semantics (or at least we will need to add some behavior flags to the mutex struct so it can still satisfy those semantics).
Quoted 1 line
So I'm thinking all of this is way premature.
So it is just an initial RFC, and we are looking for input.
But there is a strong appetite to solve this, as we're already seeing vendors doing less ideal things, like passing who the waiter thinks the owner is (racy) in via unused fields of FUTEX_WAIT, so that out-of-tree custom scheduler boosting can (temporarily - as again it can be wrong) try to get that owner to release the lock. The longer we go without a usable upstream solution, the more entrenched these less ideal solutions become.
thanks
-john
Steven Rostedt
reviewerQuoted 4 lines · On Thu, 17 Sep 2026 10:53:47 -0700 John Stultz <[email protected]> wrote:
Indeed, moving
rt_mutexesto proxy is a goal. Though the performance concerns from FUTEX_*_PI have to do with the semantics it (andrt_mutex) promises: strict RT prio order handoff - esentially FIFO forSCHED_NORMAL. Not so much the mechanism it uses for boosting.
I started working on this while still at Google on the ChromeOS/Android-on-chrome team. The biggest issue we found with FUTEX_PI was that it forced all users of it to be fair. Even SCHED_OTHER which did not even benefit from the PI code. The result, it killed performance, and nobody wanted to use it.
What I recommended was to have a new futex to allow SCHED_OTHER tasks to be unfair (just like rt_mutex is in PREEMPT_RT), and also to allow more to be done in user space and not require every contention to go into the kernel.
We had a test (Suleiman, can you share that test) which emulated the code in Chrome and by switching to FUTEX_PI the performance dropped by a large percentage (I don't recall the actual numbers but I posted them internally at Google). By switching SCHED_OTHER to be non fair (that is, when the lock was released, if the next waiting task was SCHED_OTHER, and the new SCHED_OTHER task coming in could steal the lock), and the performance almost went back to what normal FUTEX had (I was assuming that going into the kernel on all contention was the cause of not getting closer to normal FUTEX). That alone was a big improvement over FUTEX_PI.
There was talk about changing FUTEX_PI to allow SCHED_OTHER to be unfair and to steal, but that would change the semantics of it and there may be some application that requires FUTEX_PI to be fair for all tasks, even SCHED_OTHER. This is when we decided that we need a new FUTEX_PI (new generation, which I coined FUTEX_PING, but kinda of a joke so feel free to change), so that we could change the semantics without breaking backward compatibility of applications requiring the current behavior of FUTEX_PI.
But FUTEX_PI requires all contention to be handled in the kernel, where as we can get even more performance if we could change it to allow the SCHED_OTHER case (which can steal the lock) to be handled in user space.
I haven't looked at Suleiman's code yet (I'm currently traveling and don't have time until after Oct 10th). But I would expect this new futex to keep RT tasks being fair. Otherwise no RT task will use it.
In summary, the motivation of this patch was that we had a few RT tasks suffering from priority inversion from hundreds of SCHED_OTHER tasks over a shared mutex. The problem was, if we switched it to FUTEX_PI, the few RT tasks would perform correctly, but the slowdown from the hundreds of SCHED_OTHER tasks made it a show stopper. The goal was to have a futex that allowed nice PI with RT tasks, but still allowed SCHED_OTHER being unfair and stealing from each other.
-- Steve
Quoted 20 lines · Steven Rostedt
Quoted 4 lines · On Thu, 17 Sep 2026 10:53:47 -0700 John Stultz <[email protected]> wrote:
Indeed, moving
rt_mutexesto proxy is a goal. Though the performance concerns from FUTEX_*_PI have to do with the semantics it (andrt_mutex) promises: strict RT prio order handoff - esentially FIFO forSCHED_NORMAL. Not so much the mechanism it uses for boosting.I started working on this while still at Google on the ChromeOS/Android-on-chrome team. The biggest issue we found with
FUTEX_PIwas that it forced all users of it to be fair. EvenSCHED_OTHERwhich did not even benefit from the PI code. The result, it killed performance, and nobody wanted to use it.What I recommended was to have a new futex to allow
SCHED_OTHERtasks to be unfair (just likert_mutexis inPREEMPT_RT), and also to allow more to be done in user space and not require every contention to go into the kernel.
Quoted 10 lines
We had a test (Suleiman, can you share that test) which emulated the code in Chrome and by switching to
FUTEX_PIthe performance dropped by a large percentage (I don't recall the actual numbers but I posted them internally at Google). By switchingSCHED_OTHERto be non fair (that is, when the lock was released, if the next waiting task wasSCHED_OTHER, and the newSCHED_OTHERtask coming in could steal the lock), and the performance almost went back to what normal FUTEX had (I was assuming that going into the kernel on all contention was the cause of not getting closer to normal FUTEX). That alone was a big improvement overFUTEX_PI.
Your test is here: https://rostedt.org/private/lock-test.c
Your PING implementation is here:
https://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace.git/log/?h=ping/test
Quoted 10 lines
There was talk about changing
FUTEX_PIto allowSCHED_OTHERto be unfair and to steal, but that would change the semantics of it and there may be some application that requiresFUTEX_PIto be fair for all tasks, evenSCHED_OTHER. This is when we decided that we need a newFUTEX_PI(new generation, which I coinedFUTEX_PING, but kinda of a joke so feel free to change), so that we could change the semantics without breaking backward compatibility of applications requiring the current behavior ofFUTEX_PI.
Quoted 7 lines
But
FUTEX_PIrequires all contention to be handled in the kernel, where as we can get even more performance if we could change it to allow theSCHED_OTHERcase (which can steal the lock) to be handled in user space.I haven't looked at Suleiman's code yet (I'm currently traveling and don't have time until after Oct 10th). But I would expect this new futex to keep RT tasks being fair. Otherwise no RT task will use it.
Currently, my implementation allows a fair task to steal from an RT blocking task.
However, I think that we could easily change it.
I suspect that for our use case, we are ok with fair tasks occasionally stealing from RT tasks.
Quoted 8 lines
In summary, the motivation of this patch was that we had a few RT tasks suffering from priority inversion from hundreds of
SCHED_OTHERtasks over a shared mutex. The problem was, if we switched it toFUTEX_PI, the few RT tasks would perform correctly, but the slowdown from the hundreds ofSCHED_OTHERtasks made it a show stopper. The goal was to have a futex that allowed nice PI with RT tasks, but still allowedSCHED_OTHERbeing unfair and stealing from each other.
I agree with everything you've said, but I should also add that we would also like PI behavior between fair tasks, not just when RT tasks are present, because priority inversions can still occur between fair tasks. For example when using sched group shares.
The existing rtmutex based PI futexes can't address those, as far as I can tell. This is why I opted for a whole new implementation rather than your initial prototype that still used rtmutexes.
-- Suleiman
Peter Zijlstra
maintainerQuoted 8 lines · John Stultz
Quoted 3 lines
Also, the goal is to eventually delete
rt_mutexand have it be the normal mutex, in which case the existing FUTEX_*_PI things will automagically work.Indeed, moving
rt_mutexesto proxy is a goal. Though the performance concerns from FUTEX_*_PI have to do with the semantics it (andrt_mutex) promises: strict RT prio order handoff - esentially FIFO forSCHED_NORMAL. Not so much the mechanism it uses for boosting.
Yeah, mutex will probably need to grow a few feature when doing that.
Quoted 3 lines
That's why it seems a new FUTEX op is needed. Since we 1) need to communicate the owner to the kernel 2) want different semantics for lock-handoff and stealing.
So I'm not convinced. One could argue the strict requirements are dependent on the scheduling class, not the lock type. It should be feasible to make stealing behaviour depend on the lock owner or waiter class for instance.
Quoted 11 lines
Quoted 1 line
So I'm thinking all of this is way premature.
So it is just an initial RFC, and we are looking for input.
But there is a strong appetite to solve this, as we're already seeing vendors doing less ideal things, like passing who the waiter thinks the owner is (racy) in via unused fields of
FUTEX_WAIT, so that out-of-tree custom scheduler boosting can (temporarily - as again it can be wrong) try to get that owner to release the lock. The longer we go without a usable upstream solution, the more entrenched these less ideal solutions become.
So this does sound a little like blackmail. If vendors want this, then vendors had better help out upstream. If vendors don't give a toss about upstream, then why should I give a flying fuck about them?
It is then on Google to tell vendors to put up or shut up. Just tell em their hacks are no longer allowed once we have something upstream. Break their toys and tell em to kindly go cry in the corner.
So no, we don't rush this.
Quoted 19 lines · Peter Zijlstra
Quoted 17 lines · Suleiman Souhlal
Hello,
This patch series adds a new type of PI futexes, PI Next Generation, or PING (name coined by Steven Rostedt) (but other name suggestions are welcome!), that differs from classic PI futexes in that they can be stolen from the top waiter, and use Proxy Execution instead of rtmutexes internally.
The reason to allow the futexes to be stolen is that with classic PI futex's strict handoff to the top waiter, new contending lockers are now forced to wait in queue, which means that any locking operation now becomes a scheduling event. With stealing, a contending locker has the chance of taking the lock without blocking. The longer wait time of blocked tasks can be mitigated by forcing the lock to be handed off to them in a way that can't be stolen, when they've been stolen from too much, to ensure they don't get starved.
Quoted 4 lines
Quoted 2 lines
The use of Proxy Execution lets us also get Priority Inheritance for for fair tasks, which PI futexes don't really allow.
https://patch.msgid.link/1490204338-1856-1-git-send-email-longman%40redhat.com
I was not aware of this, thanks!
It actually seems very similar to this patchset (but much better written). The main functional differences that I can see from a cursory look are that on unlock it doesn't preserve the waiters bit, while PING does, and that TP futex also supports userspace rwlocks, unlike PING. And of course the fact that PING also uses Proxy Execution.
So now I know that I'm not completely crazy for wanting this. :-)
Quoted 4 lines
Also, the goal is to eventually delete
rt_mutexand have it be the normal mutex, in which case the existing FUTEX_*_PI things will automagically work.
I considered using a mutex but I was under the impression that some RT workloads really want strict RT handling such that the highest priority RT task always has to take the lock before any other contender, which mutex doesn't currently allow. For these workloads, the existing rtmutex behavior of handing off the lock to the top waiter is desirable.
Other workloads still have RT tasks, but are ok with slightly less strict handling, as long as RT tasks still get serviced reasonably fast (so they still want priority inheritance, but are ok with the occasional case where a fair task steals the lock from the RT top waiter).
I suspect Android is in this later bucket, so for them using a mutex as it's currently implemented would be ok. But others might not be. On the other hand, the current rtmutex behavior would not be desirable for users like Android, due to the performance with fair tasks that Steven brings up in his reply.
These different needs are why I wanted to add a new futex type. But maybe the different needs could be selected through a CONFIG option, but with the same user API (FUTEX_*_PI)?
I also had some other probably not insurmountable minor issues, like the fact that we probably wouldn't want to get kernel lockdep warnings for userspace deadlocks.
-- Suleiman
Peter Zijlstra
maintainerQuoted 25 lines · Suleiman Souhlal
Quoted 19 lines · Peter Zijlstra
Quoted 17 lines · Suleiman Souhlal
Hello,
This patch series adds a new type of PI futexes, PI Next Generation, or PING (name coined by Steven Rostedt) (but other name suggestions are welcome!), that differs from classic PI futexes in that they can be stolen from the top waiter, and use Proxy Execution instead of rtmutexes internally.
The reason to allow the futexes to be stolen is that with classic PI futex's strict handoff to the top waiter, new contending lockers are now forced to wait in queue, which means that any locking operation now becomes a scheduling event. With stealing, a contending locker has the chance of taking the lock without blocking. The longer wait time of blocked tasks can be mitigated by forcing the lock to be handed off to them in a way that can't be stolen, when they've been stolen from too much, to ensure they don't get starved.
Quoted 4 lines
Quoted 2 lines
The use of Proxy Execution lets us also get Priority Inheritance for for fair tasks, which PI futexes don't really allow.
https://patch.msgid.link/1490204338-1856-1-git-send-email-longman%40redhat.com
Quoted 7 lines
I was not aware of this, thanks!
It actually seems very similar to this patchset (but much better written). The main functional differences that I can see from a cursory look are that on unlock it doesn't preserve the waiters bit, while PING does, and that TP futex also supports userspace rwlocks, unlike PING. And of course the fact that PING also uses Proxy Execution.
So now I know that I'm not completely crazy for wanting this. :-)
Well, you all seem to be in violent disagreement with yourself. On the one hand you call your feature Priority Inheritance Next-Gen, while at the same time you're arguing you do NOT in fact want the strictness of PI/RT.
You cannot have it both ways.
But yes, FUTEX_LOCK/FUTEX_UNLOCK is desirable for a fair number of reasons, and Waiman's earlier attempt basically died because neither Thomas nor me found time to do a proper review :-(
One of the very few things that I remember being annoyed with is that it did handoff in the futex code, while mutex_unlock() already has this. But other than it being a annoyance, I never had enough time to dig in to understand if this was fixable or not.
Anyway, back then the motivation for FUTEX_LOCK was to get optimistic spinning for 'free' by using mutex, much like how FUTEX_LOCK_PI uses rt_mutex. These days, you'd get proxy exec as well.
But like I mentioned elsewhere, the whole futex/proxy thing needs a deadlock detector, something we don't really need for in-kernel code, since it is a hard requirement for kernel code not to have lock cycles (barring ww_mutex, which will resolve them etc.). But we cannot trust userspace to play nice.
Doing it at schedule() time is very much not ideal, this is something much better done at block time, not least because it is the ideal context to return -EDEADLK, but also because you but the cost of verifying it in the right context.