Skip to contentSkip to conversation

sched/deadline: first bandwidth accounting fixes and selftests

PATCH Superseded Mathieu Desnoyers 2 participants 31 messages Nov 18

Subsystems (5)

v1 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

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 47 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 52 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 and rebuild_record_taken skip: they need 4.

On v7.4-rc2, six cases of deadline_bw_test fail in each of 8 guests of 8 vCPUs. Patch 16 lists them. overrun_caught fails in one guest. In another 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. Each finding was checked against the code first.

Changes since v7
================

- Reviewed-by from Juri on 4, 5, 8 and 10. He reviewed the v7 code of 5, before the change listed below.
- 5: the refusal covers the whole CPU deactivation, from the Sashiko review of v7.
- 8: the fix paragraph is Juri's wording.
- 10: its message names asleep_round_trip, which tests it without PI. The two PI cases it named move to the second series.
- 15: the stack of the filler threads is at least PTHREAD_STACK_MIN. The semaphores are destroyed.
- The messages credit the Sashiko AI review without the number of the posting, as Juri suggested.

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]/

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         | 5468 +++++++++++++++++
 .../sched/deadline/deadline_switch_test.c     | 1115 ++++
 .../testing/selftests/sched/deadline/settings |    1 +
 13 files changed, 6829 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
#1 lore raw

PATCH 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
index 0ec401af80d1..89b0d5787f45 100644
@@ -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
#2 lore raw

PATCH 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.

Fixes a509a7cd7974 ("sched/uclamp: Extend sched_setattr() to support utilization clamping")
---
 kernel/sched/syscalls.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +9 -1
index 89b0d5787f45..6f8ce5fd94a1 100644
@@ -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
#3 lore raw

PATCH 3/16 sched: Let a task boosted by a deadline waiter change its policy

In reply to Mathieu Desnoyers

A 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.

Fixes 332ac17ef5bf ("sched/deadline: Add bandwidth management for SCHED_DEADLINE tasks")
---
 kernel/sched/syscalls.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +13 -1
index 6f8ce5fd94a1..cb115aa9b0b3 100644
@@ -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
#4 lore raw

PATCH 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.

Fixes daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks")
---
 kernel/sched/deadline.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/sched/deadline.c +9 -2
index dfae08625342..b614d5fc1a1a 100644
@@ -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
#5 lore raw

Re: [PATCH 04/16] sched/deadline: Do not divide by zero active CPUs of a root domain

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] sched/deadline: integer overflow in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] sched/deadline: integer overflow in __dl_sub() and __dl_add()
[1]
--

commit 976d925f6742563bd97b6e12f465ca24230d49b8
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Do not divide by zero active CPUs of a root domain

This commit guards the extra_bw updates in __dl_sub() and __dl_add() against a zero active CPU count in a root domain during CPU hotplug.

Quoted 20 lines
kernel/sched/deadline.c +7 -1
index dfae08625342e..b614d5fc1a1ac 100644
@@ -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);

kernel/sched/deadline.c void __dl_update(struct dl_bw *dl_b, s64 bw) · line 211

Quoted 10 lines
kernel/sched/deadline.c +2 -1
 }
 
 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));
 }

[Severity: High]
This problem wasn't introduced by this patch, but can casting tsk_bw to s32 in __dl_sub() and __dl_add() overflow and flip the sign [1]?

During a large cpuset bandwidth migration (cpuset_reserve_dl_bw() -> dl_bw_alloc()), tsk_bw can exceed S32_MAX on systems with many CPUs. Truncating tsk_bw to a negative s32 before dividing by cpus reverses the sign of the delta passed to __dl_update(), corrupting per-runqueue extra_bw accounting and breaking SCHED_DEADLINE admission control.

[1] https://sashiko.dev/#/bug/linux-ebf16093-b39b-4cd9-a580-85c7bb17302b

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#6 lore raw

Re: [PATCH 04/16] sched/deadline: Do not divide by zero active CPUs of a root domain

Quoted 2 lines

This problem wasn't introduced by this patch, but can casting tsk_bw to s32 in __dl_sub() and __dl_add() overflow and flip the sign [1]?

Yes, by reading. cpuset_can_attach() passes the sum of the bandwidth of the tasks it moves to dl_bw_alloc(), which calls __dl_add() with it. One CPU is 1 << 20, so the sum goes above S32_MAX past 2048 CPUs of deadline bandwidth. That needs a machine with more than 2048 CPUs.

This series does not change the cast. I will fix it in a separate patch, with a 64-bit division.

Thanks,

Mathieu

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

PATCH 5/16 sched/deadline: Refuse dl_server debugfs writes while the rq is offline

In reply to Mathieu Desnoyers

Commit 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.

Fixes d741f297bcea ("sched/fair: Fair server interface")
---
 kernel/sched/debug.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
kernel/sched/debug.c +10 -1
index e6a3b516c703..ddb382df454b 100644
@@ -410,7 +410,16 @@ static ssize_t sched_server_write_common(struct file *filp, const char __user *u
 			return  -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
#8 lore raw

PATCH 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/0x150

A 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.

Fixes 111cd11bbc54 ("sched/cpuset: Bring back cpuset_mutex")
---
 kernel/sched/syscalls.c | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
kernel/sched/syscalls.c +23 -3
index cb115aa9b0b3..9b04e77297ae 100644
@@ -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
#9 lore raw

Re: [PATCH 06/16] sched: Take cpuset_mutex for a deadline policy change only with pi

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] sched/deadline: bandwidth leak in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] sched/deadline: bandwidth leak in __sched_setscheduler() on TASK_DEAD task [1]
--

