sched/deadline: first bandwidth accounting fixes and selftests
Subsystems (5)
v2 cover sched/deadline: first bandwidth accounting fixes and selftests
Hi Ingo, Juri,
This series fixes 13 bugs of SCHED_DEADLINE. Then it shows the deadline bandwidth of each runqueue in sched_debug, and adds two selftests. The fixes come first, so that stable can take patches 1 to 13.
Two of the bugs take the kernel down: a division by zero (patch 4), and an owner's CPU that locks up (patch 8). One leaves cpuset_mutex locked (patch 6). One leaves a task that never runs again (patch 7). Most of the others leave total_bw of a root domain, or this_bw of a runqueue, wrong. The root domain then admits deadline tasks beyond its capacity, or refuses every one.
These are the first 14 patches of "sched/deadline: bandwidth accounting fixes and selftests" v7 [1], as Juri proposed [2]. Their v7 numbers are 1-8, 10, 13, 14, 16, 20 and 37. The rest of v7 will follow as v8 of that series, on top of this one.
Patch 11 is Juri's, patch 13 is Andrea Parri's. I carry them unchanged. Sebastian reviewed patch 13. Juri, three of your four fixes that Ingo dropped from sched/urgent are here:
- 2/4 is patch 10.
- 3/4 is patch 1.
- 4/4 is patch 11.
1/4 stays in the second series.
The fixes
=========
1 Refuse SCHED_FLAG_KEEP_PARAMS requests that would change the policy
or the class.
2 Skip admission for parameters that SCHED_FLAG_KEEP_PARAMS keeps. 3 Let a task boosted by a deadline waiter change its policy. 4 Do not divide by zero active CPUs of a root domain. 5 Refuse a dl_server debugfs write while the runqueue is offline. 6 Take cpuset_mutex for a deadline policy change only with pi, so
that sysrq-n does not leave it locked.
7 Replenish a throttled task switched out and back, so that it runs
again.
8 Do not refill a boost from cleared parameters, so that the owner's
CPU no longer locks up.
9 Reset the deadline and the runtime with the parameters. 10 Release the bandwidth of a task that leaves the class asleep. 11 Reject SCHED_DEADLINE on exited tasks (Juri Lelli).
12 Keep this_bw right when a task changes during a remote wakeup. 13 Check the affinity of a deadline task under the runqueue lock, so
that sched_setaffinity() and sched_setattr() cannot both succeed (Andrea Parri).
Patch 14 shows the deadline bandwidth of each runqueue in sched_debug. Patch 15 adds deadline_switch_test. Patch 16 adds deadline_bw_test, with the 46 of its 112 cases that pass with these fixes. The other cases come with their fixes, in the second series.
Known limit
===========
Patch 10 clears the parameters of a task that leaves the class asleep. On v7.4-rc2, such a task kept them. That hid a bug of the rtmutex chain
walk: an owner can keep as its donor a deadline task that left the class. Another deadline task then gets too little CPU time. With patch 10, the case pi_chain_top_moves shows this in every run. It passes on v7.4-rc2. The case is new in the second series, with the two rtmutex fixes that make it pass with patch 10.
Testing
=======
The 51 cases pass wherever they run, with lockdep and no kernel warning, in 25 QEMU guests:
- 9 guests of 8 vCPUs, one with proxy execution off, and 1 of 4 vCPUs.
- 5 guests with PREEMPT_RT, 4 of 8 vCPUs and 1 of 4.
- 3 guests without CONFIG_CPUSETS, of 4, 4 and 5 vCPUs.
- 4 guests of 5 vCPUs booted with isolcpus=domain,1,2 or isolcpus=domain,0,1, 2 of them with PREEMPT_RT.
- 1 guest of 8 vCPUs booted with isolcpus=domain,6,7.
- 2 guests with CONFIG_RT_GROUP_SCHED, of 8 and 4 vCPUs. move_cancelled runs only in the last group. Without CONFIG_CPUSETS, the cases that need a cpuset skip. With 3 CPUs that are not isolated, params_waking skips: it needs 4.
On v7.4-rc2, six cases of deadline_bw_test fail in each of 16 guests of 8 vCPUs, in two runs. Patch 16 lists them. overrun_caught fails in 3 guests. In one, hotplug_server crashed the kernel with the division by zero that patch 4 fixes. throttled_round_trip and asleep_round_trip of deadline_switch_test fail too. The sysrq cases did not run there:
sysrq-n leaves cpuset_mutex locked, which patch 6 fixes. In earlier runs with them, sysrq_normalize failed.
Each of the 14 kernel patches builds alone. The whole series also builds without CONFIG_CPUSETS, with PREEMPT_RT and with CONFIG_RT_GROUP_SCHED. The selftests build with no warning.
Not tested: cgroup v1 cpusets, the sched_ext server, and CPUs of unequal capacity.
How this was developed
======================
An LLM coding assistant wrote these patches, their messages and the tests, under my direction and review. It did not write patches 11 and
13. I know the concepts behind SCHED_DEADLINE, but not its implementation well. So I ask those who know this code for a careful reading of the fixes. A reproducer that stops failing shows that the symptom goes away. It does not show that the fix is the one you would have written.
The bugs came from:
- flaky cgroup selftests of a feature I am developing;
- the review of Juri's four fixes, and his review of v5;
- building deadline_bw_test, and reading the code;
- the Sashiko AI reviews of v1 to v7 of the original series, and of v1 of this one. Each finding was checked against the code first.
Changes since v1
================
From the Sashiko AI review of v1, in deadline_bw_test:
- rebuild_record_taken moves to the second series. It tests a fix of that series, and fails without it when CPU 0 is isolated.
- move_cancelled runs from the root cgroup. It turns the cpu controller off at the end only if it turned it on.
- Its setter thread is joined after a timeout too, and its result is atomic.
- The shared lock of the death cases is made consistent and destroyed before it is set up again.
- A failed probe fails the case, in hotplug_server, move_refused and move_zero_bw.
Based on tip sched/urgent, ec6f6731538e (v7.4-rc2).
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
v1: https://lore.kernel.org/all/[email protected]/
Andrea Parri (1):
sched/deadline: Check SCHED_DEADLINE affinity under the rq lock
Juri Lelli (1):
sched/deadline: Reject SCHED_DEADLINE on exited tasks
Mathieu Desnoyers (14):
sched: Refuse SCHED_FLAG_KEEP_PARAMS that would change the policy or
the class
sched/deadline: Do not admit bandwidth for parameters that are kept
sched: Let a task boosted by a deadline waiter change its policy sched/deadline: Do not divide by zero active CPUs of a root domain sched/deadline: Refuse dl_server debugfs writes while the rq is
offline
sched: Take cpuset_mutex for a deadline policy change only with pi sched/deadline: Do not lose a throttled task switched out and back sched/deadline: Do not replenish a boost from cleared parameters sched/deadline: Reset the deadline and the runtime with the parameters sched/deadline: Release the bandwidth of a task that leaves the class
asleep
sched/deadline: Fix this_bw when a task is changed during a remote
wakeup
sched/debug: Show the deadline bandwidth of each runqueue selftests/sched: Add a test of SCHED_DEADLINE policy round trips selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
include/linux/sched.h | 5 + kernel/sched/core.c | 11 + kernel/sched/deadline.c | 125 +- kernel/sched/debug.c | 13 +- kernel/sched/sched.h | 1 + kernel/sched/syscalls.c | 103 +- tools/testing/selftests/Makefile | 1 + .../selftests/sched/deadline/.gitignore | 2 + .../testing/selftests/sched/deadline/Makefile | 8 + tools/testing/selftests/sched/deadline/config | 5 + .../sched/deadline/deadline_bw_test.c | 5246 +++++++++++++++++ .../sched/deadline/deadline_switch_test.c | 1115 ++++ .../testing/selftests/sched/deadline/settings | 1 + 13 files changed, 6607 insertions(+), 29 deletions(-) create mode 100644 tools/testing/selftests/sched/deadline/.gitignore create mode 100644 tools/testing/selftests/sched/deadline/Makefile create mode 100644 tools/testing/selftests/sched/deadline/config create mode 100644 tools/testing/selftests/sched/deadline/deadline_bw_test.c create mode 100644 tools/testing/selftests/sched/deadline/deadline_switch_test.c create mode 100644 tools/testing/selftests/sched/deadline/settings
base-commit: ec6f6731538e0d45872eb279fdeb477bed152d6f
Signature · 1 line
2.47.3
PATCH v2 1/16 sched: Refuse SCHED_FLAG_KEEP_PARAMS that would change the policy or the class
A sched_setattr() request with SCHED_FLAG_KEEP_PARAMS can ask for another policy. __sched_setscheduler() then applies only half of the change, and returns 0:
- SCHED_OTHER to SCHED_BATCH leaves the policy as it was.
- SCHED_DEADLINE to SCHED_OTHER sets DEQUEUE_CLASS. switched_from_dl() then runs on a task that stays in the class. It would release bandwidth the task still uses.
- SCHED_DEADLINE on a task of another policy reserves bandwidth in sched_dl_overflow(). The task keeps its policy and a dl_bw of 0, so nothing releases that bandwidth. For a task boosted into the deadline class, it is not even a class change.
SCHED_FLAG_KEEP_PARAMS came with utilization clamping. With SCHED_FLAG_KEEP_POLICY, it lets sched_setattr() change only the clamps of a task. So __sched_setscheduler() skips __setscheduler_params(), which sets p->policy, and the sched_class assignment. Nothing checks that the request keeps the policy.
In testing on v7.4-rc2, a deadline waiter boosted a SCHED_OTHER mutex owner with a 40ms slice. One such call on the owner left 0.4 CPU in total_bw, until the next rebuild of the root domains.
Fix this by refusing a request for another policy or class with EINVAL. Move sched_dl_overflow() after it, as the last check. Nothing gives back the bandwidth it reserves. A refused request also leaves sched_reset_on_fork alone.
With this patch, that call is refused and total_bw does not change. The params_keep_boosted case of deadline_bw_test, added later in this series, tests it.
Juri Lelli found the class change, from a report by Tejun Heo. The Sashiko AI review of this series found the policy change and the boosted case.
--- kernel/sched/syscalls.c | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-)
kernel/sched/syscalls.c +29 -11
@@ -647,17 +647,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);
@@ -677,9 +666,38 @@ int __sched_setscheduler(struct task_struct *p, prev_class = p->sched_class; next_class =__setscheduler_class (policy, newprio); +/* +* With SCHED_FLAG_KEEP_PARAMS, the change below skips +* __setscheduler_params() and the sched_class assignment. The +* policy and the class stay as they are. Refuse a request for +* another policy or class, rather than carry out half of it. +* +* The class depends on the priority, which priority inheritance +* can raise. It also depends on whether a BPF scheduler is in +* charge. So test the class too, not only the policy. +*/ +if ((attr->sched_flags &SCHED_FLAG_KEEP_PARAMS ) && + (policy != p->policy || prev_class != next_class)) { + retval = -EINVAL ; + goto unlock; + } +if (prev_class != next_class) 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. Keep this check last. If a later check failed, +* nothing would give 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
PATCH v2 2/16 sched/deadline: Do not admit bandwidth for parameters that are kept
In reply to Mathieu Desnoyers__sched_setscheduler() runs the deadline admission test on a request with SCHED_FLAG_KEEP_PARAMS. But the task keeps its parameters: the call skips __setscheduler_params().
Commit f4dddf90d58d ("sched: Skip priority checks with SCHED_FLAG_KEEP_PARAMS") made sys_sched_setattr() copy the task's own parameters into such a request. Then the priority checks pass. get_params() copies them without a lock.
Another call can change the task's parameters before __sched_setscheduler() takes the runqueue lock. The request is then stale, and dl_param_changed() takes it for a change. sched_dl_overflow() would put the stale bandwidth in place of the task's own in total_bw, and in this_bw for a sleeping task. But the task keeps its own dl_bw. Its release at the 0-lag time takes that dl_bw, and the difference stays behind.
Fix this by skipping sched_dl_overflow() for SCHED_FLAG_KEEP_PARAMS. There is nothing to admit for parameters that are kept.
Found by reading, after the Sashiko AI review of this series raised the boosted case of the previous patch. Not reproduced: the parameter change must land inside that window.
--- kernel/sched/syscalls.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +9 -1
@@ -690,8 +690,16 @@ int __sched_setscheduler(struct task_struct *p,* of a SCHED_DEADLINE task) we need to check if enough bandwidth * is available. Keep this check last. If a later check failed, * nothing would give back the bandwidth it reserves. +* +* With SCHED_FLAG_KEEP_PARAMS, the task keeps its parameters, so +* there is nothing to admit. Such a call changes other attributes, +* such as the utilization clamps. A deadline task does not use its +* clamps, but keeps them for when it leaves the class. The +* parameters in attr may also be stale: sys_sched_setattr() read +* them from the task without a lock. */ -if ((dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { +if (!(attr->sched_flags &SCHED_FLAG_KEEP_PARAMS ) && + (dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { retval = -EBUSY ; goto unlock; }
Signature · 1 line
2.47.3
PATCH v2 3/16 sched: Let a task boosted by a deadline waiter change its policy
In reply to Mathieu DesnoyersA SCHED_OTHER or SCHED_FIFO task that holds an rt_mutex can be boosted into the deadline class by a deadline waiter. Then a sched_setattr() or sched_setscheduler() call on it fails with EBUSY, unless it asks for SCHED_DEADLINE. sysrq-n would not reset it either.
The admission test runs "if setscheduling to SCHED_DEADLINE (or changing the parameters of a SCHED_DEADLINE task)", as its comment says. sched_dl_overflow() then handles three cases, by the task's
policy: the task enters, leaves or stays in SCHED_DEADLINE. But the call site tests dl_task(p). That tests the priority, so a boosted task passes it. For such a task and another policy, sched_dl_overflow() matches no case and returns -1.
Fix this by testing the policy, with task_has_dl_policy(). A boosted task has no bandwidth of its own to admit or release.
Now sysrq-n can take a boosted task out of the class. normalize_rt_tasks() calls __sched_setscheduler() without pi, so the task gets its normal priority. Nothing then drops the boost. At the unlock, rt_mutex_setprio() sees no change of priority. The pi_se of the task would keep pointing to the waiter, which can exit. So also drop the boost in __setscheduler_dl_pi() when the task leaves the class, as rt_mutex_setprio() does.
The boosted_owner_policy case of deadline_bw_test, added later in this series, fails with EBUSY on v7.4-rc2. It passes with this series. The sysrq_boosted_owner case of deadline_switch_test tests the sysrq-n path.
--- kernel/sched/syscalls.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +13 -1
@@ -304,6 +304,13 @@ static inline void __setscheduler_dl_pi(int newprio, int policy, scope->flags |= ENQUEUE_REPLENISH; } } + +/* +* Without pi, as from normalize_rt_tasks(), a boosted task can leave +* the class. Drop its boost then, as rt_mutex_setprio() does. +*/ +if (!dl_prio (newprio)) + p->dl.pi_se = &p->dl; }#else /* !CONFIG_RT_MUTEXES */ static inline void __setscheduler_dl_pi(int newprio, int policy,
@@ -691,6 +698,10 @@ int __sched_setscheduler(struct task_struct *p,* is available. Keep this check last. If a later check failed, * nothing would give back the bandwidth it reserves. * +* Test the policy, not the priority. A task boosted into the class +* by priority inheritance has no bandwidth of its own to admit or +* release. +* * With SCHED_FLAG_KEEP_PARAMS, the task keeps its parameters, so * there is nothing to admit. Such a call changes other attributes, * such as the utilization clamps. A deadline task does not use its
@@ -699,7 +710,8 @@ int __sched_setscheduler(struct task_struct *p,* them from the task without a lock. */ if (!(attr->sched_flags &SCHED_FLAG_KEEP_PARAMS ) && - (dl_policy (policy) ||dl_task (p)) &&sched_dl_overflow (p, policy, attr)) { + (dl_policy (policy) ||task_has_dl_policy (p)) && +sched_dl_overflow (p, policy, attr)) { retval = -EBUSY ; goto unlock; }
Signature · 1 line
2.47.3
PATCH v2 4/16 sched/deadline: Do not divide by zero active CPUs of a root domain
In reply to Mathieu Desnoyers__dl_sub() and __dl_add() divide by their cpus argument. Most callers pass dl_bw_cpus(), the number of active CPUs of a root domain. That number can be 0, and the division then traps.
Commit daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks") added extra_bw, the bandwidth that deadline tasks can reclaim on a runqueue. A change of a root domain's total_bw is spread over the extra_bw of its active CPUs.
During hotplug, a CPU sits in the default root domain, which can then have no active CPU. This lasts from the rebuild in sched_cpu_deactivate() to the offline, and from the online to sched_cpu_activate(). A debugfs write to the runtime or period of its fair or ext server divides there. A write of the current value passes admission in the window. In 8-CPU VMs of v7.4-rc2, a loop of such writes oopses at the first offline and online:
Oops: divide error: 0000 [#1] SMP NOPTI RIP: 0010:dl_server_apply_params+0x335/0x380 Call Trace: sched_server_write_common.isra.0+0x1c0/0x260 full_proxy_write+0x58/0x90 vfs_write+0xcb/0x550
By reading, two other paths would divide by zero:
- inactive_task_timer(), for a task that left SCHED_DEADLINE or died, if its CPU went offline.
- sched_setattr(SCHED_DEADLINE) on a task asleep on an offline CPU, with admission control off.
Fix this by changing total_bw alone when the root domain has no active CPU.
With this patch, the reproducer survives 20 rounds with no warning.
--- 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) } } +/* +* Spread a change of total_bw over the extra_bw of the active CPUs of the +* root domain. @cpus is their number. With no active CPU, as can happen +* during CPU hotplug, change total_bw alone. +*/ 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 v2 5/16 sched/deadline: Refuse dl_server debugfs writes while the rq is offline
In reply to Mathieu DesnoyersCommit 4043f5498416 ("sched/deadline: Reject debugfs dl_server writes for offline CPUs") refuses a write to a dl_server's runtime or period on an offline CPU. Its message says that such a write has no meaningful semantics.
It tests cpu_online(). But during hotplug the CPU is still online while it sits in the default root domain. This lasts from the rebuild in sched_cpu_deactivate() to the offline, and from the online to sched_cpu_activate(). That root domain does not count the server's bandwidth. A write in the window still goes through admission. With admission control off, it changes total_bw there. On v7.4-rc2, a write of the current value divides by zero in that window. The previous patch removes the division, not the write.
Fix this by testing rq->online instead. It is set under the runqueue lock when the CPU joins a root domain that counts it, after cpu_active() is set. Test cpu_active() too. On the way down, it is cleared before rq->online.
A write now fails with EBUSY while the CPU goes offline or comes online, as a write on an offline CPU already does. Writes at any other time are unchanged.
Applied without the previous patch, this patch alone also stops the oops. The reproducer survives 20 rounds with no warning, in 3 VMs of 3.
--- kernel/sched/debug.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
kernel/sched/debug.c +10 -1
@@ -410,7 +410,16 @@ static ssize_t sched_server_write_common(struct file *filp, const char __user *ureturn -EINVAL ; } -if (!cpu_online (cpu_of (rq))) +/* +* Refuse the write while the runqueue is offline. This +* includes the windows where the CPU goes offline or comes +* online. The root domain then does not count the server's +* bandwidth, and may have no active CPU. rq->online is set +* under this lock when the CPU joins a root domain that +* counts it. cpu_active() is set before that. On the way +* down, cpu_active() is cleared first. +*/ +if (!rq->online || !cpu_active (cpu_of (rq)))return -EBUSY ;update_rq_clock (rq);
Signature · 1 line
2.47.3
PATCH v2 6/16 sched: Take cpuset_mutex for a deadline policy change only with pi
In reply to Mathieu Desnoyers__sched_setscheduler() takes cpuset_mutex for a change that involves SCHED_DEADLINE. On success, it releases it only when pi is set. normalize_rt_tasks(), for sysrq-n, is the one caller with pi unset. It runs under read_lock(&tasklist_lock). So sysrq-n takes the mutex in atomic context for a deadline task, and never releases it. Every later change that involves SCHED_DEADLINE then blocks forever.
Commit 710da3c8ea7d ("sched/core: Prevent race condition between cpuset and __sched_setscheduler()") took the cpuset lock only when pi is set. normalize_rt_tasks() cannot take it under tasklist_lock. Its changelog accepts this: after sysrq-n, the deadline guarantees are gone anyway. Commit 111cd11bbc54 ("sched/cpuset: Bring back cpuset_mutex") then took the mutex only for deadline tasks. It replaced the pi test by a policy test, and left the release under pi.
Fix this by taking the mutex for a deadline change only when pi is set.
The policy test reads p->policy before the runqueue lock. It is checked again under the lock only when the caller gave no policy. Otherwise, the task can enter SCHED_DEADLINE in between. The call then takes it out of the class without the mutex. A rebuild of the root domain accounting could run at the same time. So check again under the runqueue lock, and retry with the mutex.
sysrq-n on v7.4-rc2, with a deadline task and lockdep on:
sysrq: Nice All RT Tasks
BUG: sleeping function called from invalid context at kernel/locking/mutex.c:623
in_atomic(): 1, irqs_disabled(): 0, non_block: 0, pid: 4356, name: deadline_switch
locks held by deadline_switch/4356: 4, on CPU#3:
...
#3: ffffffff83006098 (tasklist_lock){.+.+}-{3:3}, at: normalize_rt_tasks+0x34/0x150A sched_setattr(SCHED_DEADLINE) after it never returned, in 8 VMs of 8. The sysrq_normalize case of deadline_switch_test, added later in this series, tests this with DEADLINE_TEST_SYSRQ=1. It passes with this series.
--- kernel/sched/syscalls.c | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-)
kernel/sched/syscalls.c +23 -3
@@ -561,9 +561,11 @@ int __sched_setscheduler(struct task_struct *p,/* * SCHED_DEADLINE bandwidth accounting relies on stable cpusets -* information. +* information. Do not take cpuset_mutex when pi is unset: the +* caller is normalize_rt_tasks(), which holds tasklist_lock and +* cannot sleep. */ -if (dl_policy (policy) ||dl_policy (p->policy)) { +if (pi && (dl_policy (policy) ||dl_policy (p->policy))) { cpuset_locked = true;cpuset_lock (); }
@@ -643,7 +645,13 @@ int __sched_setscheduler(struct task_struct *p, } } -/* Re-check policy now with rq lock held: */ +/* +* The caller gave no policy (SETPARAM_POLICY): the request was +* derived from an unlocked read of p->policy above. If the task +* changed policy since, re-derive the request from scratch, and +* release cpuset_mutex: the re-derived request re-decides whether +* it is needed. +*/ if (unlikely (oldpolicy !=-1 && oldpolicy != p->policy)) { policy = oldpolicy =-1 ;task_rq_unlock (rq, p, &rf);
@@ -654,6 +662,18 @@ int __sched_setscheduler(struct task_struct *p, goto recheck; } +/* +* The caller gave an explicit policy, so the request needs no +* re-derivation (oldpolicy is -1 above). But the decision to +* take cpuset_mutex used the same unlocked read: the task +* entered SCHED_DEADLINE since, and the change below would take +* it out of the class. Retry to take the mutex. +*/ +if (unlikely (pi && !cpuset_locked &&task_has_dl_policy (p))) { +task_rq_unlock (rq, p, &rf); + goto recheck; + } + oldprio = p->prio; newprio =__normal_prio (policy, attr->sched_priority, attr->sched_nice);
Signature · 1 line
2.47.3
PATCH v2 7/16 sched/deadline: Do not lose a throttled task switched out and back
In reply to Mathieu DesnoyersA SCHED_DEADLINE task can be throttled, switched to another policy, and switched back before its 0-lag time. It may then never run again, not even to die of a fatal signal.
A task that leaves SCHED_DEADLINE keeps its parameters until its 0-lag time, so that leaving and coming back gains nothing. Commit 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization") moved their reset from the replenishment timer to the inactive timer, which switched_to_dl() cancels.
This misses a task that was throttled when it left. An overrun can put its 0-lag time after its replenishment timer. That timer fires while the task is out of the class, and does nothing. On the return of the task, enqueue_dl_entity() leaves it to that timer, which has fired. The task is then on no dl_rq, with no timer pending, until it leaves SCHED_DEADLINE again.
Fix this by replenishing the task when the timer finds it out of the class, as for a throttled task that is not queued. Its return then enqueues it.
Clearing dl_throttled alone would not do. It would forgive the overrun. A yield left set, or the old deadline of a constrained task, would throttle the task again. The Sashiko AI review of this series found this in the first version of this patch.
A cgroup selftest under development hung on this bug about once in 1350 runs. The throttled_round_trip case of deadline_switch_test, added later in this series, fails 8 times out of 8 on v7.3 and v7.4-rc2. It passes with this patch.
--- kernel/sched/deadline.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +10 -1
@@ -1233,9 +1233,18 @@ 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()). +* It keeps its parameters until its 0-lag time. If it comes back +* before then, nothing else would lift its throttle. So replenish +* it now, as the !queued case below does. Its return enqueues it. */ -if (!dl_task (p)) +if (!dl_task (p)) { +if (dl_se->dl_throttled && !is_dl_boosted (dl_se)) { +sched_clock_tick (); +update_rq_clock (rq); +replenish_dl_entity (dl_se); + } goto unlock; + }/* * The task might have been boosted by someone else and might be in the
Signature · 1 line
2.47.3
PATCH v2 8/16 sched/deadline: Do not replenish a boost from cleared parameters
In reply to Mathieu DesnoyersWhen a SCHED_DEADLINE waiter boosts the owner of an rt_mutex, the owner runs on the waiter's parameters, through dl.pi_se. Commit 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic") calls this a temporary solution. The owner is never throttled. When its runtime runs out, replenish_dl_entity() refills it at once from the waiter's dl_runtime.
The waiter can leave SCHED_DEADLINE before the chain walk deboosts the owner. Its parameters can be cleared in between, at its 0-lag time. replenish_dl_entity() then loops forever on a dl_runtime of 0. It holds the rq lock with interrupts off, so the owner's CPU locks up.
O is a SCHED_OTHER task that holds the rt_mutex L. W is a SCHED_DEADLINE task. T is any other task:
CPU 0 (O) CPU 1 (W) CPU 2 (T)
locks L
blocks on L
rt_mutex_setprio(O, W)
O->dl.pi_se = &W->dl
sleeps
task_non_contending()
arms W's inactive timer
sched_setscheduler(W)
W leaves SCHED_DEADLINE task_rq_unlock(W)
<W's inactive timer> inactive_task_timer()
__dl_clear_params()
W->dl.dl_runtime = 0
<tick>
update_curr_dl_se()
enqueue_task_dl()
replenish_dl_entity()
runtime += W->dl.dl_runtime
loops forever
rt_mutex_adjust_pi(W)
rt_mutex_setprio(O, W)
spins on O's rq lock
Fix this by not refilling from cleared parameters. The donor's parameters are cleared under the donor's rq lock, not the owner's, so replenish_dl_entity() can see them change under it. Read dl_runtime, dl_deadline and dl_period once, and bail out if any of them is 0.
On bailing out, the owner gets no new runtime, but stays runnable and unthrottled. It runs until the chain walk deboosts it, or until it releases the lock. Keeping it runnable also covers sysrq-n:normalize_rt_tasks() changes the waiter without a chain walk, so a throttled owner might never get to release the lock.
The bandwidth the owner consumed while boosted belongs to the donor, so a negative runtime is reset to 0 rather than charged to the owner's own reservation. An owner with no parameters of its own gets a deadline of now. Its deadline must not stay 0: the dl_rq uses an earliest deadline of 0 to mean that no deadline entity is queued (see inc_dl_deadline()).
Until the deboost (which should happen "soon enough"), such an owner sorts first on its CPU's dl_rq and runs ahead of the other deadline tasks there.
The warning is kept for an entity that is not boosted.
The reset bounds the overrun. But a runtime of 0 still counts as exceeded. So until the deboost, update_curr_dl_se() still requeues the owner at each update. An owner with SCHED_FLAG_DL_OVERRUN still gets SIGXCPU.
With a 300ms debug delay before rt_mutex_adjust_pi(), v7.4-rc2 locks up in 8-CPU VMs. A kernel with this patch does not.
The Sashiko AI review of this series found the lockup.
--- kernel/sched/deadline.c | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-)
kernel/sched/deadline.c +35 -5
@@ -807,8 +807,38 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se) {struct dl_rq *dl_rq =dl_rq_of_se (dl_se);struct rq *rq =rq_of_dl_rq (dl_rq); +struct sched_dl_entity *pi_se =pi_of (dl_se); +u64 runtime =READ_ONCE (pi_se->dl_runtime); +u64 deadline =READ_ONCE (pi_se->dl_deadline); +u64 period =READ_ONCE (pi_se->dl_period); -WARN_ON_ONCE (pi_of (dl_se)->dl_runtime <=0 ); +/* +* A boosted entity runs on the parameters of its donor, the top +* waiter of an rt_mutex. The donor can leave the class and have them +* cleared before the chain walk deboosts this entity. They are +* cleared under the donor's rq lock, which can be another one. So +* read each of them once, and check all three. Refilling from a +* runtime of 0 would loop forever. Leave the entity runnable +* instead: the walk deboosts it, or its task releases the lock. +* +* Add no runtime. Do not keep a negative one: the overrun comes +* from the boost, and the entity's own reservation does not pay for +* it. A task with no parameters of its own gets a deadline of now, +* as a donor's relative deadline of 0 would give. A deadline of 0 +* means an empty dl_rq to inc_dl_deadline(). +*/ +if (unlikely (!runtime || !deadline || !period)) { +WARN_ON_ONCE (!is_dl_boosted (dl_se)); +if (!dl_se->dl_deadline) { + dl_se->deadline =rq_clock (rq); + dl_se->runtime =0 ; + } +if (dl_se->runtime <0 || dl_se->dl_yielded) + dl_se->runtime =0 ; + dl_se->dl_yielded =0 ; + dl_se->dl_throttled =0 ; +return ; + }/* * This could be the case for a !-dl task that is boosted.
@@ -822,8 +852,8 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)*/ if (dl_se->dl_deadline ==0 || (dl_se->dl_defer_armed &&dl_entity_overflow (dl_se,rq_clock (rq)))) { - dl_se->deadline =rq_clock (rq) +pi_of (dl_se)->dl_deadline; - dl_se->runtime =pi_of (dl_se)->dl_runtime; + dl_se->deadline =rq_clock (rq) + deadline; + dl_se->runtime = runtime; }if (dl_se->dl_yielded && dl_se->runtime >0 )
@@ -836,8 +866,8 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)* arbitrary large. */ while (dl_se->runtime <=0 ) { - dl_se->deadline +=pi_of (dl_se)->dl_period; - dl_se->runtime +=pi_of (dl_se)->dl_runtime; + dl_se->deadline += period; + dl_se->runtime += runtime; }/*
Signature · 1 line
2.47.3
PATCH v2 9/16 sched/deadline: Reset the deadline and the runtime with the parameters
In reply to Mathieu DesnoyersA task that leaves SCHED_DEADLINE keeps its parameters until its 0-lag time, so that leaving and coming back gains nothing. Commit 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization") moved their reset to that time. Before it, the replenishment timer did the reset at the deadline. So a task back after the reset found its deadline passed, and started a new period. But __dl_clear_params() resets neither the deadline nor the runtime.
Now a task back after its 0-lag time can be enqueued on its old deadline and runtime. With runtime left, its 0-lag time comes before its deadline. Back before that deadline, it would first spend the runtime of the reservation it gave back. Back after it, a constrained task would be throttled until its old period ends. "sched/deadline: Do not lose a throttled task switched out and back" moves the deadline of a throttled task on. This widens the window before the deadline to about a period.
A task with no parameters of its own, boosted by a deadline waiter, keeps the donor's deadline and runtime after its deboost. If it then enters SCHED_DEADLINE before that deadline, it runs on the donor's runtime. On v7.4-rc2, a task of 10ms per 100ms ran 40ms of its first period.
Fix this by resetting the deadline and the runtime in __dl_clear_params(), and in switched_from_dl() at the deboost of a task with no parameters. The next enqueue then starts a new period.
The Sashiko AI review of this series found the first case and the deboost. The deboost_resets_period case of deadline_bw_test, added later in this series, tests the deboost.
--- kernel/sched/deadline.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +15 -1
@@ -3569,6 +3569,16 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)if (task_on_rq_queued (p) && p->dl.dl_runtime)task_non_contending (&p->dl, false); +/* +* A task with no parameters of its own was boosted into the class. +* Its deadline and runtime are the donor's. Reset them, so that its +* next entry into the class starts a new period. +*/ +if (!p->dl.dl_runtime) { + p->dl.deadline =0 ; + p->dl.runtime =0 ; + } +/* * In case a task is setscheduled out from SCHED_DEADLINE we need to * keep track of that on its cpuset (for correct bandwidth tracking).
@@ -3984,7 +3994,8 @@ bool __checkparam_dl(const struct sched_attr *attr) }/* -* This function clears the sched_dl_entity static params. +* Clear the static parameters of @dl_se. Also reset its deadline and its +* runtime, so that its next enqueue starts a new period. */ static void __dl_clear_params (struct sched_dl_entity *dl_se) {
@@ -3995,6 +4006,9 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se) dl_se->dl_bw =0 ; dl_se->dl_density =0 ; + dl_se->deadline =0 ; + dl_se->runtime =0 ; + dl_se->dl_throttled =0 ; dl_se->dl_yielded =0 ; dl_se->dl_non_contending =0 ;
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH v2 09/16] sched/deadline: Reset the deadline and the runtime with the parameters
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: donor runtime and deadline retained after PI deboost - [Medium] sched/deadline…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: donor runtime and deadline retained after PI deboost
- [Medium] sched/deadline: uncanceled dl_timer in __dl_clear_params() --
commit d69ea33f8330709357d7bb1bbbe6f7eeb0c68972
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Reset the deadline and the runtime with the parameters
This commit resets a deadline entity's runtime and deadline in __dl_clear_params() and upon deboost in switched_from_dl() so that its next entry into SCHED_DEADLINE starts a new period.
Quoted 11 lines
kernel/sched/deadline.c +3
-0@@ -3569,6 +3569,16 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)if (task_on_rq_queued (p) && p->dl.dl_runtime)task_non_contending (&p->dl, false); +/* +* A task with no parameters of its own was boosted into the class. +* Its deadline and runtime are the donor's. Reset them, so that its
kernel/sched/deadline.c static void switched_from_dl(struct rq *rq, struct task_struct *p) · line 3584
Quoted 10 lines
kernel/sched/deadline.c +7
-0+* next entry into the class starts a new period. +*/ +if (!p->dl.dl_runtime) { + p->dl.deadline =0 ; + p->dl.runtime =0 ; + } +/* * In case a task is setscheduled out from SCHED_DEADLINE we need to * keep track of that on its cpuset (for correct bandwidth tracking).
[Severity: Medium]
Can a task still retain the donor's runtime and deadline after a PI deboost when p->dl.dl_runtime is non-zero?
If a task that left SCHED_DEADLINE before its 0-lag time is PI-boosted by a deadline waiter before inactive_timer fires, switched_to_dl() cancels inactive_timer and replenish_dl_entity() overwrites p->dl.deadline and p->dl.runtime from the donor while p->dl.dl_runtime still holds the task's own prior parameter. When the task is deboosted, switched_from_dl() sees p->dl.dl_runtime != 0, skips this reset, and passes the donor's deadline and runtime to task_non_contending(), allowing the task to run on the donor's runtime if it re-enters SCHED_DEADLINE before that deadline.
Similarly, if a non-deadline task is switched to SCHED_DEADLINE via sched_setattr() while PI-boosted, prev_class and next_class are both dl_sched_class, so neither switched_from_dl() nor switched_to_dl() runs. __setparam_dl() sets p->dl.dl_runtime without clearing the donor's deadline and runtime (and for a sleeping task, skipping switched_to_dl() also misses add_rq_bw()), so when rt_mutex_setprio() later restores p->dl.pi_se = &p->dl, enqueue_dl_entity() sees the donor's future deadline and skips setup_new_dl_entity().
Quoted 11 lines
kernel/sched/deadline.c +2
-1@@ -3984,7 +3994,8 @@ bool __checkparam_dl(const struct sched_attr *attr) }/* -* This function clears the sched_dl_entity static params. +* Clear the static parameters of @dl_se. Also reset its deadline and its +* runtime, so that its next enqueue starts a new period. */ static void __dl_clear_params (struct sched_dl_entity *dl_se) {
kernel/sched/deadline.c static void __dl_clear_params(struct sched_dl_entity *dl_se) · line 4014
Quoted 9 lines
kernel/sched/deadline.c +3
-0@@ -3995,6 +4006,9 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se) dl_se->dl_bw =0 ; dl_se->dl_density =0 ; + dl_se->deadline =0 ; + dl_se->runtime =0 ; + dl_se->dl_throttled =0 ; dl_se->dl_yielded =0 ; dl_se->dl_non_contending =0 ;
[Severity: Medium]
Does zeroing dl_se->deadline, dl_se->runtime, and dl_se->dl_throttled here without canceling dl_se->dl_timer leave a stale replenishment timer queued from the old period?
If a task throttles when its 0-lag time is earlier than dl_next_period(dl_se) (such as after sched_yield() with positive remaining runtime, or with a constrained deadline dl_deadline < dl_period) and leaves SCHED_DEADLINE, __dl_clear_params() runs at the 0-lag time while dl_se->dl_timer is still queued for the old period end. If the task re-enters SCHED_DEADLINE and throttles in its new period before that old timer expires, start_dl_timer() sees hrtimer_is_queued(&dl_se->dl_timer) and skips arming the timer for the new period, so dl_task_timer() replenishes and unthrottles the task at the old period boundary instead.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Re: [PATCH v2 09/16] sched/deadline: Reset the deadline and the runtime with the parameters
Quoted 6 lines
Can a task still retain the donor's runtime and deadline after a PI deboost when
p->dl.dl_runtimeis non-zero?Does zeroing
dl_se->deadline,dl_se->runtime, anddl_se->dl_throttledhere without cancelingdl_se->dl_timerleave a stale replenishment timer queued from the old period?
These are the two points of v1. My answer there still holds [1]. The second series handles both:
- "sched/deadline: Reset the donor's runtime at a deboost in the class" and "sched/deadline: Count the bandwidth a boosted task is given", for the first one.
- "sched/deadline: Cancel the replenishment timer with the parameters", for the second one.
[1] https://lore.kernel.org/all/[email protected]/
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
PATCH v2 10/16 sched/deadline: Release the bandwidth of a task that leaves the class asleep
In reply to Mathieu DesnoyersA task that leaves SCHED_DEADLINE while it is not queued can keep its bandwidth in total_bw until the next rebuild of the root domains. Repeated, this fills total_bw up to the admission limit. Then sched_setattr(SCHED_DEADLINE) and CPU offlining fail with EBUSY.
A task that leaves the class keeps its bandwidth until its 0-lag time. Releasing it earlier would allow temporary overloads. For a queued task, switched_from_dl() calls task_non_contending(). It releases the bandwidth if the 0-lag time is past. Otherwise it arms the inactive timer, which releases it then. For a task that is not queued, switched_from_dl() relies on the timer armed when the task blocked.
But the timer is not always pending when the task leaves the class:
- The task blocked after its 0-lag time. The timer was not armed.
- The timer fired while the task was still in the class. It only removed running_bw.
- The task was woken up on another CPU and is not enqueued there yet. The wakeup cancelled the timer.
- The task came back to the class asleep. switched_to_dl() cancelled the timer.
Then nothing releases total_bw.
Fix this in switched_from_dl(). For a task that is not queued and has no timer pending, call task_non_contending(), as for a queued task. It arms the timer if the 0-lag time is ahead. Otherwise it releases the bandwidth now and clears the parameters, as inactive_task_timer() does.
Clearing the parameters keeps later paths from releasing the bandwidth again:
- A timer handler that already started finds a dl_bw of 0.
- The deboost of a later priority inheritance boost finds no parameters.
An owner that the task boosts as a waiter can find the parameters cleared too. "sched/deadline: Do not replenish a boost from cleared parameters" handles this, so a backport needs it first. Without it, the owner's CPU can lock up as soon as the waiter leaves the class.
Juri Lelli's first fix, since dropped from tip, released the bandwidth here without clearing dl_bw. The bandwidth of a boosted task was then released twice.
Juri Lelli suggested the call to task_non_contending() in review.
The Sashiko AI review of this series found the two cases with the 0-lag time ahead. deadline_switch_test, added later in this series, tests the release in asleep_round_trip.
--- kernel/sched/deadline.c | 8 ++++++++ 1 file changed, 8 insertions(+)
kernel/sched/deadline.c +8 -0
@@ -3595,6 +3595,14 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)if (p->dl.dl_non_contending)sub_running_bw (&p->dl, &rq->dl);sub_rq_bw (&p->dl, &rq->dl); +/* +* Without an armed timer, nothing releases total_bw. Do as for +* a queued task: arm the timer if the 0-lag time is ahead, or +* release the bandwidth and clear the parameters now. Call +* task_non_contending() after sub_rq_bw(), which needs dl_bw. +*/ +if (!p->dl.dl_non_contending) +task_non_contending (&p->dl, false); }/*
Signature · 1 line
2.47.3
[email protected]
AI reviewRe: [PATCH v2 10/16] sched/deadline: Release the bandwidth of a task that leaves the class asleep
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: stale params and s64 overflow in task_non_contending() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: stale params and s64 overflow in task_non_contending()
--
commit f6b619684c21aa7de4c182929a5157b957fed874
Author: Mathieu Desnoyers <[email protected]>
sched/deadline: Release the bandwidth of a task that leaves the class asleep
This commit calls task_non_contending() in switched_from_dl() when an unqueued task leaves SCHED_DEADLINE without an armed inactive timer, so that its total_bw contribution is released immediately or at the 0-lag time.
Quoted 6 lines
kernel/sched/deadline.c +0
-0@@ -3595,6 +3595,14 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)if (p->dl.dl_non_contending)
kernel/sched/deadline.c static void switched_from_dl(struct rq *rq, struct task_struct *p) · line 3605
Quoted 10 lines
kernel/sched/deadline.c +8
-0sub_running_bw (&p->dl, &rq->dl);sub_rq_bw (&p->dl, &rq->dl); +/* +* Without an armed timer, nothing releases total_bw. Do as for +* a queued task: arm the timer if the 0-lag time is ahead, or +* release the bandwidth and clear the parameters now. Call +* task_non_contending() after sub_rq_bw(), which needs dl_bw. +*/ +if (!p->dl.dl_non_contending) +task_non_contending (&p->dl, false);
[Severity: Medium]
Can task_non_contending() compute a bogus zerolag_time here when a sleeping task had its deadline parameters updated before leaving the class?
When a sleeping task re-enters SCHED_DEADLINE before its 0-lag time (or updates its SCHED_DEADLINE parameters in place while asleep), switched_to_dl() or dl_rq_change_utilization() cancels inactive_timer and __setparam_dl() overwrites dl_runtime, dl_deadline and dl_period while leaving the dynamic runtime and deadline from the previous reservation to be updated at the next wakeup. If the task then leaves SCHED_DEADLINE while still asleep, task_non_contending() mixes the old runtime and deadline with the new dl_period and dl_runtime:
kernel/sched/deadline.c:task_non_contending() {
...
zerolag_time = dl_se->deadline -
div64_long((dl_se->runtime * dl_se->dl_period),
dl_se->dl_runtime);
...
}If the task had negative runtime under the old reservation and was given a smaller dl_runtime / dl_period ratio, (-runtime * dl_period) / dl_runtime is scaled up by the new ratio and can arm inactive_timer days in the future, pinning total_bw and the task_struct reference; if runtime was positive and dl_runtime was lowered below runtime, zerolag_time becomes negative before the true 0-lag time and releases total_bw early.
Also, in the same calculation, dl_se->runtime * dl_se->dl_period is evaluated in unscaled 64-bit arithmetic (unlike dl_entity_overflow(), which shifts by DL_SCALE), so valid parameters within the default sysctl_sched_dl_period_max (~4.19s, e.g. dl_period = 4s and remaining runtime = 2.4s) overflow S64_MAX and wrap the dividend negative, pushing zerolag_time past the deadline.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Re: [PATCH v2 10/16] sched/deadline: Release the bandwidth of a task that leaves the class asleep
Quoted 3 lines
Can
task_non_contending()compute a boguszerolag_timehere when a sleeping task had its deadline parameters updated before leaving the class?
Yes. The new parameters take effect at the next period. Until then, task_non_contending() mixes them with the old runtime and deadline. This is older than this patch. A task can change its parameters while it runs, then block. The dequeue then gets the same mix. This patch adds one more path to it. I will look at it in a separate patch.
Quoted 6 lines
Also, in the same calculation,
dl_se->runtime*dl_se->dl_periodis evaluated in unscaled 64-bit arithmetic (unlikedl_entity_overflow(), which shifts byDL_SCALE), so valid parameters within the defaultsysctl_sched_dl_period_max(~4.19s, e.g.dl_period= 4s and remaining runtime = 2.4s) overflowS64_MAXand wrap the dividend negative, pushingzerolag_timepast the deadline.
Right. This is older than this patch too. "sched/deadline: Fix an overflow of the 0-lag time with long periods" fixes it [1]. As Juri suggested, it will come before this patch in v3.
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
PATCH v2 11/16 sched/deadline: Reject SCHED_DEADLINE on exited tasks
In reply to Mathieu DesnoyersFrom: Juri Lelli <[email protected]>
sched_setattr(SCHED_DEADLINE) on a zombie task succeeds and charges total_bw via sched_dl_overflow(), but the task has already done its final schedule() and will never run again. Nothing releases the reserved bandwidth. Repeating this fills total_bw to the admission cap, after which sched_setattr(SCHED_DEADLINE) and CPU offline fail with -EBUSY.
Reject sched_setattr(SCHED_DEADLINE) on exited tasks with -ESRCH.
A task of the class that exited, switched to another policy, runs switched_from_dl(), which decrements the count of deadline tasks of its cpuset that cgroup_task_dead() decremented already: at 0 with a deadline task left in it, the cpuset is skipped by the next rebuild of the root domains' accounting, and that task's bandwidth with it. Reject that as well. The deadline_bw_test selftest added later in this series has the case, death_zombie_switched: on v7.4-rc1 the switch is accepted, and the one-CPU partition root the zombie ran in admits 9 tasks of 10% after a rebuild, with a task of 30% still in it, where 6 are due.
[mathieu: reject a task of the class leaving it too, found by the
Sashiko AI review of the patch]
--- kernel/sched/syscalls.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)
kernel/sched/syscalls.c +13 -0
@@ -592,6 +592,19 @@ int __sched_setscheduler(struct task_struct *p,if (retval) goto unlock; +/* +* Reject SCHED_DEADLINE on exited tasks. A zombie will never be +* scheduled again, so sched_dl_overflow() would charge total_bw +* that nothing will ever release. And reject a change of policy of +* one in the class: cgroup_task_dead() took it off the count of +* deadline tasks of its cpuset, which switched_from_dl() would +* decrement a second time. +*/ +if ((dl_policy (policy) ||dl_task (p)) && p->exit_state) { + retval = -ESRCH ; + goto unlock; + } +/* * If not changing anything there's no need to proceed further, * but store a possible modification of reset_on_fork.
Signature · 1 line
2.47.3
PATCH v2 12/16 sched/deadline: Fix this_bw when a task is changed during a remote wakeup
In reply to Mathieu DesnoyersThe this_bw of a runqueue is the bandwidth of the deadline tasks assigned to it, running or not. GRUB uses it to compute the inactive utilization of the runqueue. When a task wakes up on another CPU, migrate_task_rq_dl() takes its bandwidth off the old runqueue. The enqueue adds it to the new one.
Between these two steps, no runqueue counts the bandwidth. try_to_wake_up() can leave the enqueue to the wake list of the new CPU, and return before it runs. task_cpu() already points at the new CPU. A change of the task in that window gets this_bw wrong.
In this example, T is a deadline task. S is another task. It changes the bandwidth of T from "old bw" to "new bw":
CPU 0 CPU 1 CPU 2
T blocks
this_bw of CPU 0 counts T
<timer> try_to_wake_up(T)
set_task_cpu(T, 1)
migrate_task_rq_dl()
sub_rq_bw(): CPU 0 drops T
T on the wake list of CPU 1
return
S: sched_setattr(T)
task_rq_lock(T): CPU 1 T is not queued dl_change_utilization()
this_bw of CPU 1:
- old bw + new bw
sched_ttwu_pending()
enqueue_task_dl(T)
task_contending()
add_rq_bw():
this_bw of CPU 1:
+ new bw
CPU 1 then counts the new bandwidth twice, less the old one. Repeated, this makes this_bw drift until it underflows. If T left the class in that window, switched_from_dl() would take its bandwidth off CPU 1 the same way. A task that enters the class in that window would be counted twice, by switched_to_dl() and by the enqueue.
This needs a wakeup that moves the task, so a root domain of more than one CPU, with busy CPUs. CONFIG_SCHED_PROXY_EXEC=y makes such wakeups more common. In testing, a task sleeps and wakes in a busy two-CPU partition root, and another CPU changes its runtime. The kernel warns within a second in each of 8 VMs:
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
Fix this with a new bit, dl_bw_oncpu, that tells whether a runqueue counts the bandwidth of the task. add_rq_bw() adds the bandwidth only if no runqueue counts it. sub_rq_bw() takes it off only if one does. dl_change_utilization() does nothing while no runqueue counts the bandwidth. The enqueue adds the new one.
With this patch, none of the 8 VMs warns. deadline_bw_test, added later in this series, tests this in params_waking. The Sashiko
AI review of this series found the double count, and a bit that the first version of this patch left set.
--- include/linux/sched.h | 5 +++++ kernel/sched/deadline.c | 39 +++++++++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 4 deletions(-)
include/linux/sched.h +5 -0
@@ -706,6 +706,10 @@ struct sched_dl_entity {* contributes to the root domain's total_bw. Only meaningful for server * entities (@dl_server == 1). Allows toggling the reservation on/off * without losing the configured @dl_runtime/@dl_period. +* +* @dl_bw_oncpu tells if the this_bw of a runqueue counts the task's +* @dl_bw: add_rq_bw() and sub_rq_bw() set and clear it, under that +* runqueue's lock. Not for servers, which keep @dl_bw_attached. */ unsigned int dl_throttled : 1; unsigned int dl_yielded : 1;
@@ -718,6 +722,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_oncpu : 1;/* * Bandwidth enforcement timer. Each -deadline task has its
kernel/sched/deadline.c +35 -4
@@ -267,18 +267,35 @@ void __sub_rq_bw(u64 dl_bw, struct dl_rq *dl_rq)WARN_ON_ONCE (dl_rq->running_bw > dl_rq->this_bw); } +/* +* @dl_se->dl_bw_oncpu tells whether the this_bw of a runqueue counts the +* bandwidth of @dl_se. add_rq_bw() adds the bandwidth only if no runqueue +* counts it. sub_rq_bw() subtracts it only if one does. +* +* A wakeup on another CPU takes the bandwidth off the old runqueue. The +* enqueue on the new CPU adds it back later. A change of the task in +* between must not count the bandwidth twice, nor take it off a runqueue +* that does not count it. +* +* The servers track their bandwidth with dl_bw_attached. They call +* __add_rq_bw() and __sub_rq_bw() directly. +*/ static inline void add_rq_bw (struct sched_dl_entity *dl_se,struct dl_rq *dl_rq) { -if (!dl_entity_is_special (dl_se)) -__add_rq_bw (dl_se->dl_bw, dl_rq); +if (dl_entity_is_special (dl_se) || dl_se->dl_bw_oncpu) +return ; +__add_rq_bw (dl_se->dl_bw, dl_rq); + dl_se->dl_bw_oncpu =1 ; }static inline void sub_rq_bw (struct sched_dl_entity *dl_se,struct dl_rq *dl_rq) { -if (!dl_entity_is_special (dl_se)) -__sub_rq_bw (dl_se->dl_bw, dl_rq); +if (dl_entity_is_special (dl_se) || !dl_se->dl_bw_oncpu) +return ; +__sub_rq_bw (dl_se->dl_bw, dl_rq); + dl_se->dl_bw_oncpu =0 ; } static inline
@@ -347,6 +364,14 @@ static void dl_change_utilization(struct task_struct *p, u64 new_bw)if (task_on_rq_queued (p))return ; +/* +* The task is waking up on another CPU, and no runqueue counts its +* bandwidth. The enqueue adds it, with the new parameters that +* __setparam_dl() sets right after this. +*/ +if (!p->dl.dl_bw_oncpu) +return ; +dl_rq_change_utilization (task_rq (p), &p->dl, new_bw); }
@@ -2726,6 +2751,11 @@ static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unused*/ cancel_inactive_timer (&p->dl); } +/* +* set_task_cpu() points task_cpu() at the new CPU next. The runqueue +* of that CPU counts this bandwidth only once the enqueue there adds +* it. Until then, no runqueue counts it, as dl_bw_oncpu now says. +*/ sub_rq_bw (&p->dl, &rq->dl);rq_unlock (rq, &rf); }
@@ -4025,6 +4055,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_oncpu =0 ;#ifdef CONFIG_RT_MUTEXES dl_se->pi_se = dl_se;
Signature · 1 line
2.47.3
PATCH v2 13/16 sched/deadline: Check SCHED_DEADLINE affinity under the rq lock
In reply to Mathieu DesnoyersFrom: Andrea Parri <[email protected]>
A task can end up SCHED_DEADLINE with an affinity narrower than its root domain when sched_setaffinity() and sched_setattr() race on it. Both calls succeed, although each fails when made after the other:sched_setattr() with -EPERM, sched_setaffinity() with -EBUSY.
__sched_setaffinity() calls dl_task_check_affinity() before __set_cpus_allowed_ptr() takes task_rq_lock(), whereas __sched_setscheduler() runs its admission test and switches the policy under a single task_rq_lock(). So both calls can pass their checks:
CPU 1: sched_setaffinity(p, cpu0) CPU 2: sched_setattr(p, DEADLINE)
dl_task_check_affinity()
!task_has_dl_policy(p): return 0
task_rq_lock() admission test passes p->policy = SCHED_DEADLINE task_rq_unlock()
__set_cpus_allowed_ptr()
task_rq_lock()
p->cpus_mask = cpu0The window includes CPU 1 spinning on task_rq_lock() while CPU 2 holds it. With one thread narrowing a sleeping task to CPU 0 while another makes it SCHED_DEADLINE, 923514, 959547 and 983997 of 1000000 rounds ended with both calls succeeding on three boots of a 4-CPU guest.
Move the check into __set_cpus_allowed_ptr_locked(), next to the PF_NO_SETAFFINITY re-check, under the same lock as the admission test. Whichever call takes task_rq_lock() second then sees the other's
result: sched_setaffinity() fails with -EBUSY if p is already SCHED_DEADLINE, and sched_setattr() fails with -EPERM if p's affinity is already cpu0.
A new SCA_DL_CHECK flag selects the check, and only __sched_setaffinity() sets it, so sched_setaffinity() and relax_compatible_cpus_allowed_ptr() keep the check and other callers stay unchecked. restrict_cpus_allowed_ptr() already does its deadline check this way.
__sched_setaffinity() clears SCA_DL_CHECK before the second __set_cpus_allowed_ptr() call it makes after racing with a cpuset update, so the cpuset mask still wins there, as it does when cpuset_update_tasks_cpumask() narrows a deadline task. SCA_CHECK stays set for the PF_NO_SETAFFINITY re-check.
With this applied, the same test ends with both calls succeeding in 0 of 1000000 rounds on each of three boots, and sched_setaffinity() fails with -EBUSY whenever it loses.
The race was reported by Sebastian. The fix was written with the help of an LLM.
--- kernel/sched/core.c | 11 +++++++++++ kernel/sched/sched.h | 1 + kernel/sched/syscalls.c | 12 +++++++----- 3 files changed, 19 insertions(+), 5 deletions(-)
kernel/sched/core.c +11 -0
@@ -3195,6 +3195,17 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p, goto out; } +/* +* Check under the same lock that __sched_setscheduler() holds for +* its admission test, so that p cannot become SCHED_DEADLINE +* between this check and the mask update below. +*/ +if (ctx->flags &SCA_DL_CHECK ) { + ret =dl_task_check_affinity (p, ctx->new_mask); +if (ret) + goto out; + } +if (!(ctx->flags &SCA_MIGRATE_ENABLE )) {if (cpumask_equal (&p->cpus_mask, ctx->new_mask)) {if (ctx->flags &SCA_USER )
kernel/sched/sched.h +1 -0
@@ -2972,6 +2972,7 @@ extern struct task_struct *pick_task_idle(struct rq *rq, struct rq_flags *rf);#define SCA_MIGRATE_DISABLE 0x02#define SCA_MIGRATE_ENABLE 0x04#define SCA_USER 0x08 +#define SCA_DL_CHECK 0x10extern void update_group_capacity (struct sched_domain *sd,int cpu);
kernel/sched/syscalls.c +7 -5
@@ -1225,11 +1225,7 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)cpumask_and (new_mask, ctx->new_mask, cpus_allowed); ctx->new_mask = new_mask; - ctx->flags |=SCA_CHECK ; - - retval =dl_task_check_affinity (p, new_mask); -if (retval) - goto out_free_new_mask; + ctx->flags |=SCA_CHECK |SCA_DL_CHECK ; retval =__set_cpus_allowed_ptr (p, ctx);if (retval)
@@ -1258,6 +1254,12 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)if (empty)cpumask_copy (new_mask, cpus_allowed); } + +/* +* The cpuset mask must win here, as it does when +* cpuset_update_tasks_cpumask() sets it on a deadline task. +*/ + ctx->flags &= ~SCA_DL_CHECK ;__set_cpus_allowed_ptr (p, ctx); retval = -EINVAL ; }
Signature · 1 line
2.47.3
PATCH v2 14/16 sched/debug: Show the deadline bandwidth of each runqueue
In reply to Mathieu DesnoyersFor each CPU, sched_debug prints the deadline bandwidth of its root domain. It does not print the two sums of its runqueue. this_bw is the bandwidth of the deadline tasks assigned to the CPU. running_bw is the part of it that belongs to active tasks.
GRUB reclaiming depends on both sums. grub_reclaim() takes this_bw - running_bw as the inactive bandwidth of the CPU. The more inactive bandwidth, the slower a reclaiming task uses up its runtime.
The kernel warns when a sum wraps around, and when running_bw exceeds this_bw. Bandwidth left behind in this_bw triggers no warning.
Print both sums. The deadline_bw_test selftest added later in this series reads this_bw in its params_waking case. It checks that this_bw is back to its first value once the tasks of the case are gone.
--- kernel/sched/debug.c | 2 ++ 1 file changed, 2 insertions(+)
kernel/sched/debug.c +2 -0
@@ -1175,6 +1175,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 v2 15/16 selftests/sched: Add a test of SCHED_DEADLINE policy round trips
In reply to Mathieu DesnoyersNo selftest runs a SCHED_DEADLINE task.
Add deadline_switch_test, with five cases:
- throttled_round_trip: a task of 10ms every 2s spins, so it is throttled in every period. Right after a throttle, the test switches it to SCHED_OTHER. The test switches it back 200us after its deadline, between its replenishment timer and its 0-lag time. It must then run again.
- asleep_round_trip: a task of 9ms every 10ms runs 0.2ms, then sleeps 50ms. While it sleeps past its 0-lag time, the test switches it to SCHED_OTHER and back. A leak at each round trip fills the root domain, and the switch back fails with EBUSY.
- sysrq_normalize: sysrq-n takes a deadline task out of the class. Another task must then still enter SCHED_DEADLINE.
- sysrq_boosted_owner: sysrq-n takes a SCHED_OTHER task out of the deadline class while a deadline waiter boosts it. After the unlock, the task enters SCHED_DEADLINE at 10ms every 100ms. It must not run more than its runtime in its first period.
- sysrq_running_owner: a SCHED_OTHER task spins alone on a CPU, with a lock held. A deadline waiter of 100us every 1ms boosts it. The test starts 2048 sleeping SCHED_FIFO threads, then fires sysrq-n. Every thread must end, and the owner must no longer be boosted.
The cases need CAP_SYS_NICE, and skip without it. asleep_round_trip also skips without admission control, when sched_rt_runtime_us is -1. sysrq-n changes the policy of every real-time user task. So the three sysrq cases run only with DEADLINE_TEST_SYSRQ set. They also need root and CONFIG_MAGIC_SYSRQ. The two owner cases run only if sysrq_normalize passed.
On a kernel with the bugs, asleep_round_trip and sysrq_normalize keep new tasks out of SCHED_DEADLINE. So they run last, followed only by the two owner cases.
On v7.4-rc2, in 8-CPU VMs, three of the five cases fail:
- throttled_round_trip. "sched/deadline: Do not lose a throttled task switched out and back" fixes it.
- asleep_round_trip. "sched/deadline: Release the bandwidth of a task that leaves the class asleep" fixes it.
- sysrq_normalize. "sched: Take cpuset_mutex for a deadline policy change only with pi" fixes it.
sysrq_boosted_owner tests "sched: Let a task boosted by a deadline waiter change its policy". Without the sysrq-n part of that fix, the owner ran 99-100ms of its first period, in 4 runs of 4. With it, it ran 10-11ms.
sysrq_running_owner tests "sched/deadline: Do not replenish a boost from cleared parameters". With the early return of that fix disabled, the guest locked up in 3 runs of 3.
With the whole series, the five cases pass, with and without PREEMPT_RT.
The test goes in a new selftest target, sched/deadline.
--- tools/testing/selftests/Makefile | 1 + .../selftests/sched/deadline/.gitignore | 1 + .../testing/selftests/sched/deadline/Makefile | 8 + tools/testing/selftests/sched/deadline/config | 1 + .../sched/deadline/deadline_switch_test.c | 1115 +++++++++++++++++ 5 files changed, 1126 insertions(+) create mode 100644 tools/testing/selftests/sched/deadline/.gitignore create mode 100644 tools/testing/selftests/sched/deadline/Makefile create mode 100644 tools/testing/selftests/sched/deadline/config create mode 100644 tools/testing/selftests/sched/deadline/deadline_switch_test.c
tools/testing/selftests/Makefile +1 -0
@@ -120,6 +120,7 @@ TARGETS += rlimits TARGETS += rseq TARGETS += rtc TARGETS += rust +TARGETS += sched/deadline TARGETS += sched_ext TARGETS += seccomp TARGETS += sgx
tools/testing/selftests/sched/deadline/.gitignore new file +1 -0
@@ -0,0 +1 @@ +deadline_switch_test
tools/testing/selftests/sched/deadline/Makefile new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0+ + +CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES) +LDLIBS += -lpthread + +TEST_GEN_PROGS := deadline_switch_test + +include ../../lib.mk
tools/testing/selftests/sched/deadline/config new file +1 -0
@@ -0,0 +1 @@ +CONFIG_MAGIC_SYSRQ=y
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +1115 -0
1,115 lines not on this page · raw message
Signature · 1 line
2.47.3
PATCH v2 16/16 selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
In reply to Mathieu DesnoyersUpstream has no selftest of the SCHED_DEADLINE bandwidth accounting. A leak or a double release does not show at once. Later, the root domain refuses deadline tasks, or admits more than it can run.
Add deadline_bw_test, with 46 cases. Most cases count the tasks of 10ms every 100ms that a root domain admits, before and after they run. Once the tasks of the case are gone and past their 0-lag time, the two counts must be equal. The cases cover:
- priority inheritance, boost and deboost
- parameter changes, SCHED_FLAG_KEEP_PARAMS among them
- cpuset moves
- deaths, sched_yield() and runtime overruns
- a stopped task
- bandwidth reclaiming and fair server changes
- CPU hotplug
- parameter changes while a task wakes on another CPU (params_waking)
The comment above each case gives its scenario. params_waking also compares the this_bw of its CPUs, which "sched/debug: Show the deadline bandwidth of each runqueue" prints. Two cases follow reproducers of Juri Lelli's sched-deadline-tests: stopped_switched_out and pi_chain_two_owners.
The test needs root, deadline admission control and 3 CPUs. Most cases need the cgroup v2 cpuset controller, and some need debugfs, CPU hotplug or 4 CPUs. move_cancelled needs CONFIG_RT_GROUP_SCHED. A case skips without what it needs.
The message of each fix in this series names the cases that test it. These cases are not named there. Each fails without its fix, and passes with it:
- overrun_caught and stopped_switched_out: "sched/deadline: Release the bandwidth of a task that leaves the class asleep"
- params_keep_class_change: "sched: Refuse SCHED_FLAG_KEEP_PARAMS that would change the policy or the class"
overrun_caught fails in part of the runs only.
On v7.4-rc2, in two runs of 8 VMs of 8 CPUs, six cases fail in every VM:
- boosted_owner_policy
- deboost_resets_period
- death_zombie_switched
- params_keep_boosted
- params_keep_class_change
- stopped_switched_out
overrun_caught fails in 3 VMs of 16. In one VM, hotplug_server crashed the kernel with a divide error in inactive_task_timer(). "sched/deadline: Do not divide by zero active CPUs of a root domain" fixes it.
Two cases skip there. params_waking needs the this_bw that "sched/debug:
Show the deadline bandwidth of each runqueue" prints. move_cancelled needs CONFIG_RT_GROUP_SCHED.
With the whole series, every case passes wherever it runs, PREEMPT_RT included. The test also ran in guests built without cpusets, and in guests booted with isolcpus=domain,1,2 or isolcpus=domain,0,1. move_cancelled ran in two guests built with CONFIG_RT_GROUP_SCHED. No kernel warning is logged.
--- .../selftests/sched/deadline/.gitignore | 1 + .../testing/selftests/sched/deadline/Makefile | 2 +- tools/testing/selftests/sched/deadline/config | 4 + .../sched/deadline/deadline_bw_test.c | 5246 +++++++++++++++++ .../testing/selftests/sched/deadline/settings | 1 + 5 files changed, 5253 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/sched/deadline/deadline_bw_test.c create mode 100644 tools/testing/selftests/sched/deadline/settings
tools/testing/selftests/sched/deadline/.gitignore +1 -0
@@ -1 +1,2 @@ deadline_switch_test +deadline_bw_test
tools/testing/selftests/sched/deadline/Makefile +1 -1
@@ -3,6 +3,6 @@ CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES) LDLIBS += -lpthread -TEST_GEN_PROGS := deadline_switch_test +TEST_GEN_PROGS := deadline_switch_test deadline_bw_test include ../../lib.mk
tools/testing/selftests/sched/deadline/config +4 -0
@@ -1 +1,5 @@ +CONFIG_CGROUPS=y +CONFIG_CPUSETS=y +CONFIG_DEBUG_FS=y +CONFIG_HOTPLUG_CPU=y CONFIG_MAGIC_SYSRQ=y
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +5246 -0
2,986 lines not on this page · raw message
tools/testing/selftests/sched/deadline/settings new file +1 -0
Lines of this file are not shown. View the 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 v2 16/16] selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [Medium] selftests/sched: unhandled SCHED_FIFO EPERM in server_client() - [Medium] selftests/sched…
Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [Medium] selftests/sched: unhandled SCHED_FIFO EPERM in server_client()
- [Medium] selftests/sched: pi_chain_donor_leaves() fails due to unpropagated dl.pi_se
- [Medium] selftests/sched: zero waiter deadline in deboost_new_params_reboost()
- [Low] selftests/sched: process-private ready flag in shm_lock_init()
- [Low] selftests/sched: write-only fair_tid, unused isol, and dead mode branches
--
commit 027ae545afaed0101b592ecd773abaab9b25aeca
Author: Mathieu Desnoyers <[email protected]>
selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
This commit adds the deadline_bw_test selftest covering SCHED_DEADLINE bandwidth accounting across priority inheritance, parameter changes, cpuset moves, task exits, bandwidth reclaiming, fair servers, and CPU hotplug.
Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +0
-0
[ ... ]
Quoted 26 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +26
-0+static void *reboost_owner (void *arg) +{ +uint64_t t0; +int err; + + owner_tid =gettid_ (); +if (take_pi_lock ()) +return (void *)1 ; + owner_holds =2 ; +sem_wait_sig (&owner_go); +if (rb_abort) { +drop_pi_lock (); +return NULL ; + } + err =set_deadline (0 ,50 *NSEC_PER_MSEC ,PERIOD ); +if (err) { +ksft_print_msg ("the owner refused as a deadline task: %s\n" , +strerror (-err)); + goto out; + } +sem_post (&rb_donor_go); + t0 =now_ns (); +while (!rb_donor_locking ||proc_state_of (donor_tid) !='S' ) { +if (now_ns () - t0 >NSEC_PER_SEC ) { +ksft_print_msg ("the donor did not block on the lock\n" ); + err =-1 ;
tools/testing/selftests/sched/deadline/deadline_bw_test.c line 2112
Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10
-0+ goto out; + } + } + err =set_deadline (rb_waiter_tid,2 *NSEC_PER_MSEC ,PERIOD ); +if (err) { +ksft_print_msg ("the waiter refused as a deadline task: %s\n" , +strerror (-err)); + goto out; + } + err =set_deadline (0 ,5 *NSEC_PER_MSEC ,PERIOD );
[Severity: Medium]
Does calling set_deadline() on rb_waiter_tid while W is already blocked on pi_lock give W an absolute deadline of 0 instead of a deadline later than O and D?
Because W is not queued on a runqueue, __setparam_dl() sets its static parameters while leaving W->dl.deadline at 0, and switched_to_dl() returns early without enqueuing W. rt_mutex_adjust_pi() then updates W's waiter node on pi_lock with tree.deadline = 0, which sorts ahead of D (dl_time_before(0, D->dl.deadline) is true) and makes W the top waiter boosting O right away. When D times out 20ms later, D is no longer the top waiter, so remove_waiter() returns without deboosting or reboosting O.
[ ... ]
Quoted 2 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +2
-0+static int pi_init_lock2 (void ) +{
[ ... ]
tools/testing/selftests/sched/deadline/deadline_bw_test.c line 2462
Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +5
-0+ donor_tid =0 ; + x_tid =0 ; + fair_tid =0 ; +return 0 ; +}
[Severity: Low]
This isn't a bug, but fair_tid is only written here and never read (which triggers -Wunused-but-set-variable under Clang). In addition, main() populates isol via read_online(&isol, 1) without using or freeing it, wait_spinner(), hold() and release_held() have unused forward declarations, and several helpers retain unreachable branches with no callers in p_cases[] or hp_cases[] (sleeper_cpu >= 0 in dl_sleeper_tid(), was_dl != 0 in sleeping_owner() and pi_asleep(), modes 1 and 2 in deboost_case(), spin_ms == 8 in refill_case(), modes 0 and 2-5 in return_case() along with set_constrained(), MV_YIELDED in mover(), and hp_case::no_hp).
[ ... ]
Quoted 4 lines
+/*
+ * A chain walk must pass a new donor on to the end of the chain. This
+ * holds even when the sort keys of the task in the middle do not change.
+ *
[ ... ]
Quoted 20 lines
+ * 5. Z blocks on L1. Z's deadline is earlier than W's, so Z becomes M's
+ * donor. M sleeps, so its deadline does not move. The chain walk must
+ * go on to O and make Z O's donor too.
+ * 6. The main thread switches W toSCHED_OTHER. W sleeps and has run
+ * almost nothing, so its parameters are cleared at once.
+ * 7. 250ms later, the main thread wakes O up. O has no deadline ahead, so
+ * its wakeup starts a new period from its donor. O spins 100ms.
+ * Then it measures the CPU time Y gets over 200ms, and unlocks L2.
+ *
+ * With Z as its donor, O gets 2ms every 80ms. Y's deadline is soon the
+ * earlier one, and Y gets about its 60ms. With W as its donor, O runs on
+ * cleared parameters. Each refill gives it no runtime and a deadline of
+ * about now. O then runs before Y all the time, and Y gets close to
+ * nothing. The case fails if Y gets less than 30ms.
+ *
+ * W does not exit before O unlocks L2. It waits for L1, which M releases
+ * after it gets L2.
+ */tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +2
-0+static int pi_chain_donor_leaves (void ) +{
[ ... ]
tools/testing/selftests/sched/deadline/deadline_bw_test.c line 2782
Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +5
-0+ }else if (ret ==KSFT_PASS && y_ns <30 * (long long )NSEC_PER_MSEC ) { +ksft_print_msg ("Y ran %lld ms of 200: O ran on the cleared parameters of W\n" , + y_ns / (long long )NSEC_PER_MSEC ); + ret =KSFT_FAIL ; + }
[Severity: Medium]
Does pi_chain_donor_leaves() pass on this series without an rt_mutex chain walk change to propagate M->dl.pi_se to O when M's sort keys do not move?
When Z blocks on L1 in step 5, rt_mutex_setprio(M, Z) updates M->dl.pi_se to &Z->dl, but M is sleeping on L2, so M->prio and M->dl.deadline stay unchanged. In rt_mutex_adjust_prio_chain(), rt_waiter_node_equal() sees that M's waiter node on L2 still matches task_to_waiter_node(M), skips requeueing M on L2, and never calls rt_mutex_adjust_prio() on O:
kernel/locking/rtmutex.c:rt_mutex_adjust_prio_chain() {
...
if (rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task))) {
if (!detect_deadlock)
goto out_unlock_pi;
else
requeue = false;
}
...
}O->dl.pi_se stays &W->dl after W switches to SCHED_OTHER and has its parameters cleared. When O wakes in step 7, replenish_dl_entity() keeps resetting O->dl.deadline to rq_clock(rq) and O->dl.runtime to 0 from W's cleared parameters, starving Y on P's CPU and failing this check.
[ ... ]
Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10
-0+/* Set up shm_lock. Return 0, or -1 if it cannot be set up. */ +static int shm_lock_init (void ) +{ +static int ready; +pthread_mutexattr_t a; +int err; + +/* +* A case can kill the owner while it holds the lock. Take the lock +* back and release it, so that it can be destroyed.
tools/testing/selftests/sched/deadline/deadline_bw_test.c line 3481
Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10
-0+*/ +if (ready) { + err =pthread_mutex_trylock (shm_lock); +if (err ==EOWNERDEAD ) + err =pthread_mutex_consistent (shm_lock); +if (!err) +pthread_mutex_unlock (shm_lock); +pthread_mutex_destroy (shm_lock); + ready =0 ; + }
[Severity: Low]
Since death_pi_waiter, death_pi_owner, and death_pi_deadline_owner each run in a separate child process forked by run_in(), doesn't the process-private static ready variable start at 0 in every child?
In death_pi_waiter, reap(owner) kills the owner while it holds shm_lock, leaving *shm_lock in MAP_SHARED memory in the EOWNERDEAD state. When death_pi_owner and death_pi_deadline_owner run in new child processes, ready is 0, so the EOWNERDEAD recovery and pthread_mutex_destroy() block is skipped and pthread_mutex_init() is called directly on the active mutex. Should ready live in the MAP_SHARED mv_state buffer (or should pi_death() clean up shm_lock before exiting)?
[ ... ]
Quoted 20 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +20
-0+static pid_t server_client (int rt) +{ +pid_t pid =fork_child (rt ?"a real-time task of P" :"a fair task of P" ); + +if (!pid) { +struct sched_param sp = { .sched_priority =1 }; + +if (enter (cg_p,getpid ()) || + (rt &&sched_setscheduler (0 ,SCHED_FIFO , &sp))) +_exit (1 ); + mv_state[0 ]++; +for (;;) { +wait_set (&mv_state[4 + rt]); +spin_ns (rt ?50 *NSEC_PER_MSEC :NSEC_PER_MSEC ); +if (rt) +sleep_ns (NSEC_PER_MSEC ); + } + } +return pid; +}
[ ... ]
Quoted 2 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +2
-0+static int server_states (void ) +{
[ ... ]
tools/testing/selftests/sched/deadline/deadline_bw_test.c line 4569
Quoted 7 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +7
-0+ fair =server_client (0 ); + rt =server_client (1 ); +if (fair <0 || rt <0 ||wait_for (5000 , mv_state[0 ] >=2 )) { +if (fair >=0 && rt >=0 ) +ksft_print_msg ("a fair or real-time task of P could not start\n" ); + ret =KSFT_FAIL ; + }
[Severity: Medium]
On a CONFIG_RT_GROUP_SCHED=y system where the cpu controller is already enabled in root/cgroup.subtree_control, won't server_client(1) fail sched_setscheduler(0, SCHED_FIFO, &sp) in cg_p with EPERM and cause server_states() to time out and fail instead of skipping?
As noted in move_cancelled(), child cgroups have no RT runtime in cgroup v2 when CONFIG_RT_GROUP_SCHED is enabled with the cpu controller active. Because move_cancelled() only disables the cpu controller on exit if it added "+cpu" itself, sched_setscheduler() in server_client(1) fails and calls _exit(1) without updating mv_state[0], so server_states() waits the full 5 seconds and returns KSFT_FAIL.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
Re: [PATCH v2 16/16] selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting
Quoted 3 lines
Does calling
set_deadline()onrb_waiter_tidwhile W is already blocked onpi_lockgive W an absolute deadline of 0 instead of a deadline later than O and D?
Yes. I checked it in a guest. On this series, a task made SCHED_DEADLINE while it waits on a PI mutex keeps a deadline of 0. So W boosts O at once, and the case passes without the deboost it was written for. On v7, the case failed without "sched/deadline: Check the runtime of a task whose parameters change". v7 also had "sched/deadline:
Start a period for a task that enters the class blocked", which gives W a new period. Both are in the second series. I will move the case there.
Quoted 2 lines
This isn't a bug, but
fair_tidis only written here and never read (which triggers -Wunused-but-set-variable under Clang).
Same as v1 [1]: these are left from the split, and the second series uses them.
Quoted 2 lines
Does
pi_chain_donor_leaves()pass on this series without anrt_mutexchain walk change to propagateM->dl.pi_seto O when M's sort keys do not move?
Same as v1: it passes in every run, in 25 guests with this series.
Quoted 3 lines
Since
death_pi_waiter,death_pi_owner, anddeath_pi_deadline_ownereach run in a separate child process forked byrun_in(), doesn't the process-private static ready variable start at 0 in every child?
Right. My v2 fix does not work. I will keep the flag in the shared mapping, next to the lock.
Quoted 4 lines
On a
CONFIG_RT_GROUP_SCHED=ysystem where the cpu controller is already enabled in root/cgroup.subtree_control, won'tserver_client(1)failsched_setscheduler(0, SCHED_FIFO, &sp)incg_pwith EPERM and causeserver_states()to time out and fail instead of skipping?
Right. Our guests with CONFIG_RT_GROUP_SCHED did not have the cpu controller on. I will make the case skip there.
[1] https://lore.kernel.org/all/[email protected]/
Thanks,
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com
Juri Lelli
maintainerHello,
Quoted 5 lines · Mathieu Desnoyers
Hi Ingo, Juri,
This series fixes 13 bugs of
SCHED_DEADLINE. Then it shows the deadline bandwidth of each runqueue insched_debug, and adds two selftests. The fixes come first, so that stable can take patches 1 to 13.
Thanks for splitting this out. I ran v2 in 8-CPU guests with lockdep and proxy exec on. deadline_switch_test passes 5/5 (sysrq cases included), and deadline_bw_test passes 45/46 (move_cancelled skips without RT_GROUP_SCHED). There were no splats. Reverting patch 10 brings back asleep_round_trip, stopped_switched_out and overrun_caught, as claimed. cgroup's test_cpuset_prs.sh also passes, as on rc2.
I also covered two of the "not tested" items:
- cgroup v1 cpusets (two exclusive cpusets, root load balancing off):
admission, affinity, refused moves and hotplug all behave as on v2. On both v1 and v2, moving a task A -> B -> A leaves its bandwidth in B, so A is under-counted once the task dies. The leak is on rc2 too and the full v7 fixes it, so it is not a regression.
- sched_ext: the in-tree sched_ext selftests pass on v2, total_bw included (dsp_local_on needs IKCONFIG_PROC for its __kconfig extern). With scx_simple loaded, deadline_switch_test passes. The server cases of deadline_bw_test fail, because they configure fair_server, which is detached while ext is enabled. Pointed at ext_server, server_params, server_rebuilds, server_states and server_reclaim pass. hotplug_server still fails there, as scx_simple gets ejected when the CPU goes offline (I haven't dug further). Could the test pick the server that is active?
...
Quoted 3 lines
Patch 10 clears the parameters of a task that leaves the class asleep. On v7.4-rc2, such a task kept them. That hid a bug of the rtmutex chain walk
Please move this into the changelog of patch 10 itself, as the cover won't end up in git. IIUC, the owner then sits in the patch 8 bail-out with a deadline of "now" until it unlocks. Other deadline tasks keep their bandwidth, but lose latency, and RT/fair tasks on that CPU get possibly starved.
Doesn't your separate "Fix an overflow of the 0-lag time with long periods" also fits here, right before patch 10, which adds a caller of that computation?
Patch 5: yes, keep my Reviewed-by on the version with the cpu_active() check.
Thanks!
Juri
Hi Juri,
Quoted 2 lines · Juri Lelli
Thanks for splitting this out. I ran v2 in 8-CPU guests with lockdep and proxy exec on.
[...]
Quoted 1 line
I also covered two of the "not tested" items:
Thanks for these runs. In v3, I will drop cgroup v1 and sched_ext from "Not tested", and say that you tested them.
Quoted 5 lines
- cgroup v1 cpusets (two exclusive cpusets, root load balancing off):
admission, affinity, refused moves and hotplug all behave as on v2. On both v1 and v2, moving a task A -> B -> A leaves its bandwidth in B, so A is under-counted once the task dies. The leak is on rc2 too and the full v7 fixes it, so it is not a regression.
OK. The second series keeps that fix.
Quoted 5 lines
Pointed at
ext_server,server_params,
server_rebuilds,server_statesandserver_reclaimpass.hotplug_serverstill fails there, asscx_simplegets ejected when the CPU goes offline (I haven't dug further). Could the test pick the server that is active?
Yes. The server cases will use ext_server while a sched_ext scheduler is loaded. hotplug_server will skip then.
Quoted 5 lines
Please move this into the changelog of patch 10 itself, as the cover won't end up in git. IIUC, the owner then sits in the patch 8 bail-out with a deadline of "now" until it unlocks. Other deadline tasks keep their bandwidth, but lose latency, and RT/fair tasks on that CPU get possibly starved.
Yes, that is what the test sees: each refill gives the owner no runtime and a deadline of about now. I will move the paragraph into patch 10, with your impact.
Quoted 3 lines
Doesn't your separate "Fix an overflow of the 0-lag time with long periods" also fits here, right before patch 10, which adds a caller of that computation?
Yes. I will move it before patch 10 in v3.
Quoted 2 lines
Patch 5: yes, keep my Reviewed-by on the version with the
cpu_active()check.
Thanks.
Mathieu
Signature · 3 lines
Mathieu Desnoyers EfficiOS Inc. https://www.efficios.com