Skip to contentSkip to conversation

sched/proxy: fixes for proxy execution, with selftests

RFC PATCH In review Mathieu Desnoyers 3 participants 22 messages Nov 16 – Nov 24

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

cover sched/proxy: fixes for proxy execution, with selftests

Hi John, Peter,

This series fixes six problems of proxy execution, and adds a test module and a selftest for them. I found them while I looked at how SCHED_DEADLINE priority inheritance could move to proxy execution.

It applies on top of v6 of my deadline series (link below). Patches 4 and 6 need it: they change code that v6 adds to the deadline bandwidth accounting. Patches 1, 2, 3 and 5 do not.

The fixes:

1 Reschedule when a blocked task is woken under a proxy, so that the
old owner stops running on the donor's context.
2 Wake blocked RT and deadline tasks through the full wake-up path, so
that they are pushable and another CPU can take them.
3 Stop the chain walk when the blocked_on chain is a cycle, so that a
mutex deadlock no longer locks up the CPU.
4 Tell the class about a proxy migration, so that the load of a fair
donor is attached to the runqueue it moves to. The bandwidth of a deadline donor stays in its root domain.
5 Clear blocked_donor when the donor stops donating, so that the
unlock path does not use a task that can be freed.
6 Check and admit a proxy-migrated deadline task in its own root
domain, so that sched_setattr() no longer fails with EPERM.

The selftest shows the behaviour that patches 1 to 4 and 6 fix. Patch 5 comes from reading the code: I have no reproducer for it.

The tests:

7 test_proxy_exec, a module with kernel mutexes that user space can
hold, take and chain through debugfs. Proxy execution acts on tasks blocked on a struct mutex, and no system call lets user space block tasks on one in a chosen way.
8 proxy_exec_test, a selftest with eight cases. Each fails with proxy
execution and passes with the fix its comment names. All pass with sched_proxy_exec=0. The deadlock case runs only with PROXY_EXEC_TEST_DEADLOCK=1: a kernel without patch 3 locks up.

Points I would like your opinion on:
- Patch 2 sends RT and deadline tasks through the full wake-up again. That undoes part of commit 7918cf369361 ("sched/proxy: Only return migrate when needed") for these classes. Putting the woken task on the pushable list in place would keep the optimization, but it needs a hook into the classes.
- Patch 1 reschedules for any blocked task woken on a runqueue that runs a proxy. A fair task woken from a delayed dequeue there also triggers it. That is harmless, but not free.
- Patch 3 also stops the donation on a ww_mutex cycle that the wound or die path is about to break. The donor then sleeps on its mutex.
- Patch 4 repeats in proxy_set_task_cpu() what set_task_cpu() does around __set_task_cpu(). A helper shared by both would keep them from drifting apart. I left it out to keep the fix small.

Not in this series:
- A donor's reservation used in a root domain that did not admit it. This happens when the affinities of the donor and the owner do not overlap.

Testing
=======

The tests ran in x86-64 QEMU guests with PREEMPT_LAZY and lockdep:
- proxy_exec_test on 4 CPUs: 8 runs with proxy execution and 8 with sched_proxy_exec=0 pass, half of them with the deadlock case. On deadline v6 with the test module alone, every case fails with proxy execution, in 8 runs of 8. The deadlock case hangs the guest there.
- The deadline selftests of v6 pass in 10 guests, with and without proxy execution.
- locktorture passes with mutex_lock and with ww_mutex_lock (16 writers on 8 CPUs, 180s), with and without proxy execution. So do the ww_mutex, locking API and futex selftests.

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

An LLM coding assistant reviewed the proxy execution code under my direction. It wrote these patches, their messages and the tests, which I reviewed. A reproducer that stops failing shows that the symptom goes away. It does not show that the fix is the one you would have written, so I ask for a careful reading.

Based on tip sched/urgent, ec6f6731538e, with v6 of "sched/deadline:
bandwidth accounting fixes and selftests" applied first:
https://lore.kernel.org/all/[email protected]/

Mathieu Desnoyers (8):
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: Stop the chain walk when the blocked_on chain is a cycle sched/proxy: Tell the class about a proxy migration sched/proxy: Clear blocked_donor when the donor stops donating sched/deadline: Use the root domain a proxy-migrated task runs in
lib: Add test_proxy_exec, kernel mutexes that user space can hold selftests/sched: Add tests of proxy execution

 kernel/sched/core.c                           |  94 +-
 kernel/sched/deadline.c                       |  10 +-
 kernel/sched/sched.h                          |  23 +
 kernel/sched/syscalls.c                       |   9 +-
 lib/Kconfig.debug                             |  11 +
 lib/Makefile                                  |   1 +
 lib/test_proxy_exec.c                         | 132 +++
 tools/testing/selftests/Makefile              |   1 +
 .../selftests/sched/proxy_exec/.gitignore     |   1 +
 .../selftests/sched/proxy_exec/Makefile       |   7 +
 .../testing/selftests/sched/proxy_exec/config |   5 +
 .../sched/proxy_exec/proxy_exec_test.c        | 913 ++++++++++++++++++
 .../selftests/sched/proxy_exec/settings       |   1 +
 13 files changed, 1200 insertions(+), 8 deletions(-)
 create mode 100644 lib/test_proxy_exec.c
 create mode 100644 tools/testing/selftests/sched/proxy_exec/.gitignore
 create mode 100644 tools/testing/selftests/sched/proxy_exec/Makefile
 create mode 100644 tools/testing/selftests/sched/proxy_exec/config
 create mode 100644 tools/testing/selftests/sched/proxy_exec/proxy_exec_test.c
 create mode 100644 tools/testing/selftests/sched/proxy_exec/settings

base-commit: ec6f6731538e0d45872eb279fdeb477bed152d6f
prerequisite-patch-id: 5e2478ffdfb7583751bf44bdf87fb930bc23551b
prerequisite-patch-id: d5e5ef986ff2d9bc39a87b56e96a2acbd3158687
prerequisite-patch-id: 99e47f80396008ee2b2576157d37842481ce52d2
prerequisite-patch-id: a10824f98c11a4c902dad55cab3ec03b3dbe2c8a
prerequisite-patch-id: 6a944081caf562b37b617f6a763fb9c5e93b7671
prerequisite-patch-id: 16acf1d18f01d20310d6db767dfbec2f072e0372
prerequisite-patch-id: e1946bb015a7b14ed4e2cd0421e5e30b0c7afdda
prerequisite-patch-id: 13ae41e148238564753e668868311a4d5e905020
prerequisite-patch-id: f8b34127a06e7503c069fb08e275574569aa1663
prerequisite-patch-id: d76a04cc6382c157d75b79231e6cba472367d875
prerequisite-patch-id: fb69a0665dc38ca9022cc2bd75234a90e2035b7f
prerequisite-patch-id: e5b851fc06511b47520dbbd96a7823cb28e83904
prerequisite-patch-id: 6e7ce0551aae3d1e5cdffcb79a9dfad9572d171e
prerequisite-patch-id: 8574b50d81a09ec6091e42d65338adcab2986d71
prerequisite-patch-id: cf098d7617ec51026a60140b231640a73a67be83
prerequisite-patch-id: b4ace4d6fbffab1d45765c86650ca535c4bade7e
prerequisite-patch-id: f6b9bef6e53a08be446fd431a8d6790470c74234
prerequisite-patch-id: 1aa25df96d60d30f549c71fdfba5589cb239928f
prerequisite-patch-id: 3f22a07ea1846d81570daafd00db92f077a6703e
prerequisite-patch-id: e1dd6913718da692992ed4c0304e56b93195327e
prerequisite-patch-id: ca239064b2461ed44c672e2e0cc3f53ff372f134
prerequisite-patch-id: a005df845d96a168895545d1ee2e003b353fbf98
prerequisite-patch-id: 002838bd7a490b5652baa9e9ff4807fcd7a2abe8
prerequisite-patch-id: f4c7d346d9b538b65385631a620a6b154b85a848
prerequisite-patch-id: 12e92679eab6c8262b962c9aabd221a2d3bccfd4
prerequisite-patch-id: 0518465685600028b5cef2695868f32ca9705ea7
prerequisite-patch-id: f75ff674ec8c99e53c6460a8f70828060947bd39
prerequisite-patch-id: 9f785aa3a5378bded94e838c9fb9305cb90d1d33
prerequisite-patch-id: 73b7bf5a66a4b43ebc393b7a77ec59cf92c6f944
prerequisite-patch-id: 9b860d340021441081e605651f409c46769501f2
prerequisite-patch-id: bddfc273edbf8d9c19aa8429731c93fb62a26395
prerequisite-patch-id: 1c864890d70c38372dc4ae9326e41b794e163ab8
prerequisite-patch-id: f8b569a9b72ed4acb0c8d7f7bfeaa91ada80f7f4
prerequisite-patch-id: d38384e0b7d043a3556ee02fb09316a6227038da
prerequisite-patch-id: 1f13e48ca223d57cf3a2087600949330f82457c1
prerequisite-patch-id: 727a8041cecc638f8051ad069b7606515c1739c4
prerequisite-patch-id: 566a6e8350b5ae85e6aaf0579d84c2227672b56d