commit eb6bc35bf21202354f98c206678837ac0c913d54
Author: Mathieu Desnoyers <[email protected]>

sched: Take cpuset_mutex for a deadline policy change only with pi

This commit avoids taking cpuset_mutex in __sched_setscheduler() when pi is unset, and retries under the runqueue lock if the target task entered SCHED_DEADLINE after the unlocked policy check.

Quoted 42 lines
kernel/sched/syscalls.c +16 -3
index cb115aa9b0b33..9b04e77297aeb 100644
@@ -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

kernel/sched/syscalls.c int __sched_setscheduler(struct task_struct *p, · line 679

Quoted 10 lines
kernel/sched/syscalls.c +7 -0
+	 * 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);

[Severity: High]
This problem wasn't introduced by this patch, but can __sched_setscheduler() leak deadline bandwidth and cpuset deadline task counters if called on a zombie task [1]?

A task that has reached TASK_DEAD and been deactivated from its runqueue remains reachable by PID until reaped. If sched_setattr() sets SCHED_DEADLINE on it, sched_dl_overflow() adds the requested bandwidth to dl_b->total_bw and rq->dl.extra_bw, and switched_to_dl() increments cs->nr_deadline_tasks via inc_dl_tasks_cs() and adds the bandwidth to rq->dl.this_bw:

kernel/sched/deadline.c:switched_to_dl() {
	...
	inc_dl_tasks_cs(p);

	/* 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;
	}
	...
}

Because a TASK_DEAD task never wakes or runs again and release_task() does not release deadline bandwidth or decrement cs->nr_deadline_tasks, the bandwidth and cpuset task count are leaked until reboot, blocking cpuset changes and eventually causing __dl_overflow() to reject all new SCHED_DEADLINE admissions with -EBUSY.

[1] https://sashiko.dev/#/bug/linux-6b520332-dcc7-4d6b-b09a-5ec47df1d3cc

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#10 lore raw

Re: [PATCH 06/16] sched: Take cpuset_mutex for a deadline policy change only with pi

Quoted 3 lines

This problem wasn't introduced by this patch, but can __sched_setscheduler() leak deadline bandwidth and cpuset deadline task counters if called on a zombie task [1]?

Yes. Patch 11 of this series fixes it: "sched/deadline: Reject SCHED_DEADLINE on exited tasks". sched_setattr() then refuses SCHED_DEADLINE for a task that has exited.

Thanks,

Mathieu

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

PATCH 7/16 sched/deadline: Do not lose a throttled task switched out and back

In reply to Mathieu Desnoyers

A 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.

Fixes 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization")
---
 kernel/sched/deadline.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +10 -1
index b614d5fc1a1a..e4d7cbf4861d 100644
@@ -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
#12 lore raw

Re: [PATCH 07/16] sched/deadline: Do not lose a throttled task switched out and back

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] sched/deadline: stale dl_timer and…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] sched/deadline: stale dl_timer and deadline after __dl_clear_params() [1]
--

commit e6978eb9fe65441d4ddb2d45bfc7400e644913a5
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Do not lose a throttled task switched out and back

This commit replenishes a throttled SCHED_DEADLINE task in dl_task_timer() if the task has switched to another scheduling policy, so that it can be enqueued if it switches back to SCHED_DEADLINE before its 0-lag time.

Quoted 11 lines
kernel/sched/deadline.c +3 -0
index b614d5fc1a1ac..e4d7cbf4861de 100644
@@ -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.

kernel/sched/deadline.c static enum hrtimer_restart dl_task_timer(struct hrtimer *timer) · line 1247

Quoted 10 lines
kernel/sched/deadline.c +7 -1
 	 */
-	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;
+	}

[Severity: High]
This problem wasn't introduced by this patch, but in the opposite order where the 0-lag time elapses before dl_se->dl_timer fires [1], does __dl_clear_params() leave a stale dl_se->dl_timer armed along with stale dl_se->deadline and dl_se->runtime values?

When a task calls sched_yield() with remaining runtime (or a constrained-deadline task overruns slightly), its 0-lag time is earlier than dl_next_period(dl_se). If the task then switches out of SCHED_DEADLINE, task_non_contending() or inactive_task_timer() calls __dl_clear_params(), which clears dl_se->dl_throttled without cancelling dl_se->dl_timer or resetting dl_se->deadline and dl_se->runtime:

kernel/sched/deadline.c:__dl_clear_params() {
	dl_se->dl_runtime		= 0;
	dl_se->dl_deadline		= 0;
	dl_se->dl_period		= 0;
	dl_se->flags			= 0;
	dl_se->dl_bw			= 0;
	dl_se->dl_density		= 0;

	dl_se->dl_throttled		= 0;
	dl_se->dl_yielded		= 0;
    ...
}

If the task switches back to SCHED_DEADLINE before the old period ends, enqueue_dl_entity() with ENQUEUE_MOVE sees dl_se->deadline still in the future and skips setup_new_dl_entity(), running the task with stale runtime and deadline values. If the task then throttles under its new reservation while the old dl_se->dl_timer is still queued, start_dl_timer() sees hrtimer_is_queued(&dl_se->dl_timer) and skips reprogramming it, delaying replenishment until the old timer expires.

[1] https://sashiko.dev/#/bug/linux-5f16aeeb-544a-4da3-a8a9-3a7be85e8892

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#13 lore raw

