sched/deadline: bandwidth accounting fixes and selftests
Subsystems (5)
cover sched/deadline: bandwidth accounting fixes and selftests
Hi Juri,
Please find in this series eight fixes to SCHED_DEADLINE bandwidth accounting, on top of your four in sched/urgent, with the selftests that catch them.
One word before the details: I am at home with the concepts behind SCHED_DEADLINE, but not with its implementation, and these patches were written with an LLM assistant under my review ("How this was developed" below). So I am asking those who know this code for a careful reading of the fixes themselves. Each of them has a reproducer and was measured in VMs, which says that the symptom goes away, not that the fix is the one you would have written.
Two take the kernel down: a divide by zero in __dl_sub(), reachable from a debugfs write to a fair server while its CPU goes offline or comes online, and a BUG() when a deadline task's affinity has no active CPU left, which priority inheritance and CPU hotplug reach on a default kernel. The other six leave a root domain's total_bw, or a runqueue's this_bw, holding what its tasks do not: the root domain then admits deadline tasks beyond the capacity of its CPUs, or refuses every one of them and refuses to offline its last CPU, and on the runqueue side the kernel warns of the underflow.
They came out of a cgroup feature under development whose selftests hung and flaked where the accounting drifts. Each fix has a reproducer: five fail a case of the selftests here, one needs a kernel built without cpusets, and the two that crash have standalone reproducers I can post.
The fixes
=========
1 sched_setattr() with SCHED_FLAG_KEEP_PARAMS from SCHED_OTHER to
SCHED_DEADLINE fails after reserving bandwidth that nothing gives back.
2 __dl_sub() and __dl_add() divide a change of total_bw by the number
of active CPUs of the root domain, which is 0 while a CPU passes through the default one.
3 dl_task_root_domain_cpu() BUG()s when a deadline task's mask has no
active CPU, as a boosted mutex owner's does when its CPU goes offline.
4 a throttled task switched out of SCHED_DEADLINE and back before its
0-lag time is left throttled with nothing to replenish it: it never runs again, and a fatal signal cannot make it run.
5 a sleeper leaving the class releases bandwidth the root domain no
longer holds, or never held.
7 a rebuild of the root domains' accounting (any cpuset partition
change, CPU hotplug) forgets the bandwidth of the tasks that left the class, or died, before their 0-lag time: the inactive timer then removes it a second time, or from a root domain that never had it.
9 a task whose wakeup is left to the target CPU has its bandwidth on
no runqueue while task_cpu() already names the destination: a parameter change meanwhile takes it off a runqueue that never held it, and this_bw underflows there for good.
11 dl_rebuild_rd_accounting() is a stub without CONFIG_CPUSETS, so such
a kernel loses the bandwidth of every deadline task at the first hotplug.
Patch 10 is not a fix: sched_debug gains each runqueue's this_bw and running_bw, which is what makes patch 9's bug visible from userspace. Patches 6, 8 and 12 are the selftests, 48 cases in three programs.
Testing
=======
In 8 QEMU guests of 8 vCPUs, the 48 cases pass on the series, every time. No case fails on 4 vCPUs either, with PREEMPT_RT, with CONFIG_SCHED_PROXY_EXEC on and off, or on a kernel built without CONFIG_CPUSETS, where the cases that want a cpuset partition root skip. No kernel warning in any run.
A bisect over the series, one kernel per patch that changes kernel code, 2 guests each and the same test binaries throughout, says what each patch is worth in the suite:
base params_keep_class_change, throttled_round_trip,
pi_former_owner_asleep, dies_before_rebuild, switched_out_before_rebuild, moved_after_switch_out and random_mix fail
+1 params_keep_class_change passes
+4 throttled_round_trip passes
+5 pi_former_owner_asleep passes
+7 the three rebuild cases and random_mix pass
params_waking needs patch 10's sched_debug sums to run at all: on a kernel with patch 10 and without patch 9 it fails in 6 guests of 6, and random_mix catches that bug too, in 1 of 3. Patch 11 shows in the five hotplug cases of a kernel built without cpusets: three fail and two skip for want of room without it, and the five pass with it. Patches 2 and 3 move nothing in the suite, by design: an unfixed kernel dies, so their reproducers stand apart.
How this was developed
======================
These patches, their messages and the tests were written by an LLM coding assistant under my direction and review.
It started from the cgroup selftests of a feature I am developing, which the assistant also wrote: one of them hung about once in 1350 runs, and another failed about once in ten. Asking it to root-cause those two flakes, rather than work around them, gave patches 4 and 7. Reviewing your four fixes in sched/urgent with it gave patches 1 and 5. I then asked for a selftest of the bandwidth accounting in its own right, and for one area of coverage at a time: priority inheritance, parameter changes, cpuset moves, deaths, sched_yield(), runtime overruns, GRUB reclaiming, the fair servers, CPU hotplug, proxy execution, and a randomized mix of all of them. That is deadline_bw_test, and building it turned up patch 9, through the kernel's own this_bw underflow warning under a parameter-change load, and patch 11, on a build without cpusets. Patches 2 and 3 came from reading the code instead; their reproducers were written afterwards, and each takes an unfixed kernel down on the first round.
A second model reviewed the series, and its findings are folded in. The assistant got things wrong on the way as well: one diagnosis of patch 9's bug was wrong twice over and was settled only by instrumenting a kernel, and one assertion it had put in a test was itself racy and had to go. The per-patch bisect above exists because I asked whether every fix had a reproducer of its own.
Based on tip sched/urgent, at commit a2b67e904401 ("sched/deadline:
Reject SCHED_DEADLINE on exited tasks"); patch 5 builds on commit 41a7968022ca ("sched/deadline: Fix total_bw leak when switching away from SCHED_DEADLINE while !queued") there.
Mathieu Desnoyers (12):
sched: Reject SCHED_FLAG_KEEP_PARAMS before reserving deadline
bandwidth
sched/deadline: Do not divide by zero active CPUs of a root domain sched/deadline: Do not BUG() on a deadline task with no active CPU
allowed
sched/deadline: Do not lose a throttled task switched out and back sched/deadline: Do not release a departing sleeper's bandwidth twice selftests/sched: Add a test of SCHED_DEADLINE policy round trips sched/deadline: Keep departing bandwidth across a root domain rebuild selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain
rebuild
sched/deadline: Do not take a waking task's bandwidth off a runqueue
it left
sched/debug: Show the deadline bandwidth of each runqueue sched/deadline: Rebuild the root domains' accounting without cpusets
too
selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
include/linux/cpuset.h | 5 - include/linux/sched.h | 15 + include/linux/sched/deadline.h | 6 +- kernel/cgroup/cpuset.c | 11 +- kernel/sched/deadline.c | 316 +- kernel/sched/debug.c | 2 + kernel/sched/syscalls.c | 24 +- tools/testing/selftests/sched/.gitignore | 3 + tools/testing/selftests/sched/Makefile | 1 + .../selftests/sched/deadline_bw_test.c | 3182 +++++++++++++++++ .../selftests/sched/deadline_rebuild_test.c | 462 +++ .../selftests/sched/deadline_switch_test.c | 332 ++ 12 files changed, 4292 insertions(+), 67 deletions(-) create mode 100644 tools/testing/selftests/sched/deadline_bw_test.c create mode 100644 tools/testing/selftests/sched/deadline_rebuild_test.c create mode 100644 tools/testing/selftests/sched/deadline_switch_test.c
Signature · 1 line
2.47.3
PATCH 1/12 sched: Reject SCHED_FLAG_KEEP_PARAMS before reserving deadline bandwidth
__sched_setscheduler() returns -EINVAL for a SCHED_FLAG_KEEP_PARAMS request that would change scheduling class, after sched_dl_overflow() has reserved the bandwidth of the request, and nothing gives it back. Switching a SCHED_OTHER task to SCHED_DEADLINE that way fails and leaks the runtime that sched_setattr() filled in from the task's slice, up to 100ms with a custom one, into the root domain's total_bw. Repeated, it makes the root domain refuse every deadline task, and refuse to offline its last CPU.
Reserve the bandwidth after that check, last of the checks. A refused request also leaves sched_reset_on_fork as it was again.
--- kernel/sched/syscalls.c | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-)
kernel/sched/syscalls.c +13 -11
@@ -655,17 +655,6 @@ int __sched_setscheduler(struct task_struct *p, goto recheck; } -/* -* If setscheduling to SCHED_DEADLINE (or changing the parameters -* of a SCHED_DEADLINE task) we need to check if enough bandwidth -* is available. -*/ -if ((dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { - retval = -EBUSY ; - goto unlock; - } - - p->sched_reset_on_fork = reset_on_fork; oldprio = p->prio; newprio =__normal_prio (policy, attr->sched_priority, attr->sched_nice);
@@ -699,6 +688,19 @@ int __sched_setscheduler(struct task_struct *p, queue_flags |=DEQUEUE_CLASS ; } +/* +* If setscheduling to SCHED_DEADLINE (or changing the parameters +* of a SCHED_DEADLINE task) we need to check if enough bandwidth +* is available. Last of the checks: nothing gives back the +* bandwidth it reserves. +*/ +if ((dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { + retval = -EBUSY ; + goto unlock; + } + + p->sched_reset_on_fork = reset_on_fork; +scx_prepare_setscheduler (p, policy); scoped_guard (sched_change, p, queue_flags) {
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 01/12] sched: Reject SCHED_FLAG_KEEP_PARAMS before reserving deadline bandwidth
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] sched: bandwidth leak in __sched_setscheduler() under SCHED_FLAG_KEEP_PARAMS --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] sched: bandwidth leak in __sched_setscheduler() under SCHED_FLAG_KEEP_PARAMS --
commit 7875cab1acc5b85b363d87da8587a9ad5e4642f8
Author: Mathieu Desnoyers <[email protected]>
sched: Reject SCHED_FLAG_KEEP_PARAMS before reserving deadline bandwidth
This commit moves the sched_dl_overflow() check and sched_reset_on_fork update in __sched_setscheduler() after the SCHED_FLAG_KEEP_PARAMS class change check so rejected requests do not leak deadline bandwidth.
Quoted 26 lines
kernel/sched/syscalls.c +0
-11@@ -655,17 +655,6 @@ int __sched_setscheduler(struct task_struct *p, goto recheck; } -/* -* If setscheduling to SCHED_DEADLINE (or changing the parameters -* of a SCHED_DEADLINE task) we need to check if enough bandwidth -* is available. -*/ -if ((dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { - retval = -EBUSY ; - goto unlock; - } - - p->sched_reset_on_fork = reset_on_fork; oldprio = p->prio; newprio =__normal_prio (policy, attr->sched_priority, attr->sched_nice);@@ -699,6 +688,19 @@ int __sched_setscheduler(struct task_struct *p, queue_flags |=DEQUEUE_CLASS ; }
kernel/sched/syscalls.c int __sched_setscheduler(struct task_struct *p, · line 700
Quoted 10 lines
kernel/sched/syscalls.c +10
-0+/* +* If setscheduling to SCHED_DEADLINE (or changing the parameters +* of a SCHED_DEADLINE task) we need to check if enough bandwidth +* is available. Last of the checks: nothing gives back the +* bandwidth it reserves. +*/ +if ((dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { + retval = -EBUSY ; + goto unlock; + }
[Severity: High]
Can __sched_setscheduler() in kernel/sched/syscalls.c still leak dl_b->total_bw or corrupt rq->dl bandwidth accounting when SCHED_FLAG_KEEP_PARAMS is set?
When attr->sched_flags & SCHED_FLAG_KEEP_PARAMS is set, the sched_change block skips __setscheduler_params(p, attr):
kernel/sched/syscalls.c:__sched_setscheduler() {
...
scoped_guard (sched_change, p, queue_flags) {
if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
__setscheduler_params(p, attr);
p->sched_class = next_class;
p->prio = newprio;
__setscheduler_dl_pi(newprio, policy, p, scope);
}
__setscheduler_uclamp(p, attr);
...
}Because __setscheduler_params() is skipped, neither p->policy nor p->dl.dl_bw is updated. However, SCHED_FLAG_KEEP_PARAMS is only rejected when prev_class != next_class, and sched_dl_overflow(p, policy, attr) is still called even when SCHED_FLAG_KEEP_PARAMS is set.
This allows sched_dl_overflow() to modify deadline bandwidth without updating p->dl.dl_bw or p->policy in two paths:
1. If a non-deadline task (e.g. p->policy == SCHED_NORMAL, so !task_has_dl_policy(p) and p->dl.dl_bw == 0) is PI-boosted by a SCHED_DEADLINE waiter via rt_mutex_setprio(), p->sched_class is &dl_sched_class while p->policy remains SCHED_NORMAL. Calling sys_sched_setattr() with sched_policy = SCHED_DEADLINE and SCHED_FLAG_KEEP_PARAMS populates attr.sched_runtime = p->se.slice via get_params(). In __sched_setscheduler(), both prev_class and next_class are &dl_sched_class, so the prev_class != next_class check is bypassed. sched_dl_overflow() then sees dl_policy(policy) && !task_has_dl_policy(p) and adds new_bw to dl_b->total_bw via __dl_add(), while the SCHED_FLAG_KEEP_PARAMS check skips __setscheduler_params(), leaving p->policy as SCHED_NORMAL and p->dl.dl_bw as 0. When p deboosts, new_bw is never subtracted from dl_b->total_bw.
2. In SYSCALL_DEFINE3(sched_setattr), get_params(p, &attr, 0) reads p's deadline parameters without holding p->pi_lock or rq->__lock:
kernel/sched/syscalls.c:SYSCALL_DEFINE3(sched_setattr) {
...
if (attr.sched_flags & SCHED_FLAG_KEEP_PARAMS)
get_params(p, &attr, 0);
return sched_setattr(p, &attr);
}If a concurrent sched_setattr() updates a SCHED_DEADLINE task's parameters before __sched_setscheduler() acquires task_rq_lock(p, &rf), attr holds stale parameters where new_bw != p->dl.dl_bw while prev_class == next_class == &dl_sched_class. sched_dl_overflow() then updates dl_b->total_bw and calls dl_change_utilization(p, new_bw) to update rq->dl.this_bw and rq->dl.running_bw to the stale new_bw, while __setscheduler_params() is skipped, leaving p->dl.dl_bw out of sync with dl_b->total_bw and rq->dl.
Should __sched_setscheduler() also reject SCHED_FLAG_KEEP_PARAMS when policy != p->policy, and skip sched_dl_overflow() when SCHED_FLAG_KEEP_PARAMS is set?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Re: [PATCH 01/12] sched: Reject SCHED_FLAG_KEEP_PARAMS before reserving deadline bandwidth
On 2026-11-04 10:30, [email protected] wrote:
[...]
Quoted 4 lines
Should
__sched_setscheduler()also rejectSCHED_FLAG_KEEP_PARAMSwhen policy !=p->policy, and skipsched_dl_overflow()whenSCHED_FLAG_KEEP_PARAMSis set?
Both, and the first one is reproducible. Thank you, this is a real bug and not the one patch 1 fixes.
The boosted case, confirmed: __normal_prio(SCHED_DEADLINE) gives MAX_DL_PRIO - 1, so next_class is &dl_sched_class, and a task that priority inheritance has boosted is of that class already. prev_class == next_class, so the check of commit 8a70415351ba ("sched: Reject SCHED_FLAG_KEEP_PARAMS when it would change scheduling class") does not fire, sched_dl_overflow() takes its first branch (p->policy is still SCHED_NORMAL, so !task_has_dl_policy(p)) and adds the bandwidth of the request, and the skipped __setscheduler_params() never gives it to the task. Its dl_bw stays 0, so switched_from_dl() has nothing to release at the deboost.
A SCHED_OTHER owner of a PTHREAD_PRIO_INHERIT mutex with a slice of 40ms, boosted by a deadline waiter blocked on it, with one sched_setattr(SCHED_DEADLINE | SCHED_FLAG_KEEP_PARAMS) on the owner:
total_bw 419424 -> 838854 (+419430, 0.4 of a CPU), and there to stay
in 8-CPU VMs, on v7.4-rc1 with the four deadline fixes of sched/urgent as on this series, so it predates both.
The stale parameters: also real, by reading. sys_sched_setattr() fills the request in from the task (get_params()) with no lock held, and dl_param_changed() then takes the stale copy for a change, so sched_dl_overflow() moves total_bw, and this_bw and running_bw through dl_change_utilization(), to a bandwidth the task does not have; the release at its 0-lag time takes the task's own dl_bw and leaves the difference behind. I have not reproduced that one: it needs a parameter change of the task to land inside the window.
v2 will carry both fixes as two patches after patch 1:
- refuse SCHED_FLAG_KEEP_PARAMS that would change the policy, where only a class change was refused before. This also closes the boosted case, and it stops the kernel from answering 0 to a request it carries out by half: SCHED_OTHER to SCHED_BATCH with SCHED_FLAG_KEEP_PARAMS returns 0 today and leaves the policy alone. That is an ABI change, so say if you would rather keep accepting it;
- skip sched_dl_overflow() when SCHED_FLAG_KEEP_PARAMS is set, since there is nothing to admit for parameters that are kept. This is what closes the stale-parameter window.
Both carry Fixes: a509a7cd7974 ("sched/uclamp: Extend sched_setattr() to support utilization clamping"), which added the flag and the skip of __setscheduler_params(), and the selftest of patch 12 gains a case for the boosted one (params_keep_boosted).
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
PATCH 2/12 sched/deadline: Do not divide by zero active CPUs of a root domain
In reply to Mathieu Desnoyers__dl_sub() and __dl_add() spread a change of a root domain's total_bw over the extra_bw of its active CPUs, dividing it by their number, which their callers take from dl_bw_cpus(). That number is 0 for a root domain whose CPUs all went offline, such as the default root domain, which holds the offline CPUs: the division then traps.
A debugfs write of a fair server's runtime or period reaches it while its CPU goes offline or comes online. From the rebuild of the root domains in sched_cpu_deactivate() until the CPU is offline, and from the CPU online until sched_cpu_activate(), the CPU sits in the default root domain, with no active CPU. A write that leaves the server's bandwidth as it is passes admission there, __dl_overflow() comparing that root domain's capacity, 0, with total_bw less the old bandwidth plus the new, 0 as well, and dl_server_apply_params() divides. Any other value is refused with EBUSY, higher directly, lower through the unsigned subtraction. Once the CPU is offline the write is refused, since commit 4043f5498416 ("sched/deadline: Reject debugfs dl_server writes for offline CPUs").
Writing a fair server's own runtime back in a loop while its CPU goes offline and online oopses on the first round, in 8-CPU VMs of v7.4-rc1 with the four deadline fixes of sched/urgent:
Oops: divide error: 0000 [#1] SMP NOPTI CPU: 6 UID: 0 PID: 110 Comm: dl_server_div0 RIP: 0010:dl_server_apply_params+0x335/0x380 Call Trace: <TASK> sched_server_write_common.isra.0+0x1c0/0x260 full_proxy_write+0x58/0x90 vfs_write+0xcb/0x550 ksys_write+0x6c/0xe0 do_syscall_64+0x109/0x5d0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
inactive_task_timer() can reach it too, found by reading: it releases the bandwidth of a task that left SCHED_DEADLINE, or died, before its 0-lag time from the root domain of the CPU the task is on, and that CPU may go offline before the timer fires. With admission control off, so may sched_setattr() to SCHED_DEADLINE of a task asleep on an offline CPU.
With no active CPU there is no extra_bw to update: change total_bw alone. 20 rounds of the reproducer leave no warning then.
--- kernel/sched/deadline.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/sched/deadline.c +9 -2
@@ -189,18 +189,25 @@ void __dl_update(struct dl_bw *dl_b, s64 bw) } } +/* +* @cpus is the number of active CPUs of the root domain, whose extra_bw +* shares the change: none once they all went offline, and total_bw alone +* changes then. +*/ static inline void __dl_sub (struct dl_bw *dl_b,u64 tsk_bw,int cpus) { dl_b->total_bw -= tsk_bw; -__dl_update (dl_b, (s32 )tsk_bw / cpus); +if (cpus) +__dl_update (dl_b, (s32 )tsk_bw / cpus); }static inline void __dl_add (struct dl_bw *dl_b,u64 tsk_bw,int cpus) { dl_b->total_bw += tsk_bw; -__dl_update (dl_b, -((s32 )tsk_bw / cpus)); +if (cpus) +__dl_update (dl_b, -((s32 )tsk_bw / cpus)); } static inline bool
Signature · 1 line
2.47.3
PATCH 3/12 sched/deadline: Do not BUG() on a deadline task with no active CPU allowed
In reply to Mathieu Desnoyersdl_task_root_domain_cpu() finds the root domain that holds a deadline task's bandwidth from the first active CPU of the task's mask, and BUG()s when the mask has none. A mask can have none:
- a task boosted into the deadline class by priority inheritance keeps the affinity of its own policy, which may allow one CPU alone, or a cpuset of one. dl_task_needs_bw_move() and set_cpus_allowed_dl() take it for a deadline task, dl_task(p) being true, and look the root domain up from the mask they are replacing, which allows that CPU, inactive by then: the cpuset code updates the masks of a cpuset's tasks once the CPU is inactive, and select_fallback_rq() widens the mask of a task it pushes off that CPU;
- with admission control off (sched_rt_runtime_us at -1), a deadline task may be pinned to fewer CPUs than its root domain spans, and those may all go offline.
Both take the kernel down on the first try, in 8-CPU VMs of v7.4-rc1 with the four deadline fixes of sched/urgent. The priority inheritance one, which asks for no unusual configuration, through the wakeup of the boosted owner:
kernel BUG at kernel/sched/deadline.c:3340!
CPU: 7 UID: 0 PID: 0 Comm: swapper/7 RIP: 0010:set_cpus_allowed_dl+0xf0/0x100 Call Trace: <IRQ> set_cpus_allowed_force+0x9f/0xf0 cpuset_cpus_allowed_fallback+0x12b/0x1d0 select_fallback_rq+0x238/0x340 try_to_wake_up+0x2a0/0xb70
Fall back to the CPU the task last ran on, which these callers used before the commit this one fixes. Its root domain may have no active CPU
left: the previous patch has __dl_sub() and __dl_add() take that. Ten rounds of each case leave no warning with it.
--- kernel/sched/deadline.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +7 -1
@@ -3338,13 +3338,19 @@ static void task_woken_dl(struct rq *rq, struct task_struct *p)* current cpus_mask (not yet updated to the new mask) to find the * actual root domain. Use cpus_mask rather than cpus_ptr, which * may be temporarily narrowed by migrate_disable(). +* +* The mask has no active CPU left when the CPUs it allows went offline, +* which the affinity of a deadline task allows with admission control +* off, and that of a task boosted into the deadline class by priority +* inheritance always: fall back to the CPU the task last ran on. */ static unsigned int dl_task_root_domain_cpu (struct task_struct *p) {unsigned int cpu; cpu =cpumask_first_and (&p->cpus_mask, cpu_active_mask); -BUG_ON (cpu >= nr_cpu_ids); +if (cpu >= nr_cpu_ids) + cpu =task_cpu (p);return cpu; }
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 03/12] sched/deadline: Do not BUG() on a deadline task with no active CPU allowed
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] sched/deadline: stale root domain in dl_task_root_domain_cpu() fallback --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] sched/deadline: stale root domain in dl_task_root_domain_cpu() fallback --
commit 1ac76c29bedf1013e2c606590748a52f51b1170b
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Do not BUG() on a deadline task with no active CPU allowed
This commit replaces the BUG_ON(cpu >= nr_cpu_ids) in dl_task_root_domain_cpu() with a fallback to task_cpu(p) when a deadline task's cpus_mask contains no active CPUs.
Quoted 14 lines
kernel/sched/deadline.c +5
-0@@ -3338,13 +3338,19 @@ static void task_woken_dl(struct rq *rq, struct task_struct *p)* current cpus_mask (not yet updated to the new mask) to find the * actual root domain. Use cpus_mask rather than cpus_ptr, which * may be temporarily narrowed by migrate_disable(). +* +* The mask has no active CPU left when the CPUs it allows went offline, +* which the affinity of a deadline task allows with admission control +* off, and that of a task boosted into the deadline class by priority +* inheritance always: fall back to the CPU the task last ran on. */
kernel/sched/deadline.c static void task_woken_dl(struct rq *rq, struct task_struct *p) · line 3355
Quoted 10 lines
kernel/sched/deadline.c +2
-1static unsigned int dl_task_root_domain_cpu (struct task_struct *p) {unsigned int cpu; cpu =cpumask_first_and (&p->cpus_mask, cpu_active_mask); -BUG_ON (cpu >= nr_cpu_ids); +if (cpu >= nr_cpu_ids) + cpu =task_cpu (p);return cpu; }
[Severity: High]
When a deadline task's cpus_mask has no active CPUs left, can falling back to task_cpu(p) in dl_task_root_domain_cpu() return an offline or stale CPU whose root domain no longer holds p->dl.dl_bw?
For example, with admission control disabled (sched_rt_runtime_us == -1), suppose a SCHED_DEADLINE task p in top_cpuset is pinned via sched_setaffinity() to CPU 1 (so p->cpus_mask is {1}), runs on CPU 1 (task_cpu(p) == 1), and blocks.
When CPU 1 goes offline via sched_cpu_deactivate(), cpuset_handle_hotplug() does not rewrite p->cpus_mask for tasks in top_cpuset, so p->cpus_mask remains {1} and task_cpu(p) remains 1. During the domain rebuild:
partition_sched_domains_locked()
detach_destroy_domains() -> attaches offline CPU 1 to def_root_domain
build_sched_domains() -> attaches remaining active CPUs to rd_active
dl_rebuild_rd_accounting()
dl_clear_root_domain() -> sets def_root_domain.dl_bw.total_bw = 0
dl_add_task_root_domain(p)In kernel/sched/deadline.c:dl_add_task_root_domain():
msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl); dl_get_task_effective_cpus(p, msk); cpu = cpumask_first_and(cpu_active_mask, msk); BUG_ON(cpu >= nr_cpu_ids); rq = cpu_rq(cpu); dl_b = &rq->rd->dl_bw; raw_spin_lock(&dl_b->lock); __dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
dl_get_task_effective_cpus() queries cpuset_cpus_allowed_locked(), so p's bandwidth is accounted into rd_active->dl_bw.total_bw, whereas cpu_rq(task_cpu(p))->rd is def_root_domain. (Similarly, if a sleeping deadline task last ran on CPU A in partition A, was moved to a 1-CPU cpuset on CPU B without waking up, and CPU B goes offline, task_cpu(p) still points to CPU A in partition A.)
Because dl_task_root_domain_cpu(p) returns task_cpu(p) (CPU 1) while p->cpus_mask has no active CPUs:
1. In switched_from_dl(), if p changes policy away from SCHED_DEADLINE while sleeping, __dl_sub() subtracts p->dl.dl_bw from def_root_domain.dl_bw.total_bw (underflowing it from 0) instead of rd_active->dl_bw.total_bw, leaking p->dl.dl_bw in rd_active.
2. In dl_task_needs_bw_move() and set_cpus_allowed_dl():
cpu = dl_task_root_domain_cpu(p); return !cpumask_intersects(cpu_rq(cpu)->rd->span, new_mask);
cpu_rq(1)->rd->span is def_root_domain.span, which contains only offline CPUs and does not intersect any new_mask of active CPUs. Updating p's affinity to active CPUs in rd_active via sched_setaffinity() or cpuset_cpus_allowed_fallback() causes dl_task_needs_bw_move() to return true and set_cpus_allowed_dl() to subtract p->dl.dl_bw from def_root_domain.dl_bw.total_bw. Moving p via cpuset_can_attach() and cpuset_attach_task() to a child cpuset in the same root domain rd_active causes cpuset_reserve_dl_bw() to add p->dl.dl_bw a second time to rd_active->dl_bw.total_bw while set_cpus_allowed_dl() subtracts from def_root_domain; moving p to a different partition subtracts from def_root_domain instead of rd_active, leaking p->dl.dl_bw in rd_active.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
PATCH 4/12 sched/deadline: Do not lose a throttled task switched out and back
In reply to Mathieu DesnoyersA SCHED_DEADLINE task that is throttled, switched to another policy and switched back before its 0-lag time can be left throttled with nothing to replenish it: runnable, queued as far as the core is concerned, but on no dl_rq and with no timer pending. It never runs again, and a fatal signal cannot make it run; only another switch out of SCHED_DEADLINE requeues it.
1. the task exhausts its runtime: dl_throttled is set, and the
replenishment timer armed for the start of its next period;
2. sched_setscheduler() switches it to SCHED_OTHER: switched_from_dl()
calls task_non_contending(), which arms the inactive timer for the
0-lag time; the parameters are kept until then, so that leaving and
reentering SCHED_DEADLINE gains no bandwidth;
3. the replenishment timer fires: dl_task_timer() finds a task that is
not a deadline task and returns, dl_throttled still set; 4. sched_setattr() switches it back before the 0-lag time:
switched_to_dl() cancels the inactive timer, and enqueue_dl_entity() leaves a throttled task to its replenishment timer, which has fired already.
The window between the deadline and the 0-lag time is the overrun scaled by period/runtime: about 100us for an overrun of 20us at 20% bandwidth. The replenishment timer cleared the parameters, dl_throttled included, of a task it found out of SCHED_DEADLINE until commit 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization") moved that reset to the inactive timer, at the 0-lag time.
Clear dl_throttled there again. The deadline has passed by then, so a return before the 0-lag time starts a new period when the task is enqueued (ENQUEUE_MOVE, or the wakeup of a sleeper), as the replenishment would have; a return after it finds the parameters reset by the inactive timer, as before.
The selftest added two patches later fails its throttled_round_trip case 8 times out of 8, on v7.3 as on v7.4-rc1 with the four deadline fixes of sched/urgent, and passes it 8 times out of 8 with this change. It was found by a cgroup selftest under development, test_concurrency_deadline, which hung about once in 1350 runs.
--- kernel/sched/deadline.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/sched/deadline.c +9 -2
@@ -1232,10 +1232,17 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)/* * The task might have changed its scheduling policy to something -* different than SCHED_DEADLINE (through switched_from_dl()). +* different than SCHED_DEADLINE (through switched_from_dl()). It +* keeps its parameters until its 0-lag time and may come back to +* SCHED_DEADLINE before then, switched_to_dl() cancelling the +* inactive timer: it must not come back throttled, since this was +* its replenishment. Its deadline has passed: the enqueue starts a +* new period. */ -if (!dl_task (p)) +if (!dl_task (p)) { + dl_se->dl_throttled =0 ; goto unlock; + }/* * The task might have been boosted by someone else and might be in the
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 04/12] sched/deadline: Do not lose a throttled task switched out and back
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] sched/deadline: incomplete replenishment when clearing dl_throttled - [Medium] sched/deadline…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] sched/deadline: incomplete replenishment when clearing dl_throttled
- [Medium] sched/deadline: stale dl_yielded left set by dl_task_timer()
--
commit b274aa4dbc0a2822908373f43a14a8b8436d20eb
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Do not lose a throttled task switched out and back
This commit clears dl_se->dl_throttled in dl_task_timer() when a throttled SCHED_DEADLINE task has been switched to another scheduling policy before its replenishment timer fires, so that switching back to SCHED_DEADLINE before the 0-lag time does not leave the task permanently throttled.
Quoted 11 lines
kernel/sched/deadline.c +2
-1@@ -1232,10 +1232,17 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)/* * The task might have changed its scheduling policy to something -* different than SCHED_DEADLINE (through switched_from_dl()). +* different than SCHED_DEADLINE (through switched_from_dl()). It +* keeps its parameters until its 0-lag time and may come back to
kernel/sched/deadline.c static enum hrtimer_restart dl_task_timer(struct hrtimer *timer) · line 1245
Quoted 10 lines
kernel/sched/deadline.c +7
-1+* SCHED_DEADLINE before then, switched_to_dl() cancelling the +* inactive timer: it must not come back throttled, since this was +* its replenishment. Its deadline has passed: the enqueue starts a +* new period. */ -if (!dl_task (p)) +if (!dl_task (p)) { + dl_se->dl_throttled =0 ; goto unlock; + }
[Severity: Medium]
Could clearing only dl_se->dl_throttled here without calling replenish_dl_entity(dl_se) forgive negative runtime overruns and leave dl_se->deadline stale when the task switches back to SCHED_DEADLINE before its 0-lag time?
The window between the replenishment timer and the inactive timer exists specifically when a task has overrun its runtime (dl_se->runtime < 0), making the 0-lag time later than dl_next_period(dl_se). Normal replenishment in replenish_dl_entity() deducts that overrun from subsequent periods:
kernel/sched/deadline.c:replenish_dl_entity() {
...
while (dl_se->runtime <= 0) {
dl_se->deadline += pi_of(dl_se)->dl_period;
dl_se->runtime += pi_of(dl_se)->dl_runtime;
}
...
}By only clearing dl_se->dl_throttled and leaving dl_se->deadline in the past and dl_se->runtime negative, a task returning to SCHED_DEADLINE before its 0-lag time enters enqueue_dl_entity(), where setup_new_dl_entity() (on ENQUEUE_MOVE) or update_dl_entity() (on ENQUEUE_WAKEUP) calls replenish_dl_new_period(dl_se, rq):
kernel/sched/deadline.c:enqueue_dl_entity() {
...
} else if ((flags & ENQUEUE_MOVE) &&
!is_dl_boosted(dl_se) &&
dl_time_before(dl_se->deadline, rq_clock(rq_of_dl_se(dl_se)))) {
setup_new_dl_entity(dl_se);
}
...
}replenish_dl_new_period() unconditionally resets dl_se->runtime to the full pi_of(dl_se)->dl_runtime rather than deducting the prior negative runtime overrun, allowing the task to bypass bandwidth enforcement by switching policies across its replenishment point.
In addition, in enqueue_dl_entity(), dl_check_constrained_dl() runs before the ENQUEUE_MOVE branch:
kernel/sched/deadline.c:enqueue_dl_entity() {
...
if (!dl_se->dl_throttled && !dl_is_implicit(dl_se))
dl_check_constrained_dl(dl_se);
...
}If the task returns with constrained-deadline parameters (for example, with a larger dl_period passed to sched_setattr() so that dl_se->deadline < rq_clock(rq) < dl_next_period(dl_se)), dl_check_constrained_dl() sees the un-advanced dl_se->deadline and re-throttles the task before setup_new_dl_entity() is reached. And if the task migrated to another CPU while in SCHED_OTHER whose rq_clock(rq) has not yet strictly passed dl_se->deadline when it switches back, dl_time_before(dl_se->deadline, rq_clock(rq)) evaluates to false and the task is enqueued onto dl_rq with dl_se->runtime <= 0.
[Severity: Medium]
What happens if the task had also called sched_yield() in the period where it was throttled, leaving dl_se->dl_yielded set to 1 when dl_task_timer() fires?
In yield_task_dl(), rq->donor->dl.dl_yielded = 1 is set before calling update_curr_dl(rq) -> update_curr_dl_se():
kernel/sched/deadline.c:yield_task_dl() {
...
rq->donor->dl.dl_yielded = 1;
update_rq_clock(rq);
update_curr_dl(rq);
...
}If the elapsed execution time in that slice also pushes dl_se->runtime < 0, update_curr_dl_se() throttles the task with both dl_se->dl_throttled == 1 and dl_se->dl_yielded == 1, and arms the inactive timer for a 0-lag time later than the deadline when the task switches out of SCHED_DEADLINE.
Unlike replenish_dl_entity() and __dl_clear_params(), which clear both dl_se->dl_yielded and dl_se->dl_throttled:
kernel/sched/deadline.c:replenish_dl_entity() {
...
if (dl_se->dl_yielded)
dl_se->dl_yielded = 0;
if (dl_se->dl_throttled)
dl_se->dl_throttled = 0;
...
}neither the !dl_task(p) path in dl_task_timer() nor replenish_dl_new_period() clears dl_se->dl_yielded. When the task switches back to SCHED_DEADLINE before its 0-lag time, wouldn't it be enqueued with a stale dl_se->dl_yielded == 1 and immediately get throttled again for an entire new period on the next call to update_curr_dl_se()?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
PATCH 5/12 sched/deadline: Do not release a departing sleeper's bandwidth twice
In reply to Mathieu DesnoyersCommit 41a7968022ca ("sched/deadline: Fix total_bw leak when switching away from SCHED_DEADLINE while !queued") releases the bandwidth of a task that leaves SCHED_DEADLINE asleep with no inactive timer pending. Three cases release what the root domain no longer holds, or never held:
- the task keeps its parameters. inactive_task_timer() resets them once it has released the bandwidth (__dl_clear_params()); left in place, task_contending() and task_non_contending() take the task, now of another policy, for one with bandwidth when priority inheritance boosts it into the deadline class, and a deboost while it sleeps releases that bandwidth from total_bw a second time. The root domain then admits deadline tasks beyond its capacity;
- a task deboosted from priority inheritance with no parameters of its own, and a special one (SCHED_FLAG_SUGOV), have no bandwidth in total_bw. Releasing 0 changes nothing, and the root domain that dl_task_root_domain_cpu() finds from the task's mask means nothing
either: a sleeping task of another policy may have no active CPU in its mask, a CPU it is pinned to having gone offline, until its next wakeup widens it;
- migrate_task_rq_dl() clears dl_non_contending when it cannot cancel the inactive timer because its handler runs. That handler, once it takes the task's locks, finds it out of SCHED_DEADLINE and releases total_bw itself.
Release for a task with parameters of its own, not special, and reset its parameters afterwards, once sub_rq_bw(), which reads its dl_bw, is
done: a handler that runs late then finds no bandwidth to release. A test of hrtimer_active() would not tell that handler apart: it stays true after the handler returns, until the hrtimer code clears its running state, and the bandwidth of a task switched out meanwhile would never be released.
The deadline_bw_test selftest, added later in this series, reproduces the first case as pi_former_owner_asleep: in a one-CPU partition with room, the waiter of its second round is refused as a deadline task, total_bw having wrapped. The other two were found by reading.
--- kernel/sched/deadline.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +21 -1
@@ -3567,6 +3567,8 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)dec_dl_tasks_cs (p);if (!task_on_rq_queued (p)) { +bool released = false; +if (p->dl.dl_non_contending) {/* * Inactive timer is armed. However, p is leaving
@@ -3579,12 +3581,18 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)* release total_bw via __dl_sub(). */ sub_running_bw (&p->dl, &rq->dl); - }else { + }else if (p->dl.dl_runtime && !dl_entity_is_special (&p->dl)) {/* * No pending inactive timer: the task never ran as * DEADLINE or the timer already fired while still * DEADLINE (only dropping running_bw at that time). * Nobody else will release total_bw, do it now. +* +* Not for a task without parameters of its own, one +* deboosted from priority inheritance, whose mask may +* have no active CPU for dl_task_root_domain_cpu(), +* nor for a special one: neither has bandwidth in +* total_bw. */ unsigned int cpu =dl_task_root_domain_cpu (p);struct dl_bw *dl_b = &cpu_rq (cpu)->rd->dl_bw;
@@ -3592,8 +3600,20 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)raw_spin_lock (&dl_b->lock);__dl_sub (dl_b, p->dl.dl_bw,dl_bw_cpus (cpu));raw_spin_unlock (&dl_b->lock); + released = true; }sub_rq_bw (&p->dl, &rq->dl); +/* +* Released: reset the parameters, as inactive_task_timer() +* does. Kept, they would make the task one with bandwidth to +* task_contending() and task_non_contending() once priority +* inheritance boosts it, and a deboost while it sleeps would +* release that bandwidth again. So would the inactive timer's +* handler when it runs late, dl_non_contending cleared under +* it by migrate_task_rq_dl(): it finds !dl_task(p). +*/ +if (released) +__dl_clear_params (&p->dl); }/*
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 05/12] sched/deadline: Do not release a departing sleeper's bandwidth twice
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] sched/deadline: infinite loop in replenish_dl_entity() on PI donor clear --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] sched/deadline: infinite loop in replenish_dl_entity() on PI donor clear --
commit 0ea45c3b24aa9d9591791893080fc323c30a9de8
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Do not release a departing sleeper's bandwidth twice
This commit prevents switched_from_dl() from releasing root domain bandwidth for tasks without their own deadline parameters or special sugov entities, and clears the deadline parameters after releasing a departing sleeper's bandwidth so it cannot be released a second time.
Quoted 41 lines
kernel/sched/deadline.c +11
-1@@ -3567,6 +3567,8 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)dec_dl_tasks_cs (p);if (!task_on_rq_queued (p)) { +bool released = false; +if (p->dl.dl_non_contending) {/* * Inactive timer is armed. However, p is leaving @@ -3579,12 +3581,18 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)* release total_bw via __dl_sub(). */ sub_running_bw (&p->dl, &rq->dl); - }else { + }else if (p->dl.dl_runtime && !dl_entity_is_special (&p->dl)) {/* * No pending inactive timer: the task never ran as * DEADLINE or the timer already fired while still * DEADLINE (only dropping running_bw at that time). * Nobody else will release total_bw, do it now. +* +* Not for a task without parameters of its own, one +* deboosted from priority inheritance, whose mask may +* have no active CPU for dl_task_root_domain_cpu(), +* nor for a special one: neither has bandwidth in +* total_bw. */ unsigned int cpu =dl_task_root_domain_cpu (p);struct dl_bw *dl_b = &cpu_rq (cpu)->rd->dl_bw;@@ -3592,8 +3600,20 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)raw_spin_lock (&dl_b->lock);__dl_sub (dl_b, p->dl.dl_bw,dl_bw_cpus (cpu));raw_spin_unlock (&dl_b->lock); + released = true; }sub_rq_bw (&p->dl, &rq->dl); +/*
kernel/sched/deadline.c static void switched_from_dl(struct rq *rq, struct task_struct *p) · line 3616
Quoted 10 lines
kernel/sched/deadline.c +10
-0+* Released: reset the parameters, as inactive_task_timer() +* does. Kept, they would make the task one with bandwidth to +* task_contending() and task_non_contending() once priority +* inheritance boosts it, and a deboost while it sleeps would +* release that bandwidth again. So would the inactive timer's +* handler when it runs late, dl_non_contending cleared under +* it by migrate_task_rq_dl(): it finds !dl_task(p). +*/ +if (released) +__dl_clear_params (&p->dl);
[Severity: High]
Can calling __dl_clear_params(&p->dl) in switched_from_dl() cause an infinite loop in replenish_dl_entity() when p is blocked on an rt_mutex and acting as the priority inheritance donor for the lock owner?
If a non-deadline owner holds an rt_mutex and a SCHED_DEADLINE task p blocks on it as the top waiter, task_blocks_on_rt_mutex() -> rt_mutex_setprio() sets owner->dl.pi_se = &p->dl and places the owner into dl_sched_class.
If p's 0-lag time has already elapsed while p sleeps on the lock (so p->dl.dl_non_contending == 0) and p is switched to another policy via __sched_setscheduler() in kernel/sched/syscalls.c, switched_from_dl() runs inside the sched_change guard before rt_mutex_adjust_pi(p) is called:
scoped_guard (sched_change, p, queue_flags) {
/* sched_change_begin() -> switched_from_dl() */
...
}
preempt_disable();
head = splice_balance_callbacks(rq);
task_rq_unlock(rq, p, &rf);
if (pi) {
if (cpuset_locked)
cpuset_unlock();
rt_mutex_adjust_pi(p);
}At that point __dl_clear_params(&p->dl) zeroes p->dl.dl_runtime, p->dl.dl_deadline, and p->dl.dl_period while the lock owner still has owner->dl.pi_se pointing to &p->dl.
Even once rt_mutex_adjust_pi(p) calls rt_mutex_setprio() in kernel/sched/core.c to deboost the owner, sched_change_begin() dequeues and updates the owner before resetting owner->dl.pi_se:
scoped_guard (sched_change, p, queue_flag) {
/* sched_change_begin() -> dequeue_task_dl() -> update_curr_dl() */
...
} else {
if (dl_prio(oldprio))
p->dl.pi_se = &p->dl;If the boosted owner exhausts its runtime (or yields) either concurrently on another CPU before rt_mutex_adjust_pi(p) runs, or during the dequeue in rt_mutex_setprio(), update_curr_dl_se() sees is_dl_boosted(&owner->dl) and calls:
enqueue_task_dl(rq, owner, ENQUEUE_REPLENISH)
-> enqueue_dl_entity()
-> replenish_dl_entity(&owner->dl)In kernel/sched/deadline.c:replenish_dl_entity(), pi_of(dl_se) still resolves to &p->dl where dl_runtime and dl_period are now 0:
WARN_ON_ONCE(pi_of(dl_se)->dl_runtime <= 0);
...
while (dl_se->runtime <= 0) {
dl_se->deadline += pi_of(dl_se)->dl_period;
dl_se->runtime += pi_of(dl_se)->dl_runtime;
}Wouldn't this trigger the warning and spin forever with the runqueue lock held and interrupts disabled?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
PATCH 6/12 selftests/sched: Add a test of SCHED_DEADLINE policy round trips
In reply to Mathieu DesnoyersAdd deadline_switch_test, with a case for the fix two patches back and one for commit 41a7968022ca ("sched/deadline: Fix total_bw leak when switching away from SCHED_DEADLINE while !queued"):
- throttled_round_trip: a task with a runtime of 10ms per 2s period spins, so that each replenishment throttles it again at once. Right after a throttle it is switched to SCHED_OTHER, and back 200us after its deadline: past its replenishment timer, and before its 0-lag time, which the overrun scaled by 200 puts later. It must run again within a period and a half. Three attempts;
- asleep_round_trip: a task of 9ms every 10ms, running 0.2ms and sleeping 50ms, is switched to SCHED_OTHER and back while it sleeps past its 0-lag time, enough times that a leak of its bandwidth at each round trip fills the root domain: sched_setattr() then fails with EBUSY. Skipped without admission control (sched_rt_runtime_us at -1). A kernel that leaks is left without SCHED_DEADLINE bandwidth until a reboot, so this case runs last.
In 8 VMs of 8 vCPUs each, v7.3 fails both cases, and v7.4-rc1 with the four deadline fixes of sched/urgent fails the first; with the two previous patches as well both pass; every time.
--- tools/testing/selftests/sched/.gitignore | 1 + tools/testing/selftests/sched/Makefile | 1 + .../selftests/sched/deadline_switch_test.c | 332 ++++++++++++++++++ 3 files changed, 334 insertions(+) create mode 100644 tools/testing/selftests/sched/deadline_switch_test.c
tools/testing/selftests/sched/.gitignore +1 -0
@@ -1 +1,2 @@ cs_prctl_test +deadline_switch_test
tools/testing/selftests/sched/Makefile +1 -0
@@ -10,5 +10,6 @@ LDLIBS += -lpthread TEST_GEN_FILES := cs_prctl_test TEST_PROGS := cs_prctl_test +TEST_GEN_PROGS := deadline_switch_test include ../lib.mk
tools/testing/selftests/sched/deadline_switch_test.c new file +332 -0
332 lines not on this page · raw message
Signature · 1 line
2.47.3
PATCH 7/12 sched/deadline: Keep departing bandwidth across a root domain rebuild
In reply to Mathieu DesnoyersA task that leaves SCHED_DEADLINE, or dies, before its 0-lag time keeps its bandwidth in the total_bw of its root domain until that time, when inactive_task_timer() removes it from the root domain of the CPU the task is on (commit 387e31300b57 ("sched/deadline: Fix the update of the total -deadline utilization")). Two things break that:
1. a rebuild of the root domains' accounting, dl_rebuild_rd_accounting() on any change of the cpuset partitions and on CPU hotplug, clears every root domain and adds back the bandwidth of the deadline tasks it finds in the cpusets. A task out of the policy is not one, and a dead one is in no cpuset any more:
its bandwidth is dropped, and the timer then removes it again, from whichever root domain its CPU is in by then. total_bw wraps around, and that root domain admits deadline tasks beyond its capacity until the next rebuild;
2. a task out of the policy may move meanwhile, as any other task, to a CPU of another root domain, moved to another cpuset partition:
the timer then removes the bandwidth from that root domain, which never had it, and leaves it for good in the one that has it.
Keep each departing task on a list, from its departure to its timer, with a CPU of the root domain that holds its bandwidth: the CPU a dying task runs on, and for one that leaves the policy, a CPU of its mask (dl_task_root_domain_cpu()), since the CPU it last ran on may be of another root domain, when it was moved asleep. A rebuild puts that bandwidth back in the root domain of that CPU, and the timer removes it from there.
dl_non_contending tells a task departed, its inactive timer armed and that timer's handler yet to run; hrtimer_active() stays true for a while after the handler returns, and would leave the task on the list with nothing to take it off. A count of the rebuilds, which each task records when its bandwidth is counted, settles the races with a death and with a CPU going inactive: a rebuild that dropped the bandwidth since leaves nothing to remove, as for a task that exits while a rebuild runs, which neither the cpuset walk, skipping exiting tasks, nor the list, if it is not dead yet when the list is put back, finds. A switch back to SCHED_DEADLINE before the timer has sched_dl_overflow() release the old bandwidth from the root domain that keeps it, the new one reserved in the task's current root domain; a boost into the deadline class by priority inheritance in that window, whose switched_to_dl() cancels the timer, takes the task off the list, its bandwidth removed when it leaves the class again, from the root domain of its mask by then, as before. The list's lock nests inside the rq and pi locks, and outside the root domains' dl_bw locks.
dl_cookie and dl_bw_visited() have no user outside deadline.c left:
make them static.
The selftest added by the next patch fails its three cases every time without this change, and passes them with it. A standalone reproducer, a task of 400ms every second that runs 380ms and then exits, switches to SCHED_OTHER or moves, a partition root made or unmade before its 0-lag time, has a one-CPU partition root admit two tasks of 600ms every second on v7.3, every time, and refuse the second with this change, in 36 runs out of 36. It was found by a cgroup selftest under development, test_concurrency_deadline_domain, which failed about once in ten runs when it followed a test whose deadline task had died just before.
--- include/linux/sched.h | 14 +++ include/linux/sched/deadline.h | 5 +- kernel/cgroup/cpuset.c | 11 +- kernel/sched/deadline.c | 222 ++++++++++++++++++++++++++++----- 4 files changed, 208 insertions(+), 44 deletions(-)
include/linux/sched.h +14 -0
@@ -734,6 +734,20 @@ struct sched_dl_entity {*/ struct hrtimer inactive_timer; +/* +* A task that leaves SCHED_DEADLINE, or dies, before its "0-lag +* time" keeps its bandwidth in its root domain until the inactive +* timer removes it. @dl_departed_cpu is then a CPU of the root domain +* that counts that bandwidth, and @dl_departed_node links it on the +* list that a rebuild of the root domains' accounting puts that +* bandwidth back from; -1 otherwise. @dl_bw_gen is the +* rebuild that last counted the task's bandwidth: one since then +* dropped it, and nothing is to be removed. +*/ +struct list_head dl_departed_node; +int dl_departed_cpu; +unsigned int dl_bw_gen; +/* * Bits for DL-server functionality. Also see the comment near * dl_server_update().
include/linux/sched/deadline.h +1 -4
@@ -32,7 +32,7 @@ static inline bool dl_time_before(u64 a, u64 b)struct root_domain ;extern void dl_add_task_root_domain (struct task_struct *p);extern void dl_clear_root_domain (struct root_domain *rd); -extern void dl_clear_root_domain_cpu (int cpu); +extern void dl_clear_root_domains (void );/* * Return whether moving DL task @p to @new_mask requires moving DL * bandwidth accounting between root domains. This helper is specific to
@@ -43,9 +43,6 @@ extern void dl_clear_root_domain_cpu(int cpu);extern bool dl_task_needs_bw_move (struct task_struct *p,const struct cpumask *new_mask); -extern u64 dl_cookie; -extern bool dl_bw_visited (int cpu,u64 cookie); -static inline bool dl_server (struct sched_dl_entity *dl_se) {return dl_se->dl_server;
kernel/cgroup/cpuset.c +2 -9
@@ -985,21 +985,14 @@ void dl_rebuild_rd_accounting(void) {struct cpuset *cs =NULL ;struct cgroup_subsys_state *pos_css; -int cpu; -u64 cookie = ++dl_cookie;lockdep_assert_cpuset_lock_held ();lockdep_assert_cpus_held ();lockdep_assert_held (&sched_domains_mutex); -rcu_read_lock (); - -for_each_possible_cpu (cpu) { -if (dl_bw_visited (cpu, cookie)) -continue ; +dl_clear_root_domains (); -dl_clear_root_domain_cpu (cpu); - } +rcu_read_lock ();cpuset_for_each_descendant_pre (cs, pos_css, &top_cpuset) {
kernel/sched/deadline.c +191 -31
329 lines not on this page · raw message
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 07/12] sched/deadline: Keep departing bandwidth across a root domain rebuild
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] sched/deadline: bandwidth leak and underflow in switched_to_dl() on PI boost - [High]…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] sched/deadline: bandwidth leak and underflow in switched_to_dl() on PI boost
- [High] sched/deadline: dl_clear_root_domains() drops and resurrects departed bw
- [High] sched/deadline: exiting tasks lose or corrupt bandwidth across rd rebuild
- [High] sched/deadline: task_non_contending() uses task_cpu() instead of mask CPU --
commit e37776f3c05c45d876702021f65c587c9806cb26
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Keep departing bandwidth across a root domain rebuild
This commit tracks tasks that leave SCHED_DEADLINE or die before their 0-lag time on a departed list associated with a CPU of their root domain, and uses a rebuild generation counter to preserve or release their bandwidth across root domain accounting rebuilds.
Quoted 4 lines
kernel/sched/deadline.c +0
-0
[ ... ]
Quoted 28 lines
kernel/sched/deadline.c +24
-0@@ -217,6 +223,88 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)cap_scale (dl_b->bw, cap) < dl_b->total_bw - old_bw + new_bw; } +/* +* A task that leaves SCHED_DEADLINE, or dies, before its 0-lag time keeps +* its bandwidth in total_bw until then: the inactive timer removes it. A +* rebuild of the root domains' accounting meanwhile (dl_clear_root_domains() +* and dl_add_task_root_domain(), on any change of the partitions or CPU +* hotplug) finds no such task among the deadline tasks of the cpusets: it +* puts that bandwidth back from dl_departed_list, which holds them from +* their departure to their timer, in the root domain each left, found by +* its mask then (dl_task_root_domain_cpu()), or by the CPU it dies on: the +* CPU it last ran on may be of another one, when it was moved asleep. The +* task may run anywhere meanwhile, as another policy; its timer holds a +* reference to it. +* +* dl_bw_gen counts the rebuilds, and each task records the one that last +* counted its bandwidth. A rebuild that dropped it since then leaves +* nothing to remove: the CPU recorded was no longer active, or the task +* exited while the rebuild ran, which the cpuset walk skips, and was not +* dead yet when the list was put back. Both counts, and the list, are under +* dl_departed_lock, taken with interrupts disabled (under the task's rq +* lock or pi_lock, or by the rebuild) and before any dl_bw lock. +*/ +static LIST_HEAD (dl_departed_list); +static DEFINE_RAW_SPINLOCK (dl_departed_lock); +static unsigned int dl_bw_gen;
[ ... ]
Quoted 10 lines
kernel/sched/deadline.c +10
-0+static void dl_task_release_bw (struct task_struct *p,int cpu) +{ +struct sched_dl_entity *dl_se = &p->dl; +struct dl_bw *dl_b; + +lockdep_assert_irqs_disabled (); +guard (raw_spinlock)(&dl_departed_lock); +if (dl_se->dl_departed_cpu >=0 ) { + cpu = dl_se->dl_departed_cpu; + dl_se->dl_departed_cpu =-1 ;
kernel/sched/deadline.c __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw) · line 306
Quoted 10 lines
kernel/sched/deadline.c +10
-0+list_del (&dl_se->dl_departed_node); + } +if (dl_se->dl_bw_gen == dl_bw_gen) { + dl_b =dl_bw_of (cpu); +raw_spin_lock (&dl_b->lock); +__dl_sub (dl_b, dl_se->dl_bw,dl_bw_cpus (cpu)); +raw_spin_unlock (&dl_b->lock); + } + dl_se->dl_bw_gen = dl_bw_gen; +}
[Severity: High]
What happens when dl_rebuild_rd_accounting() runs while a SCHED_DEADLINE task is in the middle of do_exit()?
In do_exit(), exit_signals() sets PF_EXITING and decrements signal->live to 0 near the beginning of task teardown, before exit_mm(), exit_files(), exit_notify(), and cgroup_exit(), whereas do_task_dead() -> __schedule() -> deactivate_task() -> dequeue_task_dl() -> task_non_contending() -> dl_task_depart() only runs at the very end of do_exit().
If dl_rebuild_rd_accounting() runs during that window (or if the task reaches do_task_dead() after dl_clear_root_domains() has walked dl_departed_list, and unlinks from its cset before dl_update_tasks_root_domain() walks it), dl_clear_root_domains() increments dl_bw_gen without finding the task on dl_departed_list, and dl_update_tasks_root_domain() calls css_task_iter_start(&cs->css, 0, &it) without CSS_TASK_ITER_WITH_DEAD, which skips the task because PF_EXITING is set and signal->live is 0.
Doesn't that cause three problems for an exiting deadline task?
1. Its bandwidth is dropped from total_bw while the task is still running in do_exit() and before its 0-lag time.
2. When the task finally reaches do_task_dead() -> task_non_contending() with zerolag_time >= 0, task_non_contending() unconditionally calls dl_task_depart(p, task_cpu(p)) without checking whether p->dl.dl_bw_gen matches dl_bw_gen. If a second rebuild runs before inactive_task_timer() fires, dl_clear_root_domains() will add p->dl.dl_bw back into total_bw on top of any bandwidth admitted after the first rebuild.
3. If the task is migrated while in do_exit() after the first rebuild dropped its bandwidth (for example via set_cpus_allowed_dl() or dl_task_offline_migration()), those paths subtract p->dl.dl_bw from the source root domain without checking p->dl.dl_bw_gen == dl_bw_gen (underflowing total_bw), and dl_task_offline_migration() adds p->dl.dl_bw to later_rq->rd->dl_bw without updating p->dl.dl_bw_gen, so dl_task_release_bw() later skips subtracting it and leaks p->dl.dl_bw in later_rq->rd.
[ ... ]
Quoted 23 lines
kernel/sched/deadline.c +3
-7@@ -449,13 +537,9 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)sub_running_bw (dl_se, dl_rq);if (!dl_task ||READ_ONCE (p->__state) ==TASK_DEAD ) { -struct dl_bw *dl_b =dl_bw_of (task_cpu (p)); -if (READ_ONCE (p->__state) ==TASK_DEAD )sub_rq_bw (dl_se, &rq->dl); -raw_spin_lock (&dl_b->lock); -__dl_sub (dl_b, dl_se->dl_bw,dl_bw_cpus (task_cpu (p))); -raw_spin_unlock (&dl_b->lock); +dl_task_release_bw (p,task_cpu (p));__dl_clear_params (dl_se); } }@@ -464,8 +548,18 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task) } dl_se->dl_non_contending =1 ; -if (!dl_server (dl_se)) -get_task_struct (dl_task_of (dl_se)); +if (!dl_server (dl_se)) { +struct task_struct *p =dl_task_of (dl_se);
kernel/sched/deadline.c static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task) · line 562
Quoted 10 lines
kernel/sched/deadline.c +10
-0+ +get_task_struct (p); +/* +* Dying: its bandwidth is in the root domain of the CPU it +* runs on. switched_from_dl() records one that leaves +* SCHED_DEADLINE. +*/ +if (READ_ONCE (p->__state) ==TASK_DEAD ) +dl_task_depart (p,task_cpu (p)); + }
[Severity: High]
Should task_non_contending() use dl_task_root_domain_cpu(p) instead of task_cpu(p) when calling dl_task_release_bw() and dl_task_depart()?
Suppose a SCHED_DEADLINE task p is running on CPU 0 in RD_0 (or has is_migration_disabled(p) true) while it is moved to a cpuset partition in RD_1:
cpuset_can_attach()
-> reserves p->dl.dl_bw in RD_1->dl_bw.total_bw
cpuset_attach_task()
-> set_cpus_allowed_ptr()
-> __set_cpus_allowed_ptr_locked()
-> do_set_cpus_allowed()
-> set_cpus_allowed_dl()
-> subtracts p->dl.dl_bw from RD_0->dl_bw.total_bw
-> updates p->cpus_mask to RD_1
-> affine_move_task()
-> task_on_cpu(rq0, p) or is_migration_disabled(p) is true
-> unlocks rq0 and queues migration_cpu_stop (or waits for
migrate_enable())Before migration_cpu_stop runs on CPU 0 (or while migration remains disabled), p's bandwidth is already accounted in RD_1 (matching p->cpus_mask), but task_cpu(p) is still CPU 0 in RD_0.
If p then exits into do_task_dead() -> dequeue_task_dl() -> task_non_contending(&p->dl, true), or switches policy via switched_from_dl() -> task_non_contending(&p->dl, false) when zerolag_time < 0 or hrtimer_active(&dl_se->inactive_timer) is true, passing task_cpu(p) causes dl_task_release_bw() or dl_task_depart() to target RD_0 instead of RD_1, underflowing RD_0->dl_bw.total_bw and leaking p->dl.dl_bw in RD_1->dl_bw.total_bw.
[ ... ]
Quoted 28 lines
kernel/sched/deadline.c +21
-2@@ -3542,9 +3653,37 @@ void dl_clear_root_domain(struct root_domain *rd)dl_server_add_bw (rd, i); } -void dl_clear_root_domain_cpu (int cpu) +/* +* Clear every root domain ahead of a rebuild of their accounting, which +* dl_add_task_root_domain() then fills with the deadline tasks of the +* cpusets: put back their servers, and the bandwidth of the tasks that +* left SCHED_DEADLINE, or died, before their 0-lag time, which no cpuset +* holds as a deadline task, in the root domain of the CPU recorded for +* each; dropped if it is no longer active. +*/ +void dl_clear_root_domains (void ) { -dl_clear_root_domain (cpu_rq (cpu)->rd); +struct sched_dl_entity *dl_se; +u64 cookie = ++dl_cookie; +struct dl_bw *dl_b; +int cpu; + +guard (raw_spinlock_irqsave)(&dl_departed_lock); + dl_bw_gen++; +for_each_possible_cpu (cpu) { +if (!dl_bw_visited (cpu, cookie)) +dl_clear_root_domain (cpu_rq (cpu)->rd); + } +list_for_each_entry (dl_se, &dl_departed_list, dl_departed_node) {
kernel/sched/deadline.c void dl_clear_root_domain(struct root_domain *rd) · line 3687
Quoted 10 lines
kernel/sched/deadline.c +9
-0+ cpu = dl_se->dl_departed_cpu; +if (!cpu_active (cpu)) +continue ; + dl_b =dl_bw_of (cpu); +raw_spin_lock (&dl_b->lock); +__dl_add (dl_b, dl_se->dl_bw,dl_bw_cpus (cpu)); +raw_spin_unlock (&dl_b->lock); + dl_se->dl_bw_gen = dl_bw_gen; + } }
[Severity: High]
Can dl_clear_root_domains() prematurely drop departed bandwidth in a multi-CPU root domain and later resurrect it?
When a task departs or dies in a root domain spanning CPUs 0 and 1, dl_task_depart() records only a single CPU in dl_se->dl_departed_cpu (for example, CPU 1). If CPU 1 is then taken offline via sched_cpu_deactivate(1) before the task's 0-lag time while CPU 0 remains active in the same root domain, dl_bw_deactivate(1) succeeds if CPU 0 has enough capacity for the root domain's total_bw. However, when cpuset_cpu_inactive() -> dl_rebuild_rd_accounting() -> dl_clear_root_domains() runs, cpu_active(1) is false, so dl_clear_root_domains() skips dl_se and drops its bandwidth from the still-active root domain before its 0-lag time.
In addition, when dl_clear_root_domains() skips an entry because !cpu_active(cpu), the entry stays on dl_departed_list with its old dl_bw_gen. If CPU 1 becomes active again and another rebuild runs before inactive_task_timer() fires, dl_clear_root_domains() does not check whether dl_se->dl_bw_gen matched the previous generation before dl_bw_gen++, so it adds dl_se->dl_bw back into dl_bw_of(cpu) and updates dl_se->dl_bw_gen = dl_bw_gen after that bandwidth was already dropped.
[ ... ]
Quoted 14 lines
kernel/sched/deadline.c +10
-0@@ -3642,6 +3786,16 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)static void switched_to_dl (struct rq *rq,struct task_struct *p) {cancel_inactive_timer (&p->dl); +/* +* Boosted back into the class before its 0-lag time (a policy change +* released that bandwidth in sched_dl_overflow()): the inactive +* timer will not remove it, but its leaving the class again. That +* forgets the CPU recorded: moved to another root domain meanwhile, +* the task then removes the bandwidth from that one, as it did +* before departures were recorded. +*/ +if (p->dl.dl_departed_cpu >=0 ) +dl_task_undepart (p);
[ ... ]
Quoted 9 lines
kernel/sched/deadline.c +5
-0@@ -3909,6 +4055,19 @@ int sched_dl_overflow(struct task_struct *p, int policy, }raw_spin_unlock (&dl_b->lock); +/* +* Back before its 0-lag time, the task still has the bandwidth it +* left with, which the new one replaces: removed from the root +* domain that keeps it (dl_task_release_bw()). A rebuild cannot +* run meanwhile: the caller holds cpuset_mutex.
kernel/sched/deadline.c int sched_dl_overflow(struct task_struct *p, int policy, · line 4072
Quoted 10 lines
kernel/sched/deadline.c +8
-0+*/ +if (!err &&dl_policy (policy) && !task_has_dl_policy (p)) { +lockdep_assert_cpuset_lock_held (); +if (p->dl.dl_departed_cpu >=0 ) +dl_task_release_bw (p,-1 ); + p->dl.dl_bw_gen = dl_bw_gen; + } +return err; }
[Severity: High]
Does calling dl_task_undepart(p) in switched_to_dl() when a departed task is PI-boosted cause bandwidth leaks and cross-root-domain underflows?
When a SCHED_DEADLINE task p switches to SCHED_OTHER before its 0-lag time, switched_from_dl() arms inactive_timer, keeps p->dl.dl_runtime and p->dl.dl_bw set, and records the origin root domain CPU in p->dl.dl_departed_cpu via dl_task_depart(). If p is then boosted into dl_sched_class via rt_mutex_setprio() before the timer fires, switched_to_dl() cancels inactive_timer and calls dl_task_undepart(p), which resets p->dl.dl_departed_cpu to -1 and removes p from dl_departed_list without releasing p->dl.dl_bw from the origin root domain:
1. If p is switched back to SCHED_DEADLINE via sched_setattr() while still PI-boosted (!task_has_dl_policy(p) is true), sched_dl_overflow() adds new_bw to dl_b->total_bw and then checks:
if (p->dl.dl_departed_cpu >= 0) dl_task_release_bw(p, -1);
Because switched_to_dl() already set p->dl.dl_departed_cpu = -1 (or if p was already PI-boosted when it earlier switched from SCHED_DEADLINE to SCHED_OTHER, so switched_from_dl() never ran), dl_task_release_bw() is skipped and __setparam_dl() overwrites p->dl.dl_bw with new_bw, permanently leaking the old p->dl.dl_bw in total_bw (and in rq->dl.this_bw if p was not queued when boosted).
2. If p migrated to another root domain (RD_B) while in SCHED_OTHER and is then PI-boosted, dl_task_undepart(p) forgets the origin root domain (RD_A) recorded in dl_departed_cpu. When p is later deboosted in RD_B, switched_from_dl() releases or re-departs p->dl.dl_bw from RD_B via dl_task_root_domain_cpu(p), underflowing RD_B->dl_bw.total_bw and leaking the bandwidth in RD_A->dl_bw.total_bw.
3. If p is sleeping when PI-boosted and the waiter times out or is interrupted while p is still sleeping (!task_on_rq_queued(p)), deboosting p calls switched_from_dl() with p->dl.dl_non_contending == 0, which enters:
} else if (p->dl.dl_runtime && !dl_entity_is_special(&p->dl)) {
dl_task_release_bw(p, dl_task_root_domain_cpu(p));
released = true;
}and releases p->dl.dl_bw immediately before p's 0-lag time.
4. If dl_clear_root_domains() runs while p is PI-boosted (so p is not on dl_departed_list) and p is deboosted before dl_add_task_root_domain(p) visits it, dl_add_task_root_domain(p) sees !dl_task(p) and returns early, dropping p's bandwidth before its 0-lag time.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
PATCH 8/12 selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild
In reply to Mathieu DesnoyersAdd deadline_rebuild_test, for the previous patch. In each case a task of 400ms every second runs 380ms, then leaves SCHED_DEADLINE, its 0-lag time some 570ms ahead; past that time, the one-CPU partition root P must admit one task of 600ms every second and refuse a second with EBUSY:
- dies_before_rebuild: the task, in P, exits, and a second partition root is made meanwhile, which rebuilds the accounting of every root domain;
- switched_out_before_rebuild: the same, the task switched to SCHED_OTHER and asleep in P;
- moved_after_switch_out: the task, outside P, switches to SCHED_OTHER, moves into P and dies there.
A kernel that removes the bandwidth from P's root domain when a rebuild dropped it, or when P never had it, admits both. Skipped without root, the cgroup v2 cpuset controller, deadline admission control (that is, with sched_rt_runtime_us at -1) or 3 CPUs.
In 8 VMs of 8 vCPUs each, three runs in each, v7.4-rc1 with the four deadline fixes of sched/urgent fails the three cases, and so does it with the previous patches but the last; with it, the three pass; every time. v7.3 fails them as well (2 VMs, three runs in each).
--- tools/testing/selftests/sched/.gitignore | 1 + tools/testing/selftests/sched/Makefile | 2 +- .../selftests/sched/deadline_rebuild_test.c | 462 ++++++++++++++++++ 3 files changed, 464 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/sched/deadline_rebuild_test.c
tools/testing/selftests/sched/.gitignore +1 -0
@@ -1,2 +1,3 @@ cs_prctl_test deadline_switch_test +deadline_rebuild_test
tools/testing/selftests/sched/Makefile +1 -1
@@ -10,6 +10,6 @@ LDLIBS += -lpthread TEST_GEN_FILES := cs_prctl_test TEST_PROGS := cs_prctl_test -TEST_GEN_PROGS := deadline_switch_test +TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test include ../lib.mk
tools/testing/selftests/sched/deadline_rebuild_test.c new file +462 -0
462 lines not on this page · raw message
Signature · 1 line
2.47.3
PATCH 9/12 sched/deadline: Do not take a waking task's bandwidth off a runqueue it left
In reply to Mathieu DesnoyersA deadline task that wakes on another CPU has its bandwidth taken off the runqueue it slept on by migrate_task_rq_dl(), from set_task_cpu(), and charged to the one it wakes on by the enqueue that follows. That enqueue can be left to the target CPU through the wake list, and try_to_wake_up() returns before it runs: the task's task_cpu() is then the CPU it wakes on while its bandwidth is on no runqueue at all.
sched_setattr() of that task meanwhile finds it off the runqueues, and dl_change_utilization() takes its old bandwidth off the runqueue of task_cpu(), which never held it. this_bw of that CPU underflows, which costs every other task and the fair server there their own, for good. switched_from_dl() leaves the class through the same hole.
Reaching it needs a deadline task whose wakeup migrates, which asks for more than one CPU in its root domain and for them to be taken. It is easier to reach with CONFIG_SCHED_PROXY_EXEC=y, where a task blocked on a mutex is migrated to the CPU of its owner and wakes back on its own.
In 8 VMs of 8 vCPUs, a task of 10ms every 100ms that sleeps and wakes in a partition root of two CPUs, both taken by deadline tasks of an earlier deadline, its runtime changed between 10ms and 20ms from a CPU outside, warns in all 8 within a second, and the warnings spread to the idle task's accounting of both CPUs:
WARNING: kernel/sched/deadline.c:352 at dl_rq_change_utilization+0x71/0x2e0, CPU#0: wake_race/109 __sub_rq_bw(): this_bw underflow WARNING: kernel/sched/deadline.c:316 at task_contending+0x244/0x260, CPU#6: swapper/6/0 __add_running_bw(): running_bw overflow
Record that window in the entity, as dl_bw_offrq, and leave the runqueue alone while it is set: the enqueue to come charges the CPU the task wakes on, with the new bandwidth, which __setparam_dl() sets right after sched_dl_overflow(). add_rq_bw() clears it, so every path that charges a runqueue does. The 8 VMs above warn no more. deadline_bw_test, added later in this series, has params_waking for this: without this change it fails on every one of those VMs, and random_mix on one of three.
--- include/linux/sched.h | 1 + kernel/sched/deadline.c | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-)
include/linux/sched.h +1 -0
@@ -718,6 +718,7 @@ struct sched_dl_entity { unsigned int dl_defer_running : 1; unsigned int dl_defer_idle : 1; unsigned int dl_bw_attached : 1; + unsigned int dl_bw_offrq : 1;/* * Bandwidth enforcement timer. Each -deadline task has its
kernel/sched/deadline.c +19 -1
@@ -358,6 +358,7 @@ void __sub_rq_bw(u64 dl_bw, struct dl_rq *dl_rq)static inline void add_rq_bw (struct sched_dl_entity *dl_se,struct dl_rq *dl_rq) { + dl_se->dl_bw_offrq =0 ;if (!dl_entity_is_special (dl_se))__add_rq_bw (dl_se->dl_bw, dl_rq); }
@@ -435,6 +436,14 @@ static void dl_change_utilization(struct task_struct *p, u64 new_bw)if (task_on_rq_queued (p))return ; +/* +* Waking up on another CPU, the task has its bandwidth on no +* runqueue: the enqueue to come charges the new one, with the new +* parameters, which __setparam_dl() sets right after this. +*/ +if (p->dl.dl_bw_offrq) +return ; +dl_rq_change_utilization (task_rq (p), &p->dl, new_bw); }
@@ -2785,6 +2794,12 @@ static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unusedcancel_inactive_timer (&p->dl); }sub_rq_bw (&p->dl, &rq->dl); +/* +* Until the enqueue on the CPU it wakes on charges it there, which +* add_rq_bw() tells of, this bandwidth is on no runqueue: the rq of +* task_cpu() is not the one it was taken from. +*/ + p->dl.dl_bw_offrq =1 ;rq_unlock (rq, &rf); }
@@ -3736,7 +3751,9 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)dl_task_release_bw (p,dl_task_root_domain_cpu (p)); released = true; } -sub_rq_bw (&p->dl, &rq->dl); +if (!p->dl.dl_bw_offrq) +sub_rq_bw (&p->dl, &rq->dl); + p->dl.dl_bw_offrq =0 ;/* * Released: reset the parameters, as inactive_task_timer() * does. Kept, they would make the task one with bandwidth to
@@ -4191,6 +4208,7 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se) dl_se->dl_defer =0 ; dl_se->dl_defer_running =0 ; dl_se->dl_defer_armed =0 ; + dl_se->dl_bw_offrq =0 ;#ifdef CONFIG_RT_MUTEXES dl_se->pi_se = dl_se;
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 09/12] sched/deadline: Do not take a waking task's bandwidth off a runqueue it left
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] sched/deadline: double add_rq_bw() in task_contending() on wake_list switch - [Medium]…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] sched/deadline: double add_rq_bw() in task_contending() on wake_list switch
- [Medium] sched/deadline: migrate_task_rq_dl() leaves dl_bw_offrq set for dl_runtime == 0 --
commit 38f78e09a172accddd40a9e36af4e6c19f0febc1
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Do not take a waking task's bandwidth off a runqueue it left
This commit adds a dl_bw_offrq bit to struct sched_dl_entity to track when a waking deadline task has had its bandwidth removed from its previous runqueue by migrate_task_rq_dl() but has not yet been enqueued on its target CPU. While dl_bw_offrq is set, dl_change_utilization() and switched_from_dl() avoid subtracting the task's bandwidth from the target CPU's runqueue before the wakeup enqueue charges it via add_rq_bw().
Quoted 4 lines
kernel/sched/deadline.c +0
-0
[ ... ]
kernel/sched/deadline.c static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unused · line 2804
Quoted 12 lines
kernel/sched/deadline.c +6
-0@@ -2785,6 +2794,12 @@ static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unusedcancel_inactive_timer (&p->dl); }sub_rq_bw (&p->dl, &rq->dl); +/* +* Until the enqueue on the CPU it wakes on charges it there, which +* add_rq_bw() tells of, this bandwidth is on no runqueue: the rq of +* task_cpu() is not the one it was taken from. +*/ + p->dl.dl_bw_offrq =1 ;rq_unlock (rq, &rf); }
[Severity: Medium]
What happens if a non-deadline task boosted via priority inheritance (with p->dl.dl_runtime == 0) blocks and migrates on wakeup through try_to_wake_up() -> set_task_cpu() -> migrate_task_rq_dl()?
Here migrate_task_rq_dl() unconditionally sets p->dl.dl_bw_offrq = 1, but when the wakeup enqueues the task via enqueue_task_dl() -> enqueue_dl_entity() -> task_contending(), task_contending() returns early before calling add_rq_bw():
kernel/sched/deadline.c:task_contending() {
if (dl_se->dl_runtime == 0)
return;
if (flags & ENQUEUE_MIGRATED)
add_rq_bw(dl_se, dl_rq);Because switched_from_dl() only clears dl_bw_offrq when !task_on_rq_queued(p), won't p->dl.dl_bw_offrq remain stuck at 1 after the wakeup completes?
If the task later blocks while still PI-boosted in dl_sched_class and sched_setattr() assigns it SCHED_DEADLINE parameters, __sched_setscheduler() sees prev_class == next_class == &dl_sched_class and does not call switched_to_dl(). Wouldn't the stale p->dl.dl_bw_offrq == 1 then cause dl_change_utilization() or a subsequent switched_from_dl() while blocked to skip updating rq->dl.this_bw?
kernel/sched/deadline.c static void switched_from_dl(struct rq *rq, struct task_struct *p) · line 3756
Quoted 8 lines
kernel/sched/deadline.c +3
-1@@ -3736,7 +3751,9 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)dl_task_release_bw (p,dl_task_root_domain_cpu (p)); released = true; } -sub_rq_bw (&p->dl, &rq->dl); +if (!p->dl.dl_bw_offrq) +sub_rq_bw (&p->dl, &rq->dl); + p->dl.dl_bw_offrq =0 ;
[Severity: High]
Can this leak p->dl.dl_bw into the target CPU's rq->dl.this_bw when a task queued on the target CPU's wake_list switches out of SCHED_DEADLINE and back into SCHED_DEADLINE before sched_ttwu_pending() runs?
When try_to_wake_up() migrates a waking deadline task and queues it via ttwu_queue_wakelist(), p->sched_remote_wakeup is set to 1 while !task_on_rq_queued(p) and migrate_task_rq_dl() sets p->dl.dl_bw_offrq = 1.
If the task then leaves SCHED_DEADLINE before sched_ttwu_pending() runs, switched_from_dl() sees p->dl.dl_bw_offrq == 1, skips sub_rq_bw(), and clears p->dl.dl_bw_offrq = 0. If the task is then switched back to SCHED_DEADLINE (or if a non-deadline task on the wake_list with p->sched_remote_wakeup == 1 switches to SCHED_DEADLINE) while still waiting on the wake_list, switched_to_dl() charges the target CPU's rq->dl.this_bw immediately:
kernel/sched/deadline.c:switched_to_dl() {
...
/* If p is not queued we will update its parameters at next wakeup. */
if (!task_on_rq_queued(p)) {
add_rq_bw(&p->dl, &rq->dl);
return;
}When sched_ttwu_pending() subsequently runs on the target CPU, it sees p->sched_remote_wakeup == 1 and calls ttwu_do_activate() with WF_MIGRATED, which passes ENQUEUE_MIGRATED into enqueue_task_dl() -> enqueue_dl_entity() -> task_contending():
kernel/sched/deadline.c:task_contending() {
...
if (flags & ENQUEUE_MIGRATED)
add_rq_bw(dl_se, dl_rq);Since task_contending() checks (flags & ENQUEUE_MIGRATED) rather than dl_se->dl_bw_offrq, won't it call add_rq_bw() a second time on the target CPU's dl_rq even though switched_to_dl() already added p->dl.dl_bw and cleared dl_bw_offrq?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
PATCH 10/12 sched/debug: Show the deadline bandwidth of each runqueue
In reply to Mathieu Desnoyerssched_debug prints the bandwidth each root domain has handed out (dl_bw->total_bw), and nothing of the two sums each runqueue keeps:this_bw, the bandwidth of every deadline task of that CPU, and running_bw, the part of it whose tasks are active. GRUB drains the runtime of a reclaiming task at the rate the two give, the bandwidth of its CPU that is reserved and active (grub_reclaim(): max_bw - (this_bw - running_bw) - extra_bw): the less of its CPU is active, the slower its runtime drains, and the longer it runs on.
Both sums have invariants a test can check, which the kernel itself warns about when they break: neither may wrap, and running_bw never exceeds this_bw. Print them.
--- kernel/sched/debug.c | 2 ++ 1 file changed, 2 insertions(+)
kernel/sched/debug.c +2 -0
@@ -1166,6 +1166,8 @@ void print_dl_rq(struct seq_file *m, int cpu, struct dl_rq *dl_rq) SEQ_printf(m, " .%-30s: %lu\n", #x, (unsigned long)(dl_rq->x))PU (dl_nr_running); +PU (running_bw); +PU (this_bw); dl_bw = &cpu_rq (cpu)->rd->dl_bw;SEQ_printf (m," .%-30s: %lld\n" ,"dl_bw->bw" , dl_bw->bw);SEQ_printf (m," .%-30s: %lld\n" ,"dl_bw->total_bw" , dl_bw->total_bw);
Signature · 1 line
2.47.3
PATCH 11/12 sched/deadline: Rebuild the root domains' accounting without cpusets too
In reply to Mathieu DesnoyersA change of the root domains, which CPU hotplug and suspend and resume make, clears their deadline bandwidth accounting and fills it back: the servers of each CPU, and the bandwidth of the deadline tasks of each cpuset. The walk that puts the tasks back lives in the cpuset code, dl_rebuild_rd_accounting(), and is a stub without CONFIG_CPUSETS: such a kernel loses the bandwidth of every deadline task at the first hotplug, total_bw of the new root domain holding its servers alone.
The tasks are never told. Each still takes its bandwidth out of total_bw once it leaves SCHED_DEADLINE, or dies: it underflows, and admission afterwards refuses every deadline task of the root domain.
Walk the tasks instead of the cpusets, which is all there is without them, and keep one declaration beside dl_clear_root_domains() for both.
In 8-CPU VMs built without CONFIG_CPUSETS, the hotplug_sleepers case of the selftest added later in this series admits 9 tasks of 10ms every 100ms before taking a CPU offline and back, and 0 after, on v7.4-rc1 as with the patches before this one; hotplug_departed and hotplug_server_refused fail after it, and two more hotplug cases skip for want of room. The five pass with this change, in 4 VMs, with no warning.
--- include/linux/cpuset.h | 5 ----- include/linux/sched/deadline.h | 1 + kernel/sched/deadline.c | 22 ++++++++++++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-)
include/linux/cpuset.h +0 -5
@@ -129,7 +129,6 @@ static inline int cpuset_do_page_mem_spread(void)extern bool current_cpuset_is_being_rebound (void ); -extern void dl_rebuild_rd_accounting (void );extern void rebuild_sched_domains (void );extern void cpuset_print_current_mems_allowed (void );
@@ -273,10 +272,6 @@ static inline bool current_cpuset_is_being_rebound(void)return false; } -static inline void dl_rebuild_rd_accounting (void ) -{ -} -static inline void rebuild_sched_domains (void ) {guard (cpus_read_lock)();
include/linux/sched/deadline.h +1 -0
@@ -33,6 +33,7 @@ struct root_domain;extern void dl_add_task_root_domain (struct task_struct *p);extern void dl_clear_root_domain (struct root_domain *rd);extern void dl_clear_root_domains (void ); +extern void dl_rebuild_rd_accounting (void );/* * Return whether moving DL task @p to @new_mask requires moving DL * bandwidth accounting between root domains. This helper is specific to
kernel/sched/deadline.c +22 -0
@@ -3668,6 +3668,28 @@ void dl_clear_root_domain(struct root_domain *rd)dl_server_add_bw (rd, i); } +#ifndef CONFIG_CPUSETS +/* +* Rebuild the root domains' accounting, where no cpuset holds the +* deadline tasks of each: they are found by walking them all, which +* dl_rebuild_rd_accounting() of the cpusets does per cpuset instead. +*/ +void dl_rebuild_rd_accounting (void ) +{ +struct task_struct *g, *p; + +lockdep_assert_cpus_held (); +lockdep_assert_held (&sched_domains_mutex); + +dl_clear_root_domains (); + +read_lock (&tasklist_lock); +for_each_process_thread (g, p) +dl_add_task_root_domain (p); +read_unlock (&tasklist_lock); +} +#endif /* !CONFIG_CPUSETS */ +/* * Clear every root domain ahead of a rebuild of their accounting, which * dl_add_task_root_domain() then fills with the deadline tasks of the
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH 11/12] sched/deadline: Rebuild the root domains' accounting without cpusets too
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] sched/deadline: race between dl_rebuild_rd_accounting() and sched_dl_overflow() - [High]…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] sched/deadline: race between dl_rebuild_rd_accounting() and sched_dl_overflow()
- [High] sched/deadline: BUG_ON() in dl_add_task_root_domain() when isolated CPUs offline
- [High] sched/deadline: dl_get_task_effective_cpus() picks isolated CPU for hk tasks --
commit c1e57d1e06a701583f3de7582594314893352edf
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Rebuild the root domains' accounting without cpusets too
This commit implements dl_rebuild_rd_accounting() in kernel/sched/deadline.c for kernels built without CONFIG_CPUSETS by clearing the root domains and walking all threads under tasklist_lock to re-add their deadline bandwidth. It also moves the declaration of dl_rebuild_rd_accounting() from include/linux/cpuset.h to include/linux/sched/deadline.h.
Quoted 12 lines
kernel/sched/deadline.c +4
-0@@ -3668,6 +3668,28 @@ void dl_clear_root_domain(struct root_domain *rd)dl_server_add_bw (rd, i); } +#ifndef CONFIG_CPUSETS +/* +* Rebuild the root domains' accounting, where no cpuset holds the +* deadline tasks of each: they are found by walking them all, which
kernel/sched/deadline.c void dl_clear_root_domain(struct root_domain *rd) · line 3684
Quoted 10 lines
kernel/sched/deadline.c +10
-0+* dl_rebuild_rd_accounting() of the cpusets does per cpuset instead. +*/ +void dl_rebuild_rd_accounting (void ) +{ +struct task_struct *g, *p; + +lockdep_assert_cpus_held (); +lockdep_assert_held (&sched_domains_mutex); + +dl_clear_root_domains ();
[Severity: High]
What serializes this rebuild against concurrent __sched_setscheduler() -> sched_dl_overflow() calls when CONFIG_CPUSETS is disabled?
With CONFIG_CPUSETS enabled, __sched_setscheduler() in kernel/sched/syscalls.c calls cpuset_lock() when entering, leaving, or updating SCHED_DEADLINE:
if (dl_policy(policy) || dl_policy(p->policy)) {
cpuset_locked = true;
cpuset_lock();
}and sched_dl_overflow() in kernel/sched/deadline.c relies on cpuset_mutex to prevent a rebuild from running concurrently:
/*
* Back before its 0-lag time, the task still has the bandwidth it
* left with, which the new one replaces: removed from the root
* domain that keeps it (dl_task_release_bw()). A rebuild cannot
* run meanwhile: the caller holds cpuset_mutex.
*/
if (!err && dl_policy(policy) && !task_has_dl_policy(p)) {
lockdep_assert_cpuset_lock_held();
if (p->dl.dl_departed_cpu >= 0)
dl_task_release_bw(p, -1);
p->dl.dl_bw_gen = dl_bw_gen;
}When !CONFIG_CPUSETS, cpuset_lock() and lockdep_assert_cpuset_lock_held() in include/linux/cpuset.h are no-op stubs, while dl_rebuild_rd_accounting() only holds cpu_hotplug_lock and sched_domains_mutex, neither of which is taken by __sched_setscheduler().
Without mutual exclusion between dl_rebuild_rd_accounting() and __sched_setscheduler(), can they interleave and corrupt rd->dl_bw.total_bw? For example:
1. A task entering SCHED_DEADLINE calls sched_dl_overflow(), which adds new_bw to dl_b->total_bw under dl_b->lock and drops dl_b->lock before setting p->dl.dl_bw_gen = dl_bw_gen and before __setparam_dl() updates p->dl.dl_bw and p->prio. If dl_clear_root_domains() runs in that window, it increments dl_bw_gen and resets rd->dl_bw.total_bw to 0 (wiping out new_bw), after which sched_dl_overflow() writes the new dl_bw_gen into p->dl.dl_bw_gen. When dl_add_task_root_domain() later visits p, it sees p->dl.dl_bw_gen == dl_bw_gen and skips it, leaving new_bw uncounted until p exits and underflows total_bw.
2. If an existing SCHED_DEADLINE task updates its parameters after dl_clear_root_domains() zeroes total_bw and before for_each_process_thread() reaches p, sched_dl_overflow() adjusts total_bw by new_bw - old_bw without updating p->dl.dl_bw_gen, __setparam_dl() sets p->dl.dl_bw = new_bw, and dl_add_task_root_domain() subsequently adds new_bw a second time.
3. If a task switches out of SCHED_DEADLINE after dl_clear_root_domains() has walked dl_departed_list and before for_each_process_thread() visits p, switched_from_dl() moves p to dl_departed_list and clears its deadline priority, so dl_add_task_root_domain() sees !dl_task(p) and drops its bandwidth before its 0-lag time.
4. Between dl_clear_root_domains() and the end of the tasklist walk, concurrent sched_dl_overflow() admission checks evaluate __dl_overflow() against a zeroed or partially rebuilt total_bw.
kernel/sched/deadline.c void dl_clear_root_domain(struct root_domain *rd) · line 3688
Quoted 4 lines
kernel/sched/deadline.c +4
-0+ +read_lock (&tasklist_lock); +for_each_process_thread (g, p) +dl_add_task_root_domain (p);
[Severity: High]
Can walking all tasks with for_each_process_thread() trigger the BUG_ON(cpu >= nr_cpu_ids) in dl_add_task_root_domain() when CPUs isolated via isolcpus=domain are taken offline?
In kernel/sched/deadline.c, dl_add_task_root_domain() computes the effective CPU mask and checks BUG_ON(cpu >= nr_cpu_ids) before checking p->dl.dl_bw_gen, p->dl.dl_departed_cpu, or p->dl.dl_bw:
raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
if (!dl_task(p) || dl_entity_is_special(&p->dl)) {
raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
return;
}
msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
dl_get_task_effective_cpus(p, msk);
cpu = cpumask_first_and(cpu_active_mask, msk);
BUG_ON(cpu >= nr_cpu_ids);And dl_get_task_effective_cpus() handles HK_TYPE_DOMAIN isolation as follows:
if (housekeeping_enabled(HK_TYPE_DOMAIN)) {
if (!cpumask_intersects(p->cpus_ptr, hk_msk)) {
/*
* CPUs isolated by isolcpu="domain" always belong to
* def_root_domain.
*/
cpumask_andnot(cpus, cpu_active_mask, hk_msk);
return;
}
}Because for_each_process_thread() visits every task in the system, it visits unreaped EXIT_ZOMBIE deadline tasks whose bandwidth has already been released or moved to dl_departed_list (where p->prio is still < MAX_DL_PRIO, so dl_task(p) is true), as well as PI-boosted tasks with p->dl.dl_bw == 0. Since those tasks carry no active bandwidth in def_root_domain to block dl_bw_deactivate(), all isolated CPUs outside hk_msk can be taken offline. When that happens, cpumask_andnot(cpus, cpu_active_mask, hk_msk) is empty, cpumask_first_and(cpu_active_mask, msk) returns nr_cpu_ids, and dl_add_task_root_domain() hits BUG_ON(cpu >= nr_cpu_ids).
[Severity: High]
Also in the dl_add_task_root_domain() -> dl_get_task_effective_cpus() path on !CONFIG_CPUSETS, could housekeeping deadline tasks have their bandwidth added to def_root_domain instead of the housekeeping root domain when isolcpus=domain is used?
In dl_get_task_effective_cpus():
hk_msk = housekeeping_cpumask(HK_TYPE_DOMAIN);
if (housekeeping_enabled(HK_TYPE_DOMAIN)) {
if (!cpumask_intersects(p->cpus_ptr, hk_msk)) {
cpumask_andnot(cpus, cpu_active_mask, hk_msk);
return;
}
}
cpuset_cpus_allowed_locked(p, cpus);When !CONFIG_CPUSETS, cpuset_cpus_allowed_locked() in include/linux/cpuset.h copies task_cpu_possible_mask(p) into cpus without masking out the CPUs isolated by HK_TYPE_DOMAIN:
static inline void cpuset_cpus_allowed_locked(struct task_struct *p,
struct cpumask *mask)
{
cpumask_copy(mask, task_cpu_possible_mask(p));
}For a housekeeping deadline task where p->cpus_ptr intersects hk_msk, dl_add_task_root_domain() then picks:
cpu = cpumask_first_and(cpu_active_mask, msk);
If an active isolated CPU has a lower CPU number than the active housekeeping CPUs (for example with isolcpus=domain,0), cpu resolves to CPU 0, whose cpu_rq(cpu)->rd is def_root_domain rather than the housekeeping root domain. Wouldn't that account the housekeeping task's bandwidth into def_root_domain during the rebuild, and later underflow the housekeeping root domain's total_bw when the task leaves SCHED_DEADLINE or exits?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
PATCH 12/12 selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
In reply to Mathieu DesnoyersAdd deadline_bw_test, 43 cases that take deadline tasks through priority inheritance, parameter changes, cpuset moves, deaths, sched_yield(), runtime overruns, bandwidth reclaiming, changes to the fair servers, a randomized mix of all of those, and CPU hotplug.
Each case measures the free bandwidth of a root domain before and after it runs, as the number of tasks of 10ms every 100ms the root domain admits, and wants the two equal once the case's tasks are gone and their 0-lag time is past: fewer is bandwidth leaked, more is bandwidth released twice. A deadline task that a case keeps running must also make progress.
The reclaiming and server cases measure instead the share of a CPU a deadline task with SCHED_FLAG_RECLAIM gets, which tells of the bandwidth its CPU keeps as reclaimable (extra_bw) where the admission of probe() tells of the root domain's own (total_bw): of a CPU of its own, a task of 10ms every 100ms got 66% of it, where one without the flag got 9%, and it follows the fair server of that CPU, 49% with a server of 10% and 24% with one of 30%, as GRUB has it.
params_waking and random_mix check the two sums each runqueue keeps, this_bw and running_bw, which "sched/debug: Show the deadline bandwidth of each runqueue" prints: parameter changes of a deadline task whose wakeups move it between the two CPUs of a partition root, and six tasks taking random transitions of their own while the case moves, kills and reparameterizes them and changes the fair servers, three thousand transitions in three seconds. Both want this_bw of each CPU back where it started. random_mix's seed is fixed, so a failure can be replayed.
The cases in the partition root each get a new one, the accounting rebuilt in between, so that a case that breaks it does not fail the next ones. The server cases put the fair servers back as they found them. Skipped without root or deadline admission control, and the cases that need them without a cpuset partition root, debugfs, CPU hotplug or enough CPUs.
Kprobes confirmed the states the cases mean to reach: the inactive timer pending at a kill, the replenishment, the boost, and the fair server stopped, deferred and serving at the debugfs writes. A write cannot find a server in two of its states: throttled after serving, which the last of the served task's runtime, charged as background running, turns at once into deferred anew; and its idle wait, which on a CPU with no tick in idle begins and ends in one timer callback.
In 8 VMs of 8 vCPUs, v7.4-rc1 with the four deadline fixes of sched/urgent fails three cases, every time:
- pi_former_owner_asleep: the waiter of its second round is refused with EBUSY in a partition with room, total_bw having wrapped when the deboost of the first round released the owner's bandwidth a second time;
- params_keep_class_change: the refused request leaves 40% of the partition reserved;
- random_mix: the partition root admits 5, 8 or 10 tasks of 10% where it admitted 9 before, bandwidth leaked and bandwidth released twice both.
params_waking fails on every VM of 8 vCPUs and of 4 without "sched/deadline: Do not take a waking task's bandwidth off a runqueue it left": this_bw of one of the two CPUs ends elsewhere than it started, having lost or gained the bandwidth of a task or of a fair server, and the kernel warns of the underflow that got it there. random_mix catches that one on 1 VM of 3, a race being what it is.
With this series, all 43 cases pass every time, with PREEMPT_RT as well, and with no warning. Built without cpusets they need the previous patch:
without it hotplug_sleepers fails, and the hotplug cases after it fail or skip for want of room, every time, the root domain that a CPU hotplug makes getting back the bandwidth of its servers alone.
--- tools/testing/selftests/sched/.gitignore | 1 + tools/testing/selftests/sched/Makefile | 2 +- .../selftests/sched/deadline_bw_test.c | 3182 +++++++++++++++++ 3 files changed, 3184 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/sched/deadline_bw_test.c
tools/testing/selftests/sched/.gitignore +1 -0
@@ -1,3 +1,4 @@ cs_prctl_test deadline_switch_test deadline_rebuild_test +deadline_bw_test
tools/testing/selftests/sched/Makefile +1 -1
@@ -10,6 +10,6 @@ LDLIBS += -lpthread TEST_GEN_FILES := cs_prctl_test TEST_PROGS := cs_prctl_test -TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test +TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test deadline_bw_test include ../lib.mk
tools/testing/selftests/sched/deadline_bw_test.c new file +3182 -0
2,989 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.47.3
Part of the diff is not shown here. View the raw message.
[email protected]
AI reviewRe: [PATCH 12/12] selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider: - [Medium] selftests/sched: deadline_bw_test exceeds default 45s kselftest timeout - [Medium]…
Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider:
- [Medium] selftests/sched: deadline_bw_test exceeds default 45s kselftest timeout
- [Medium] selftests/sched: hardcoded 64 KiB thread stack in probe() and hold()
- [Medium] selftests/sched: mix_worker() reuses r % 8 making r % 4 and r % 2 always 0
- [Medium] selftests/sched: overrun_group_death() triggers SIGXCPU before sibling setup
- [Medium] selftests/sched: cpu_up() in hotplug_departed() masks bandwidth corruption
- [Medium] selftests/sched: missing shm_lock_init() call in random_mix()
- [Medium] selftests/sched: return -1 from probe() when pthread_create() fails
- [Low] selftests/sched: silent KSFT_SKIP returns without reason strings
--
commit e47dbb10f477e11f4985642a757e69830e31cc5f
Author: Mathieu Desnoyers <[email protected]>
selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
This commit adds the deadline_bw_test selftest with 43 test cases exercising SCHED_DEADLINE bandwidth accounting across priority inheritance, parameter changes, cpuset moves, task deaths, sched_yield(), runtime overruns, GRUB bandwidth reclaiming, fair server changes, a randomized mix, and CPU hotplug.
tools/testing/selftests/sched/Makefile LDLIBS += -lpthread · line 13
Quoted 10 lines
tools/testing/selftests/sched/Makefile +1
-1@@ -10,6 +10,6 @@ LDLIBS += -lpthread TEST_GEN_FILES := cs_prctl_test TEST_PROGS := cs_prctl_test -TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test +TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test deadline_bw_test
[Severity: Medium]
When deadline_bw_test is added to TEST_GEN_PROGS in tools/testing/selftests/sched/Makefile without a companion tools/testing/selftests/sched/settings file, the kselftest runner applies the default 45-second timeout (kselftest_default_timeout=45 in tools/testing/selftests/kselftest/runner.sh).
In main() -> run_p_cases(), the 43 sequential test cases perform unconditional sleeps totaling over 74 seconds when all features are enabled (including 25 MEASURED_IN_P cases sleeping at least 900ms each across two probe() calls and measured(), server_states() sleeping 9.9s, params_waking() sleeping 5.3s, and random_mix() sleeping 5.3s), and over 51 seconds even when the debugfs and hotplug cases are skipped.
Because deadline_bw_test does not handle SIGTERM, when runner.sh kills the test after 45 seconds it exits without running remove_p(), remove_partition(cg_q), server_restore(), or restoring cgroup.subtree_control, leaving active cpuset partitions and modified fair_server parameters on the system.
Should tools/testing/selftests/sched/settings be added with a higher timeout (and a signal handler installed to clean up cgroups and fair_server state on termination)?
Quoted 5 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +0
-0
[ ... ]
Quoted 11 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +11
-0+static int probe (const char *cg) +{ +int fd[2 ], n =-1 , max =16 * ncpus +16 ; +pid_t pid; + +if (pipe (fd)) { +ksft_print_msg ("pipe: %s\n" ,strerror (errno)); +return -1 ; + } + pid =fork_child ("the admission check" ); +if (!pid) {
tools/testing/selftests/sched/deadline_bw_test.c line 436
Quoted 10 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +10
-0+struct probe_slot *s =calloc (max,sizeof (*s)); +pthread_attr_t a; +int i, k =0 ; + +close (fd[0 ]); +if (!s ||sem_init (&probe_done,0 ,0 ) ||pipe (probe_hold) || + (cg &&enter (cg,getpid ()))) +_exit (1 ); +if (pthread_attr_init (&a) ||pthread_attr_setstacksize (&a,64 *1024 )) +_exit (1 );
[Severity: Medium]
On architectures where PTHREAD_STACK_MIN is larger than 64 KiB (for example, ppc64le where PTHREAD_STACK_MIN is 128 KiB, or kernels configured with 64 KiB pages), will pthread_attr_setstacksize(&a, 64 * 1024) fail with EINVAL in both probe() and hold()?
In probe(), that causes the child to exit with 1 and probe() to return -1, which causes measured() to skip all 25 MEASURED_IN_P cases and fails the remaining cases that call probe() directly.
In hold(), the same call also logs strerror(errno) even though pthread_attr_init() and pthread_attr_setstacksize() return the error number directly rather than setting errno:
if (pthread_attr_init(&a) || pthread_attr_setstacksize(&a, 64 * 1024)) {
ksft_print_msg("pthread_attr: %s\n", strerror(errno));
return -1;
}Should the stack size in probe() and hold() be clamped to at least PTHREAD_STACK_MIN, and hold() pass the returned error code to strerror()?
tools/testing/selftests/sched/deadline_bw_test.c line 439
Quoted 3 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +3
-0+for (i =0 ; i < max; i++) { +if (pthread_create (&s[i].t, &a, probe_thread, &s[i])) +break ;
[Severity: Medium]
If pthread_create() fails partway through the admission loop in probe() (for example with EAGAIN due to RLIMIT_NPROC, cgroup pids.max, or memory pressure when probing across many CPUs), breaking out of the loop leaves k at the number of threads created so far rather than setting k = -1.
Won't probe() then write that partial count k to the pipe and return it as a valid admission count, causing callers like measured(), admits_in(), and moves() to misreport a bandwidth leak or double-release?
[ ... ]
Quoted 35 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +35
-0+/* The deadline threads of overrun_group_death(). */ +static void *og_thread (void *arg) +{ +switch ((int )(long )arg) { +case 0 :/* overruns its runtime: SIGXCPU to the group */ +if (set_deadline_flags (0 ,10 *NSEC_PER_MSEC ,PERIOD , +SCHED_FLAG_DL_OVERRUN )) +_exit (1 ); +spin_ns (30 *NSEC_PER_MSEC ); +break ; +case 1 :/* asleep, its 0-lag time past */ +if (set_deadline (0 ,20 *NSEC_PER_MSEC ,PERIOD )) +_exit (1 ); +spin_ns (NSEC_PER_MSEC ); +break ; +case 2 :/* asleep, mostly before its 0-lag time */ +if (set_deadline (0 ,15 *NSEC_PER_MSEC ,PERIOD )) +_exit (1 ); +for (;;) { +spin_ns (3 *NSEC_PER_MSEC ); +sleep_ns (22 *NSEC_PER_MSEC ); + } + } +for (;;) +pause (); +} + +/* +* The SIGXCPU of an overrun kills the whole thread group: the bandwidth +* of its three deadline threads comes back. +*/ +static int overrun_group_death (void ) +{ +pid_t pid =fork_child ("a group of deadline threads" ); +int i, status;
tools/testing/selftests/sched/deadline_bw_test.c line 1738
Quoted 10 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +10
-0+ +if (!pid) { +pthread_t t; + +for (i =0 ; i <3 ; i++) +if (pthread_create (&t,NULL , og_thread, (void *)(long )i)) +_exit (1 ); +for (;;) +pause (); + }
[Severity: Medium]overrun_group_death() runs inside cg_p, which is a single-CPU cpuset partition root, and creates thread 0 first without waiting for threads 1 and 2 to reach their sleeping states.
In og_thread(), thread 0 immediately enters SCHED_DEADLINE with a 10ms runtime and 100ms period and calls spin_ns(30 * NSEC_PER_MSEC) on P's single CPU. Even if threads 1 and 2 also enter SCHED_DEADLINE before thread 0 starts spinning, all three share the same 100ms relative deadline so thread 0 has the earliest deadline and monopolizes the single CPU until it overruns at 10ms and delivers SIGXCPU to the thread group.
Doesn't this kill the process before threads 1 and 2 can spin and go to sleep in their intended states?
[ ... ]
Quoted 18 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +18
-0+static pid_t mix_worker (int idx,unsigned int seed) +{ +static const uint64_t runtime[] = {5 ,10 ,20 ,30 }; +static const uint64_t period[] = {50 ,100 }; +static const uint64_t flag[] = {0 ,SCHED_FLAG_RECLAIM ,SCHED_FLAG_DL_OVERRUN }; +pid_t pid =fork_child ("a worker of the mix" ); + +if (!pid) { +struct sigaction sa = { .sa_handler = catch_xcpu }; +int err; + +if (sigaction (SIGXCPU , &sa,NULL )) +_exit (1 ); + seed += idx; +/* +* A refusal is part of the mix: each call below is made in +* whatever state the worker is in, and an error is what the +* kernel is entitled to answer.
tools/testing/selftests/sched/deadline_bw_test.c line 2601
Quoted 10 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +10
-0+*/ +while (!mix_state[0 ]) { +unsigned int r =rand_r (&seed); + +switch (r %8 ) { +case 0 : +set_deadline_flags (0 , runtime[r %4 ] *NSEC_PER_MSEC , + period[r %2 ] *NSEC_PER_MSEC , + flag[r %3 ]); +break ;
[Severity: Medium]
In mix_worker(), case 0 of switch (r % 8) is only entered when r is a multiple of 8. Because runtime[r % 4] and period[r % 2] use r directly without dividing by 8, aren't r % 4 and r % 2 always 0 here, causing mix_worker() to only ever select runtime[0] (5ms) and period[0] (50ms)?
[ ... ]
Quoted 10 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +10
-0+case 5 : + err =pthread_mutex_trylock (shm_lock); +if (err ==EOWNERDEAD )/* its owner died holding it */ + err =pthread_mutex_consistent (shm_lock); +if (!err) { +spin_ns (NSEC_PER_MSEC ); +if (pthread_mutex_unlock (shm_lock)) +_exit (1 ); + } +break ;
[ ... ]
Quoted 2 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +2
-0+static int random_mix (void ) +{
[ ... ]
tools/testing/selftests/sched/deadline_bw_test.c line 2674
Quoted 10 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +10
-0+ mix_state = mv_state +16 ; +for (i =0 ; i <=MIX_WORKERS ; i++) + mix_state[i] =0 ; +for (i =0 ; i <MIX_WORKERS ; i++) { + pid[i] =mix_worker (i, seed); +if (pid[i] <0 ) { + ret =KSFT_FAIL ; + goto out; + } + }
[Severity: Medium]
In random_mix(), the mix_worker() child processes lock and unlock shm_lock across processes while random_mix() periodically kills workers with SIGKILL, but random_mix() never calls shm_lock_init().
In main(), shm_lock is only pointed at zero-initialized MAP_SHARED memory:
shm_lock = (pthread_mutex_t *)((char *)mv_state + 256);
shm_lock_init() (which configures PTHREAD_PROCESS_SHARED, PTHREAD_PRIO_INHERIT, and PTHREAD_MUTEX_ROBUST) is only called inside pi_death() for the earlier death_pi_* cases. If the death_pi_* cases were skipped in measured(), or if shm_lock_init() failed there, shm_lock remains a zero-initialized process-private non-robust mutex when random_mix() runs; and if an earlier death_pi_* case failed before its waiter recovered and unlocked shm_lock, shm_lock enters random_mix() in an inconsistent or unrecoverable state.
Should random_mix() call shm_lock_init() (or skip case 5 in mix_worker() when shm_lock_init() fails)?
[ ... ]
Quoted 26 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +26
-0+static int hotplug_departed (void ) +{ +int base =probe (NULL ), after, cpu, ret =KSFT_PASS ; +pid_t pid; + + mv_state[0 ] =0 ; + mv_state[1 ] =0 ; + pid =mover (MV_THROTTLED ,40 *NSEC_PER_MSEC ); +if (pid <0 ||child_up ("a departing deadline task" ,0 )) { +reap (pid); +return KSFT_FAIL ; + } +sleep_ns (PERIOD /2 ); +/* Running and queued: its bandwidth stays until its 0-lag time. */ +if (set_other (pid)) + ret =KSFT_FAIL ; + cpu =task_cpu_of (pid); +if (cpu <=0 ) { +cpu_set_t set; + +/* Out of the class now: it may be moved to the CPU we offline. */ + cpu = hp_cpu; +CPU_ZERO (&set); +CPU_SET (cpu, &set); +if (sched_setaffinity (pid,sizeof (set), &set)) + ret =KSFT_FAIL ;
tools/testing/selftests/sched/deadline_bw_test.c line 2902
Quoted 10 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +10
-0+ } +if (ret ==KSFT_PASS &&cpu_online (cpu,0 )) { +ksft_print_msg ("offline of CPU %d refused\n" , cpu); + ret =KSFT_FAIL ; + } +sleep_ns (2 *PERIOD ); +cpu_up (cpu); +reap (pid); +sleep_ns (3 *PERIOD ); + after =probe (NULL );
[Severity: Medium]
In hotplug_departed(), after offlining cpu and sleeping 2 * PERIOD (so inactive_task_timer() has already fired and cleared the departed task's deadline parameters), the test calls cpu_up(cpu) before calling after = probe(NULL).
Doesn't bringing cpu back online trigger dl_rebuild_rd_accounting() -> dl_clear_root_domains(), resetting the root domain's total_bw to 0 and recomputing it from scratch before probe(NULL) measures it, which masks any total_bw leak or underflow that occurred when the inactive timer fired while cpu was offline?
Also, since pid runs in the root cgroup with all online CPUs in its affinity mask when set_other(pid) is called, switched_from_dl() -> dl_task_root_domain_cpu() picks the first CPU in pid's cpus_mask (CPU 0) as dl_departed_cpu rather than the CPU offlined here. Should probe(NULL) be checked while cpu is still offline (or should pid's affinity be restricted to include cpu and exclude CPU 0 before entering SCHED_DEADLINE)?
[ ... ]
tools/testing/selftests/sched/deadline_bw_test.c line 3028
Quoted 9 lines
tools/testing/selftests/sched/deadline_bw_test.c new file +9
-0+static void report (const char *name,int ret) +{ +if (ret ==KSFT_PASS ) +ksft_test_result_pass ("%s\n" , name); +else if (ret ==KSFT_SKIP ) +ksft_test_result_skip ("%s\n" , name); +else +ksft_test_result_fail ("%s\n" , name); +}
[Severity: Low]
In report(), ksft_test_result_skip("%s\n", name) only prints the test name, and many of the KSFT_SKIP return paths (such as in run_in(), params_refused(), params_keep_class_change(), yield_switched_out(), overrun_caught(), reclaim_runs(), reclaim_switched(), server_params(), server_rebuilds(), server_states(), server_reclaim(), params_waking(), random_mix(), hotplug_refused(), hotplug_server(), and hotplug_server_refused()) return KSFT_SKIP without printing why the test was skipped.
Could the skip paths pass or log a reason string explaining which prerequisite was missing, per kselftest conventions?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Quoted 5 lines · Mathieu Desnoyers
Hi Juri,
Please find in this series eight fixes to
SCHED_DEADLINEbandwidth accounting, on top of your four in sched/urgent, with the selftests that catch them.
I'm taking care of issues found by Sashiko, including additional preexisting bugs. I'm also taking care of yet more preexisting sched deadline bugs identified by a round of Fable review over my updated series.
v2 will include fixes for 17 sched deadline bugs, most of which have reproducers.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com