Signature · 1 line
2.47.3
#1 lore raw

RFC PATCH 1/8 sched/proxy: Reschedule when a blocked task is woken under a proxy

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.

Fixes 7918cf369361 ("sched/proxy: Only return migrate when needed")
---
 kernel/sched/core.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
kernel/sched/core.c +12 -1
index dc270a23179d..326026ba0b2b 100644
@@ -4057,9 +4057,20 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)
 
 	update_rq_clock(rq);
 	if (p->is_blocked) {
+		bool returned;
+
 		if (p->se.sched_delayed)
 			enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED);
-		if (proxy_needs_return(rq, p))
+		returned = proxy_needs_return(rq, p);
+		/*
+		 * @p was blocked and this CPU runs a proxy. If @p is the donor
+		 * or a task of its chain, the donor no longer waits for the
+		 * task that runs. wakeup_preempt() compares @p with the donor,
+		 * so it does not see this. Pick again.
+		 */
+		if (rq->donor != rq->curr)
+			resched_curr(rq);
+		if (returned)
 			return 0;
 	}
 	if (!task_on_cpu(rq, p)) {
Signature · 1 line
2.47.3
#2 lore raw

Re: [RFC PATCH v1 1/8] sched/proxy: Reschedule when a blocked task is woken under a proxy

Quoted 51 lines · Mathieu Desnoyers

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.

Fixes 7918cf369361 ("sched/proxy: Only return migrate when needed")
---
 kernel/sched/core.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
kernel/sched/core.c +3 -1
index dc270a23179d..326026ba0b2b 100644
@@ -4057,9 +4057,20 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)
 
        update_rq_clock(rq);
        if (p->is_blocked) {
+               bool returned;
+
                if (p->se.sched_delayed)
                        enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED);
-               if (proxy_needs_return(rq, p))
+               returned = proxy_needs_return(rq, p);

kernel/sched/core.c static int ttwu_runnable(struct task_struct *p, int wake_flags) · line 4074

Quoted 10 lines
kernel/sched/core.c +9 -0
+               /*
+                * @p was blocked and this CPU runs a proxy. If @p is the donor
+                * or a task of its chain, the donor no longer waits for the
+                * task that runs. wakeup_preempt() compares @p with the donor,
+                * so it does not see this. Pick again.
+                */
+               if (rq->donor != rq->curr)
+                       resched_curr(rq);
+               if (returned)
                        return 0;

I need to think on this some more, but my gut reaction is this feels a bit too subtle or possibly too broad. Particularly the check being done after proxy_needs_return, but before the exit, it feels like it's leaning too much on a non-obvious side-effect of proxy_needs_return().

Both the comment and the commit message are also confusing, as if at the start of ttwu_runnable() if p is the donor, proxy_needs_return() will have called proxy_reset_donor(), setting rq->donor = rq->curr (and already calling resched_curr()).

So it seems this patch is mainly trying to handle the case of a mid-chain wakeup, where p isn't the current donor, but is in the current chain? I agree that looks to be a problem, but the donor != curr check just is testing that we are proxying, not that p is in the active chain. It could be previously blocked on a different unselected chain. That said, this may be a good enough approximation (especially as doing the donor->curr chain walk feels expensive).

Though it feels like maybe the check should be pushed into proxy_needs_return() instead so it can be more clearly aligned with the similar proxy_reset_donor() call?

Or am I missing something more?

thanks
-john

#3 lore raw

Re: [RFC PATCH v1 1/8] sched/proxy: Reschedule when a blocked task is woken under a proxy

Quoted 4 lines · John Stultz

Both the comment and the commit message are also confusing, as if at the start of ttwu_runnable() if p is the donor, proxy_needs_return() will have called proxy_reset_donor(), setting rq->donor = rq->curr (and already calling resched_curr()).

Only when the donor was proxy-migrated. When the donor is still on its own CPU, task_cpu(p) == p->wake_cpu. proxy_needs_return() then returns false at its first check, before proxy_reset_donor(). That is the case the commit message describes: the owner was on the donor's CPU, so no proxy migration happened. handoff_fifo hits it on one CPU.

Once the shortcut is gone, as you propose for patch 2, the donor goes through proxy_reset_donor(). Then this patch only matters for a task in the middle of the chain.

Quoted 5 lines

So it seems this patch is mainly trying to handle the case of a mid-chain wakeup, where p isn't the current donor, but is in the current chain? I agree that looks to be a problem, but the donor != curr check just is testing that we are proxying, not that p is in the active chain.

Yes. All the tasks of the running chain are on this runqueue:
find_proxy_task() migrates the donor when an owner is on another CPU. So a woken chain member is always seen here. A blocked task outside the chain also triggers the reschedule. I found no cheap test for chain membership.

Quoted 3 lines

Though it feels like maybe the check should be pushed into proxy_needs_return() instead so it can be more clearly aligned with the similar proxy_reset_donor() call?

Agreed. Without the shortcut, this would be an else of the task_current_donor() check:

        if (task_current_donor(rq, p))
                proxy_reset_donor(rq);
        else if (rq->donor != rq->curr)
                resched_curr(rq);

I tried this on your proxy-exec-v33-7.4-pre-rc1 branch: no shortcut, and this else branch. Cases 1 to 4 then pass, in 3 runs of 3. No case wakes a task in the middle of the chain, so the else branch itself is not tested.

Your suggestion on the cover letter also fits. On tip, a task woken from a delayed dequeue is never in the running chain: find_proxy_task() stops at a delayed owner. So the reschedule can be skipped for it.

Thanks,

Mathieu

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

Re: [RFC PATCH v1 1/8] sched/proxy: Reschedule when a blocked task is woken under a proxy

In reply to Mathieu Desnoyers

Hi Mathieu, John,

A field report for patch 1, from a single-CPU system running 6.18.y. We tracked down the same bug independently on real hardware and only then came across your series. It may help with two open points: the shortcut in proxy_needs_return(), and 6.18.y.