Re: [PATCH 07/16] sched/deadline: Do not lose a throttled task switched out and back

Quoted 4 lines

This problem wasn't introduced by this patch, but in the opposite order where the 0-lag time elapses before dl_se->dl_timer fires [1], does __dl_clear_params() leave a stale dl_se->dl_timer armed along with stale dl_se->deadline and dl_se->runtime values?

Yes. Two patches fix it:
- Patch 9 of this series resets the deadline and the runtime in __dl_clear_params(). It is "sched/deadline: Reset the deadline and the runtime with the parameters".
- "sched/deadline: Cancel the replenishment timer with the parameters" cancels the timer there. It is in the second series, which applies on top of this one.

Thanks,

Mathieu

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

PATCH 8/16 sched/deadline: Do not replenish a boost from cleared parameters

In reply to Mathieu Desnoyers

When 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.

Fixes a5e7be3b28a2 ("sched/deadline: Clear dl_entity params when setscheduling to different class")
---
 kernel/sched/deadline.c | 40 +++++++++++++++++++++++++++++++++++-----
 1 file changed, 35 insertions(+), 5 deletions(-)
kernel/sched/deadline.c +35 -5
index e4d7cbf4861d..71b1c155c242 100644
@@ -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
#15 lore raw

Re: [PATCH 08/16] sched/deadline: Do not replenish a boost from cleared parameters

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] sched/deadline: use-after-free of pi_se…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] sched/deadline: use-after-free of pi_se via rt_mutex_adjust_prio_chain() [1]
--

commit 961bc9d5ebb4610c191709612415310c77835eeb
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Do not replenish a boost from cleared parameters

This commit prevents an infinite loop in replenish_dl_entity() when an rt_mutex donor leaves SCHED_DEADLINE and has its deadline parameters cleared before the priority-inheritance chain walk deboosts the lock owner.

kernel/sched/deadline.c static void replenish_dl_entity(struct sched_dl_entity *dl_se) · line 813

Quoted 12 lines
kernel/sched/deadline.c +4 -0
index e4d7cbf4861de..71b1c155c2424 100644
@@ -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);

[Severity: High]
This problem wasn't introduced by this patch, but can pi_se point to a freed task_struct after a nested rt_mutex wait is aborted [1]?

Suppose deadline task M with positive remaining runtime holds lock L1, and deadline task W with an earlier deadline blocks on L1. rt_mutex_setprio() sets M->dl.pi_se = &W->dl while replenish_dl_entity() leaves M->dl.deadline unchanged, and when M blocks on L2 held by O, O->dl.pi_se becomes &W->dl.

When W aborts its wait on L1, remove_waiter() resets M->dl.pi_se to &M->dl without changing M->dl.deadline and calls rt_mutex_adjust_prio_chain() on M:

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;
    ...
}

Because rt_waiter_node_equal() compares only prio and deadline, it sees no change for M's waiter on L2 and stops the walk before reaching O. Once W exits and is freed, replenishing O here dereferences a dangling O->dl.pi_se (use-after-free).

[1] https://sashiko.dev/#/bug/linux-e1386e80-9bd4-4219-9441-8f56e84f7735

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#16 lore raw

Re: [PATCH 08/16] sched/deadline: Do not replenish a boost from cleared parameters

Quoted 2 lines

This problem wasn't introduced by this patch, but can pi_se point to a freed task_struct after a nested rt_mutex wait is aborted [1]?

Yes. When W aborts its wait, remove_waiter() makes M its own donor again. The sort keys of M stay equal, so the walk stops at M. "rtmutex:
Continue the chain walk when a waiter's deadline donor changes" fixes it. It records the donor in the waiter with the sort keys, so the walk goes on to O. It is in the second series, which applies on top of this one. Its message describes this deboost case.

Thanks,

Mathieu

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

PATCH 9/16 sched/deadline: Reset the deadline and the runtime with the parameters

In reply to Mathieu Desnoyers

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 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.

Fixes 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization")
---
 kernel/sched/deadline.c | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
kernel/sched/deadline.c +15 -1
index 71b1c155c242..d6d2657dcddd 100644
@@ -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
#18 lore raw

