Sleeping Owner Handling for Proxy Execution (v34)
Subsystems (5)
v34 cover Sleeping Owner Handling for Proxy Execution (v34)
Hey All,
Just wanted to send out this next iteration of Proxy Execution:
Sleeping Owner Handling.
Unfortunately it’s been an unexpectedly busy time since LPC and I just haven’t had much time until right before the long weekend to try to respond and address all the great feedback that has been shared. My apologies, I really do appreciate all the feedback and suggestions! The good news is that during this time, there were a lot of practical proxy related issues uncovered and fixed, so those items (which applied to this portion of the series or upstream) are included here.
(Folks may remember back in the heady days of September w/ v32 of the series, where this chunk was only 2 patches! Fond memories!).
Peter: Even if the full set submitted here isn’t queued, it likely would be good to take some of the earlier fixups in this set if you don’t have objections to them. Let me know if there’s a better way for me to queue and handle fixes vs features to send to you.
As always, I’m trying to submit this larger work in smallish digestible pieces. A quick overview of the journey so far:
1) Prep patches
2) Single rq proxying
3) Simple donor migration
4) Optimized donor migration
5) Sleeping owner handling <-- We are here!
6) K Prateek’s core-sched fixes
7) Chain level balancing
8) Suleiman’s proxy rwsems
9) Suleiman’s proxy futexes
10) ...
On top of a number of correctness fixes, the main feature in this series is the sleeping owner handling patch, which addresses what to do when a task is blocked on a mutex whose owner is sleeping. Since there is nothing we can do to boost the sleeping owner at that point, we instead deactivate and queue the waiter on a list attached to the owner. Then when the owner wakes up, we will activate the waiters on the same runqueue, so they can then boost the owner to run.
But since the simple sounding things hide subtlety, this ends up being a pretty complex bit of logic. You can effectively get trees of waiters, and it's possible to have tasks in the middle of the tree be woken up. Then handling wakeups as they cascade down the tree properly is also a bit complex, as there are extra lists to manage the recursive style work without actually recursing.
In this series I’ve also aggregated fixes from K Prateek, Shubhang Kaushik, as well as included some initial proxy-chain cycle detection logic combining parallel efforts from Zhidao Su and Hui Su. Additional fixes from Mathieu Desnoyers, Yu-Ting Tseng, as well as ones suggested by Andrea Righi, K Prateek Nayak and Juri Lelli are included this time.
Further, I’ve folded a number of fixes suggested by Jichao, Andrea, Kayra, and K Prateek into the sleeping-owner-enqueuing change.
Again, thank you to everyone for contributing bug reports, fixes and improvements! I really appreciate it!
New in v34 of this set:
* Improvements to PSI fix suggested by K Prateek
* Fixes for proxy edge cases with DL and RT tasks from Mathieu Desnoyers
* Fixes for the blocked_donor back-pointer handling from Mathieu Desnoyers
* Along with other fixes inspired by Mathieu raising blocked_donor issues
* Further care around lock cycle avoidance with blocked_donor traversal (preparation for future proxy futex logic, where userland may intentionally create cycles)
* A proxy migration correctness issue, where we weren’t calling migrate_task_rq(), found and fixed by Yu-Ting Tseng.
* Fixes to an issue Andrea Righi raised on the find_proxy_task() task_current() shortcuts skipping important logic done in the wakeup path for core scheduling.
* Fixes to the find_proxy_task() lock-cycle deactivation logic to avoid deactivating current
* Fix to sleeping owner handling to avoid re-activating TASK_DEAD tasks, found and suggested by Jichao Zou
* Fix to sleeping owner handling’s do_activate_blocked_watier() logic to take blocked_lock earlier address a race K Prateek pointed out.
* Change to pass DEQUEUE_SPECIAL to block_task() in proxy_enqueue_on_owner() to fix issue Kaya and Andrea raised with sched_delayed tasks
* Only call activate_blocked_tasks() if the task was actually woken, as suggested by Andrea and Kaya
* A new fix to migrate_task_rq_dl() issue that Andrea raised, as suggested by K Prateek and Juri
* Fix for a RCU / proxy-exec deadlock discovered by Yu-Che Cheng.
* As well as lots of smaller polish issues suggested by K Prateek, Andrea and Kaya.
Additionally I’d appreciate any testing or comments that folks have with the full Proxy Execution series! You can find the full Proxy Exec series here:
https://github.com/johnstultz-work/linux-dev/commits/proxy-exec-v34-7.4-rc5
https://github.com/johnstultz-work/linux-dev.git proxy-exec-v34-7.4-rc5
New changes to the full patch series in this revision include:
* Number of cycle avoidance changes to the chain-migration logic.
* Fix for a crash issue in chain-migration logic reported and fixed by Yu-Ting Tseng
* blocked_donor pointer handling fixes in proxy-rwsem logic, related to blocked_donor issues Mathieu raised in this set.
Issues still to address with the full series:
* Need to polish and fold down changes in the full series, as my focus on this chunk of the set I’m submitting for review has left the rest of the series a little messy.
* Beyond the migrate_task_rq() correctness issue, Yu-Ting Tseng found some issues with PELT handling with proxy-exec that I’m evaluating how to best fix.
* Need to update and include Suleiman’s latest Proxy enabled futexes series, which fixes a lot of recently uncovered edge cases.
* Maria Yu raised a subtle difference in how the nr_iowait counting might be attributed with proxy-exec: potentially proxy-migrated donors that become blocked on sleeping owners could increment/decrement the value on the owners cpu rq, instead of on the donor’s original cpu rq. It’s unclear to me what the impact of this would be, if at all, but it is potentially an observable difference with proxy-exec, so I’m going to take a swing at addressing it.
* Reevaluate performance regression K Prateek Nayak found with the full series earlier.
* The chain migration functionality needs further iterations and better validation to ensure it truly maintains the RT/DL load balancing invariants (despite this being broken in vanilla upstream with RT_PUSH_IPI currently)
Future work:
* Expand to more locking primitives: Binder PI is something else we’re exploring.
* Eventually: Work to replace rt_mutexes and get things happy with PREEMPT_RT
Credit/Disclaimer:
—--------------------
As always, this Proxy Execution series has a long history with lots of developers that deserve credit:
First described in a paper[1] by Watkins, Straub, Niehaus, then from patches from Peter Zijlstra, extended with lots of work by Juri Lelli, Valentin Schneider, and Connor O'Brien. (and thank you to Steven Rostedt for providing additional details here!). Thanks also to Joel Fernandes, Dietmar Eggemann, Metin Kaya, K Prateek Nayak, Suleiman Souhlal, Christian Loehle, and Andrea Righi for their substantial review, suggestion, and patch contributions.
So again, many thanks to those above, as all the credit for this series really is due to them - while the mistakes are surely mine.
Thanks so much!
-john
[1] https://static.lwn.net/images/conf/rtlws11/papers/proc/p38.pdf
Hui Su (1):
sched/proxy: Detect cycles in proxy walks earlier
John Stultz (5):
sched/psi: Preserve sleep-persistent PSI flags on off-CPU sleeping
dequeues
sched/mutex: Use READ_ONCE/WRITE_ONCE for concurrent blocked_donor
accesses
sched/proxy: Avoid transient blocked_donor cycles sched/deadline: Try to handle dl bandwidth properly with proxy
blocked-waiter activations
rcu-tasks: Treat proxy-exec blocked tasks as voluntary sleeps
K Prateek Nayak (1):
sched/core: Activate blocked donor when no owner is found
Mathieu Desnoyers (3):
sched/proxy: Reschedule when a blocked task is woken under a proxy sched/proxy: Wake blocked RT and deadline tasks through the full path sched/proxy: Clear blocked_donor when the donor stops donating
Peter Zijlstra (1):
sched/proxy: Add deactivated (sleeping) owner handling to
find_proxy_task()
Shubhang Kaushik (Ampere) (1):
sched/core: Use the scheduling context for remote ticks
Yu-Ting Tseng (1):
sched/proxy: Invoke migrate_task_rq() on proxy-migration
zhidao su (Xiaomi) (1):
sched/proxy: Break cyclic proxy chains by deactivating blocked tasks
include/linux/sched.h | 7 + include/linux/sched/task.h | 1 + init/init_task.c | 6 + kernel/fork.c | 6 + kernel/locking/mutex.c | 4 +- kernel/rcu/tasks.h | 45 ++-- kernel/sched/core.c | 527 ++++++++++++++++++++++++++++++++----- kernel/sched/deadline.c | 14 +- kernel/sched/stats.h | 28 +- 9 files changed, 547 insertions(+), 91 deletions(-)
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 1/14 sched/psi: Preserve sleep-persistent PSI flags on off-CPU sleeping dequeues
Normally, when a task goes to sleep (DEQUEUE_SLEEP), psi_dequeue() does nothing because psi_sched_switch() -> psi_task_switch() immediately follows and handles the runnable-to-sleeping PSI transition (clearing TSK_ONCPU, TSK_RUNNING, and TSK_MEMSTALL_RUNNING, setting TSK_IOWAIT, and leaving sleep-persistent TSK_MEMSTALL set).
With Proxy Execution, mutex-blocked tasks stay on the runqueue across context switches, so psi_sched_switch() runs with sleep=false and only clears TSK_ONCPU. If the blocked donor task is later deactivated via block_task(), psi_dequeue() is called with DEQUEUE_SLEEP while TSK_ONCPU is already cleared.
Commit c2ae8b0df2d1 ("sched/core: Fix psi_dequeue() for Proxy Execution") checked for (flags & DEQUEUE_SLEEP) && (p->psi_flags & TSK_ONCPU), falling through topsi_task_change(p, p->psi_flags, 0) when TSK_ONCPU was not set. However, clearing all of p->psi_flags treats the sleeping dequeue as a migration and wipes sleep-persistent flags like TSK_MEMSTALL (and fails to set TSK_IOWAIT).
When the task later wakes up on the same cpu without ENQUEUE_MIGRATED, psi_enqueue() assumes TSK_MEMSTALL is still set from when the task went to sleep and only sets TSK_RUNNING | TSK_MEMSTALL_RUNNING. This leaves things in an inconsistent state (TSK_MEMSTALL_RUNNING set without TSK_MEMSTALL), causing psi.mem.full to exceed psi.mem.some, delta underflows in get_recent_times(), and spurious psi.mem.full events.
So fix psi_dequeue() such that when DEQUEUE_SLEEP is set and TSK_ONCPU is not set, we do the same runnable-to-sleeping flag transition as psi_task_switch() (clearing TSK_RUNNING and TSK_MEMSTALL_RUNNING, setting TSK_IOWAIT, and preserving TSK_MEMSTALL).
Tejun also noted this issue could be reproduced without CONFIG_SCHED_PROXY_EXEC:
https://lore.kernel.org/lkml/[email protected]/
---
v34:
* Uses K Prateek's suggestion to reorder logic and preserve single psi_task_change call
* Also use K Prateek's suggestion to use DEQUEUE_DELAYED check instead of p->se.sched_delayed which Peter objected to.
--- kernel/sched/stats.h | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-)
kernel/sched/stats.h +22 -6
@@ -161,6 +161,9 @@ static inline void psi_enqueue(struct task_struct *p, int flags)static inline void psi_dequeue (struct task_struct *p,int flags) { +int clear = p->psi_flags; +int set =0 ; +if (static_branch_likely (&psi_disabled))return ;
@@ -175,18 +178,31 @@ static inline void psi_dequeue(struct task_struct *p, int flags)* Do nothing here. * * In the SCHED_PROXY_EXECUTION case we may do sleeping -* dequeues that are not followed by a task switch, so check -* TSK_ONCPU is set to ensure the task switch is imminent. -* Otherwise clear the flags as usual. +* dequeues that are not followed by a task switch. If TSK_ONCPU +* is not set (meaning we already switched away while the task +* stayed on the rq as a blocked donor), handle the sleeping +* state transition here so sleep-persistent states (TSK_MEMSTALL, +* TSK_IOWAIT) are preserved. */ -if ((flags &DEQUEUE_SLEEP ) && (p->psi_flags &TSK_ONCPU )) -return ; +if (flags &DEQUEUE_SLEEP ) { + clear =TSK_RUNNING ; + +if (p->psi_flags &TSK_ONCPU ) +return ; +if (flags &DEQUEUE_DELAYED ) +return ; + +if (p->in_memstall) + clear |=TSK_MEMSTALL_RUNNING ; +if (p->in_iowait) + set |=TSK_IOWAIT ; + }/* * When migrating a task to another CPU, clear all psi * state. The enqueue callback above will work it out. */ -psi_task_change (p, p->psi_flags,0 ); +psi_task_change (p, clear, set); }static inline void psi_ttwu_dequeue (struct task_struct *p)
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 2/14 sched/core: Use the scheduling context for remote ticks
In reply to John StultzFrom: "Shubhang Kaushik (Ampere)" <[email protected]>
sched_tick_remote() assumes that a CPU in full dynticks mode has only one running task. It therefore assumes that proxy execution cannot be active and that rq->curr == rq->donor.
However, sched_can_stop_tick() can stop the tick with multiple tasks on the runqueue. With exactly one SCHED_RR task, the tick is not needed for round-robin timeslice rotation. When there are no SCHED_RR tasks, SCHED_FIFO tasks do not require the tick because they have no forced tick preemption. Lower scheduling-class tasks can still be queued in both cases.
Consequently, a SCHED_FIFO task blocked on a SCHED_NORMAL mutex owner can remain rq->donor while find_proxy_task() selects the owner to execute as rq->curr. sched_tick_remote() can therefore run with rq->curr != rq->donor.
The full-nohz state check in sched_tick_remote() is intentionally racy and can allow an extra or missed remote tick. This issue does not rely on that race: the tick can be legitimately stopped in the cases above.
Use rq->donor for the remote class tick and its full-nohz tick-interval sanity check, matching sched_tick() and hrtick().
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/core.c | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-)
kernel/sched/core.c +4 -10
@@ -5966,26 +5966,20 @@ static void sched_tick_remote(struct work_struct *work)*/ if (tick_nohz_tick_stopped_cpu (cpu)) {guard (rq_lock_irq)(rq); -struct task_struct *curr = rq->curr; +struct task_struct *donor = rq->donor;if (cpu_online (cpu)) { -/* -* Since this is a remote tick for full dynticks mode, -* we are always sure that there is no proxy (only a -* single task is running). -*/ -WARN_ON_ONCE (rq->curr != rq->donor);update_rq_clock (rq); -if (!is_idle_task (curr)) { +if (!is_idle_task (donor)) {/* * Make sure the next tick runs within a * reasonable amount of time. */ -u64 delta =rq_clock_task (rq) - curr->se.exec_start; +u64 delta =rq_clock_task (rq) - donor->se.exec_start;WARN_ON_ONCE (delta > (u64 )NSEC_PER_SEC *30 ); } - curr->sched_class->task_tick (rq, curr,0 ); + donor->sched_class->task_tick (rq, donor,0 );calc_load_nohz_remote (rq); }
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 3/14 sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to John StultzFrom: Mathieu Desnoyers <[email protected]>
With proxy execution, a task blocked on a mutex stays on its runqueue. The scheduler can pick it as the donor and run the mutex owner in its place. When the donor is woken, the CPU must stop running the owner on the donor's context.
Commit 7918cf369361 ("sched/proxy: Only return migrate when needed") wakes a blocked task in place when it is still on its original CPU. ttwu_runnable() then relies on wakeup_preempt() to preempt the running task. But every class compares the woken task with rq->donor. When the woken task is the donor, it compares the task with itself, and no reschedule is requested. Only sched_ext handles this, with WF_TTWU_RQ.
So the old owner keeps the donor's context after the mutex hand-off or after a signal. With a SCHED_FIFO donor nothing bounds this: the owner runs at the donor's priority until it blocks. With a SCHED_DEADLINE donor the owner consumes the donor's runtime.
In a test on one CPU, a SCHED_OTHER owner kept spinning in user space after it released the mutex. A SCHED_FIFO waiter then ran 800ms late. A SCHED_DEADLINE waiter ran one period late.
The same would happen when a task in the middle of a chain is woken. proxy_needs_return() resets the donor only when the woken task is the donor.
Fix this in ttwu_runnable(). When a blocked task is woken on a runqueue that runs a proxy, reschedule. The next pick walks the chain again. A blocked task outside the donor's chain causes a harmless reschedule too.
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/core.c | 8 ++++++++ 1 file changed, 8 insertions(+)
kernel/sched/core.c +8 -0
@@ -3981,6 +3981,14 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)if (p->is_blocked) {if (p->se.sched_delayed)enqueue_task (rq, p,ENQUEUE_NOCLOCK |ENQUEUE_DELAYED ); +/* +* If we're waking a blocked task and we are +* currently proxying, force a resched in case +* the woken task p is in the current donor chain +*/ +if (rq->donor != rq->curr) +resched_curr (rq); +if (proxy_needs_return (rq, p))return 0 ; }
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 4/14 sched/proxy: Wake blocked RT and deadline tasks through the full path
In reply to John StultzFrom: Mathieu Desnoyers <[email protected]>
With proxy execution, a task blocked on a mutex stays on its runqueue. The RT and deadline classes do not put such a task on their pushable lists. enqueue_task_rt() and put_prev_task_rt() skip a blocked task. enqueue_task_dl() and put_prev_task_dl() do the same. find_proxy_task() migrates it instead.
Commit 7918cf369361 ("sched/proxy: Only return migrate when needed") wakes a blocked task in place when it is still on its original CPU. That wake-up does no enqueue. It also skips select_task_rq() and the task_woken() method of the class. So the woken task is runnable, but it is not pushable, and no other CPU can pull it.
A SCHED_FIFO task woken this way waits behind a higher priority task while another CPU is idle. In a test on two CPUs, it ran 500ms after the mutex was released, when the higher priority task stopped. Without proxy execution it ran at once on the idle CPU. The test uses SCHED_FIFO. The deadline class has the same code path.
Fix this in proxy_needs_return(). An RT or deadline task takes the full wake-up path, as a task that was proxy-migrated does. The other classes keep the in-place wake-up.
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/sched/core.c +6 -1
@@ -3875,8 +3875,13 @@ static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p)* only set p->wake_cpu when !p->on_rq, and since here p->on_rq, this * will not apply. But if it did, this check is the safe way around * and would migrate. +* +* The RT and deadline classes place a task at wake-up: +* select_task_rq(), the pushable list, a push to another CPU. An +* in-place wake-up skips all of that. So their tasks take the full +* wake-up path too. */ -if (task_cpu (p) == p->wake_cpu) +if (task_cpu (p) == p->wake_cpu && !rt_or_dl_task (p))return false; scoped_guard(raw_spinlock, &p->blocked_lock) {
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 5/14 sched/proxy: Clear blocked_donor when the donor stops donating
In reply to John StultzFrom: Mathieu Desnoyers <[email protected]>
find_proxy_task() sets owner->blocked_donor to the task that donates to the owner. __mutex_unlock_slowpath() reads current->blocked_donor to hand the mutex to that task. The comment of the field says that it is set in schedule() and only stable under preempt_disable(). So the pointer is valid until the owner schedules again.
But the donor can stop donating while the owner keeps running. It is woken, or a change of its scheduling class or of its affinity takes it off the runqueue. The owner keeps its blocked_donor until it schedules. Meanwhile the donor can run on another CPU and exit.
This would be a use after free: __mutex_unlock_slowpath() would take the blocked_lock of a freed task. It was found by reading the code, and has not been reproduced. The owner must stay in the kernel without scheduling for as long as the donor needs to exit and be freed.
Fix this by clearing rq->curr->blocked_donor when the task it points at is woken, or leaves the runqueue in sched_proxy_block_task() or via deactivate_task(). The clear takes the blocked_lock of the running task, which the unlock path holds while it uses the pointer.
[jstultz: Minor tweaks. Moved call to deactivate_task() to catch
the case more generally then calling from numerous other sites]
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/core.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+)
kernel/sched/core.c +34 -0
@@ -2186,6 +2186,8 @@ static inline void uclamp_post_fork(struct task_struct *p) { }static inline void init_uclamp (void ) { }#endif /* !CONFIG_UCLAMP_TASK */ +static inline void proxy_clear_curr_donor (struct rq *rq,struct task_struct *p); +bool sched_task_on_rq (struct task_struct *p) {return task_on_rq_queued (p);
@@ -2275,6 +2277,9 @@ void deactivate_task(struct rq *rq, struct task_struct *p, int flags)WRITE_ONCE (p->on_rq,TASK_ON_RQ_MIGRATING );ASSERT_EXCLUSIVE_WRITER (p->on_rq); +/* check curr's blocked_donor back pointer and clear it if it is p */ +proxy_clear_curr_donor (rq, p); +/* * Code explicitly relies on TASK_ON_RQ_MIGRATING begin set *before* * dequeue_task() and cleared *after* enqueue_task().
@@ -2612,6 +2617,33 @@ static inline bool is_cpu_allowed(struct task_struct *p, int cpu)* is done. */ +#ifdef CONFIG_SCHED_PROXY_EXEC +/* +* @p stops donating on @rq: it is woken, or it leaves the runqueue. The +* task that runs can still point at @p with blocked_donor until it +* schedules, and __mutex_unlock_slowpath() dereferences that pointer. +* Meanwhile @p can run on another CPU and exit. So clear the pointer. +* The unlock path reads it under the blocked_lock of the running task. +*/ +static inline void proxy_clear_curr_donor (struct rq *rq,struct task_struct *p) +{ +struct task_struct *curr = rq->curr; + +lockdep_assert_rq_held (rq); + +if (READ_ONCE (curr->blocked_donor) != p) +return ; + +guard (raw_spinlock)(&curr->blocked_lock); +if (curr->blocked_donor == p) +WRITE_ONCE (curr->blocked_donor,NULL ); +} +#else /* !CONFIG_SCHED_PROXY_EXEC */ +static inline void proxy_clear_curr_donor (struct rq *rq,struct task_struct *p) +{ +} +#endif /* !CONFIG_SCHED_PROXY_EXEC */ +/* * move_queued_task - move a queued task to new rq. *
@@ -3864,6 +3896,7 @@ static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p) {bool dequeued; +proxy_clear_curr_donor (rq, p);/* * Typically per __set_task_cpu(), task_cpu(p) == p->wake_cpu. *
@@ -6947,6 +6980,7 @@ void sched_proxy_block_task(struct rq *rq, struct task_struct *p)if (WARN_ON_ONCE (state ==TASK_RUNNING ))return ; +proxy_clear_curr_donor (rq, p);if (task_current_donor (rq, p))proxy_reset_donor (rq);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 6/14 sched/mutex: Use READ_ONCE/WRITE_ONCE for concurrent blocked_donor accesses
In reply to John StultzWith Mathieu's change adding proxy_clear_curr_donor(), it is able to clear curr->blocked_donor from a remote CPU under rq->lock and curr->blocked_lock while curr is reading/writing blocked_donor without holding the lock.
So switch the blocked_donor reads and writes to use READ_ONCE/WRITE_ONCE.
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/locking/mutex.c | 4 ++-- kernel/sched/core.c | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-)
kernel/locking/mutex.c +2 -2
@@ -1009,7 +1009,7 @@ static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigneMUTEX_WARN_ON (__owner_task (owner) != current);MUTEX_WARN_ON (owner &MUTEX_FLAG_PICKUP ); -if (sched_proxy_exec () && current->blocked_donor) { +if (sched_proxy_exec () &&READ_ONCE (current->blocked_donor)) {/* force handoff if we have a blocked_donor */ owner =MUTEX_FLAG_HANDOFF ;break ;
@@ -1045,7 +1045,7 @@ static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigneif (next_lock == lock) { next =get_task_struct (donor);__clear_task_blocked_on (next, lock); - current->blocked_donor =NULL ; +WRITE_ONCE (current->blocked_donor,NULL ); }raw_spin_unlock (&donor->blocked_lock); }
kernel/sched/core.c +3 -3
@@ -7050,7 +7050,7 @@ static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf,* before we release the lock. */ proxy_resched_idle (rq); -for (; p; p = p->blocked_donor) { +for (; p; p =READ_ONCE (p->blocked_donor)) {WARN_ON (p == rq->curr);deactivate_task (rq, p,DEQUEUE_NOCLOCK );proxy_set_task_cpu (p, target_cpu);
@@ -7225,7 +7225,7 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)* rq, therefore holding @rq->lock is sufficient to * guarantee its existence, as per ttwu_remote(). */ - owner->blocked_donor = p; +WRITE_ONCE (owner->blocked_donor, p); }WARN_ON_ONCE (owner && !owner->on_rq);
@@ -7393,7 +7393,7 @@ static void __sched notrace __schedule(int sched_mode)struct task_struct *prev_donor = rq->donor;rq_set_donor (rq, next); - next->blocked_donor =NULL ; +WRITE_ONCE (next->blocked_donor,NULL );if (unlikely (next->is_blocked)) { next =find_proxy_task (rq, next, &rf);if (!next) {
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 7/14 sched/proxy: Avoid transient blocked_donor cycles
In reply to John StultzIf a lock cycle has been introduced, it is possible the backwards pointing blocked_donor could be set to a similar cycle before calling proxy_migrate_task()
So as we traverse the p->blocked_donor in preparation to migrate the tasks, clear the blocked_donor value each step, so we only visit each node once.
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/sched/core.c +6 -1
@@ -7050,7 +7050,11 @@ static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf,* before we release the lock. */ proxy_resched_idle (rq); -for (; p; p =READ_ONCE (p->blocked_donor)) { +while (p &&task_on_rq_queued (p)) { +struct task_struct *next =READ_ONCE (p->blocked_donor); + +/* clear blocked_donor so we can't end up in cycles */ +WRITE_ONCE (p->blocked_donor,NULL );WARN_ON (p == rq->curr);deactivate_task (rq, p,DEQUEUE_NOCLOCK );proxy_set_task_cpu (p, target_cpu);
@@ -7060,6 +7064,7 @@ static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf,* we hold the rq_lock. */ list_add (&p->se.group_node, &migrate_list); + p = next; }proxy_release_rq_lock (rq, rf);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 8/14 sched/proxy: Invoke migrate_task_rq() on proxy-migration
In reply to John StultzFrom: Yu-Ting Tseng <[email protected]>
Currently, proxy_set_task_cpu() calls __set_task_cpu(p, cpu) directly without calling p->sched_class->migrate_task_rq(p, cpu).
But when proxy_migrate_task() or do_activate_blocked_waiter() moves a blocked fair donor from src_rq to target_rq, p->se.avg.last_update_time remains non-zero, so activate_task(target_rq, p) skips attach_entity_load_avg().
When p subsequently wakes and return-migrates via set_task_cpu(), remove_entity_load_avg() subtracts p's never-attached load_avg/util_avg from target_rq, driving target_rq's root cfs_rq util toward zero and distorting cpufreq/EAS CPU selection.
So split out a __do_migrate_task_rq() helper from set_task_cpu(), and then re-use it in proxy_set_task_cpu().
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/core.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-)
kernel/sched/core.c +14 -7
@@ -3444,6 +3444,16 @@ void relax_compatible_cpus_allowed_ptr(struct task_struct *p)#ifdef CONFIG_SMP +static void __do_migrate_task_rq (struct task_struct *p,unsigned int new_cpu) +{ +if (task_cpu (p) != new_cpu) { +if (p->sched_class->migrate_task_rq) + p->sched_class->migrate_task_rq (p, new_cpu); + p->se.nr_migrations++; +perf_event_task_migrate (p); + } +} +void set_task_cpu (struct task_struct *p,unsigned int new_cpu) {unsigned int state =READ_ONCE (p->__state);
@@ -3493,15 +3503,11 @@ void set_task_cpu(struct task_struct *p, unsigned int new_cpu)trace_sched_migrate_task (p, new_cpu); -if (task_cpu (p) != new_cpu) { -if (p->sched_class->migrate_task_rq) - p->sched_class->migrate_task_rq (p, new_cpu); - p->se.nr_migrations++; -perf_event_task_migrate (p); - } - +__do_migrate_task_rq (p, new_cpu); __set_task_cpu(p, new_cpu); } +#else /* CONFIG_SMP */ +static inline void __do_migrate_task_rq (struct task_struct *p,unsigned int new_cpu) {}#endif /* CONFIG_SMP */ #ifdef CONFIG_NUMA_BALANCING
@@ -6929,6 +6935,7 @@ static inline void proxy_set_task_cpu(struct task_struct *p, int cpu)* was previously runnable. */ wake_cpu = p->wake_cpu; +__do_migrate_task_rq (p, cpu);__set_task_cpu (p, cpu); p->wake_cpu = wake_cpu; }
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 9/14 sched/core: Activate blocked donor when no owner is found
In reply to John StultzFrom: K Prateek Nayak <[email protected]>
mutex_unlock_slowpath() follows:
if (owner & MUTEX_FLAG_HANDOFF)
break /* ... and do __mutex_handoff() */
if (atomic_long_try_cmpxchg_release(&lock->owner, &owner, __owner_flags(owner))) {
if (owner & MUTEX_FLAG_WAITERS)
break; /* ... and wake up the first waiter. */
MUTEX_FLAG_HANDOFF is only set by first-waiter after it has been woken up and in absence of MUTEX_FLAG_HANDOFF, the owner clears itself from the lock_word and wakes up the first waiter to try a __mutex_trylock_or_handoff().
MUTEX_FLAG_HANDOFF exists to prevent new optimistic spinners from trying to hijack the lock from waiter all the time and potentially starving them but it is not necessary for MUTEX_FLAG_HANDOFF to be always set in presence of a waiter.
If a blocked donor is deactivated when no owner is observed, it may not be woken up until it becomes the first waiter and is naturally woken up which breaks proxy in the interim.
Wake up the blocked donor and allow it to grab the lock when no owner is observed. If the task manages to grab the lock, the block chain will follow at the next proxy migration. If the task fails to grab the lock, same situation is restored and everyone migrated to the CPU of new owner.
Similarly, do the same for the NULL blocked_on/mutex pointer for consistency.
This also lets us get rid of the early returns that Andrea pointed out were problematic for core scheduling.
---
v33:
* Added similar logic for the null mutex/blocked_on case v34:
* Andrea pointed out the early returns were problematic for core scheduling, so drop them both here.
* Also due to dropping early returns we may call wakeup on is_blocked current, which is ok, so drop WARN_ON
* Remove stale comment
--- kernel/sched/core.c | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-)
kernel/sched/core.c +22 -15
@@ -4431,7 +4431,6 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)* it disabling IRQs (this allows not taking ->pi_lock). */ WARN_ON_ONCE (p->se.sched_delayed); -WARN_ON_ONCE (p->is_blocked);/* If p is current, we know we can run here, so clear blocked_on */ clear_task_blocked_on (p,NULL );if (!ttwu_state_match (p, state, &success))
@@ -7025,6 +7024,19 @@ static inline void proxy_reacquire_rq_lock(struct rq *rq, struct rq_flags *rf)update_rq_clock (rq); } +static void +proxy_activate (struct rq *rq,struct rq_flags *rf,struct task_struct *p) +__must_hold (__rq_lockp (rq)) +{ +lockdep_assert_rq_held (rq); +proxy_resched_idle (rq); +proxy_release_rq_lock (rq, rf); + +wake_up_process (p); + +proxy_reacquire_rq_lock (rq, rf); +} +/* * If the blocked-on relationship crosses CPUs, migrate @p to the * owner's CPU.
@@ -7118,15 +7130,11 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)/* Follow blocked_on chain. */ for (p = donor; p->is_blocked; p = owner) { -/* if its PROXY_WAKING, do return migration or run if current */ struct mutex *mutex = p->blocked_on; +if (!mutex) {clear_task_blocked_on (p, mutex); -if (task_current (rq, p)) { -unblock_task (p); -return p; - } - goto deactivate; + goto activate; }/*
@@ -7153,16 +7161,12 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) owner =__mutex_owner (mutex);if (!owner) {/* -* If there is no owner, either clear blocked_on -* and return p (if it is current and safe to -* just run on this rq), or return-migrate the task. +* If there is no owner, clear blocked_on +* and wake the task to try and grab the +* lock it is waiting on. */ __clear_task_blocked_on (p,NULL ); -if (task_current (rq, p)) { -unblock_task (p); -return p; - } - goto deactivate; + goto activate; }if (!READ_ONCE (owner->on_rq) || owner->se.sched_delayed) {
@@ -7252,6 +7256,9 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) resched_idle:return proxy_resched_idle (rq); +activate: +proxy_activate (rq, rf, p); +return NULL ; deactivate:proxy_deactivate (rq, p);return NULL ;
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 10/14 sched/proxy: Break cyclic proxy chains by deactivating blocked tasks
In reply to John StultzFrom: "zhidao su (Xiaomi)" <[email protected]>
find_proxy_task() follows the blocked_on/owner chain for a blocked donor. If the chain forms a cycle, __schedule() can keep walking the same chain while holding rq->lock.
Kernel locks are not allowed to have cycles (except ww_mutexes, which we handle properly), so this logic isn't likely to trip unless a bad driver has incorrect locking (which lockdep should detect). However, eventually we want to have proxy-enabled futexes, where we can't control userland's locking, and will need to avoid wasting cpu time iterating around a cycle.
Rescheduling idle is not enough here: the same blocked_on relation remains, so the next scheduling pass can select the same donor and re-enter the same cycle.
So if we hit an excessive chain depth, clear the blocked_on relation and deactivate the blocked task. This removes the task from the proxy-exec runnable-chain selection path and lets the scheduler make progress.
Use 1024 as the depth limit to match rtmutex's default max_lock_depth.
[jstultz: Simplified slightly, dropping WARN_ON and owner == donor
check, slightly reworked commit message, added curr_in_chain check]
---
v34:
* Added curr_in_chain check to make sure we don't deactivate current.
* Included fixes tag suggested by Kayra Cizmeci
--- kernel/sched/core.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
kernel/sched/core.c +12 -0
@@ -7092,6 +7092,8 @@ static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf,proxy_reacquire_rq_lock (rq, rf); } +#define MAX_PROXY_CHAIN_DEPTH 1024 +/* * Find runnable lock owner to proxy for mutex blocked donor *
@@ -7127,6 +7129,7 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)int this_cpu =cpu_of (rq);struct task_struct *p;int owner_cpu; +int chain_depth =0 ;/* Follow blocked_on chain. */ for (p = donor; p->is_blocked; p = owner) {
@@ -7236,6 +7239,15 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)*/ goto resched_idle; } + +/* Limit the depth we'll proxy to avoid cyclic deadlocks */ +if (++chain_depth >MAX_PROXY_CHAIN_DEPTH ) { +if (curr_in_chain) +return proxy_resched_idle (rq); +__clear_task_blocked_on (p,NULL ); + goto deactivate; + } +/* * OK, now we're absolutely sure @owner is on this * rq, therefore holding @rq->lock is sufficient to
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 11/14 sched/proxy: Detect cycles in proxy walks earlier
In reply to John StultzFrom: Hui Su <[email protected]>
Proxy execution follows blocked_on relationships to find a runnable lock owner. A cycle in that chain can make find_proxy_task() loop indefinitely while holding rq->lock.
Use Brent checkpoint state directly in the real owner walk. Cycle detection reuses the owner resolution already performed by that walk and requires no separate preflight traversal. The checkpoint, power, and span state are all invocation-local.
Keep the existing owner == p wakeup-race handling ahead of cycle detection. Unlike a sequence-marker approach, this adds no task_struct or runqueue state and requires no activation-time reset.
[jstultz: Minor tweaks to work with hard MAX_PROXY_CHAIN_DEPTH limit,
and shortened the commit message.]
---
v34:
* Dropped bit of the commit message referencing an older cover letter as suggested by Kayra Cizmeci
--- kernel/sched/core.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-)
kernel/sched/core.c +16 -2
@@ -7125,6 +7125,9 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)__must_hold (__rq_lockp (rq )) {struct task_struct *owner =NULL ; +struct task_struct *cycle_checkpoint = donor; +unsigned int cycle_power =1 ; +unsigned int cycle_span =0 ;bool curr_in_chain = false;int this_cpu =cpu_of (rq);struct task_struct *p;
@@ -7135,6 +7138,12 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)for (p = donor; p->is_blocked; p = owner) {struct mutex *mutex = p->blocked_on; +if (cycle_span == cycle_power) { + cycle_checkpoint = p; + cycle_power <<=1 ; + cycle_span =0 ; + } +if (!mutex) {clear_task_blocked_on (p, mutex); goto activate;
@@ -7240,8 +7249,13 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) goto resched_idle; } -/* Limit the depth we'll proxy to avoid cyclic deadlocks */ -if (++chain_depth >MAX_PROXY_CHAIN_DEPTH ) { +/* +* Check for cycles, and worst case limit the depth +* we'll proxy to avoid cyclic deadlocks +*/ + cycle_span++; +if (owner == cycle_checkpoint || + (++chain_depth >MAX_PROXY_CHAIN_DEPTH )) {if (curr_in_chain)return proxy_resched_idle (rq);__clear_task_blocked_on (p,NULL );
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 12/14 sched/deadline: Try to handle dl bandwidth properly with proxy blocked-waiter activations
In reply to John StultzAndrea raised an interesting point that with the proxy-exec sleeping owner enqueuing logic (added later in this series) we could confuse the deadline bandwidth calculations.
The case is when a task blocked on a lock owned by a sleeping owner is enqueued on that sleeping owner and off the runqueue, then when the owner wakes up, we enqueue all the waiters onto the same rq as the owner.
With earlier fixes in this series, we do now call migrate_task_rq() when this occurs, but the migrate_task_rq_dl() implementation will bail when task->__state != TASK_WAKING.
So following K Prateek and Juri's suggestion[1] soften this a bit so that we catch the case where a is_blocked task which is also !task_on_rq_migrating() is changing cpus. Fixing it before we add the sleeping owner handling.
[1] https://lore.kernel.org/lkml/[email protected]/
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/sched/deadline.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +13 -1
@@ -2656,8 +2656,20 @@ static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unused {struct rq_flags rf;struct rq *rq; +bool proxy_blocked = false; -if (READ_ONCE (p->__state) !=TASK_WAKING ) +/* +* With proxy-exec we may have woken a sleeping lock owner, and are +* activating the blocked waiters that were enqueued upon the owner. +* These tasks' are still blocked, and not TASK_WAKING, but we still +* need to handle the migration logic to keep the bw sane. +* So make sure we don't bail out early if we are is_blocked and +* !task_on_rq_migrating() +*/ +if (sched_proxy_exec () &&READ_ONCE (p->is_blocked) && !task_on_rq_migrating (p)) + proxy_blocked = true; + +if (READ_ONCE (p->__state) !=TASK_WAKING && !proxy_blocked)return ; rq =task_rq (p);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 13/14 rcu-tasks: Treat proxy-exec blocked tasks as voluntary sleeps
In reply to John StultzWith proxy-execution, a task that voluntarily calls schedule() to block on a mutex sets p->is_blocked = 1 in try_to_block_task(), but remains queued on a runqueue (p->on_rq != 0) so it can donate priority/runtime to its lock owner.
However, rcu_tasks_is_holdout() only checks !READ_ONCE(t->on_rq) to detect a voluntary-sleep quiescent state. A proxy-blocked waiter can stay on, or be put back on, a runqueue without running, so its ->nvcsw doesn't change and it remains a "holdout" until it is woken to acquire the lock.
When combined with the proxy sleeping-owner-enqueuing feature (added later in this series), this can cause a boottime deadlock when CONFIG_PROVE_RCU runs rcu_tasks_initiate_self_tests() before rcu_tasks_kthread() publishes the rtp->kthread_ptr, if rcu_tasks_one_gp() acquires tasks_gp_mutex and then calls rcu_tasks_wait_gp() and polls for holdouts while the rcu_tasks_kthread() blocks on the tasks_gp_mutex.
Without the sleeping-owner-enqueuing feature, the rcu_tasks_wait_gp() lock holder will sleep, and then the task waiting in rcu_tasks_kthread() will be deactivated and removed from the rq, avoiding this problem.
But when the sleeping-owner-enqueuing feature is present, the blocked waiters are re-added to the runqueue when the lock owner wakes, causing the holdout detection to continue to wait.
So to avoid this, check sched_proxy_exec() && t->is_blocked in rcu_tasks_is_holdout() so proxy-blocked tasks are recognized as having reached a voluntary-sleep quiescent state.
Additionally, since we aren't taking locks, use READ/WRITE_ONCE() when accessing p->is_blocked.
Since try_to_block_task() also sets ->is_blocked for tasks that DELAY_DEQUEUE leaves on the runqueue, the new check also treats ->se.sched_delayed tasks as quiescent when proxy execution is enabled. rcu_tasks_is_holdout() previously kept those as holdouts only to be conservative. But they have voluntarily blocked too, so this only affects grace-period timing.
---
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: K Prateek Nayak <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Vincent Guittot <[email protected]>
Cc: Valentin Schneider <[email protected]>
Cc: Suleiman Souhlal <[email protected]>
Cc: Andrea Righi <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Metin Kaya <[email protected]>
Cc: Dietmar Eggemann <[email protected]>
Cc: Steven Rostedt <[email protected]>
Cc: Zimuzo Ezeozue <[email protected]>
Cc: Waiman Long <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Joel Fernandes <[email protected]>
Cc: Qais Yousef <[email protected]>
Cc: Xuewen Yan <[email protected]>
Cc: kuyo chang <[email protected]>
Cc: hupu <[email protected]>
Cc: Zhan Xusheng <[email protected]>
Cc: zhidao su (Xiaomi) <[email protected]>
Cc: Hui Su <[email protected]>
Cc: Shubhang Kaushik (Ampere) <[email protected]>
Cc: [email protected]
--- kernel/rcu/tasks.h | 45 ++++++++++++++++++++++++++++++--------------- kernel/sched/core.c | 4 ++-- 2 files changed, 32 insertions(+), 17 deletions(-)
kernel/rcu/tasks.h +30 -15
@@ -920,8 +920,9 @@ static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)// // rcu_tasks_pregp_step(): // Invokes synchronize_rcu() in order to wait for all in-flight -// t->on_rq and t->nvcsw transitions to complete. This works because -// all such transitions are carried out with interrupts disabled. +// t->on_rq, t->is_blocked, and t->nvcsw transitions to complete. +// This works because all such transitions are carried out with +// interrupts disabled. // rcu_tasks_pertask(), invoked on every non-idle task: // For every runnable non-idle task other than the current one, use // get_task_struct() to pin down that task, snapshot that task's
@@ -940,10 +941,10 @@ static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)// corresponding task is removed from the holdout list. // rcu_tasks_postgp(): // Invokes synchronize_rcu() in order to ensure that all prior -// t->on_rq and t->nvcsw transitions are seen by all CPUs and tasks -// to have happened before the end of this RCU Tasks grace period. -// Again, this works because all such transitions are carried out -// with interrupts disabled. +// t->on_rq, t->is_blocked, and t->nvcsw transitions are seen by all +// CPUs and tasks to have happened before the end of this RCU Tasks +// grace period. Again, this works because all such transitions are +// carried out with interrupts disabled. // // For each exiting task, the exit_tasks_rcu_start() and // exit_tasks_rcu_finish() functions add and remove, respectively, the
@@ -961,9 +962,9 @@ static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)static void rcu_tasks_pregp_step (struct list_head *hop) {/* -* Wait for all pre-existing t->on_rq and t->nvcsw transitions -* to complete. Invoking synchronize_rcu() suffices because all -* these transitions occur with interrupts disabled. Without this +* Wait for all pre-existing t->on_rq, t->is_blocked, and t->nvcsw +* transitions to complete. Invoking synchronize_rcu() suffices because +* all these transitions occur with interrupts disabled. Without this * synchronize_rcu(), a read-side critical section that started * before the grace period might be incorrectly seen as having * started after the grace period.
@@ -991,8 +992,22 @@ static bool rcu_tasks_is_holdout(struct task_struct *t)* traditional blocked state or get woken up without outside * dependencies), not considering it such should only affect timing. * -* Be conservative for now and not include it. +* So if proxy execution is not enabled, be conservative for now +* and not include it. +* +* If proxy execution is enabled, lock blocked tasks may remain on +* the runqueue, which could confuse this logic, making it seem to +* be a holdout. So use is_blocked to detect this case. +* +* However, is_blocked also is set for DELAY_DEQUEUE, so with proxy +* execution we *do* consider sched_delayed tasks to be quiescent +* +* In both cases, the is_blocked task voluntarily slept and has not +* run since, so it cannot be within an RCU-tasks read-side critical +* section. */ +if (sched_proxy_exec () &&READ_ONCE (t->is_blocked)) +return false;/* * Idle tasks (or idle injection) within the idle loop are RCU-tasks
@@ -1137,13 +1152,13 @@ static void check_all_holdout_tasks(struct list_head *hop,static void rcu_tasks_postgp (struct rcu_tasks *rtp) {/* -* Because ->on_rq and ->nvcsw are not guaranteed to have a full -* memory barriers prior to them in the schedule() path, memory +* Because ->on_rq, ->is_blocked, and ->nvcsw are not guaranteed to have +* full memory barriers prior to them in the schedule() path, memory * reordering on other CPUs could cause their RCU-tasks read-side * critical sections to extend past the end of the grace period. -* However, because these ->nvcsw updates are carried out with -* interrupts disabled, we can use synchronize_rcu() to force the -* needed ordering on all such CPUs. +* However, because these ->on_rq, ->is_blocked, and ->nvcsw updates +* are carried out with interrupts disabled, we can use +* synchronize_rcu() to force the needed ordering on all such CPUs. * * This synchronize_rcu() also confines all ->rcu_tasks_holdout * accesses to be within the grace period, avoiding the need for
kernel/sched/core.c +2 -2
@@ -3846,7 +3846,7 @@ static inline void unblock_task(struct task_struct *p)atomic_dec (&cpu_rq (p->iowait_cpu)->nr_iowait); } - p->is_blocked =0 ; +WRITE_ONCE (p->is_blocked,0 ); }/*
@@ -6900,7 +6900,7 @@ static bool try_to_block_task(struct rq *rq, struct task_struct *p,return false; } - p->is_blocked =1 ; +WRITE_ONCE (p->is_blocked,1 );if (p->in_iowait) { p->iowait_cpu =cpu_of (rq);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v34 14/14 sched/proxy: Add deactivated (sleeping) owner handling to find_proxy_task()
In reply to John StultzFrom: Peter Zijlstra <[email protected]>
If the blocked_on chain resolves to a sleeping owner, deactivate the donor task, and enqueue it on the sleeping owner task. Then re-activate it later when the owner is woken up.
NOTE: This has been particularly challenging to get working properly, and some of the locking is particularly awkward. I'd very much appreciate review and feedback for ways to simplify this.
---
v5:
* Split out from larger proxy patch
v6:
* Major rework, replacing the single list head per task with per-task list head and nodes, creating a tree structure so we only wake up descendants of the task woken.
* Reworked the locking to take the task->pi_lock, so we can avoid mid-chain wakeup races from try_to_wake_up() called by the ww_mutex logic.
v7:
* Drop unnecessary __nested lock annotation, as we already drop the lock prior.
* Add comments on #else & #endif lines, and clearer function names, and commit message tweaks as suggested by Metin Kaya
* Move activate_blocked_entities() call from ttwu_queue to try_to_wake_up() to simplify locking. Thanks to questions from Metin Kaya
* Fix irqsave/irqrestore usage now we call this outside where the pi_lock is held
* Fix activate_blocked_entitites not preserving wake_cpu
* Fix for UP builds
v8:
* Minor checkpatch fixup
* Drop proxy_deactivate and cleanups suggested by Metin v9:
* Fix bug causing possibly uninitialized cpu value to be used with activate_blocked_entities()
* Improved comment around preserving wake_cpu suggested by Metin
* Add additional lockdep asserts, suggested by Metin
* Tweaked placement of lockdep assert, suggested by Metin
* Fixed comment referring to structure entry name
* Fix to call proxy_resched_idle() _prior_ to calling proxy_enqueue_on_owner() where we deactivate the task, this avoids stale references to rq_selected() when the task may have been migrated to another rq.
* Fix to remove the blocked_head list at the start of activate_blocked_entities() so we only do a finite amount of work, avoiding a potential livelock of two cpus removing and adding tasks to the list at the same time if the owner went back to sleep while blocked entities were being woken.
v11:
* Big rework to get rid of recursion. Had to add another list item to the task_stuct to do this as we are in atomic context and cannot allocate memory while activating blocked entities. Will need to watch carefully for bugs, as switching to a list_head in the task_struct instead of a pointer on the stack opens up the potential for races on the shared state, but I think I've got the locking sorted.
* Moved proxy_set_task_cpu helper to earlier in the series
* Minor rework for try_to_deactivate_task changes
* Minor variable name cleanups suggested by Metin
v13:
* Switch to use donor from next for proxy_enqueue_on_owner
* Switch to using block_task instead of deactivate_task v14:
* Ensure we call block_task() last in proxy_enqueue_on_owner and not touch it again to avoid races where it might be activated on another cpu
* Make sure we activate blocked_entities when we exit from ttwu
* Fix to enqueue the last task in the chain (p) on the blocked owner instead of donor, so that we preserve the chain structure so mid-chain wakeups propagate properly
* Rework of sleeping_owner handling so that we properly deal with delayed-dequeued (sched_delayed) tasks (also removes now unused proxy_deactivate() logic)
v15:
* Rework do_activate_task to be activate_task() and have it call __activate_task(), suggested by Carlos Llamas
* Put task_struct additions under CONFIG_SCHED_PROXY_EXEC v16:
* Rework do_activate_blocked_waiter locking to use scoped_guard
* Rework find_proxy_task() logic to use guard
v18:
* Integrate Suleiman's suggested optimization to check sleeping owner status before task_cpu, to avoid unnecssarily proxy-migrating tasks to then just dequeue them.
* Add on_cpu check to fix for a very hard to reproduce race where a late blocked_task_activation() happens while the task is already on_cpu elsewhere. When we get to __schedule() we block the task (!on_rq) but haven't yet switched away. blocked_task_activation() would then incorrectly activate on a different runqueue.
* Add init_task initialization for sleeping owner lists, as suggested by Suleiman
v19:
* Build fixup for !CONFIG_SMP
v22:
* Rework to avoid gotos in guard() scopes, using break and switch() on action values. Suggested by K Prateek.
v25:
* Fix elevated nr_uninterruptible and nr_iowait counts, which were causing bad loadavg values. Reported and fixed by David Stevens <[email protected]>
v28:
* In __proxy_remove_from_sleeping_owner() we call put_task(), which might free the owner while we are still holing the owners->blocked_lock. So be sure
to get_task()/put_task() around the owner usage to ensure we don't prematurely free the task.
* Also reorder the put_task/unlock lines in activate_blocked_waiters(), to avoid a similar issue
v30:
* Optimize activate_blocked_waiters() so we don't do so much unnecessary work when proxy-exec is enabled. If there are no blocked waiters, we can return early.
v31:
* K Prateek's noticed a potential race where if a sleeping owner is woken in paralell with the waiter enquing itself on the sleeping owner, the waiting task could get stuck on that owner until it sleeps and is woken up again. So double check after we grab the blocked_lock to avoid this.
* Maria Yu and Tengfei Fan reported an issue with rq->nr_iowait values getting out of balance, and provided a helpful reproducer. To fix this, make sure we do the atomic_dec() in do_activate_blocked_waiter() before we call proxy_set_task_cpu() so we always dec on the same rq we inc'ed.
v32:
* Atul Kumar Pant noticed a task could wakeup and then sleep before we call into do_activate_blocked_waiter() and in that case we would activate the task on the target_rq. As the target_rq is where the owner is being woken on, if the waiter already woke and ran the activation could move it to a cpu outside its affinity mask. So add an extra is_blocked check to ensure the task is still blocked on the owner.
* PeterZ shared a number of cleanups utilizing guard to make the code simpler.
* PeterZ pointed out we could see owner races in proxy_remove_from_sleeping_owner(), so re-sample owner after we take the lock to ensure we're consistent, and add a BUG_ON in __proxy_remove_from_sleeping_owner() to enforce p->sleeping_owner == owner.
* PeterZ noted we're calling activate_blocked_waiters() extraniously in sched_ttwu_pending(), so drop that.
v33:
* David Stevens <[email protected]> reported seeing "psi: inconsistent task state!" warnings, which was caused when we activate the blocked waiter list, proxy-migrating the tasks to the owners' rq. Since we currently don't signal to the PSI layer, the TSK_MEMSTALL flag persists when the following activation happens, throwing the error. This results in the source CPU's count of TSK_MEMSTALL becoming permanently non-zero, leading to very exaggerated memory PSI.
To avoid this, check if the target_cpu is the task_cpu(p) and if not call psi_ttwu_dequeue() to clear the flags before the activation.
* David also noted that when activating blocked tasks, the enqueue flag was being set to ENQUEUE_MIGRATED if the owner's wake_flags had WF_MIGRATED set, but the waiters task_cpu may already be the target_cpu during the activation, so we shouldn't activate the waiters with ENQUEUE_MIGRATED in this case. So change the logic that sets ENQUEUE_MIGRATED to be where we check if the waiter's task_cpu == target_cpu
* It was reported that in some cases unblocked tasks were being placed outside of their CPU affinity mask. If the call to do_activate_blocked_waiter() was delayed, its possible the task has already been woken. We already have checks for task state == TASK_WAKING, p->on_rq, task_on_cpu(), but its still possible the task woke and then blocked again (sleeping or re-waiting on the same or different mutex). So before activating on the prior sleeping owner's rq, ensure the task_is_blocked() to make sure we don't migrate a sleeping task outside of its affinity mask.
v34:
* Fix spelling nits suggested by Andrea and Kayra
* Add fix to prevent reactivating TASK_DEAD tasks which could result in us tripping the BUG() in do_task_dead(). As reported by Jichao Zou <[email protected]>.
* Add some extra get/put tasks in activate_blocked_waiters to ensure if we were very delayed after releasing the owners lock that the tasks won't have been freed while we are in do_activate_blocked_waiter().
* Take blocked_lock earlier to address K Prateek's feedback on do_activate_blocked_waiter() race
* Pass DEQUEUE_SPECIAL to block_task() in proxy_enqueue_on_owner() to fix sched_delayed issue Kaya and Andrea raised
* Only call activate_blocked_tasks() if the task was actually woken, as suggseted by Andrea and Kaya
* Use wakeup_preempt() instead of resched_curr(), as suggested by K Prateek
* Drop unnecessary code format change suggested by K Prateek
--- include/linux/sched.h | 7 + include/linux/sched/task.h | 1 + init/init_task.c | 6 + kernel/fork.c | 6 + kernel/sched/core.c | 367 ++++++++++++++++++++++++++++++++++--- 5 files changed, 357 insertions(+), 30 deletions(-)
include/linux/sched.h +7 -0
@@ -1268,6 +1268,13 @@ struct task_struct {struct mutex *blocked_on;/* lock we're blocked on */ raw_spinlock_t blocked_lock; +#ifdef CONFIG_SCHED_PROXY_EXEC +struct list_head blocked_head;/* tasks blocked on this task */ +struct list_head blocked_node;/* our entry on someone elses blocked_head */ +/* Node for list of tasks to process blocked_head list for blocked entity activations */ +struct list_head blocked_activation_node; +struct task_struct *sleeping_owner;/* task our blocked_node is enqueued on */ +#endif /* * The task that is boosting this task; a back link for the current
include/linux/sched/task.h +1 -0
@@ -160,6 +160,7 @@ static inline void put_task_struct(struct task_struct *t) } DEFINE_FREE(put_task, struct task_struct *, if (_T) put_task_struct(_T)) +DEFINE_GUARD(get_task, struct task_struct *, get_task_struct(_T), put_task_struct(_T))static inline void put_task_struct_many (struct task_struct *t,int nr) {
init/init_task.c +6 -0
@@ -213,6 +213,12 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { &init_task.alloc_lock), #endif .blocked_donor =NULL , +#ifdef CONFIG_SCHED_PROXY_EXEC + .blocked_head =LIST_HEAD_INIT (init_task.blocked_head), + .blocked_node = LIST_HEAD_INIT(init_task.blocked_node), + .blocked_activation_node = LIST_HEAD_INIT(init_task.blocked_activation_node), + .sleeping_owner = NULL, +#endif #ifdef CONFIG_RT_MUTEXES .pi_waiters =RB_ROOT_CACHED , .pi_top_task = NULL,
kernel/fork.c +6 -0
@@ -2284,6 +2284,12 @@ __latent_entropy struct task_struct *copy_process( p->blocked_on =NULL ;/* not blocked yet */ p->blocked_donor =NULL ;/* nobody is boosting p yet */ +#ifdef CONFIG_SCHED_PROXY_EXEC +INIT_LIST_HEAD (&p->blocked_head); +INIT_LIST_HEAD (&p->blocked_node); +INIT_LIST_HEAD (&p->blocked_activation_node); + p->sleeping_owner =NULL ; +#endif #ifdef CONFIG_BCACHE p->sequential_io =0 ;
kernel/sched/core.c +337 -30
478 lines not on this page · raw message
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
K Prateek Nayak
reviewerRe: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to John StultzHello John,
Quoted 7 lines · John Stultz
From: Mathieu Desnoyers <[email protected]>
With proxy execution, a task blocked on a mutex stays on its runqueue. The scheduler can pick it as the donor and run the mutex owner in its place. When the donor is woken, the CPU must stop running the owner on the donor's context.
Quoted 6 lines
Commit
7918cf369361("sched/proxy: Only return migrate when needed") wakes a blocked task in place when it is still on its original CPU.ttwu_runnable()then relies onwakeup_preempt()to preempt the running task. But every class compares the woken task withrq->donor. When the woken task is the donor, it compares the task with itself, and no reschedule is requested. Onlysched_exthandles this, withWF_TTWU_RQ.
Question: proxy_needs_return() needed to grab the &p->blocked_lock to clear the p->blocked_on relationship previously but now that we have the p->is_blocked state, we probably don't have to touch p->blocked_on at all - a successful lock acquisition will clear it on the way out of mutex_lock_common().
We can perhaps re-arrange the checks in proxy_needs_return() as:
if (task_current(rq, p)) /* implies p->on_cpu && task_cpu(p) == p->wake_cpu */
return false; if (task_current_donor(rq, p)
proxy_reset_donor(rq)
if (task_cpu(p) == p->wake_cpu && !rt_dl_task(p))
return false; /* Do the dequeue; Don't touch p->blocked_on. */
That should automatically allow ttwu_runnable() calling wakeup_preempt() to do the right thing and since p->blocked_on is only used to traverse chain if p->is_blocked is true first, there should be no harm to retain that.
One of the fist thing that is done when the task runs on CPU is to re-establish that blocked_on relation which doesn't change now. Is there any harm in retaining it?
Quoted 6 lines
kernel/sched/core.c +0
-0@@ -3981,6 +3981,14 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)if (p->is_blocked) {
kernel/sched/core.c static int ttwu_runnable(struct task_struct *p, int wake_flags) · line 3991
Quoted 10 lines
kernel/sched/core.c +8
-0if (p->se.sched_delayed)enqueue_task (rq, p,ENQUEUE_NOCLOCK |ENQUEUE_DELAYED ); +/* +* If we're waking a blocked task and we are +* currently proxying, force a resched in case +* the woken task p is in the current donor chain +*/ +if (rq->donor != rq->curr) +resched_curr (rq); +
Principally, I don't have problem with this approach but being able to keep all the proxy related handling contained in proxy_needs_return() below would be nice :-)
Quoted 3 lines
kernel/sched/core.c +0
-0if (proxy_needs_return (rq, p))return 0 ; }
Signature · 2 lines
Thanks and Regards, Prateek
K Prateek Nayak
reviewerRe: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
Quoted 5 lines · K Prateek Nayak
We can perhaps re-arrange the checks in
proxy_needs_return()as:if (task_current(rq, p)) /* implies p->on_cpu && task_cpu(p) == p->wake_cpu */ return false;
Quoted 7 lines
if (
task_current_donor(rq, p)
proxy_reset_donor(rq)if (task_cpu(p) == p->wake_cpu && !rt_dl_task(p)) return false;/* Do the dequeue; Don't touch
p->blocked_on. */
So the enqueue_task_rt() and enqueue_task_dl() do actually look at p->blocked_on to queue that balance callback so I guess that clearing is needed after all.
But the re-ordering should be still fine - if task_current() is true we still haven't lost to schedule and the task is still queued on the original rq.
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH v34 04/14] sched/proxy: Wake blocked RT and deadline tasks through the full path
In reply to John StultzHello John,
Quoted 20 lines · John Stultz
From: Mathieu Desnoyers <[email protected]>
With proxy execution, a task blocked on a mutex stays on its runqueue. The RT and deadline classes do not put such a task on their pushable lists.
enqueue_task_rt()andput_prev_task_rt()skip a blocked task.enqueue_task_dl()andput_prev_task_dl()do the same.find_proxy_task()migrates it instead.Commit
7918cf369361("sched/proxy: Only return migrate when needed") wakes a blocked task in place when it is still on its original CPU. That wake-up does no enqueue. It also skipsselect_task_rq()and thetask_woken()method of the class. So the woken task is runnable, but it is not pushable, and no other CPU can pull it.A
SCHED_FIFOtask woken this way waits behind a higher priority task while another CPU is idle. In a test on two CPUs, it ran 500ms after the mutex was released, when the higher priority task stopped. Without proxy execution it ran at once on the idle CPU. The test usesSCHED_FIFO. The deadline class has the same code path.
Quoted 8 lines
Fix this in
proxy_needs_return(). An RT or deadline task takes the full wake-up path, as a task that was proxy-migrated does. The other classes keep the in-place wake-up.Fixes 7918cf369361 ("sched/proxy: Only return migrate when needed")Signed-off-by Mathieu Desnoyers <[email protected]>[jstultz: Simplified the conditional check a touch]Signed-off-by John Stultz <[email protected]>
Feel free to include:
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to K Prateek NayakQuoted 13 lines · K Prateek Nayak
Quoted 12 lines · John Stultz
kernel/sched/core.c +4
-0@@ -3981,6 +3981,14 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)if (p->is_blocked) {if (p->se.sched_delayed)enqueue_task (rq, p,ENQUEUE_NOCLOCK |ENQUEUE_DELAYED ); +/* +* If we're waking a blocked task and we are +* currently proxying, force a resched in case +* the woken task p is in the current donor chain
Quoted 8 lines
kernel/sched/core.c static int ttwu_runnable(struct task_struct *p, int wake_flags) · line 3991
Quoted 4 lines
kernel/sched/core.c +4
-0+*/ +if (rq->donor != rq->curr) +resched_curr (rq); +Principally, I don't have problem with this approach but being able to keep all the proxy related handling contained in
proxy_needs_return()below would be nice :-)
Yeah. Hrmm.. I had the same suggestion to Mathieu when he sent the patch, and I'm not sure why I didn't do it myself here. I feel like there was some reconsideration I had but I think I may have just been doing too many things at once at the time.
I'll go ahead and push it down now and if I recall or re-learn a reason it shouldn't be there I'll be sure to write it down. :P
thanks
-john
Re: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to K Prateek NayakQuoted 14 lines · K Prateek Nayak
Quoted 5 lines · K Prateek Nayak
We can perhaps re-arrange the checks in
proxy_needs_return()as:if (task_current(rq, p)) /* implies p->on_cpu && task_cpu(p) == p->wake_cpu */ return false;Quoted 7 lines
if (
task_current_donor(rq, p)
proxy_reset_donor(rq)if (task_cpu(p) == p->wake_cpu && !rt_dl_task(p)) return false;/* Do the dequeue; Don't touch
p->blocked_on. */
Quoted 7 lines
So the
enqueue_task_rt()andenqueue_task_dl()do actually look atp->blocked_onto queue that balance callback so I guess that clearing is needed after all.But the re-ordering should be still fine - if
task_current()is true we still haven't lost to schedule and the task is still queued on the original rq.
So just that I'm understanding you properly, the idea is just to rework the logic currently done under the blocked_lock, so after the patches in this series, proxy_needs_return() would look like:
{
proxy_clear_curr_donor(rq, p);
if (rq->donor != rq->curr)
resched_curr(rq);
if (task_current(rq, p))
return false;
if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p))
return false;
if (task_current_donor(rq, p))
proxy_reset_donor(rq);
clear_task_blocked_on(p, NULL);
block_task(rq, p, TASK_WAKING, 0);
}?
I'll give that a shot here.
I'm wondering if a if (!sched_proxy_exec()) return; shortcut at the top might be nice too since we may not want to trip up the rt/dl task case and do all the work, but I know Peter wasn't happy with that being sprinkled around.
Thanks again for all your thoughts and suggestions! -john
K Prateek Nayak
reviewerRe: [PATCH v34 05/14] sched/proxy: Clear blocked_donor when the donor stops donating
In reply to John StultzHello John, Mathieu,
Quoted 8 lines · John Stultz
From: Mathieu Desnoyers <[email protected]>
find_proxy_task()setsowner->blocked_donorto the task that donates to the owner.__mutex_unlock_slowpath()readscurrent->blocked_donorto hand the mutex to that task. The comment of the field says that it is set inschedule()and only stable underpreempt_disable(). So the pointer is valid until the owner schedules again.
Quoted 4 lines
But the donor can stop donating while the owner keeps running. It is woken, or a change of its scheduling class or of its affinity takes it off the runqueue. The owner keeps its
blocked_donoruntil it schedules. Meanwhile the donor can run on another CPU and exit.
So we can just clear it in proxy_reset_donor() right? Only current->blocked_donor is ever looked at and, it the proxy breaks mid way, the only path that can be taken is via ttwu_runnable().
If the task is retained on the same CPU, it is safe to get the reference since unlock is done with preempt disable - otherwise, we check:
donor = current->blocked_donor;
guard(&donor->blocked_lock);
next_lock = __get_task_blocked_on(donor);
if (next_lock == lock)
next = get_task_struct(donor);
...If ttwu_runnable() manages to clear the blocked_on relation first under the blocked lock then we don't take a reference here and if we manage to take a reference here, the task cannot exit unexpectedly - it'll just get a spurious wakeup in the worst case.
IMO, a simple READ_ONCE() to check it here and WRITE_ONCE() in proxy_reset_donor() after the re-arrangement suggested on Patch3 should do the trick based on my understanding.
o Race:
try_to_wake_up(donor) mutex_unlock_slowpath()
ttwu_runnable(rq, donor) /* MUTEX_HANDOFF */
proxy_needs_return(rq, donor) donor = current->blocked_donor;
proxy_reset_donor(rq) raw_spin_lock_nested(donor->blocked_lock)
WRITE_ONCE(rq->curr->blocked_donor, NULL); next = get_task_struct(donor);
... /* Donor wakes up runs, exits */ /*
* t->__state = TASK_DEAD
* t->usage != 0 so freeing is deferred wake_up_process(p)
*/ !ttwu_state_match()
put_task_struct()
/* Freed via RCU */If the task runs and blocks on a different lock, wake_up_process() from mutex_unlock_slowpath() (if it still think lock has not changed) will just lead to a spurious wakeup.
Is here a scenario where proxy_reset_donor() clearing is not enough?
Signature · 2 lines
Thanks and Regards, Prateek
K Prateek Nayak
reviewerRe: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to John StultzHello John,
Quoted 45 lines · John Stultz
Quoted 14 lines · K Prateek Nayak
Quoted 5 lines · K Prateek Nayak
We can perhaps re-arrange the checks in
proxy_needs_return()as:if (task_current(rq, p)) /* implies p->on_cpu && task_cpu(p) == p->wake_cpu */ return false;Quoted 7 lines
if (
task_current_donor(rq, p)
proxy_reset_donor(rq)if (task_cpu(p) == p->wake_cpu && !rt_dl_task(p)) return false;/* Do the dequeue; Don't touch
p->blocked_on. */Quoted 7 lines
So the
enqueue_task_rt()andenqueue_task_dl()do actually look atp->blocked_onto queue that balance callback so I guess that clearing is needed after all.But the re-ordering should be still fine - if
task_current()is true we still haven't lost to schedule and the task is still queued on the original rq.So just that I'm understanding you properly, the idea is just to rework the logic currently done under the
blocked_lock, so after the patches in this series,proxy_needs_return()would look like:{ proxy_clear_curr_donor(rq, p); if (rq->donor != rq->curr) resched_curr(rq); if (task_current(rq, p)) return false; if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p)) return false; if (task_current_donor(rq, p)) proxy_reset_donor(rq); clear_task_blocked_on(p, NULL); block_task(rq, p, TASK_WAKING, 0); }
Quoted 1 line
?
Almost! what I thought looks like:
{
if (task_current(rq, p))
return false;
if (task_current_donor(rq, p))
proxy_reset_donor(rq); /* Do proxy_clear_curr_donor() within */
if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p))
return false;
clear_task_blocked_on(p, NULL);
block_task(rq, p, TASK_WAKING, 0);
}Quoted 6 lines
I'll give that a shot here.
I'm wondering if a if (!sched_proxy_exec()) return; shortcut at the top might be nice too since we may not want to trip up the rt/dl task case and do all the work, but I know Peter wasn't happy with that being sprinkled around.
Ack! That makes sense given the rt_or_dl_task() condition.
Signature · 2 lines
Thanks and Regards, Prateek
K Prateek Nayak
reviewerRe: [PATCH v34 07/14] sched/proxy: Avoid transient blocked_donor cycles
In reply to John StultzHello John,
Quoted 5 lines · John Stultz
kernel/sched/core.c +0
-0
kernel/sched/core.c static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf, · line 7057
Quoted 9 lines
kernel/sched/core.c +5
-1@@ -7050,7 +7050,11 @@ static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf,* before we release the lock. */ proxy_resched_idle (rq); -for (; p; p =READ_ONCE (p->blocked_donor)) { +while (p &&task_on_rq_queued (p)) { +struct task_struct *next =READ_ONCE (p->blocked_donor); + +/* clear blocked_donor so we can't end up in cycles */ +WRITE_ONCE (p->blocked_donor,NULL );
Ooo! Interesting. I suppose this is still needed with Patch 10 and 11 because a ww_mutex unlock can suddenly clear a cycle before the Brent checkpoint can converge but the backwards link are already cyclic?
Quoted 3 lines
kernel/sched/core.c +0
-0WARN_ON (p == rq->curr);deactivate_task (rq, p,DEQUEUE_NOCLOCK );proxy_set_task_cpu (p, target_cpu);
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to K Prateek NayakQuoted 51 lines · K Prateek Nayak
Hello John,
Quoted 45 lines · John Stultz
Quoted 14 lines · K Prateek Nayak
Quoted 5 lines · K Prateek Nayak
We can perhaps re-arrange the checks in
proxy_needs_return()as:if (task_current(rq, p)) /* implies p->on_cpu && task_cpu(p) == p->wake_cpu */ return false;Quoted 7 lines
if (
task_current_donor(rq, p)
proxy_reset_donor(rq)if (task_cpu(p) == p->wake_cpu && !rt_dl_task(p)) return false;/* Do the dequeue; Don't touch
p->blocked_on. */Quoted 7 lines
So the
enqueue_task_rt()andenqueue_task_dl()do actually look atp->blocked_onto queue that balance callback so I guess that clearing is needed after all.But the re-ordering should be still fine - if
task_current()is true we still haven't lost to schedule and the task is still queued on the original rq.So just that I'm understanding you properly, the idea is just to rework the logic currently done under the
blocked_lock, so after the patches in this series,proxy_needs_return()would look like:{ proxy_clear_curr_donor(rq, p); if (rq->donor != rq->curr) resched_curr(rq); if (task_current(rq, p)) return false; if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p)) return false; if (task_current_donor(rq, p)) proxy_reset_donor(rq); clear_task_blocked_on(p, NULL); block_task(rq, p, TASK_WAKING, 0); }Quoted 1 line
?
Quoted 8 lines
Almost! what I thought looks like:
{
if (task_current(rq, p))
return false;if (
task_current_donor(rq, p))
proxy_reset_donor(rq); /* Doproxy_clear_curr_donor()within */
I don't think that would work. If there'a a chain A->B->C where A is the donor, and C is curr. If B wakes up, we need to do the proxy_clear_curr_donor() (since its C's->blocked_donor).
If we hide that under a task_current_donor() conditional, we'll only call it if p==A.
Also, your example skipped the:
if (rq->donor != rq->curr)
resched_curr(rq);bit which is what the patch at the start of this thread is focused on.
Quoted 7 lines
if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p))
return false;
clear_task_blocked_on(p, NULL);
block_task(rq, p, TASK_WAKING, 0);
}Quoted 8 lines
Quoted 6 lines
I'll give that a shot here.
I'm wondering if a if (!sched_proxy_exec()) return; shortcut at the top might be nice too since we may not want to trip up the rt/dl task case and do all the work, but I know Peter wasn't happy with that being sprinkled around.
Ack! That makes sense given the
rt_or_dl_task()condition.
I'll add that in as well then. The reordering/reworking the logic feels separate enough I'll do it in a separate patch from the original change here from Mathieu.
thanks
-john
K Prateek Nayak
reviewerRe: [PATCH v34 08/14] sched/proxy: Invoke migrate_task_rq() on proxy-migration
In reply to John StultzHello John,
kernel/sched/core.c void relax_compatible_cpus_allowed_ptr(struct task_struct *p) · line 3445
Quoted 7 lines · John Stultz
kernel/sched/core.c +0
-0@@ -3444,6 +3444,16 @@ void relax_compatible_cpus_allowed_ptr(struct task_struct *p)#ifdef CONFIG_SMP
I think it is more cleaner to take set_task_cpu() out of CONFIG_SMP block since UP will just do a redundant __set_task_cpu() ...
Quoted 34 lines
kernel/sched/core.c +13
-7+static void __do_migrate_task_rq (struct task_struct *p,unsigned int new_cpu) +{ +if (task_cpu (p) != new_cpu) { +if (p->sched_class->migrate_task_rq) + p->sched_class->migrate_task_rq (p, new_cpu); + p->se.nr_migrations++; +perf_event_task_migrate (p); + } +} +void set_task_cpu (struct task_struct *p,unsigned int new_cpu) {unsigned int state =READ_ONCE (p->__state);@@ -3493,15 +3503,11 @@ void set_task_cpu(struct task_struct *p, unsigned int new_cpu)trace_sched_migrate_task (p, new_cpu); -if (task_cpu (p) != new_cpu) { -if (p->sched_class->migrate_task_rq) - p->sched_class->migrate_task_rq (p, new_cpu); - p->se.nr_migrations++; -perf_event_task_migrate (p); - } - +__do_migrate_task_rq (p, new_cpu); __set_task_cpu(p, new_cpu); } +#else /* CONFIG_SMP */ +static inline void __do_migrate_task_rq (struct task_struct *p,unsigned int new_cpu) {}#endif /* CONFIG_SMP */ #ifdef CONFIG_NUMA_BALANCING
kernel/sched/core.c static inline void proxy_set_task_cpu(struct task_struct *p, int cpu) · line 6939
Quoted 5 lines
kernel/sched/core.c +1
-0@@ -6929,6 +6935,7 @@ static inline void proxy_set_task_cpu(struct task_struct *p, int cpu)* was previously runnable. */ wake_cpu = p->wake_cpu; +__do_migrate_task_rq (p, cpu);__set_task_cpu (p, cpu);
... and just convert this to use set_task_cpu().
We get the consistent sched_migrating traces to follow this task and if I'm not mistaken, all the checks in set_task_cpu() should be safe when called from all the proxy contexts after Andrea's fixes the.
Quoted 2 lines
kernel/sched/core.c +0
-0p->wake_cpu = wake_cpu; }
Signature · 2 lines
Thanks and Regards, Prateek
K Prateek Nayak
reviewerRe: [PATCH v34 03/14] sched/proxy: Reschedule when a blocked task is woken under a proxy
In reply to John StultzHello John,
Quoted 37 lines · John Stultz
Quoted 24 lines
Quoted 22 lines
So just that I'm understanding you properly, the idea is just to rework the logic currently done under the
blocked_lock, so after the patches in this series,proxy_needs_return()would look like:{ proxy_clear_curr_donor(rq, p); if (rq->donor != rq->curr) resched_curr(rq); if (task_current(rq, p)) return false; if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p)) return false; if (task_current_donor(rq, p)) proxy_reset_donor(rq); clear_task_blocked_on(p, NULL); block_task(rq, p, TASK_WAKING, 0); }Quoted 1 line
?
Quoted 8 lines
Almost! what I thought looks like:
{
if (task_current(rq, p))
return false;if (
task_current_donor(rq, p))
proxy_reset_donor(rq); /* Doproxy_clear_curr_donor()within */I don't think that would work. If there'a a chain
A->B->Cwhere A is the donor, and C is curr. If B wakes up, we need to do theproxy_clear_curr_donor()(since its C's->blocked_donor).
Quoted 8 lines
If we hide that under a
task_current_donor()conditional, we'll only call it if p==A.Also, your example skipped the:
if (rq->donor != rq->curr) resched_curr(rq);bit which is what the patch at the start of this thread is focused on.
Ah! I see. So any part of chain currently proxying should call a resched and it is not trivial to detect that chain from that one wakeup without some from of traversal.
I completely missed that. Thank you for patiently explaining the problem!
Quoted 22 lines
Quoted 7 lines
if (task_cpu(p) == p->wake_cpu && !rt_or_dl_task(p)) return false; clear_task_blocked_on(p, NULL); block_task(rq, p, TASK_WAKING, 0); }Quoted 8 lines
Quoted 6 lines
I'll give that a shot here.
I'm wondering if a if (!sched_proxy_exec()) return; shortcut at the top might be nice too since we may not want to trip up the rt/dl task case and do all the work, but I know Peter wasn't happy with that being sprinkled around.
Ack! That makes sense given the
rt_or_dl_task()condition.I'll add that in as well then. The reordering/reworking the logic feels separate enough I'll do it in a separate patch from the original change here from Mathieu.
thanks
-john
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH v34 07/14] sched/proxy: Avoid transient blocked_donor cycles
In reply to K Prateek NayakQuoted 12 lines · K Prateek Nayak
Quoted 11 lines · John Stultz
kernel/sched/core.c +2
-1@@ -7050,7 +7050,11 @@ static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf,* before we release the lock. */ proxy_resched_idle (rq); -for (; p; p =READ_ONCE (p->blocked_donor)) { +while (p &&task_on_rq_queued (p)) { +struct task_struct *next =READ_ONCE (p->blocked_donor);
Quoted 8 lines
kernel/sched/core.c static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf, · line 7057
Quoted 3 lines
kernel/sched/core.c +3
-0+ +/* clear blocked_donor so we can't end up in cycles */ +WRITE_ONCE (p->blocked_donor,NULL );Ooo! Interesting. I suppose this is still needed with Patch 10 and 11 because a
ww_mutexunlock can suddenly clear a cycle before the Brent checkpoint can converge but the backwards link are already cyclic?
So less likely to be mutex related, this came up as a issue with the proxy-enabled futexes Suleiman is working on, as if userspace controls the locks, they can create lots of odd looking cycles (including stuff like locking a lock they already own, or maliciously locking it with another task's tid who then tries to lock the lock). So while we have to be careful in the main find_proxy_task(), we also have to be careful elsewhere where we walk chains to guard against infinitely looping (the later chain migration patches in the series also had a few spots like this to address).
Additionally, with the other stale blocked_donor issues that had been found, this seemed like a good place to zap them, since the primary uses of blocked_donor is to go a single step back (rq->curr->blocked_donor) when handing locks off, and the proxy_migrate_task() optimization to migrate the full chain in one go. So clearing it as we go in the migration function seemed like a good step to avoid mistakes.
thanks
-john
K Prateek Nayak
reviewerRe: [PATCH v34 05/14] sched/proxy: Clear blocked_donor when the donor stops donating
In reply to K Prateek NayakHello John,
Quoted 58 lines · K Prateek Nayak
Hello John, Mathieu,
Quoted 8 lines · John Stultz
From: Mathieu Desnoyers <[email protected]>
find_proxy_task()setsowner->blocked_donorto the task that donates to the owner.__mutex_unlock_slowpath()readscurrent->blocked_donorto hand the mutex to that task. The comment of the field says that it is set inschedule()and only stable underpreempt_disable(). So the pointer is valid until the owner schedules again.Quoted 4 lines
But the donor can stop donating while the owner keeps running. It is woken, or a change of its scheduling class or of its affinity takes it off the runqueue. The owner keeps its
blocked_donoruntil it schedules. Meanwhile the donor can run on another CPU and exit.So we can just clear it in
proxy_reset_donor()right? Onlycurrent->blocked_donoris ever looked at and, it the proxy breaks mid way, the only path that can be taken is viattwu_runnable().If the task is retained on the same CPU, it is safe to get the reference since unlock is done with preempt disable - otherwise, we check:
donor = current->blocked_donor; guard(&donor->blocked_lock); next_lock = __get_task_blocked_on(donor); if (next_lock == lock) next = get_task_struct(donor); ...If
ttwu_runnable()manages to clear theblocked_onrelation first under the blocked lock then we don't take a reference here and if we manage to take a reference here, the task cannot exit unexpectedly - it'll just get a spurious wakeup in the worst case.IMO, a simple
READ_ONCE()to check it here andWRITE_ONCE()inproxy_reset_donor()after the re-arrangement suggested on Patch3 should do the trick based on my understanding.o Race:
try_to_wake_up(donor) mutex_unlock_slowpath() ttwu_runnable(rq, donor) /* MUTEX_HANDOFF */ proxy_needs_return(rq, donor) donor = current->blocked_donor; proxy_reset_donor(rq) raw_spin_lock_nested(donor->blocked_lock) WRITE_ONCE(rq->curr->blocked_donor, NULL); next = get_task_struct(donor); ... /* Donor wakes up runs, exits *//*
*t->__state=TASK_DEAD
*t->usage!= 0 so freeing is deferredwake_up_process(p)
*/ !ttwu_state_match()put_task_struct() /* Freed via RCU */
Quoted 5 lines
If the task runs and blocks on a different lock,
wake_up_process()frommutex_unlock_slowpath()(if it still think lock has not changed) will just lead to a spurious wakeup.Is here a scenario where
proxy_reset_donor()clearing is not enough?
I guess that is not enough either since we need to clear ->blocked_donor for any wakeup in the chain :-(
Btw, for cycle detection, at some point we had a rq->proxy_pick_seq based cycle detection [1] and that can be used to detect if we should actually issue a resched_curr() + clear curr->blocked_donor or not since the tasks in chain will have the same pick_seq as rq's pick_seq.
I don't think the extra resched would be a visible problem atm but if we do hit something, we can perhaps consider that approach.
[1] https://lore.kernel.org/lkml/[email protected]/
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH v34 13/14] rcu-tasks: Treat proxy-exec blocked tasks as voluntary sleeps
In reply to John StultzHello John,
Quoted 55 lines · John Stultz
kernel/rcu/tasks.h +16
-10@@ -920,8 +920,9 @@ static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)// // rcu_tasks_pregp_step(): // Invokes synchronize_rcu() in order to wait for all in-flight -// t->on_rq and t->nvcsw transitions to complete. This works because -// all such transitions are carried out with interrupts disabled. +// t->on_rq, t->is_blocked, and t->nvcsw transitions to complete. +// This works because all such transitions are carried out with +// interrupts disabled. // rcu_tasks_pertask(), invoked on every non-idle task: // For every runnable non-idle task other than the current one, use // get_task_struct() to pin down that task, snapshot that task's @@ -940,10 +941,10 @@ static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)// corresponding task is removed from the holdout list. // rcu_tasks_postgp(): // Invokes synchronize_rcu() in order to ensure that all prior -// t->on_rq and t->nvcsw transitions are seen by all CPUs and tasks -// to have happened before the end of this RCU Tasks grace period. -// Again, this works because all such transitions are carried out -// with interrupts disabled. +// t->on_rq, t->is_blocked, and t->nvcsw transitions are seen by all +// CPUs and tasks to have happened before the end of this RCU Tasks +// grace period. Again, this works because all such transitions are +// carried out with interrupts disabled. // // For each exiting task, the exit_tasks_rcu_start() and // exit_tasks_rcu_finish() functions add and remove, respectively, the @@ -961,9 +962,9 @@ static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)static void rcu_tasks_pregp_step (struct list_head *hop) {/* -* Wait for all pre-existing t->on_rq and t->nvcsw transitions -* to complete. Invoking synchronize_rcu() suffices because all -* these transitions occur with interrupts disabled. Without this +* Wait for all pre-existing t->on_rq, t->is_blocked, and t->nvcsw +* transitions to complete. Invoking synchronize_rcu() suffices because +* all these transitions occur with interrupts disabled. Without this * synchronize_rcu(), a read-side critical section that started * before the grace period might be incorrectly seen as having * started after the grace period. @@ -991,8 +992,22 @@ static bool rcu_tasks_is_holdout(struct task_struct *t)* traditional blocked state or get woken up without outside * dependencies), not considering it such should only affect timing. * -* Be conservative for now and not include it. +* So if proxy execution is not enabled, be conservative for now +* and not include it. +* +* If proxy execution is enabled, lock blocked tasks may remain on +* the runqueue, which could confuse this logic, making it seem to +* be a holdout. So use is_blocked to detect this case.
kernel/rcu/tasks.h static bool rcu_tasks_is_holdout(struct task_struct *t) · line 1010
Quoted 10 lines
kernel/rcu/tasks.h +9
-0+* +* However, is_blocked also is set for DELAY_DEQUEUE, so with proxy +* execution we *do* consider sched_delayed tasks to be quiescent +* +* In both cases, the is_blocked task voluntarily slept and has not +* run since, so it cannot be within an RCU-tasks read-side critical +* section. */ +if (sched_proxy_exec () &&READ_ONCE (t->is_blocked)) +return false;
I think you can now replace the !p->on_rq check above with p->is_blocked directly - tasks going to sleep would have already cleared the holdout via:
__schedule(SM_NONE)
rcu_note_context_switch()
rcu_tasks_qs()
rcu_tasks_classic_qs()
WRITE_ONCE((t)->rcu_tasks_holdout, false);for the current GP. The p->on_rq gets set and p->is_blocked is cleared in the same IRQ disabled section so it should be equivalent.
P.S. rcu_note_context_switch() is done outside the rq_lock() so a task can clear its holdout and a concurrent ttwu_runnable() can win the rq_lock and wake it up before __schedule() grabs the rq_lock and tries to block the task.
I don't know if there is any dependency on rest of the wakeup path for se->sched_delayed to be considered special.
Peter, can you confirm if it is alright to just look at p->is_blocked for GP holdouts.
Other than that, feel free to include:
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH v34 14/14] sched/proxy: Add deactivated (sleeping) owner handling to find_proxy_task()
In reply to John StultzHi John,
kernel/sched/core.c int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) · line 4838
Quoted 5 lines · John Stultz
kernel/sched/core.c +2
-0ttwu_queue (p, cpu, wake_flags); } out: +if (woken) +activate_blocked_waiters (cpu_rq (task_cpu (p)), p, wake_flags);
When the owner goes through the wakelist, this can run before the owner is activated, and a donor can then be queued on the owner after the list was taken:
CPU0: ttwu(owner) CPU1: find_proxy_task(donor)
ttwu_queue_wakelist(owner)
activate_blocked_waiters()
blocked_head is empty
!owner->on_rq
lock owner->blocked_lock
!owner->on_rq
proxy_enqueue_on_owner() CPU2: sched_ttwu_pending()
activate_task(owner)
activate_task() only takes the owner off its own sleeping owner, so the donor stays on owner->blocked_head while the owner runs, until the owner sleeps and is woken again or hands it the lock.
To check, I counted donors that the owner itself wakes while they are still on its blocked_head, i.e. proxy_remove_from_sleeping_owner() with owner == current (test only). One kthread takes a mutex and sleeps a jiffy holding it, in a loop; six SCHED_FIFO kthreads take the same mutex; 20s in QEMU, 19cc08c1a6a6 with this series, 3 runs each:
4 CPUs 2 CPUs v34 221, 229, 216 141, 140, 154 + resched_idle, TASK_WAKING owner 3, 0, 0 0, 0, 0
where the second line adds, test only, before the sleeping owner branch enqueues anything:
if (READ_ONCE(owner->__state) == TASK_WAKING) goto resched_idle;
The counter also catches a donor that the owner wakes before the waker's activate_blocked_waiters() gets to it, which may be the 3. No lockdep or KASAN reports in these runs.
Activating the blocked_head where the owner is actually activated would cover it as well, but that runs under the rq lock.
Thanks,
Zhan Xusheng
K Prateek Nayak
reviewerRe: [PATCH v34 14/14] sched/proxy: Add deactivated (sleeping) owner handling to find_proxy_task()
In reply to John StultzHello John,
Quoted 17 lines · John Stultz
kernel/sched/core.c +17
-0+static void do_activate_blocked_waiter (struct rq *target_rq,struct task_struct *p,int en_flags) +{ +struct rq_flags rf; +int target_cpu =cpu_of (target_rq); + + scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { + scoped_guard (raw_spinlock, &p->blocked_lock) { +int state =READ_ONCE (p->__state); + +/* If task is no longer blocked, don't activate */ +if (!READ_ONCE (p->is_blocked)) +return ; + +/* Avoid racing with ttwu */ +if (state ==TASK_WAKING ) +return ; +
kernel/sched/core.c static inline void proxy_reset_donor(struct rq *rq) · line 4007
Quoted 10 lines
kernel/sched/core.c +10
-0+/* Dead tasks don't activate */ +if (state ==TASK_DEAD ||READ_ONCE (p->exit_state)) +return ; + +/* +* We raced with a non mutex handoff activation of p. +* That activation will also take care of activating +* all of the tasks after p in the blocked_head list, +* so we're done here. +*/
State checks vs p->on_rq check needs to be ordered with smp_mb() too based on __task_needs_rq_lock() and ...
Quoted 4 lines
kernel/sched/core.c +4
-0+if (READ_ONCE (p->on_rq)) +return ; + +/*
kernel/sched/core.c static inline void proxy_reset_donor(struct rq *rq) · line 4021
Quoted 10 lines
kernel/sched/core.c +10
-0+* Its possible this activation is very late, and +* we already were woken up and are running on a +* different cpu. If that task blocked, it could be +* dequeued (so on_rq == 0), but still on_cpu. +* Bail in this case, as we definitely don't want to +* activate a task when its on_cpu elsewhere. +* +* Use smp_load_acquire since we don't hold rq lock. +*/ +if (smp_load_acquire (&p->on_cpu))
... isn't smp_load_acquire() basically:
READ_ONCE(p->on_cpu)
smp_mb()
? I think the patten here should be:
READ_ONCE(p->on_rq)
smp_mb(); smp_cond_load_acquire(p->on_cpu, !VAL);
Quoted 175 lines
kernel/sched/core.c +139
-3+return ; + +/* +* Again, if activation is delayed, it's possible the +* task has been woken and is no longer blocked_on, +* but went back to sleep, so double check blocked_on +* before activating onto the owner's rq +*/ +if (!task_is_blocked (p)) +return ; + +/* +* This was cleared right before calling +* do_activate_blocked_waiter(), so if it is set we've +* woken, and went on to queue on a different sleeping +* owner. They will activate us later when its +* appropriate, so bail now. +*/ +if (READ_ONCE (p->sleeping_owner)) +return ; + } + +if (task_cpu (p) != target_cpu) { + en_flags |=ENQUEUE_MIGRATED ; +psi_ttwu_dequeue (p); +proxy_set_task_cpu (p, target_cpu); + } +rq_lock_irqsave (target_rq, &rf); +/* +* proxy_enqueue_on_owner() called block_task() which +* increments nr_uninterruptible, so we need to reverse +* that when we activate the blocked waiter +*/ +if (p->sched_contributes_to_load) + target_rq->nr_uninterruptible--; +update_rq_clock (target_rq); +activate_task (target_rq, p, en_flags); +wakeup_preempt (target_rq, p,0 ); +rq_unlock_irqrestore (target_rq, &rf); + } +} + +static void activate_blocked_waiters (struct rq *target_rq, +struct task_struct *owner, +int wake_flags) +{ +struct list_head bal_head; +unsigned long flags; +int en_flags =ENQUEUE_WAKEUP |ENQUEUE_NOCLOCK ; + +if (!sched_proxy_exec ()) +return ; + +/* +* A whole bunch of waiting donor tasks back this blocked +* lock owner task, wake them all up to give this task its +* 'fair' share. +* +* This is a little unique here and the locking is messy. +* At this point we only hold the blocked_lock, so the +* owner task may be able to run and do all sorts of +* things while we are processing the blocked_head list, +* including going back to sleep, which can cause tasks +* to be added to the owners->blocked_head while we are +* processing it! +* Thus, we pull the entire list off the owner->blocked_head +* here so that we will only process a finite amount of +* tasks. Tasks added after this will be processed by the +* future wake events. +* Even though we have pulled the list off the blocked_head +* the removed list is *still* "owned" and serialized by +* the owner->blocked_lock! As we have to serialize against +* mid-chain wakeups, who may try to remove themselves from +* the list. +*/ +raw_spin_lock_irqsave (&owner->blocked_lock, flags); +if (!list_empty (&owner->blocked_activation_node)) { +raw_spin_unlock_irqrestore (&owner->blocked_lock, flags); +return ; + } + +if (list_empty (&owner->blocked_head)) { +raw_spin_unlock_irqrestore (&owner->blocked_lock, flags); +return ; + } + +get_task_struct (owner); +INIT_LIST_HEAD (&bal_head); +list_add_tail (&owner->blocked_activation_node, &bal_head); +raw_spin_unlock_irqrestore (&owner->blocked_lock, flags); + +while (!list_empty (&bal_head)) { +struct list_head tmp_head; + +INIT_LIST_HEAD (&tmp_head); + owner = list_first_entry(&bal_head, struct task_struct, blocked_activation_node); + +raw_spin_lock_irqsave (&owner->blocked_lock, flags); +list_replace_init (&owner->blocked_head, &tmp_head); +list_del_init (&owner->blocked_activation_node); +while (!list_empty (&tmp_head)) { +struct task_struct *p; + + p =list_first_entry (&tmp_head, + struct task_struct, + blocked_node); +WARN_ON (p == owner); +get_task_struct (p); +__proxy_remove_from_sleeping_owner (owner, p); +raw_spin_unlock_irqrestore (&owner->blocked_lock, flags); + +do_activate_blocked_waiter (target_rq, p, en_flags); + +raw_spin_lock_irqsave (&p->blocked_lock, flags); +if (list_empty (&p->blocked_activation_node)) { +get_task_struct (p); +list_add_tail (&p->blocked_activation_node, &bal_head); + } +raw_spin_unlock_irqrestore (&p->blocked_lock, flags); +put_task_struct (p); + +raw_spin_lock_irqsave (&owner->blocked_lock, flags); + } +raw_spin_unlock_irqrestore (&owner->blocked_lock, flags); +put_task_struct (owner);// put matches get prior to adding to local bal_head + } +} + +static inline struct task_struct *proxy_resched_idle (struct rq *rq); +/* * Checks to see if task p has been proxy-migrated to another rq * and needs to be returned. If so, we deactivate the task here @@ -3931,8 +4189,7 @@ static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p)if (task_current (rq, p))return false; } - - dequeued =dequeue_block_task (rq, p,TASK_WAKING ); + dequeued =dequeue_block_task (rq, p,TASK_WAKING ,0 );/* * Dequeue @p from its scheduling class before resetting rq->donor. @@ -3954,6 +4211,10 @@ static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p) {return false; } + +static inline void activate_blocked_waiters (struct rq *target_rq, +struct task_struct *owner, +int wake_flags) {}#endif /* CONFIG_SCHED_PROXY_EXEC */ static void@@ -4023,8 +4284,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) +if (p->se.sched_delayed) { +proxy_remove_from_sleeping_owner (p);enqueue_task (rq, p,ENQUEUE_NOCLOCK |ENQUEUE_DELAYED ); + }/* * If we're waking a blocked task and we are * currently proxying, force a resched in case @@ -4411,6 +4674,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) {guard (preempt)();int cpu, success =0 ; +bool woken = false; wake_flags |=WF_TTWU ;
kernel/sched/core.c int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) · line 4705
Quoted 4 lines
kernel/sched/core.c +1
-0@@ -4438,6 +4702,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)trace_sched_waking (p);ttwu_do_wakeup (p); + woken = true;
This branch cannot have "p->is_blocked" so it probably doesn't require sleeping owner handling right?
Quoted 12 lines
kernel/sched/core.c +1
-0goto out; }@@ -4453,6 +4718,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)if (!ttwu_state_match (p, state, &success))break ; + woken = true;trace_sched_waking (p);/*
kernel/sched/core.c int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) · line 4838
Quoted 5 lines
kernel/sched/core.c +2
-0@@ -4568,6 +4834,8 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)ttwu_queue (p, cpu, wake_flags); } out: +if (woken) +activate_blocked_waiters (cpu_rq (task_cpu (p)), p, wake_flags);
I think there is a very convoluted race possible here like:
/* Wakeup from task context. */
try_to_wake_up()
ttwu_queue_wakelist()
/* sends IPI */ ---------------> ttwu_do_activate(owner)
activate_task(owner)
/* stalls */ /* Owner runs */
mutex_unlock()
wake_up_process(sleeping_donor)
activate_task()
proxy_remove_from_sleeping_owner()
put_task_struct(owner)
/* &owner->usage is 1 after this */
/* Owner dies */
finish_task_switch()
if (prev_state == TASK_DEAD)
put_task_struct_rcu_user(prev = owner);
/* owner->usage turns 0 */
/* Queues RCU callback to free owner */
/*Back */
raw_spin_rq_lock_irqrestore(p->pi_lock);
/* Preempted; RCU grace period done. */
activate_blocked_waiters(owner)
/* !!! Use after free for owner !!! */I suppose it is also possible for any remote wakeup and not necessarily dependent on TTWU_QUEUE bit. Am I missing something that prevents this?
One way to get around this is to do a guard(irqsave)() before grabbing the &p->pi_lock and that way, you should have an RCU-protected reference for the entirety of activate_blocked_waiters().
IRQs will be disabled for the duration of chain wakeup but that is also true today if the owner wakes up from an IRQ handler so it should be okay?
Quoted 3 lines
kernel/sched/core.c +0
-0if (success)ttwu_stat (p,task_cpu (p), wake_flags);
Signature · 2 lines
Thanks and Regards, Prateek