System: ARM Cortex-A5 (SAMA5D2), one CPU, 6.18.64, PREEMPT, HZ=100, SCHED_PROXY_EXEC=y. The firmware of an industrial Ethernet switch runs about 65 SCHED_FIFO threads. A ring redundancy manager (FIFO 99, 6 ms cycle) stalled for 25 to 60 ms about twice a day, together with every other RT thread. A 1 ms sampling hrtimer showed a SCHED_OTHER task running the whole time, partly in user space, with FIFO 99 threads runnable and need_resched never set.

The mechanism is the one in your commit message. The owner's mutex_unlock() clears the donor's blocked_on and wakes it. ttwu_runnable() calls wakeup_preempt(), which compares the donor with rq->donor, that is with itself, and asks for nothing. The owner keeps the FIFO 99 context until it sleeps on its own.

1) UP and the proxy_needs_return() shortcut

On a single CPU, task_cpu(p) == p->wake_cpu always holds, so the shortcut at the top of proxy_needs_return() is always taken there and the donor never goes through proxy_reset_donor(). The variant discussed in the thread puts the resched in an else branch inside proxy_needs_return(). That only helps UP if the shortcut goes away completely. If the shortcut stays for some classes, please keep the resched reachable when it is taken, as your patch 1 does.

2) Two more cases on 6.18.y

On 6.18 the wakeup itself can be a no-op, because the waiter is already TASK_RUNNING and ttwu_state_match() fails:

a) A signal to a donor in mutex_lock_interruptible() sets it TASK_RUNNING but leaves blocked_on set. find_proxy_task() then picks the owner again, and the donor cannot act on the signal until the unlock. At the unlock, the wakeup of the donor does nothing, and the owner keeps the donor's context again. This is your signal_fifo case.
b) The first waiter was woken earlier, but the lock was stolen before it ran, and the donor is queued behind it. The unlock wakes the first waiter, which is already running, so nothing reschedules.

As far as I can see, mainline hands the lock to blocked_donor, so b) should not exist there. 6.18 has no blocked_donor and picks the first waiter.

3) Measurements on the hardware

Reproducer A: a SCHED_OTHER task O writes and reads a pipe (pipe->mutex), then spins 50 ms in user space and sleeps 150 ms. D (FIFO 99) does a non-blocking read() of the same pipe every 5 ms. M (FIFO 80) runs a 1 ms clock_nanosleep() loop and records how late it wakes up.

6.18.64, proxy exec on: M up to 51 ms late in nearly every cycle

                            (= O's spin), D's read() up to 50 ms
  sched_proxy_exec=0:       M up to 21 ms, D's read() up to 220 ms
  with the patch below:     M up to 5.6 ms, D up to 1.05 ms
                            (5 runs of 60 s)

Reproducer B: a test module with one struct mutex, similar to your test_proxy_exec. O holds the mutex for 5 ms in a preemptible kernel loop, then spins 50 ms in user space. D (FIFO 99) calls mutex_lock_interruptible() every 3 ms and gets SIGUSR1 from a POSIX timer every 7 ms or 3 ms.

resched in ttwu_runnable() only: 0 EINTR, D up to 18.7 ms,

                                    M up to 19.1 ms

all three changes below: 127 / 425 EINTR, D up to 4.97 ms
(= hold time), M up to 5.2 ms

Both reproducers ran on a board with the same SoC. We have not yet tested the patch on the field units that showed the stalls. Case b) above comes from reading the code; I have no reproducer for it.

Proxy execution stays on: with sched_proxy_exec=0 the priority inversion is worse for us than the stall.

4) 6.18.y

6.18 is an LTS kernel and has SCHED_PROXY_EXEC as an option, but none of the mainline infrastructure (is_blocked, proxy_needs_return(), blocked_donor), so the mainline fix will not apply there. Could the final fix carry

Fixes 7de9d4f94638 ("sched: Start blocked_on chain processing in find_proxy_task()")

so that 6.18.y gets a backport? Below is what we run on 6.18.64, for discussion and as a starting point, not for merging as is. It reschedules in three places:

- ttwu_runnable(): after wakeup_preempt(), if rq->curr != rq->donor, as in your patch 1.
- __mutex_unlock_slowpath(): after waking a waiter, the unlocking task sets need_resched on itself if it runs as a proxy. This covers
a) and b), where the wakeup does nothing.
- find_proxy_task(): a task in the chain that is TASK_RUNNING while blocked_on is still set (signal) runs itself, so it can return from schedule() and see the signal.

I am happy to test a 6.18 backport of whatever lands upstream on this hardware.

How this was made: the analysis, both reproducers and the changes below were developed with an AI coding assistant (Claude Code) under my direction. GPT and Gemini models reviewed the changes in three rounds. I reviewed the result, and all numbers above come from runs on the hardware.

Thanks,
Ramin

-- >8 --
From: Ramin Moussavi <[email protected]>
Subject: [PATCH 6.18.y RFC] sched/proxy: Reschedule when the donor stops being blocked

---
 include/linux/sched.h  |  8 ++++++++
 kernel/locking/mutex.c |  4 ++++
 kernel/sched/core.c    | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 58 insertions(+)
include/linux/sched.h +8 -0
@@ -2228,6 +2228,14 @@ static inline void clear_task_blocked_on
 }
 #endif /* !CONFIG_PREEMPT_RT */
 
+#ifdef CONFIG_SCHED_PROXY_EXEC
+extern void sched_proxy_unlock_resched(void);
+#else
+static inline void sched_proxy_unlock_resched(void)
+{
+}
+#endif
+
 static __always_inline bool need_resched(void)
 {
 	return unlikely(tif_need_resched());
kernel/locking/mutex.c +4 -0
@@ -963,6 +963,10 @@ static noinline void __sched __mutex_unl
 		__mutex_handoff(lock, next);
 
 	raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q);
+
+	/* Current may run as proxy, see sched_proxy_unlock_resched() */
+	if (next)
+		sched_proxy_unlock_resched();
 }
 
 #ifndef CONFIG_DEBUG_LOCK_ALLOC
kernel/sched/core.c +46 -0

64 lines not on this page · raw message

#5 lore raw

RFC PATCH 2/8 sched/proxy: Wake blocked RT and deadline tasks through the full path

In reply to Mathieu Desnoyers

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.

Fixes 7918cf369361 ("sched/proxy: Only return migrate when needed")
---
 kernel/sched/core.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/sched/core.c +9 -2