Re: [PATCH 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 boost in switched_from_dl()…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: donor runtime and deadline retained after PI boost in switched_from_dl()
- [Medium] sched/deadline: uncanceled dl_timer in __dl_clear_params() unthrottles new period early
--

commit fd3c8e10959b630f111829811b626124918b2948
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Reset the deadline and the runtime with the parameters

This commit resets dl_se->deadline and dl_se->runtime in __dl_clear_params() and in switched_from_dl() when a boosted task with no parameters of its own leaves SCHED_DEADLINE, so that the next entry into the class starts a new period.

Quoted 8 lines
kernel/sched/deadline.c +3 -0
index 71b1c155c2424..d6d2657dcddd6 100644
 
+	/*
+	 * 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 if p->dl.dl_runtime is non-zero?

If a non-deadline task is PI-boosted by a SCHED_DEADLINE waiter and sched_setattr() switches it to SCHED_DEADLINE while still boosted, __sched_setscheduler() sees prev_class == next_class == &dl_sched_class and skips switched_from_dl() and switched_to_dl(). __setparam_dl() sets p->dl.dl_runtime to the task's new reservation without clearing the donor's p->dl.deadline and p->dl.runtime (and if the task is sleeping, skipping switched_to_dl() also misses add_rq_bw(), causing a later __sub_rq_bw() underflow warning). When rt_mutex_setprio() later deboosts the task, it remains in dl_sched_class with the donor's future deadline, so enqueue_dl_entity() skips setup_new_dl_entity() and the task runs on the donor's remaining runtime.

Similarly, if a task that recently left SCHED_DEADLINE is PI-boosted before its 0-lag inactive_timer expires, switched_to_dl() cancels inactive_timer while p->dl.dl_runtime is still non-zero, and replenish_dl_entity() overwrites p->dl.deadline and p->dl.runtime from the donor. On deboost, !p->dl.dl_runtime is false, so switched_from_dl() leaves the donor's deadline and runtime in place and passes them to task_non_contending().

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]
If dl_se->dl_timer was armed before the task left SCHED_DEADLINE, can leaving it queued in __dl_clear_params() unthrottle the task's new period early?

If a task throttles (for example via sched_yield() while its 0-lag time is still before the end of its period) and switches out of SCHED_DEADLINE, dl_se->dl_timer remains armed for the old period's replenishment time. When inactive_task_timer() fires at the 0-lag time, __dl_clear_params() now resets dl_se->deadline, dl_se->runtime, and dl_se->dl_throttled so that re-entering SCHED_DEADLINE starts a fresh period with a later deadline, but dl_se->dl_timer is not canceled. If the task re-enters SCHED_DEADLINE and throttles in its new period before the old timer expires, start_dl_timer() sees hrtimer_is_queued(&dl_se->dl_timer) and does not reprogram it:

kernel/sched/deadline.c:start_dl_timer() {
	...
	if (!hrtimer_is_queued(timer)) {
		if (!dl_server(dl_se))
			get_task_struct(dl_task_of(dl_se));
		hrtimer_start(timer, act, HRTIMER_MODE_ABS_HARD);
	}
	return 1;
}

When the stale timer fires at the old period boundary, dl_task_timer() replenishes and unthrottles the task before its new period ends.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#19 lore raw

Re: [PATCH 09/16] sched/deadline: Reset the deadline and the runtime with the parameters

Quoted 2 lines

Can a task still retain the donor's runtime and deadline after a PI deboost if p->dl.dl_runtime is non-zero?

Yes, in both cases. This patch only resets a task with no parameters of its own. The second series, which applies on top of this one, handles the others:
- "sched/deadline: Reset the donor's runtime at a deboost in the class" covers a task that sched_setattr() makes SCHED_DEADLINE while boosted. Its message names that case.
- "sched/deadline: Count the bandwidth a boosted task is given" adds the new bandwidth to this_bw in __setparam_dl(). The warning goes away.
- For a task boosted before its 0-lag time, I answered on v7: the 0-lag time computed from the donor's deadline is upstream behaviour. "Check the runtime of a task that comes back runnable" checks the runtime when the task comes back.

Quoted 3 lines

If dl_se->dl_timer was armed before the task left SCHED_DEADLINE, can leaving it queued in __dl_clear_params() unthrottle the task's new period early?

Yes. "sched/deadline: Cancel the replenishment timer with the parameters", in the second series, cancels it in __dl_clear_params().

Thanks,

Mathieu

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

PATCH 10/16 sched/deadline: Release the bandwidth of a task that leaves the class asleep

In reply to Mathieu Desnoyers

A 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
index d6d2657dcddd..f0e03f97fd82 100644
@@ -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
#21 lore raw

PATCH 11/16 sched/deadline: Reject SCHED_DEADLINE on exited tasks

In reply to Mathieu Desnoyers

From: 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.

Fixes 332ac17ef5bf ("sched/deadline: Add bandwidth management for SCHED_DEADLINE tasks")

[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
index 9b04e77297ae..b87b878be63f 100644
@@ -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
#22 lore raw

PATCH 12/16 sched/deadline: Fix this_bw when a task is changed during a remote wakeup

In reply to Mathieu Desnoyers

The 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.

Fixes 8fd27231c330 ("sched/deadline: Track the "total rq utilization" too")
---
 include/linux/sched.h   |  5 +++++
 kernel/sched/deadline.c | 39 +++++++++++++++++++++++++++++++++++----
 2 files changed, 40 insertions(+), 4 deletions(-)
include/linux/sched.h +5 -0
index e4f6323d7855..88cda9c10cb8 100644
@@ -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
index f0e03f97fd82..c36516210669 100644
@@ -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
#23 lore raw

Re: [PATCH 12/16] sched/deadline: Fix this_bw when a task is changed during a remote wakeup

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: this_bw desync in add_rq_bw() for PI-boosted tasks --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: this_bw desync in add_rq_bw() for PI-boosted tasks
--

commit 31f5271550e5299348b26e477800f7ac60f7e6c1
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Fix this_bw when a task is changed during a remote wakeup

This commit introduces a dl_bw_oncpu bit in struct sched_dl_entity to track whether a runqueue's this_bw currently accounts for the task's bandwidth, preventing bandwidth drift when parameters change during a remote wakeup.

Quoted 21 lines
kernel/sched/deadline.c +13 -0
index f0e03f97fd82f..c36516210669d 100644
@@ -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.
+ */

kernel/sched/deadline.c void __sub_rq_bw(u64 dl_bw, struct dl_rq *dl_rq) · line 290

Quoted 10 lines
kernel/sched/deadline.c +4 -2
 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;
 }

[Severity: Medium]
Can add_rq_bw() set dl_bw_oncpu = 1 while dl_se->dl_bw is 0 for a PI-boosted non-deadline task, causing dl_rq->this_bw to miss a later SCHED_DEADLINE bandwidth assignment?