index 326026ba0b2b..cededdcfd5a3 100644
@@ -3953,8 +3953,15 @@ 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.
-	 */
-	if (task_cpu(p) == p->wake_cpu)
+	 *
+	 * 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 &&
+	    p->sched_class != &rt_sched_class &&
+	    p->sched_class != &dl_sched_class)
 		return false;
 
 	scoped_guard(raw_spinlock, &p->blocked_lock) {
Signature · 1 line
2.47.3
#6 lore raw

Re: [RFC PATCH v1 2/8] sched/proxy: Wake blocked RT and deadline tasks through the full path

Quoted 19 lines · Mathieu Desnoyers

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.

Quoted 6 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")

I need to look more closely here but this seems likely to overlap with currently out-of-tree chain-migration patches that Conor came up with:
https://github.com/johnstultz-work/linux-dev/commit/80b820a921bf5058196314ab72f8446f5ca3bad6
https://github.com/johnstultz-work/linux-dev/commit/27f701c997a152cc831262b55a226d513fa6abab
https://github.com/johnstultz-work/linux-dev/commit/fd1c4d9c6df6183e5ad934851dbbaa31846619e1
https://github.com/johnstultz-work/linux-dev/commit/d0d409fad42196f4f41267593566c0e55f856d6d

(from my https://github.com/johnstultz-work/linux-dev/commits/proxy-exec-v33-7.4-pre-rc1/
branch)

So I'm not totally surprised to hear there's DL/RT balancing issues currently.

Also in another thread (which I can't find right now), a good point was raised that some of the early return "shortcuts" that I've used elsewhere aren't good for core-scheduling either since they can break the cookie checks, so I wonder if a better fix here would be just removing that (task_cpu(p) == p->wake_cpu) conditional all together?

thanks
-john

#7 lore raw

Re: [RFC PATCH v1 2/8] sched/proxy: Wake blocked RT and deadline tasks through the full path

Quoted 5 lines · John Stultz

Also in another thread (which I can't find right now), a good point was raised that some of the early return "shortcuts" that I've used elsewhere aren't good for core-scheduling either since they can break the cookie checks, so I wonder if a better fix here would be just removing that (task_cpu(p) == p->wake_cpu) conditional all together?

Yes, that is simpler. I kept the shortcut for the other classes only to keep the optimization of commit 7918cf369361. If the cookie checks need the full path too, I see no reason to keep it.

The reply to patch 1 has what this changes there.

Thanks,

Mathieu

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

RFC PATCH 3/8 sched/proxy: Stop the chain walk when the blocked_on chain is a cycle

In reply to Mathieu Desnoyers

find_proxy_task() follows the blocked_on chain from the donor to a task that can run. It holds the rq lock, with interrupts off. It has no bound on the number of steps.

The walk relies on the chain having an end. The ww_mutex die and wound paths clear blocked_on for that reason. Their comments say that circular blocked_on relationships would not resolve otherwise. But two tasks that take two plain mutexes in opposite orders deadlock for good. Once both are on one runqueue, the walk goes around the cycle forever.

Without proxy execution, such a deadlock leaves two tasks asleep, and the hung task detector can report them. With it, the CPU locks up with its rq lock held. Other CPUs would then block on that lock. In a test with two CPUs, the guest stopped without a message.

Fix this by detecting the cycle. The walk remembers the task it met at its last step that is a power of two. When it meets that task again, it stops the donation and deactivates the donor. The donor then sleeps on its mutex, as without proxy execution.

Fixes 7de9d4f94638 ("sched: Start blocked_on chain processing in find_proxy_task()")
---
 kernel/sched/core.c | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)
kernel/sched/core.c +25 -1
index cededdcfd5a3..24105eeeb3c7 100644
@@ -7135,7 +7135,8 @@ static struct task_struct *
 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 *owner = NULL, *mark = NULL;
+	unsigned int steps = 0, mark_at = 1;
 	bool curr_in_chain = false;
 	int this_cpu = cpu_of(rq);
 	struct task_struct *p;
@@ -7145,6 +7146,29 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf)
 	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;
+
+		/*
+		 * The walk came back to a task it already met: the chain is
+		 * a cycle. Either the tasks deadlock, or a ww_mutex cycle is
+		 * about to be broken. Do not walk it forever with the rq lock
+		 * held. Stop the donation: the donor then sleeps on its
+		 * mutex, as it does without proxy execution.
+		 *
+		 * @mark is the task met at the last step that is a power of
+		 * two. Once the walk is in a cycle, @mark is soon a task of
+		 * that cycle, and the walk meets it again.
+		 */
+		if (p == mark) {
+			if (curr_in_chain)
+				goto resched_idle;
+			p = donor;
+			clear_task_blocked_on(p, NULL);
+			goto deactivate;
+		}
+		if (++steps == mark_at) {
+			mark = p;
+			mark_at <<= 1;
+		}
 		if (!mutex) {
 			clear_task_blocked_on(p, mutex);
 			if (task_current(rq, p)) {
Signature · 1 line
2.47.3
#9 lore raw

Re: [RFC PATCH v1 3/8] sched/proxy: Stop the chain walk when the blocked_on chain is a cycle

Quoted 21 lines · Mathieu Desnoyers

find_proxy_task() follows the blocked_on chain from the donor to a task that can run. It holds the rq lock, with interrupts off. It has no bound on the number of steps.

The walk relies on the chain having an end. The ww_mutex die and wound paths clear blocked_on for that reason. Their comments say that circular blocked_on relationships would not resolve otherwise. But two tasks that take two plain mutexes in opposite orders deadlock for good. Once both are on one runqueue, the walk goes around the cycle forever.

Without proxy execution, such a deadlock leaves two tasks asleep, and the hung task detector can report them. With it, the CPU locks up with its rq lock held. Other CPUs would then block on that lock. In a test with two CPUs, the guest stopped without a message.

Fix this by detecting the cycle. The walk remembers the task it met at its last step that is a power of two. When it meets that task again, it stops the donation and deactivates the donor. The donor then sleeps on its mutex, as without proxy execution.

Quoted 5 lines
Fixes 7de9d4f94638 ("sched: Start blocked_on chain processing in find_proxy_task()")
---
 kernel/sched/core.c | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

So this looks like it duplicates the following two changes in my series:
https://lore.kernel.org/lkml/[email protected]/
https://lore.kernel.org/lkml/[email protected]/

And I've recently found there's a few other spots that we need to bound chain walking (though I believe those additional cases are still out of tree in the full proxy-exec series).

thanks
-john

#10 lore raw

RFC PATCH 4/8 sched/proxy: Tell the class about a proxy migration

In reply to Mathieu Desnoyers

find_proxy_task() moves a blocked donor to the runqueue of the mutex owner. proxy_set_task_cpu() does this with __set_task_cpu(), so that it can keep p->wake_cpu, the CPU the donor returns to.

But __set_task_cpu() skips what set_task_cpu() does around it:
- the migrate_task_rq() method of the class;
- the migration count and the perf event;
- the sched_migrate_task tracepoint.

For a fair task, the dequeue on the old runqueue detaches its load. migrate_task_rq_fair() would then reset last_update_time, which makes the enqueue on the new runqueue attach the load. Without that call, the load is attached nowhere. When the donor is woken, the return migration goes through set_task_cpu(). It removes that load from the owner's runqueue, which never got it.

So each round trip of a donor lowers the load and the utilization of the owner's runqueue. In a test, a CPU with two tasks that never sleep showed a mean util_avg of 195, where 1024 is expected. schedutil would then pick a low frequency for a CPU that is fully busy, and the load balancer would see that CPU as nearly idle.

Fix this by doing in proxy_set_task_cpu() what set_task_cpu() does around __set_task_cpu(). Tracers and perf now see a proxy migration as a migration, and nr_migrations counts it.

migrate_task_rq_dl() moves the bandwidth of a task that migrates to another root domain. "sched/deadline: Move a task's bandwidth to the root domain it runs in" added that. A proxy migration must not do it:
the task does not run where it is queued. So make migrate_task_rq_dl() leave the bandwidth of such a task in its root domain. If its wake-up then picks a CPU of another root domain, the bandwidth moves at that time.

Fixes b049b81bdff6 ("sched: Handle blocked-waiter migration (and return migration)")
---
 kernel/sched/core.c     | 13 +++++++++++++
 kernel/sched/deadline.c |  8 +++++++-
 2 files changed, 20 insertions(+), 1 deletion(-)
kernel/sched/core.c +13 -0
index 24105eeeb3c7..5d82c343662f 100644
@@ -6967,6 +6967,19 @@ static inline void proxy_set_task_cpu(struct task_struct *p, int cpu)
 	 * was previously runnable.
 	 */
 	wake_cpu = p->wake_cpu;
+	/*
+	 * Tell the class and the tracers about the migration, as
+	 * set_task_cpu() does. The fair class then attaches the load of @p
+	 * to the new runqueue. Without that, the return migration removes
+	 * load that the runqueue never got.
+	 */
+	trace_sched_migrate_task(p, cpu);
+	if (task_cpu(p) != cpu) {
+		if (p->sched_class->migrate_task_rq)
+			p->sched_class->migrate_task_rq(p, cpu);
+		p->se.nr_migrations++;
+		perf_event_task_migrate(p);
+	}
 	__set_task_cpu(p, cpu);
 	p->wake_cpu = wake_cpu;
 }
kernel/sched/deadline.c +7 -1
index 3b62ee43c209..d14ce3615ba6 100644
@@ -3030,8 +3030,14 @@ static void migrate_task_rq_dl(struct task_struct *p, int new_cpu)
 	 * the bandwidth. A mask can hold CPUs of two root domains, and
 	 * select_fallback_rq() can widen it. Move the bandwidth there, as
 	 * dl_task_offline_migration() does for a throttled task.
+	 *
+	 * Not for a task that is blocked on a mutex and only queued for
+	 * proxy execution. It does not run on the new CPU, so its bandwidth
+	 * stays in its root domain. If its wake-up then picks a CPU of another
+	 * root domain, the bandwidth moves at that time.
 	 */
-	if (unlikely(dl_task_bw_elsewhere(p, new_cpu)))
+	if (unlikely(dl_task_bw_elsewhere(p, new_cpu)) &&
+	    !(p->is_blocked && task_on_rq_migrating(p)))
 		dl_task_move_bw(p, new_cpu);
 
 	if (READ_ONCE(p->__state) != TASK_WAKING)
Signature · 1 line
2.47.3
#11 lore raw

Re: [RFC PATCH v1 4/8] sched/proxy: Tell the class about a proxy migration

Quoted 56 lines · Mathieu Desnoyers

find_proxy_task() moves a blocked donor to the runqueue of the mutex owner. proxy_set_task_cpu() does this with __set_task_cpu(), so that it can keep p->wake_cpu, the CPU the donor returns to.

But __set_task_cpu() skips what set_task_cpu() does around it:
- the migrate_task_rq() method of the class;
- the migration count and the perf event;
- the sched_migrate_task tracepoint.

For a fair task, the dequeue on the old runqueue detaches its load. migrate_task_rq_fair() would then reset last_update_time, which makes the enqueue on the new runqueue attach the load. Without that call, the load is attached nowhere. When the donor is woken, the return migration goes through set_task_cpu(). It removes that load from the owner's runqueue, which never got it.

So each round trip of a donor lowers the load and the utilization of the owner's runqueue. In a test, a CPU with two tasks that never sleep showed a mean util_avg of 195, where 1024 is expected. schedutil would then pick a low frequency for a CPU that is fully busy, and the load balancer would see that CPU as nearly idle.

Fix this by doing in proxy_set_task_cpu() what set_task_cpu() does around __set_task_cpu(). Tracers and perf now see a proxy migration as a migration, and nr_migrations counts it.

migrate_task_rq_dl() moves the bandwidth of a task that migrates to another root domain. "sched/deadline: Move a task's bandwidth to the root domain it runs in" added that. A proxy migration must not do it:
the task does not run where it is queued. So make migrate_task_rq_dl() leave the bandwidth of such a task in its root domain. If its wake-up then picks a CPU of another root domain, the bandwidth moves at that time.

Fixes b049b81bdff6 ("sched: Handle blocked-waiter migration (and return migration)")
---
 kernel/sched/core.c     | 13 +++++++++++++
 kernel/sched/deadline.c |  8 +++++++-
 2 files changed, 20 insertions(+), 1 deletion(-)
kernel/sched/core.c +6 -0
index 24105eeeb3c7..5d82c343662f 100644
@@ -6967,6 +6967,19 @@ static inline void proxy_set_task_cpu(struct task_struct *p, int cpu)
         * was previously runnable.
         */
        wake_cpu = p->wake_cpu;
+       /*
+        * Tell the class and the tracers about the migration, as
+        * set_task_cpu() does. The fair class then attaches the load of @p
+        * to the new runqueue. Without that, the return migration removes
+        * load that the runqueue never got.
+        */

kernel/sched/core.c static inline void proxy_set_task_cpu(struct task_struct *p, int cpu) · line 6985

Quoted 10 lines
kernel/sched/core.c +7 -0
+       trace_sched_migrate_task(p, cpu);
+       if (task_cpu(p) != cpu) {
+               if (p->sched_class->migrate_task_rq)
+                       p->sched_class->migrate_task_rq(p, cpu);
+               p->se.nr_migrations++;
+               perf_event_task_migrate(p);
+       }
        __set_task_cpu(p, cpu);
        p->wake_cpu = wake_cpu;
 }

So I've got a pending fix from Yu-Ting in my tree (apologies for the gerrit link, I've not cleaned up and pushed my tree out yet) that I believe duplicates the bit above:
https://r.android.com/4410518

Quoted 10 lines
kernel/sched/deadline.c +2 -0
index 3b62ee43c209..d14ce3615ba6 100644
@@ -3030,8 +3030,14 @@ static void migrate_task_rq_dl(struct task_struct *p, int new_cpu)
         * the bandwidth. A mask can hold CPUs of two root domains, and
         * select_fallback_rq() can widen it. Move the bandwidth there, as
         * dl_task_offline_migration() does for a throttled task.
+        *
+        * Not for a task that is blocked on a mutex and only queued for

kernel/sched/deadline.c static void migrate_task_rq_dl(struct task_struct *p, int new_cpu) · line 3043

Quoted 10 lines
kernel/sched/deadline.c +5 -1
+        * proxy execution. It does not run on the new CPU, so its bandwidth
+        * stays in its root domain. If its wake-up then picks a CPU of another
+        * root domain, the bandwidth moves at that time.
         */
-       if (unlikely(dl_task_bw_elsewhere(p, new_cpu)))
+       if (unlikely(dl_task_bw_elsewhere(p, new_cpu)) &&
+           !(p->is_blocked && task_on_rq_migrating(p)))
                dl_task_move_bw(p, new_cpu);
 
        if (READ_ONCE(p->__state) != TASK_WAKING)

I may need to pull this bit in separately.

thanks!
-john

#12 lore raw

Re: [RFC PATCH v1 4/8] sched/proxy: Tell the class about a proxy migration

Quoted 4 lines · John Stultz

So I've got a pending fix from Yu-Ting in my tree (apologies for the gerrit link, I've not cleaned up and pushed my tree out yet) that I believe duplicates the bit above:
https://r.android.com/4410518

Fine with me. pelt_migration (case 5) passes on your tree, so please drop the core.c part of this patch.

Quoted 6 lines

kernel/sched/deadline.c static void migrate_task_rq_dl(struct task_struct *p, int new_cpu) · line 3041

Quoted 4 lines
kernel/sched/deadline.c +2 -1
-       if (unlikely(dl_task_bw_elsewhere(p, new_cpu)))
+       if (unlikely(dl_task_bw_elsewhere(p, new_cpu)) &&
+           !(p->is_blocked && task_on_rq_migrating(p)))
                dl_task_move_bw(p, new_cpu);

I may need to pull this bit in separately.

You should not need it. On tip, migrate_task_rq_dl() returns at once for a task that is not TASK_WAKING. So a proxy migration that calls it does nothing there. Only my deadline series makes it move bandwidth, so I will carry this check in that series.

The check leaves the bandwidth where it is. task_woken_dl() moves it when the task wakes in another root domain. That needs the full wake-up path for deadline tasks, which dropping the shortcut of patch 2 keeps.

Thanks,

Mathieu

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

RFC PATCH 5/8 sched/proxy: Clear blocked_donor when the donor stops donating