When a non-deadline task (dl_runtime == 0, dl_bw == 0) is PI-boosted into dl_sched_class via rt_mutex_setprio(), enqueue_dl_entity(ENQUEUE_RESTORE) or switched_to_dl() calls add_rq_bw(), which adds 0 to this_bw and sets dl_bw_oncpu = 1.

If sched_setattr() assigns SCHED_DEADLINE with new_bw > 0 while the boosted task is unqueued (either sleeping or on a remote wake_list), prev_class and next_class are both &dl_sched_class so ENQUEUE_CLASS is not set, and !task_has_dl_policy(p) is true so sched_dl_overflow() skips dl_change_utilization(). __setparam_dl() then sets p->dl.dl_bw = new_bw while dl_bw_oncpu is already 1 and this_bw still has 0.

When the task finishes waking up, task_contending() calls add_rq_bw(), which returns early because dl_bw_oncpu is 1, and then add_running_bw() adds new_bw to running_bw, triggering WARN_ON_ONCE(dl_rq->running_bw > dl_rq->this_bw). When the task later migrates, leaves SCHED_DEADLINE, or exits, sub_rq_bw() subtracts new_bw and underflows this_bw. Should add_rq_bw() also return early when !dl_se->dl_bw (or !dl_se->dl_runtime)?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#24 lore raw

Re: [PATCH 12/16] sched/deadline: Fix this_bw when a task is changed during a remote wakeup

Quoted 3 lines

Can add_rq_bw() set dl_bw_oncpu = 1 while dl_se->dl_bw is 0 for a PI-boosted non-deadline task, causing dl_rq->this_bw to miss a later SCHED_DEADLINE bandwidth assignment?

Yes, but this patch does not cause it. Without it, the boost adds 0 to this_bw too, and the same sched_setattr() leaves the new bandwidth out.

"sched/deadline: Count the bandwidth a boosted task is given", in the second series, fixes it. __setparam_dl() changes this_bw for every task that gains deadline parameters. With dl_bw_oncpu set, the old bandwidth of 0 is replaced by the new one.

Thanks,

Mathieu

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

PATCH 13/16 sched/deadline: Check SCHED_DEADLINE affinity under the rq lock

In reply to Mathieu Desnoyers

From: 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 = cpu0

The 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
index 5ed660f099a5..32fe889e02fb 100644
@@ -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
index 92134ce326a4..20ad13f388cb 100644
@@ -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		0x10
 
 extern void update_group_capacity(struct sched_domain *sd, int cpu);
 
kernel/sched/syscalls.c +7 -5
index b87b878be63f..5983232476a9 100644
@@ -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
#26 lore raw

PATCH 14/16 sched/debug: Show the deadline bandwidth of each runqueue

In reply to Mathieu Desnoyers

For 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
index ddb382df454b..2c373adf3196 100644
@@ -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
#27 lore raw

PATCH 15/16 selftests/sched: Add a test of SCHED_DEADLINE policy round trips

In reply to Mathieu Desnoyers

No 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
index 07c3719f8b04..35b0c5e86ba7 100644
@@ -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
new file mode 100644
index 000000000000..9f203c455b91
@@ -0,0 +1 @@
+deadline_switch_test
tools/testing/selftests/sched/deadline/Makefile new file +8 -0
new file mode 100644
index 000000000000..3f4dc1ec6119
@@ -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
new file mode 100644
index 000000000000..3a3a7285a708
@@ -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
#28 lore raw

PATCH 16/16 selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting

In reply to Mathieu Desnoyers

Upstream 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 47 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 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 one VM. In another one, 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         | 5468 +++++++++++++++++
 .../testing/selftests/sched/deadline/settings |    1 +
 5 files changed, 5475 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
index 9f203c455b91..5a572318e1ba 100644
@@ -1 +1,2 @@
 deadline_switch_test
+deadline_bw_test
tools/testing/selftests/sched/deadline/Makefile +1 -1
index 3f4dc1ec6119..c3156059bdcf 100644
@@ -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
index 3a3a7285a708..b19db0c962e0 100644
@@ -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 +5468 -0

2,986 lines not on this page · raw message

tools/testing/selftests/sched/deadline/settings new file +1 -0
new file mode 100644
index 000000000000..a62d2fa1275c

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.

#29 lore raw

Re: [PATCH 16/16] selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider: - [Medium] selftests/sched: sub-cgroup start and unconditional cpu toggle in move_cancelled() - [Medium]…

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider:
- [Medium] selftests/sched: sub-cgroup start and unconditional cpu toggle in move_cancelled()
- [Medium] selftests/sched: broken PI and runtime logic in deboost_new_params_reboost()
- [Medium] selftests/sched: pi_chain_donor_leaves() fails due to unpropagated dl.pi_se
- [Medium] selftests/sched: rebuild_record_taken() fails under isolcpus=domain,0,1
- [Low] selftests/sched: rebuild_record_taken() fails instead of skipping without debugfs
- [Low] selftests/sched: data race on late.done and unjoined thread in move_cancelled()
- [Low] selftests/sched: unchecked -1 error return from probe() in bandwidth comparisons
- [Low] selftests/sched: unused variables, write-only fair_tid, and dead mode branches
- [Low] selftests/sched: re-init of active robust mutex shm_lock in shm_lock_init()
--

commit ec25de481fdb21f02eb990530342399d3485450d
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting

This commit adds deadline_bw_test, a kselftest covering SCHED_DEADLINE bandwidth accounting across priority inheritance, parameter changes, cpuset moves, task deaths, yields, runtime overruns, bandwidth reclaiming, fair server changes, and CPU hotplug.

Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +0 -0
new file mode 100644
index 0000000000000..1e64402f90df0

[ ... ]

Quoted 6 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +6 -0
+	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 2096

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 deboost_new_params_reboost() exercise reboosting after a deboost as its comment describes?

When reboost_owner() calls set_deadline() on rb_waiter_tid while W is blocked on pi_lock, W is not queued on a runqueue, so __setparam_dl() updates W's static parameters and switched_to_dl() returns without setting W->dl.deadline. rt_mutex_adjust_pi() then copies W->dl.deadline (0) into W's waiter node on pi_lock, which sorts ahead of D's deadline in rt_waiter_node_less() and makes W the top waiter boosting O immediately, before D times out.

Also, when O calls set_deadline() on itself while running, the kernel enqueues O with ENQUEUE_RESTORE | ENQUEUE_MOVE without replenishing, and rt_mutex_setprio() on deboost does not compare O's remaining runtime against its new static runtime or start a new period, so the test passes without testing a reboost on deboost.

[ ... ]

Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +5 -0
+static pthread_mutex_t pi_lock2;
+static sem_t holder_go;
+static atomic_int holder_holds, chain_waits, donor_done, x_waits, l2_takes;
+static atomic_int chain_rank, x_rank;
+static _Atomic pid_t x_tid, fair_tid;

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 2446

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]
fair_tid is set in pi_init_lock2() but never read, which triggers a -Wunused-but-set-variable warning under -Wall. Similarly, nisol and isol in main() are populated by read_online(&isol, 1) and never used or freed, sleeper_cpu is never modified from -1 (leaving the sleeper_cpu >= 0 block in dl_sleeper_tid() unreachable), struct hp_case::no_hp is never set, and several helper modes (was_dl != 0 in pi_asleep(), modes 1 and 2 in deboost_case(), spin_ms == 8 in refill_case(), modes 0 and 2..5 in return_case(), and MV_YIELDED in mover()) have no callers.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 2741

Quoted 9 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +9 -0
+	have[LV_Z] = !pthread_create(&t[LV_Z], NULL, leave_waiter, (void *)2L);
+	if (!have[LV_Z] ||
+	    wait_for(1000, (leave_tid[LV_Z] && proc_state_of(leave_tid[LV_Z]) == 'S') ||
+			   leave_err)) {
+		ksft_print_msg("Z never blocked on L1\n");
+		goto out;
+	}
+	sleep_ns(10 * NSEC_PER_MSEC);	/* the chain walk of Z is done */
+	err = leave_err ? -EINVAL : set_other(leave_tid[LV_W]);

[Severity: Medium]
Does pi_chain_donor_leaves() fail because Z is never propagated past M to O as O's donor?

When Z blocks on L1, task_blocks_on_rt_mutex() updates M->dl.pi_se to &Z->dl, but M is sleeping on L2, so M->prio (-1) and M->dl.deadline do not change. In rt_mutex_adjust_prio_chain(), rt_waiter_node_equal() sees that M's waiter node on L2 still matches M's prio and deadline and stops without requeueing M on L2 or calling 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 therefore stays &W->dl. After set_other(leave_tid[LV_W]) and the 250ms sleep clear W's deadline parameters, waking O replenishes O from W's zeroed parameters with runtime = 0 and deadline = rq_clock(rq), so O preempts and starves Y on P's CPU and fails the y_ns < 30ms check.

[ ... ]

Quoted 28 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +28 -0
+/* What late_setter() does, and the result. */
+static struct {
+	pid_t pid;
+	uint64_t runtime;
+	uint64_t delay;
+	atomic_int go;
+	int ret;
+	uint64_t done;
+} late;
+
+/*
+ * Make late.pid a deadline task of late.runtime every 100ms, late.delay
+ * ns after late.go. Store the result in late.ret and the time it returned
+ * in late.done.
+ */
+static void *late_setter(void *arg)
+{
+	uint64_t start;
+
+	while (!late.go)
+		;
+	start = now_ns();
+	while (now_ns() - start < late.delay)
+		;
+	late.ret = set_deadline(late.pid, late.runtime, PERIOD);
+	late.done = now_ns();
+	return arg;
+}

[ ... ]

Quoted 21 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +21 -0
+static int move_cancelled(void)
+{
+	int with_p, with_r, ret = KSFT_PASS, i, err;
+	const char *name = "move_cancelled";
+	uint64_t start, len;
+	pid_t pid;
+
+	mv_state[0] = 0;
+	mv_state[3] = 0;
+	mv_state[4] = 0;
+	mv_state[5] = 0;
+	pid = pinned_mover(2048, 1);
+	if (pid < 0 || child_up(name, 0) || wait_for(5000, mv_state[5])) {
+		reap(pid);
+		return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+	}
+	if (mv_state[5] < 0 || write_file(root, "cgroup.subtree_control", "+cpu")) {
+		ksft_print_msg("%s: no SCHED_FIFO thread or no cpu controller\n", name);
+		reap(pid);
+		return KSFT_SKIP;
+	}

[ ... ]

Quoted 13 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +13 -0
+		if (wait_for(5000, late.done)) {
+			ksft_print_msg("%s: sched_setattr() still waits after a cancelled move\n",
+				       name);
+			ret = KSFT_FAIL;
+			break;	/* the thread cannot be joined */
+		}
+		join(t);
+		if (late.ret) {
+			ksft_print_msg("%s: sched_setattr: %s\n", name, strerror(-late.ret));
+			ret = KSFT_FAIL;
+		}
+	}
+	sleep_ns(3 * PERIOD);

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 3240

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	if (ret == KSFT_PASS &&
+	    (admits_in(cg_p, with_p, "P, after the cancelled moves") ||
+	     admits_in(root, with_r, "the root domain of the process")))
+		ret = KSFT_FAIL;
+out:
+	reap(pid);
+	if (write_file(root, "cgroup.subtree_control", "-cpu"))
+		ksft_print_msg("%s: the cpu controller stays enabled\n", name);
+	return ret;
+}