In reply to Mathieu Desnoyers

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 move_queued_task(). The clear takes the blocked_lock of the running task, which the unlock path holds while it uses the pointer.

Fixes 1628b25248d0 ("sched: Add blocked_donor link to task for smarter mutex handoffs")
---
 kernel/sched/core.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
kernel/sched/core.c +31 -0
index 5d82c343662f..de357acfec56 100644
@@ -2584,6 +2584,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)
+		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.
  *
@@ -2595,6 +2622,7 @@ static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
 {
 	lockdep_assert_rq_held(rq);
 
+	proxy_clear_curr_donor(rq, p);
 	deactivate_task(rq, p, DEQUEUE_NOCLOCK);
 	set_task_cpu(p, new_cpu);
 	rq_unlock(rq, rf);
@@ -3995,6 +4023,7 @@ static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p)
 {
 	return false;
 }
+
 #endif /* CONFIG_SCHED_PROXY_EXEC */
 
 static void
@@ -4068,6 +4097,7 @@ static int ttwu_runnable(struct task_struct *p, int wake_flags)
 
 		if (p->se.sched_delayed)
 			enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED);
+		proxy_clear_curr_donor(rq, p);
 		returned = proxy_needs_return(rq, p);
 		/*
 		 * @p was blocked and this CPU runs a proxy. If @p is the donor
@@ -7031,6 +7061,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.47.3
#14 lore raw

Re: [RFC PATCH v1 5/8] sched/proxy: Clear blocked_donor when the donor stops donating

Quoted 17 lines · Mathieu Desnoyers

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.

Quoted 7 lines

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 move_queued_task(). The clear takes the blocked_lock of the running task, which the unlock path holds while it uses the pointer.

Fixes 1628b25248d0 ("sched: Add blocked_donor link to task for smarter mutex handoffs")

Again, I'll have to spend a bit more time looking at this one. I've been looking at some task->blocked_donor lifetime concerns recently, so I agree its definitely an issue.

The blocked_donor is used for mutex handoff, and whole-chain proxy migration. The first only needs the curr->blocked_donor to be correct and never traverses further back down the chain, where as the second is used to migrate the entire current chain. Since the while-chain proxy migration happens in __schedule()->find_proxy_task() where the blocked_donor is set, it seems like clearing the blocked_donors as we enqueue them for migration is a good idea (and cheap since we're already iterating down the chain), and I've got a patch I'm working on for this already.

This patch's approach of of checking and clearing curr->blocked_donor, a task wakeup sounds reasonable, since it would prevent the mutex handoff from potentially reaching for a task that's exited. Using proxy_needs_return() should ensure we catch tasks in the donor chain on wakeup. My only worry is that the wakeup and clearing might trip while a proxy-chain is being migrated (and we don't want unexpected writes breaking the chain), but I think we're ok because we hold the rq lock as we walk blocked_donor and create the whole chain migration list, and we shouldn't need blocked_donor after that. So, I think it seems ok.

That said, Its not immediately obvious to me why clearing on move_queued_task() is needed? Mostly because: why would a proxy blocked task be migrated before wakeup? If a proxy-blocked task were migrated away, __schedule() would just proxy migrate it back to the current lock owner's rq.

thanks
-john

#15 lore raw

Re: [RFC PATCH v1 5/8] sched/proxy: Clear blocked_donor when the donor stops donating

Quoted 5 lines · John Stultz

That said, Its not immediately obvious to me why clearing on move_queued_task() is needed? Mostly because: why would a proxy blocked task be migrated before wakeup? If a proxy-blocked task were migrated away, __schedule() would just proxy migrate it back to the current lock owner's rq.

Another task can move it. For example, sched_setaffinity() on the
donor: affine_move_task() calls move_queued_task() for a task that is queued and not running. The donor is then queued on another runqueue. If it is woken there, the clear at wake-up runs on that runqueue. It does not see the owner. The owner still runs on the old CPU, with blocked_donor pointing at the donor. Your proxy_needs_return() clear has the same limit. The proxy migration back that you describe only happens if the new CPU picks the donor before it is woken.

Quoted 1 line

as you mentioned there's no test case in your test for this logic.

Right. It was found by reading, and I did not try to reproduce it. The owner would have to stay in the kernel without scheduling while the donor exits and is freed.

Thanks,

Mathieu

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

RFC PATCH 6/8 sched/deadline: Use the root domain a proxy-migrated task runs in

In reply to Mathieu Desnoyers

With proxy execution, find_proxy_task() can queue a task blocked on a mutex on the runqueue of the mutex owner. It ignores the affinity of the task, which does not run there. The task returns to p->wake_cpu when it is woken.

__sched_setscheduler() checks that the affinity of a task covers its root domain before it lets the task use SCHED_DEADLINE. It takes the root domain from the runqueue the task is on. sched_dl_overflow() admits the bandwidth of a task that enters the class in the root domain of task_cpu(). Both predate proxy execution, when a task was always queued on a CPU it can run on.

When the mutex owner is in another root domain, both use the wrong one. sched_setattr() fails with EPERM for a deadline task that waits for the mutex, and for a task that asks for SCHED_DEADLINE while it waits. In a test with two cpuset partitions, both calls failed. Without proxy execution they work.

Fix this by adding task_home_cpu(), which returns p->wake_cpu for such a task, and by using its root domain in both places. An affinity change or a CPU hotplug can leave p->wake_cpu stale while the task is queued elsewhere. task_home_cpu() then returns an active CPU of the task's mask.

Fixes b049b81bdff6 ("sched: Handle blocked-waiter migration (and return migration)")
---
 kernel/sched/deadline.c |  2 +-
 kernel/sched/sched.h    | 23 +++++++++++++++++++++++
 kernel/sched/syscalls.c |  9 +++++++--
 3 files changed, 31 insertions(+), 3 deletions(-)
kernel/sched/deadline.c +1 -1
index d14ce3615ba6..c55967135df0 100644
@@ -4625,7 +4625,7 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	if (new_bw == p->dl.dl_bw && counted)
 		return 0;
 
-	cpu = counted && p->dl.dl_bw ? p->dl.dl_bw_cpu : task_cpu(p);
+	cpu = counted && p->dl.dl_bw ? p->dl.dl_bw_cpu : task_home_cpu(p);
 	dl_b = dl_bw_of(cpu);
 
 	/*
kernel/sched/sched.h +23 -0
index f80ea5541b3f..7f5e45a86285 100644
@@ -2585,6 +2585,29 @@ static inline int task_on_rq_queued(struct task_struct *p)
 	return READ_ONCE(p->on_rq) == TASK_ON_RQ_QUEUED;
 }
 
+/*
+ * Return the CPU where @p runs, or will run. Proxy execution can queue a
+ * task blocked on a mutex on the CPU of the mutex owner. The task does
+ * not run there. It returns to p->wake_cpu when it is woken. The caller
+ * holds the rq lock of @p.
+ */
+static inline int task_home_cpu(struct task_struct *p)
+{
+	int cpu = p->wake_cpu;
+
+	if (!sched_proxy_exec() || !p->is_blocked || !task_on_rq_queued(p))
+		return task_cpu(p);
+
+	/*
+	 * An affinity change or a CPU hotplug can leave wake_cpu stale
+	 * while the task is queued elsewhere.
+	 */
+	if (cpumask_test_cpu(cpu, p->cpus_ptr) && cpu_active(cpu))
+		return cpu;
+	cpu = cpumask_any_and(p->cpus_ptr, cpu_active_mask);
+	return cpu < nr_cpu_ids ? cpu : task_cpu(p);
+}
+
 static inline int task_on_rq_migrating(struct task_struct *p)
 {
 	return READ_ONCE(p->on_rq) == TASK_ON_RQ_MIGRATING;
kernel/sched/syscalls.c +7 -2
index 59d78ae6b9fd..a88a6ddc500e 100644
@@ -647,7 +647,12 @@ int __sched_setscheduler(struct task_struct *p,
 #endif /* CONFIG_RT_GROUP_SCHED */
 		if (dl_bandwidth_enabled() && dl_policy(policy) &&
 				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
-			cpumask_t *span = rq->rd->span;
+			/*
+			 * Use the root domain @p runs in. Proxy execution can
+			 * have queued it in the root domain of a mutex owner.
+			 */
+			struct root_domain *rd = cpu_rq(task_home_cpu(p))->rd;
+			cpumask_t *span = rd->span;
 
 			/*
 			 * Don't allow tasks with an affinity mask smaller than
@@ -655,7 +660,7 @@ int __sched_setscheduler(struct task_struct *p,
 			 * will also fail if there's no bandwidth available.
 			 */
 			if (!cpumask_subset(span, &p->cpus_mask) ||
-			    rq->rd->dl_bw.bw == 0) {
+			    rd->dl_bw.bw == 0) {
 				retval = -EPERM;
 				goto unlock;
 			}
Signature · 1 line
2.47.3
#17 lore raw

RFC PATCH 7/8 lib: Add test_proxy_exec, kernel mutexes that user space can hold

In reply to Mathieu Desnoyers

Proxy execution acts on tasks blocked on a struct mutex. To test it, user space must block tasks on a kernel mutex in a chosen way:
- hold the mutex for a chosen time;
- block on it from a chosen task and CPU;
- take two mutexes in opposite orders.

No system call gives that control. The mutexes that system calls take are held for a short time that user space does not choose. Their locking can change with the subsystem. And user space cannot make two tasks deadlock on two kernel mutexes.

Add a test module with eight mutexes and a debugfs file. A write to the file runs one command:
- hold a mutex while busy or asleep;
- take a mutex, interruptibly or not;
- take two mutexes, one inside the other. The inner lock is killable, so that a test can end a deadlock it made.
The write returns when the command is done.

The selftest added by the next patch uses it.

---
 lib/Kconfig.debug     |  11 ++++
 lib/Makefile          |   1 +
 lib/test_proxy_exec.c | 132 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 144 insertions(+)
 create mode 100644 lib/test_proxy_exec.c
lib/Kconfig.debug +11 -0
index 2d22638ec13a..8d032d7fa387 100644
@@ -1361,6 +1361,17 @@ config TEST_CSD_LOCK
 
 	  If unsure, say N.
 
+config TEST_PROXY_EXEC
+	tristate "Test module for proxy execution"
+	depends on DEBUG_FS
+	help
+	  This builds the "test_proxy_exec" module. It creates kernel
+	  mutexes that user space can hold, take and chain through
+	  debugfs. The selftests in tools/testing/selftests/sched/proxy_exec
+	  use it to block tasks on a mutex in a chosen way.
+
+	  If unsure, say N.
+
 config TEST_LOCKUP
 	tristate "Test module to generate lockups"
 	depends on m
lib/Makefile +1 -0
index a2afe954805c..8add2a1473df 100644
@@ -101,6 +101,7 @@ obj-$(CONFIG_TEST_OBJAGG) += test_objagg.o
 obj-$(CONFIG_TEST_MEMINIT) += test_meminit.o
 obj-$(CONFIG_TEST_CSD_LOCK) += test_csd_lock.o
 obj-$(CONFIG_TEST_LOCKUP) += test_lockup.o
+obj-$(CONFIG_TEST_PROXY_EXEC) += test_proxy_exec.o
 obj-$(CONFIG_TEST_HMM) += test_hmm.o
 obj-$(CONFIG_TEST_FREE_PAGES) += test_free_pages.o
 obj-$(CONFIG_TEST_REF_TRACKER) += test_ref_tracker.o
lib/test_proxy_exec.c new file +132 -0

132 lines not on this page · raw message

Signature · 1 line
2.47.3
#18 lore raw

RFC PATCH 8/8 selftests/sched: Add tests of proxy execution

In reply to Mathieu Desnoyers

Add proxy_exec_test. It blocks tasks on the mutexes of the test_proxy_exec module. It checks when the waiter runs, and what the runqueue and the root domain of the owner count.
It skips without the module.

These cases fail with proxy execution, and pass with the fix named for each:
- handoff_fifo, handoff_deadline and signal_fifo: "sched/proxy:
Reschedule when a blocked task is woken under a proxy"
- pushable_fifo: "sched/proxy: Wake blocked RT and deadline tasks through the full path"
- pelt_migration: "sched/proxy: Tell the class about a proxy migration"
- deadlock_cycle: "sched/proxy: Stop the chain walk when the blocked_on chain is a cycle"
- dl_setattr_moved and dl_admit_moved: "sched/deadline: Use the root domain a proxy-migrated task runs in"

All of them pass with sched_proxy_exec=0.

deadlock_cycle makes two tasks deadlock on two kernel mutexes, then kills them. A kernel without the fix locks up. So it runs only with PROXY_EXEC_TEST_DEADLOCK=1.

The last two cases block a task of one cpuset partition on a mutex held in another one. Proxy execution then queues it on a CPU of the other root domain. sched_setattr() must work on it there, and its bandwidth must be counted in the root domain of its own cpuset.

A waiter spins while the mutex owner runs on another CPU. It blocks only when the owner is preempted. The cases with several CPUs arrange that.

---
 tools/testing/selftests/Makefile              |   1 +
 .../selftests/sched/proxy_exec/.gitignore     |   1 +
 .../selftests/sched/proxy_exec/Makefile       |   7 +
 .../testing/selftests/sched/proxy_exec/config |   5 +
 .../sched/proxy_exec/proxy_exec_test.c        | 913 ++++++++++++++++++
 .../selftests/sched/proxy_exec/settings       |   1 +
 6 files changed, 928 insertions(+)
 create mode 100644 tools/testing/selftests/sched/proxy_exec/.gitignore
 create mode 100644 tools/testing/selftests/sched/proxy_exec/Makefile
 create mode 100644 tools/testing/selftests/sched/proxy_exec/config
 create mode 100644 tools/testing/selftests/sched/proxy_exec/proxy_exec_test.c
 create mode 100644 tools/testing/selftests/sched/proxy_exec/settings
tools/testing/selftests/Makefile +1 -0
index 35b0c5e86ba7..73c75d289090 100644
@@ -121,6 +121,7 @@ TARGETS += rseq
 TARGETS += rtc
 TARGETS += rust
 TARGETS += sched/deadline
+TARGETS += sched/proxy_exec
 TARGETS += sched_ext
 TARGETS += seccomp
 TARGETS += sgx
tools/testing/selftests/sched/proxy_exec/.gitignore new file +1 -0
new file mode 100644
index 000000000000..335ddcf0127b
@@ -0,0 +1 @@
+proxy_exec_test
tools/testing/selftests/sched/proxy_exec/Makefile new file +7 -0
new file mode 100644
index 000000000000..bbc04a47ede2
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0+
+
+CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES)
+
+TEST_GEN_PROGS := proxy_exec_test
+
+include ../../lib.mk
tools/testing/selftests/sched/proxy_exec/config new file +5 -0
new file mode 100644
index 000000000000..9a50fb341a74
@@ -0,0 +1,5 @@
+CONFIG_CGROUPS=y
+CONFIG_CPUSETS=y
+CONFIG_DEBUG_FS=y
+CONFIG_SCHED_PROXY_EXEC=y
+CONFIG_TEST_PROXY_EXEC=m
tools/testing/selftests/sched/proxy_exec/proxy_exec_test.c new file +913 -0

913 lines not on this page · raw message

tools/testing/selftests/sched/proxy_exec/settings new file +1 -0
new file mode 100644
index 000000000000..6091b45d226b
@@ -0,0 +1 @@
+timeout=120
Signature · 1 line
2.47.3
#19 lore raw
In reply to Mathieu Desnoyers
Quoted 6 lines · Mathieu Desnoyers

Hi John, Peter,

This series fixes six problems of proxy execution, and adds a test module and a selftest for them. I found them while I looked at how SCHED_DEADLINE priority inheritance could move to proxy execution.

Hey Mathieu!
Thanks so much for sending these out! I've unfortunately been
completely underwater since LPC, so I've unfortunately not been able to be very responsive on the list (and apologies also to everyone who's sent patches or feedback to my last revision of the patch set). But I have been collecting some fixes that have come up during this time to include in my next submission. I think there is some overlap in a few cases where we've both tried to fix the same problem, I'll try to get some quick feedback on your patches and see what I can pull into my pending set as well here.

I'm really excited for the additional test cases!

Thanks so much again!
-john

#20 lore raw
In reply to Mathieu Desnoyers
Quoted 11 lines · Mathieu Desnoyers

Hi John, Peter,

This series fixes six problems of proxy execution, and adds a test module and a selftest for them. I found them while I looked at how SCHED_DEADLINE priority inheritance could move to proxy execution.

It applies on top of v6 of my deadline series (link below). Patches 4 and 6 need it: they change code that v6 adds to the deadline bandwidth accounting. Patches 1, 2, 3 and 5 do not.

Just following up again after playing with your tests and patches:

So I picked up your test-driver and kselftest patches first. Initially with my tree, only tests 5 & 8 passed (with sched_proxy_exec enabled, with it disabled all but 6 pass).

Now, I know this series is dependent on your deadline series, but I figured I'd try to pull the independent changes first.

Quoted 4 lines

The fixes:

1 Reschedule when a blocked task is woken under a proxy, so that the
old owner stops running on the donor's context.

With a variation of this one, tests 1, 2, 3, 5 & 8 passed.

Quoted 2 lines

2 Wake blocked RT and deadline tasks through the full wake-up path, so
that they are pushable and another CPU can take them.

With a variation of this one (basically dropping the shortcut rather then special casing dl/rt tasks), tests 1-5 & 8 pass.

Quoted 2 lines

3 Stop the chain walk when the blocked_on chain is a cycle, so that a
mutex deadlock no longer locks up the CPU.

Already have a fix for this.

Quoted 3 lines

4 Tell the class about a proxy migration, so that the load of a fair
donor is attached to the runqueue it moves to. The bandwidth of a deadline donor stays in its root domain.

Have a partial fix for this already, but the deadline donor bit is dependent on your other series.

Quoted 2 lines

5 Clear blocked_donor when the donor stops donating, so that the
unlock path does not use a task that can be freed.

I've taken a varient of this (only clearing on proxy_needs_return() - happy to expand that but I want to understand your reasons more) and have some related changes to clearing blockd_donor in other cases, but as you mentioned there's no test case in your test for this logic.

Quoted 2 lines

6 Check and admit a proxy-migrated deadline task in its own root
domain, so that sched_setattr() no longer fails with EPERM.

This one I couldn't take as it was dependent on your other series.

Basically after the first two patches tests 6, and 7 continue to fail. Interestingly, 7 does pass with proxy-exec off, so I need to look closer to understand what is happening in that case that isn't dependent on your other DL patch series.

Quoted 6 lines

Points I would like your opinion on:
- Patch 2 sends RT and deadline tasks through the full wake-up again. That undoes part of commit 7918cf369361 ("sched/proxy: Only return migrate when needed") for these classes. Putting the woken task on the pushable list in place would keep the optimization, but it needs a hook into the classes.

I'm not opposed to dropping the optimization for now, but Peter added it so he may feel more strongly and I'd defer to him :)

Quoted 3 lines

- Patch 1 reschedules for any blocked task woken on a runqueue that runs a proxy. A fair task woken from a delayed dequeue there also triggers it. That is harmless, but not free.

Agreed. Would adding the resched_curr() logic to an else statement for the if (p->se.sched_delayed) check avoid some of this? As I replied to the patch it also catches cases where the we're proxying but the woken task is not part of the current chain.

Quoted 2 lines

- Patch 3 also stops the donation on a ww_mutex cycle that the wound or die path is about to break. The donor then sleeps on its mutex.

Is this a concern or did you verify this occurs? I thought we wound/kill tasks before the cycle gets created (see __mutex_lock_common(), before we call set_task_blocked_on()). Maybe I'm forgetting something?

Quoted 3 lines

- Patch 4 repeats in proxy_set_task_cpu() what set_task_cpu() does around __set_task_cpu(). A helper shared by both would keep them from drifting apart. I left it out to keep the fix small.

I've already done this in my version.

Thanks again for the extra testing and sending these patches out. I'll include the one's I've picked up in my next patch series iteration on the list, and hopefully we can sort out the deadline bits once your DL series has landed.

thanks
-john

#21 lore raw

Hi John,

Thanks for running the tests on your tree. I answered on patches 1, 2, 4 and 5. The rest is below.