[Severity: Medium]
What happens in move_cancelled() when deadline_bw_test is started from a non-root cgroup (such as a systemd session or service cgroup)?

Unlike kill_case() and death_group(), main() and move_cancelled() never move the test process into root before forking pinned_mover(2048, 1). With CONFIG_RT_GROUP_SCHED=y, a non-root cgroup has no RT runtime by default, so either fifo_sleeper() fails sched_setscheduler(SCHED_FIFO) with EPERM when +cpu is already enabled, or enabling +cpu on root fails with EINVAL while the child cgroup contains a SCHED_FIFO task, causing move_cancelled() to always skip. Also, unlike run_p_cases() and cs_setup() with +cpuset, move_cancelled() unconditionally writes -cpu to root/cgroup.subtree_control at exit even if the cpu controller was already enabled before the test ran.

[Severity: Low]
In the same loop, late.done is a plain uint64_t written by late_setter() while move_cancelled() polls it in wait_for(5000, late.done), which is a data race. If that wait times out, breaking out before join(t) also leaves t unjoined in the main process even though reap(pid) at out: kills pid and unblocks late_setter().

[ ... ]

Quoted 15 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +15 -0
+/* Set up shm_lock. Return 0, or -1 if it cannot be set up. */
+static int shm_lock_init(void)
+{
+	pthread_mutexattr_t a;
+	int err;
+
+	err = pthread_mutexattr_init(&a);
+	if (!err)
+		err = pthread_mutexattr_setpshared(&a, PTHREAD_PROCESS_SHARED);
+	if (!err)
+		err = pthread_mutexattr_setprotocol(&a, PTHREAD_PRIO_INHERIT);
+	if (!err)
+		err = pthread_mutexattr_setrobust(&a, PTHREAD_MUTEX_ROBUST);
+	if (!err)
+		err = pthread_mutex_init(shm_lock, &a);

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 3567

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	} else {
+		reap(waiter);
+		waiter = -1;
+		sleep_ns(50 * NSEC_PER_MSEC);	/* the owner deboosted asleep */
+	}
+out:
+	reap(waiter);
+	reap(owner);
+	return ret;
+}

[Severity: Low]
Does shm_lock_init() re-initialize shm_lock without destroying it across death_pi_waiter, death_pi_owner, and death_pi_deadline_owner?

shm_lock lives in MAP_SHARED memory, and in death_pi_waiter, reap(owner) kills the owner with SIGKILL while it still holds shm_lock, leaving the robust mutex in the FUTEX_OWNER_DIED state when the next test case calls pthread_mutex_init(shm_lock, &a). shm_lock_init() (and pi_chain_two_owners()) also omits pthread_mutexattr_destroy(&a).

[ ... ]