Quoted 4 lines · John Stultz
Quoted 2 lines

3 Stop the chain walk when the blocked_on chain is a cycle, so that a
mutex deadlock no longer locks up the CPU.

Already have a fix for this.

deadlock_cycle (case 8) passes on your tree, so please drop mine.

Quoted 4 lines
Quoted 2 lines

6 Check and admit a proxy-migrated deadline task in its own root
domain, so that sched_setattr() no longer fails with EPERM.

This one I couldn't take as it was dependent on your other series.

Only one line of it depends on that series. On tip, that line becomes task_home_cpu(p) in place of task_cpu(p) in sched_dl_overflow(). I can post patch 6 on tip if you want to take it.

Quoted 4 lines

Basically after the first two patches tests 6, and 7 continue to fail. Interestingly, 7 does pass with proxy-exec off, so I need to look closer to understand what is happening in that case that isn't dependent on your other DL patch series.

Case 7 is what patch 6 fixes. Its sched_setattr() checks the root domain of the CPU the waiter was proxy-migrated to. That is the root domain of the mutex owner, not the waiter's own.

You also see case 6 fail with proxy execution off. It fails the same way on tip, so it is not a proxy execution bug. The waiter changes its parameters and then leaves SCHED_DEADLINE while it is blocked. Its bandwidth stays counted in its root domain:

  # total_bw A: before 52428, at 300ms 262143, after 262143

My deadline series fixes this. With it, the case passes with proxy execution off.

I also ran the selftest on your public proxy-exec-v33-7.4-pre-rc1 branch, with the test module added. The results match yours, except for case 5: Yu-Ting's fix is not on that branch.

Quoted 7 lines
Quoted 2 lines

- Patch 3 also stops the donation on a ww_mutex cycle that the wound or die path is about to break. The donor then sleeps on its mutex.

Is this a concern or did you verify this occurs? I thought we wound/kill tasks before the cycle gets created (see __mutex_lock_common(), before we call set_task_blocked_on()). Maybe I'm forgetting something?

You are right, and it was not verified. I wrote it from reading, and my was wrong. A task that wounds or kills another first clears the blocked_on of that task. The victim sets its blocked_on again under the wait_lock of its mutex. It then sees that it must back off, and clears blocked_on before it drops that lock. The chain walk takes the same lock before it follows the victim. So the walk never sees the cycle. Please ignore that point.

Thanks,

Mathieu

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