Quoted 15 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +15 -0
+static int hotplug_server(void)
+{
+	int base, off10, off30;
+
+	if (server_set(hp_cpu, SERVER_RUNTIME, SERVER_PERIOD)) {
+		ksft_print_msg("the fair server of CPU %d cannot be set\n", hp_cpu);
+		return KSFT_SKIP;
+	}
+	base = probe(NULL);
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("offline of CPU %d refused\n", hp_cpu);
+		return KSFT_FAIL;
+	}
+	off10 = probe(NULL);
+	cpu_up(hp_cpu);

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 4945

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	if (server_set(hp_cpu, 3 * SERVER_RUNTIME, SERVER_PERIOD) ||
+	    admits(base - 2, "a fair server of 30%"))
+		return KSFT_FAIL;
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("offline of CPU %d refused, its fair server at 30%%\n", hp_cpu);
+		return KSFT_FAIL;
+	}
+	off30 = probe(NULL);
+	cpu_up(hp_cpu);
+	if (off30 != off10) {

[Severity: Low]
Can hotplug_server() pass when probe(NULL) fails and returns -1?

If both offline probes return -1, off30 != off10 evaluates to false; base is not checked for <= 0 either. move_refused() and move_zero_bw() similarly compare probe(cg_p) != base_p || probe(root) != base_r without checking whether base_p or base_r failed with -1.

[ ... ]

Quoted 24 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +24 -0
+static int rebuild_record_taken(void)
+{
+	int a = top_cpu(3), b = top_cpu(2), c = online[0], d = top_cpu(1);
+	int fd[2] = { -1, -1 }, i, n, err, cpu, ret = KSFT_SKIP;
+	long long q, h, q0, h0, bw;
+	char buf[4096];
+	pid_t pid = -1;
+
+	if (ncpus < 4 || !cpu_hotpluggable(a) || !cpu_hotpluggable(b) ||
+	    !cpu_hotpluggable(d)) {
+		ksft_print_msg("needs 4 CPUs, 3 of them hotpluggable\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	/* Q has every housekeeping CPU but A, B and D. */
+	for (i = n = 0; i < ncpus - 3; i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%s%d", n ? "," : "",
+			      online[i]);
+	if (make_partition_cpus(cs_q, buf)) {
+		ksft_print_msg("Q cannot be a partition root of CPUs %s\n", buf);
+		goto out;
+	}
+	ret = KSFT_FAIL;

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 5134

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	err = cpu_online(d, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d: %s\n", d, strerror(-err));
+		goto out;
+	}
+	bw = total_bw_of(a);
+	if (bw == -1 || pipe(fd)) {
+		ksft_print_msg("no total_bw of CPU %d, or no pipe\n", a);
+		goto out;
+	}

[Severity: Low]
Should rebuild_record_taken() return KSFT_SKIP instead of KSFT_FAIL when total_bw_of(a) returns -1 because /sys/kernel/debug/sched/debug is not available?

ret is set to KSFT_FAIL before total_bw_of(a) is checked, whereas the other debugfs-dependent cases skip when debugfs files cannot be read.

Quoted 12 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +12 -0
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a deadline task");
+	if (!pid) {
+		cpu_set_t set;
+		char ch;
+
+		CPU_ZERO(&set);
+		CPU_SET(a, &set);
+		CPU_SET(b, &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD)) {

[ ... ]

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	if (fallback_wake(fd[1], pid))
+		goto out;
+	/* Go on after a failure: the totals tell more. */
+	cpu = task_cpu_of(pid);
+	if (cpu != c)
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, c);
+	else if (!totals_check("woken", d, c, q, h))
+		ret = KSFT_PASS;
+	reap(pid);
+	pid = -1;

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 5208

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	sleep_ns(3 * PERIOD);
+	if (totals_of(d, c, &q0, &h0)) {
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	if (q != q0 || h != h0 + bw) {
+		ksft_print_msg("Q counts %lld of %lld, the root cgroup %lld\n",
+			       q - q0, bw, h - h0);
+		ret = KSFT_FAIL;
+	}

[Severity: Medium]
Does rebuild_record_taken() fail when CPU 0 is isolated with isolcpus=domain,0,1?

When CPU 0 is isolated, online[0] is the first housekeeping CPU (for example, c = 2). The child in the root cgroup overwrites its inherited housekeeping affinity with {a, b}. Once a and b are taken offline and cs_q takes the remaining housekeeping CPUs except c, dl_add_task_root_domain() queries cpuset_cpus_allowed_locked() for top_cpuset, which includes the isolated CPUs 0 and 1, so cpumask_first_and(cpu_active_mask, msk) picks CPU 0 and adds bw to CPU 0's default root domain rather than CPU c's housekeeping root domain (leaving h == h0 instead of h0 + bw). Likewise, waking pid via fallback_wake() hits select_fallback_rq() -> cpuset_cpus_allowed_fallback(), which resets pid's affinity to top_cpuset.cpus_allowed and wakes pid on CPU 0 instead of CPU c.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#30 lore raw

Re: [PATCH 16/16] selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting

Quoted 2 lines

Does deboost_new_params_reboost() exercise reboosting after a deboost as its comment describes?

It reaches the check it was written for. It failed on v7, before the split, with the bug that "sched/deadline: Check the runtime of a task whose parameters change" fixes. I have not checked your point on the deadline of 0 in the waiter node.

Quoted 2 lines

fair_tid is set in pi_init_lock2() but never read, which triggers a -Wunused-but-set-variable warning under -Wall.

These come from splitting the test. They serve the cases that the second series adds back. The test builds with no warning, as fair_tid is a global.

Quoted 2 lines

Does pi_chain_donor_leaves() fail because Z is never propagated past M to O as O's donor?

No. It passes in every run, in 25 guests with this series. The missed propagation is what pi_chain_top_moves tests. That case comes with the two rtmutex fixes, in the second series.

Quoted 2 lines

What happens in move_cancelled() when deadline_bw_test is started from a non-root cgroup (such as a systemd session or service cgroup)?

Right. The case assumes the root cgroup, and it turns the cpu controller off even if it was on before. I will fix both.

Quoted 3 lines

In the same loop, late.done is a plain uint64_t written by late_setter() while move_cancelled() polls it in wait_for(5000, late.done), which is a data race.

Right. I will make it atomic, and join the thread after the reap.

Quoted 2 lines

Does shm_lock_init() re-initialize shm_lock without destroying it across death_pi_waiter, death_pi_owner, and death_pi_deadline_owner?

Yes. I will destroy the mutex and its attributes.

Quoted 1 line

Can hotplug_server() pass when probe(NULL) fails and returns -1?

Yes. I will check the probes in the three cases.

Quoted 3 lines

Should rebuild_record_taken() return KSFT_SKIP instead of KSFT_FAIL when total_bw_of(a) returns -1 because /sys/kernel/debug/sched/debug is not available?

Yes.

Quoted 2 lines

Does rebuild_record_taken() fail when CPU 0 is isolated with isolcpus=domain,0,1?

Yes. With 7 CPUs and isolcpus=domain,0,1, it fails in 3 runs of 3:
the task wakes on CPU 0. With the second series, it passes in 3 of 3. The case tests "sched/deadline: Make a rebuild count a task in the root domain it runs in", of the second series. It belongs there. It passed in our runs only because the guests with isolated CPUs had too few CPUs to run it. I will move it to the second series.

Thanks,

Mathieu

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