Skip to contentSkip to conversation

sched/deadline: bandwidth accounting fixes and selftests

PATCH Superseded Mathieu Desnoyers 3 participants 81 messages Nov 17 – Nov 18

Subsystems (7)

v7 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

v7 cover sched/deadline: bandwidth accounting fixes and selftests

Hi Ingo, Juri,

This series fixes 36 bugs of SCHED_DEADLINE. Most of them are in its bandwidth accounting. Then it shows the deadline bandwidth of each runqueue in sched_debug, and adds three selftests. The fixes come first, as you asked, so that stable can take patches 1 to 36.

Three of the bugs take the kernel down (patches 4, 8 and 26). One is a use after free in the rtmutex chain walk (patch 9). One leaves a task that never runs again (patch 12). One leaves cpuset_mutex locked (patch 6). 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.

Patch 20 is Andrea Parri's. I carry it unchanged, with his agreement. It is reviewed by Sebastian. It adds an affinity flag and a check next to the code that patch 21 changes. Take it by whichever route you prefer.

Juri, your four fixes that Ingo dropped from sched/urgent are still here, renumbered:
- 1/4 is patch 18.
- 2/4 is patch 13.
- 3/4 is patch 1.
- 4/4 is patch 14.

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 Continue the rtmutex chain walk when the deadline donor of a waiter
changes, so that no owner keeps a donor that can exit.
10 Reset the deadline and the runtime with the parameters. 11 Start a new period at a deboost in the class, if the boost
refilled the task's runtime from its donor.
12 Replenish a throttled task that a waiter boosts while it sleeps, so
that it runs again.
13 Release the bandwidth of a task that leaves the class asleep. 14 Reject SCHED_DEADLINE on exited tasks (Juri Lelli).
15 Keep the bandwidth of departing tasks across a root domain rebuild. 16 Keep this_bw right when a task changes during a remote wakeup. 17 Rebuild the root domains' accounting from the task list. 18 Record the root domain that holds a task's bandwidth.
19 Leave out of a rebuild a dying task that released its bandwidth. 20 Check the affinity of a deadline task under the runqueue lock, so
that sched_setaffinity() and sched_setattr() cannot both succeed (Andrea Parri).
21 Move a task's bandwidth only where an attach made room for it. 22 Wait for an attach before rebuilding the sched domains. 23 Make a policy or affinity change of a deadline task wait for a
cpuset attach in progress.
24 Give back the bandwidth an attach did not move.
25 Reserve an attach's bandwidth in the root domain each task moves to. 26 Make a rebuild count a task in the root domain it runs in. 27 Move a task's bandwidth to the root domain it runs in. 28 Pick a CPU for a task in the root domain that counts its
bandwidth, when that root domain has one.
29 Refuse to take offline the last CPU a task has in the root domain
that counts its bandwidth.
30 Refuse a cpuset change that leaves a deadline task no CPU in the
root domain that counts its bandwidth.
31 Cancel the replenishment timer with the parameters.
32 Count in this_bw the bandwidth a boosted task is given. 33 Give a deadline to a task that enters the class while it waits on
an rt_mutex.
34 Cap the runtime left of a constrained task at dl_runtime when its
parameters change.
35 Check the runtime left of a task that comes back to the class
runnable, as a wakeup does.
36 Check the runtime left of a runnable task whose parameters change.

Patches 18, 19 and 21 to 30 go together. 18 records the root domain that counts a task's bandwidth. 19 and 21 to 27 fix the rebuild, attach and migration paths that the record exposes. 28 to 30 keep a task in the root domain that counts it, as long as that root domain has a CPU for it. Patch 32 completes patch 16. Patch 37 shows this_bw in sched_debug. Patches 38 to 40 add 112 cases in tools/testing/selftests/sched/deadline, as Juri suggested.

Peter, patch 9 changes the rtmutex chain walk: a waiter records its deadline donor with its sort keys. Patch 25 also touches __set_cpus_allowed_ptr_locked(). A cpuset attach can reserve a deadline task's bandwidth in one root domain. If the CPU picked for the task is in the other one, the patch steers the task to the reserved CPU. Patch 23 touches __sched_setscheduler() and sched_setaffinity(). A change of a deadline task waits there for a cpuset attach in progress. Patch 28 touches select_fallback_rq() and __set_cpus_allowed_ptr_locked() for deadline tasks.

Waiman, patches 29 and 30 add refusals. They apply when a change would leave a deadline task no CPU in the root domain that counts it. That needs a cpuset with CPUs of two root domains: with isolcpus="domain", or on cgroup v1 with sched_load_balance off. A CPU offline or a write to cpuset.cpus then fails with EBUSY. cpuset makes a partition root invalid, with a new reason. Nothing is refused with admission control off (sched_rt_runtime_us set to -1).

Known limits
============

The fixes leave these cases open. Each patch named below also states its limit in its message.

- Patch 9: two chain walks can overlap on a chain of three locks or more. The owners further down keep the old donor until the first walk reaches them.
- Patch 15: a task that left the class keeps its bandwidth until its 0-lag time. A rebuild still drops it earlier if the CPU of the task is inactive, or if the task dies during the rebuild.
- Patch 27: a task can run in a root domain that does not count its bandwidth. The bandwidth then moves there without a check for room, as dl_task_offline_migration() does upstream.
- Patch 28: a CPU picked while the sched domains are rebuilt has no preference for a root domain, as upstream. No bandwidth moves meanwhile. But a wakeup can pick its CPU inside the rebuild and be queued after it. Its bandwidth can then move to the other root domain with no check for room. Push and pull between the two root domains during the rebuild are part of the same limit. This was found by reading, not reproduced.
- Patches 28 to 30: a task with no CPU left in the root domain that counts it still moves, and its bandwidth with it. With admission control on, patches 29 and 30 refuse the CPU offline and the cpuset changes that I found to lead there. Nothing is refused during a suspend, or with admission control off.
- A cpuset that holds isolated and housekeeping CPUs still admits a deadline task. Juri pointed at the XXX in dl_bw_capacity() for this in the v5 thread. It is left for later.

Found, left for separate patches
================================

The Sashiko review of v6 found two upstream bugs outside the scope of this series. Both were found by reading. I will post their fixes separately:
- The 0-lag time in task_non_contending() can overflow with periods of a few seconds. The bandwidth would then be released seconds late.
- dl_task_offline_migration() and dl_add_task_root_domain() spread extra_bw over the whole span, offline CPUs included. Tasks with SCHED_FLAG_RECLAIM would then reclaim a little more than their share, until the next rebuild.

Testing
=======

The 112 cases pass wherever they run, with lockdep and no kernel warning, in 19 QEMU guests:
- 5 guests of 8 vCPUs, one with proxy execution off, and 1 of 4 vCPUs.
- 3 guests with PREEMPT_RT, of 8, 8 and 4 vCPUs.
- 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.
The 23 isolcpus cases run in the fourth group. There, the cases that need 4 CPUs that are not isolated skip. rebuild_waking_keeps also skips with isolcpus=domain,1,2: it needs the first CPU isolated. Some of the 23 also run in the fifth group. move_cancelled runs only in the last group.

No guest combines isolcpus=domain with a kernel without CONFIG_CPUSETS. Such a kernel hits a BUG at boot on v7.4-rc2 with isolcpus=domain,0,1. The BUG is in select_fallback_rq() called from workqueue_init(). I will report it separately.

On v7.4-rc2, 35 cases of deadline_bw_test fail in 8 guests of 8 vCPUs, as patch 40 lists. overrun_caught fails in part of the runs. The three cases of deadline_rebuild_test fail there too, and so do throttled_round_trip, asleep_round_trip and sysrq_normalize of deadline_switch_test. tip sched/urgent, the base of this series, gives the same results.

Each case added for a fix fails without that fix. Each fix names the cases that test it, and patch 40 lists the rest. There are four exceptions:
- deboost_blocked_keeps_order passes on v7.4-rc2, and fails on v5.
- return_asleep_new_params passes everywhere. It covers the wakeup path that patches 35 and 36 copy.
- deboost_keeps_own_runtime passes with and without the flag of patch
11. It checks that a task keeps the runtime of its own reservation.
- pi_chain_donor_leaves passes on v7.4-rc2. There, a blocked task that leaves SCHED_DEADLINE keeps its parameters. It fails on v6.

sysrq_running_owner passes on v6 too. It locks the guest up once the early return of patch 8 is disabled. Two cases pass on v7.4-rc2 and add coverage only: frozen_moved_switched and pi_chain_two_owners. So do the affinity changes in random_mix.

The three sysrq cases only run with DEADLINE_TEST_SYSRQ=1, which the 19 guests set. move_normalized is one of them.

For patches 13, 15 and 22, a kernel built with the series up to that patch confirms the claim of its message. Each of the 40 patches builds alone. The whole series also builds without CONFIG_CPUSETS, with PREEMPT_RT and with CONFIG_RT_GROUP_SCHED. kernel/sched/ also builds without CONFIG_RT_MUTEXES, which v6 broke. The cpuset selftest test_cpuset_prs.sh passes, with and without PREEMPT_RT.

Not tested: cgroup v1 cpusets, threaded cgroups (every move is a write to cgroup.procs), 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. 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 v6. Each finding was checked against the code first.

Changes since v6
================

- The base is unchanged: tip sched/urgent ec6f6731538e.
- Fixes from the Sashiko review of v6. Three are new patches, for bugs that upstream has:
- New patch 9: the rtmutex chain walk stopped at a waiter whose keys did not change. The owner further down could then keep a donor that exits. pi_chain_donor_leaves tests it.
- New patch 12: a task throttled as it blocked, then boosted while it slept, would never be replenished. It would never run again. This was found by reading.
- New patch 34: a constrained task given a shorter dl_deadline could keep more runtime than its new dl_runtime. change_constrained_new_params and wake_constrained_new_params test it.
- Fixes to v6 patches, from the same review:
- 8: the donor's runtime, deadline and period are all tested. A negative runtime is reset to 0. An owner with no parameters of its own gets a deadline of now.
- 11: it builds without CONFIG_RT_MUTEXES. fork() does not copy dl_donor_refill.
- 23: after a race with a cpuset update, sched_setaffinity() sets the mask a second time. That second change waits for an attach too.
- 25: the v2 fast path clears the reservation record. The span of the default root domain leaves out offline CPUs. move_back_cpu_offline tests it.
- 26: with admission control off, a task put outside its mask by the offline fallback is counted where it runs.
- 27: no bandwidth moves to a CPU that is not active.
- 28: the offline migration of a throttled task stays in its root domain. The span stays known while the recorded CPU goes offline. hotplug_spinner_keeps, hotplug_waking_keeps and hotplug_isolated_keeps test it.
- 29: the fallback CPUs follow the affinity set by the user. A dead task does not block the offline. hotplug_user_mask_refused and hotplug_dead_accepted test it.
- 30: the new masks are computed from the top down. A scratch mask no longer overwrites effective_xcpus. An invalid partition gives no CPUs back. A mask that grows within the user affinity is checked. Four new cases test it.
- 33: a new donor of a blocked task with no parameters starts a period.
- 36: a boosted task keeps the mark of its parameter change until an enqueue after its deboost. change_boosted_new_params tests it.
- Patches 27 and 28: no bandwidth moves and no span is used while the sched domains are rebuilt. A partition root made and removed while a task woke up often could move its bandwidth to the isolated root domain. rebuild_waking_keeps tests it. With isolcpus=domain,0,1, it fails in most runs without the fix.
- Patch 27: proxy execution can migrate a task blocked on a mutex. Its bandwidth now stays in the root domain that counts it. This came up in the review of the proxy execution RFC.
- The claims made "on v7.4-rc1" were run again on v7.4-rc2 and on tip sched/urgent. They all hold, and the messages now say v7.4-rc2. Patch 40 lists 35 failing cases, not 32.
- The selftest guards of the hotplug cases are fixed. affinity_vs_setattr waits for its target to sleep, so its target no longer overruns.

Not changed:
- A departed task that priority inheritance boosts back into the class is counted once across a rebuild. The rebuild counts it where it runs. If the deboost races the rebuild, its bandwidth is dropped until its 0-lag time. Nothing is counted twice.
- At a deboost, the 0-lag time of a task comes from the deadline and runtime it ran on during the boost, as upstream.
- sched_setattr() still fails with EPERM for a task moved asleep to another partition. The task is still on a CPU of the old root domain, and the affinity check of __sched_setscheduler() reads that one. The check is upstream code, and it refuses but never admits wrongly.
- An attach whose mask keeps a CPU of the task's root domain reserves nothing. The task then stays in that root domain.
- A write to cpuset.cpus that makes a partition root invalid is not refused. A deadline task can then run in a root domain that did not admit it, as upstream. CPU hotplug and a write of "member" do the same and cannot fail. The next rebuild counts the task where it runs.

Based on tip sched/urgent, ec6f6731538e (v7.4-rc2).

v6: https://lore.kernel.org/all/[email protected]/
v5: https://lore.kernel.org/all/[email protected]/
v4: 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 (38):
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
rtmutex: Continue the chain walk when a waiter's deadline donor
changes
sched/deadline: Reset the deadline and the runtime with the parameters sched/deadline: Reset the donor's runtime at a deboost in the class sched/deadline: Replenish a throttled task boosted while asleep sched/deadline: Release the bandwidth of a task that leaves the class
asleep
sched/deadline: Keep departing bandwidth across a root domain rebuild sched/deadline: Fix this_bw when a task is changed during a remote
wakeup
sched/deadline: Rebuild the root domains' accounting from the task
list
sched/deadline: Record the root domain holding a task's bandwidth sched/deadline: Leave a dying task out of a rebuild of the accounting sched/deadline: Move a task's bandwidth only where room was made cgroup/cpuset: Wait for an attach before rebuilding the sched domains
sched: Make deadline policy and affinity changes wait for a cpuset
attach
cgroup/cpuset: Give back the bandwidth an attach did not move cgroup/cpuset: Reserve the bandwidth in the root domain a task moves
to
sched/deadline: Make a rebuild count a task in the root domain it runs
in
sched/deadline: Move a task's bandwidth to the root domain it runs in sched/deadline: Keep a task in the root domain that counts its
bandwidth
sched/deadline: Keep the last CPU a task has in its root domain cgroup/cpuset: Refuse to take a deadline task out of its root domain sched/deadline: Cancel the replenishment timer with the parameters sched/deadline: Count the bandwidth a boosted task is given sched/deadline: Start a period for a task that enters the class
blocked
sched/deadline: Cap the runtime left of a constrained task at
dl_runtime
sched/deadline: Check the runtime of a task that comes back runnable sched/deadline: Check the runtime of a task whose parameters change sched/debug: Show the deadline bandwidth of each runqueue selftests/sched: Add a test of SCHED_DEADLINE policy round trips selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain
rebuild
selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting

 include/linux/cpuset.h                        |   20 +-
 include/linux/sched.h                         |   43 +
 include/linux/sched/deadline.h                |   39 +-
 kernel/cgroup/cgroup.c                        |    3 -
 kernel/cgroup/cpuset-internal.h               |   15 +-
 kernel/cgroup/cpuset.c                        |  549 +-
 kernel/locking/rtmutex.c                      |   22 +-
 kernel/locking/rtmutex_api.c                  |    2 +-
 kernel/locking/rtmutex_common.h               |    3 +
 kernel/sched/core.c                           |  126 +-
 kernel/sched/deadline.c                       | 1350 ++-
 kernel/sched/debug.c                          |   12 +-
 kernel/sched/sched.h                          |   21 +
 kernel/sched/syscalls.c                       |  177 +-
 kernel/sched/topology.c                       |   11 +
 tools/testing/selftests/Makefile              |    1 +
 .../selftests/sched/deadline/.gitignore       |    3 +
 .../testing/selftests/sched/deadline/Makefile |    8 +
 tools/testing/selftests/sched/deadline/config |    5 +
 .../sched/deadline/deadline_bw_test.c         | 9597 +++++++++++++++++
 .../sched/deadline/deadline_rebuild_test.c    |  497 +
 .../sched/deadline/deadline_switch_test.c     | 1089 ++
 .../testing/selftests/sched/deadline/settings |    1 +
 23 files changed, 13282 insertions(+), 312 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_rebuild_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 v7 1/40 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 the first posting 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 v7 2/40 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 the first posting 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 v7 3/40 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 v7 4/40 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
#6 lore raw

PATCH v7 5/40 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.

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 | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
kernel/sched/debug.c +9 -1
index e6a3b516c703..e0d6cd3bd607 100644
@@ -410,7 +410,15 @@ 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.
+		 */
+		if (!rq->online)
 			return -EBUSY;
 
 		update_rq_clock(rq);
Signature · 1 line
2.47.3
#11 lore raw

PATCH v7 6/40 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
#12 lore raw

PATCH v7 7/40 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 the first posting 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
#13 lore raw

PATCH v7 8/40 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 reading the inherited runtime, deadline and period once, and by not refilling from cleared ones. They are cleared under the waiter's rq lock, not the owner's. So test all three. The owner stays runnable. It gets no runtime. A negative runtime is reset to 0: the owner's own reservation does not pay for the boost. An owner with no parameters of its own gets a deadline of now. A deadline of 0 would mark its dl_rq as empty. The wakeup of a boosted task already gives that deadline when its donor is cleared. The owner runs until the chain walk deboosts it, or until it releases the lock. That also covers sysrq-n:
normalize_rt_tasks() changes the waiter without a chain walk. The warning stays 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 the third posting found the lockup. Juri Lelli suggested this fix in place of a larger one.

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
#18 lore raw

PATCH v7 9/40 rtmutex: Continue the chain walk when a waiter's deadline donor changes

In reply to Mathieu Desnoyers

A task boosted by a SCHED_DEADLINE waiter runs on the parameters of a donor, dl.pi_se. Commit 2279f540ea7d ("sched/deadline: Fix priority inheritance with multiple scheduling classes") made the donor follow the chain. rt_mutex_setprio() copies the donor of the top waiter to the owner. So the owner at the end of a chain points at the deadline task at its head. That task waits on no lock the owner holds.

The chain walk stops at a task whose waiter has the same sort keys as the task: the priority and the deadline. Then "there is no further priority adjustment necessary". Before 2279f540ea7d, this was enough. The refill read the parameters of the owner's own top waiter, which is blocked and so alive.

But a boost can change the donor of a blocked task and leave its keys as they were. The task keeps a deadline priority. It sleeps, so no refill moves its deadline. The walk then stops one lock too early.

M and O are SCHED_OTHER tasks. W and Z are SCHED_DEADLINE tasks. Z has the earlier deadline. L1, L1' and L2 are rt_mutexes:

O M W Z

locks L2 locks L1 and L1'
blocks on L1'
rt_mutex_setprio(M, W)
M->dl.pi_se = &W->dl
blocks on L2
rt_mutex_setprio(O, M)
O->dl.pi_se = &W->dl
blocks on L1
rt_mutex_setprio(M, Z)
M->dl.pi_se = &Z->dl
chain walk at M:
keys equal, stops
times out on L1'
exits

O runs on W's parameters, with a later deadline than Z's, while Z waits for it. After W exits, O's next refill would read W's freed task_struct.

A deboost has the same effect. Take a deadline task that a waiter with an earlier deadline boosts, and that blocks on a second lock. It keeps its own deadline. When that waiter leaves, rt_mutex_setprio() makes the task its own donor again. Its keys stay equal. A policy change in __setscheduler_dl_pi() can also change the donor of a blocked task with no change of keys. rt_mutex_adjust_pi() then skips the walk.

Setting up the deadline tasks needs CAP_SYS_NICE. The timeout of a FUTEX_LOCK_PI needs no privilege. The Sashiko AI review of the sixth posting of this series found the deboost case.

Fix this by recording the donor in the waiter with the sort keys, in waiter_update_prio(). rt_waiter_up_to_date() compares both. The walk and rt_mutex_adjust_pi() use it. A new donor then takes the walk on to the next owner, and rt_mutex_setprio() gives that owner the new donor. The waiter's copy is only compared, never dereferenced. A task without a deadline priority is always its own donor, so its walks do not change.

A known limit remains. Two walks can overlap on a chain of three locks or more. The owners further down then keep the old donor until the first walk reaches them.

The case pi_chain_donor_leaves of deadline_bw_test, added later in this series, tests the missed boost. W leaves SCHED_DEADLINE there, in place of exiting. Without this patch, another deadline task gets no CPU time. On v7.4-rc2 the case passes. There, a blocked task that leaves SCHED_DEADLINE keeps its parameters, so O runs on W's.

Fixes 2279f540ea7d ("sched/deadline: Fix priority inheritance with multiple scheduling classes")
Cc [email protected] # v5.15+
---
 kernel/locking/rtmutex.c        | 22 ++++++++++++++++++++--
 kernel/locking/rtmutex_api.c    |  2 +-
 kernel/locking/rtmutex_common.h |  3 +++
 3 files changed, 24 insertions(+), 3 deletions(-)
kernel/locking/rtmutex.c +20 -2
index 5a9534c715b8..c78dfe9c93fc 100644
@@ -369,10 +369,12 @@ static __always_inline void
 waiter_update_prio(struct rt_mutex_waiter *waiter, struct task_struct *task)
 {
 	lockdep_assert_held(&waiter->lock->wait_lock);
+	lockdep_assert_held(&task->pi_lock);
 	lockdep_assert(RB_EMPTY_NODE(&waiter->tree.entry));
 
 	waiter->tree.prio = __waiter_prio(task);
 	waiter->tree.deadline = task->dl.deadline;
+	waiter->pi_se = task->dl.pi_se;
 }
 
 /*
@@ -433,6 +435,21 @@ static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left,
 	return 1;
 }
 
+/*
+ * Return true if @waiter is up to date with its task @task. Compare the
+ * sort keys and the deadline donor, which rt_mutex_setprio() copies from
+ * @task to the lock owner. A boost or a deboost of @task can change its
+ * donor and leave its keys as they were. The owner must then get the new
+ * donor: the old one can exit. The caller holds @task->pi_lock, which
+ * protects @task->dl.pi_se. @waiter->pi_se is never dereferenced.
+ */
+static __always_inline bool
+rt_waiter_up_to_date(struct rt_mutex_waiter *waiter, struct task_struct *task)
+{
+	return rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task)) &&
+	       waiter->pi_se == task->dl.pi_se;
+}
+
 static inline bool rt_mutex_steal(struct rt_mutex_waiter *waiter,
 				  struct rt_mutex_waiter *top_waiter)
 {
@@ -824,12 +841,13 @@ static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
 
 	/*
 	 * If the waiter priority is the same as the task priority
-	 * then there is no further priority adjustment necessary.  If
+	 * then there is no further priority adjustment necessary. The
+	 * task must also pass on the same deadline donor.  If
 	 * deadlock detection is off, we stop the chain walk. If its
 	 * enabled we continue, but stop the requeueing in the chain
 	 * walk.
 	 */
-	if (rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task))) {
+	if (rt_waiter_up_to_date(waiter, task)) {
 		if (!detect_deadlock)
 			goto out_unlock_pi;
 		else
kernel/locking/rtmutex_api.c +1 -1
index eb18b094473c..6bdbd36bac94 100644
@@ -510,7 +510,7 @@ void __sched rt_mutex_adjust_pi(struct task_struct *task)
 	raw_spin_lock_irqsave(&task->pi_lock, flags);
 
 	waiter = task->pi_blocked_on;
-	if (!waiter || rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task))) {
+	if (!waiter || rt_waiter_up_to_date(waiter, task)) {
 		raw_spin_unlock_irqrestore(&task->pi_lock, flags);
 		return;
 	}
kernel/locking/rtmutex_common.h +3 -0
index c38b7bdea7b3..c0f391c352e3 100644
@@ -43,6 +43,8 @@ struct rt_waiter_node {
  * @pi_tree:		node to enqueue into the mutex owner waiters tree
  * @task:		task reference to the blocked task
  * @lock:		Pointer to the rt_mutex on which the waiter blocks
+ * @pi_se:		The deadline donor of @task when @tree was last updated.
+ *			Only compared, never dereferenced.
  * @wake_state:		Wakeup state to use (TASK_NORMAL or TASK_RTLOCK_WAIT)
  * @ww_ctx:		WW context pointer
  *
@@ -54,6 +56,7 @@ struct rt_mutex_waiter {
 	struct rt_waiter_node	pi_tree;
 	struct task_struct	*task;
 	struct rt_mutex_base	*lock;
+	struct sched_dl_entity	*pi_se;
 	unsigned int		wake_state;
 	struct ww_acquire_ctx	*ww_ctx;
 };
Signature · 1 line
2.47.3
#23 lore raw

PATCH v7 10/40 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 found the first case in the second posting of this series, and the deboost in the third. 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
#26 lore raw

PATCH v7 11/40 sched/deadline: Reset the donor's runtime at a deboost in the class

In reply to Mathieu Desnoyers

A task boosted by a deadline waiter, its donor, runs on the donor's reservation. Commit 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic") uses the waiter's parameters "during the whole period it holds the pi-lock".

A boosted task that runs out of runtime is not throttled. replenish_dl_entity() refills it from the waiter's parameters: it adds the waiter's runtime, and moves the deadline by the waiter's period. From then on, the runtime and the deadline of the task are not those of its own reservation.

A task that leaves the class at its deboost does not keep them. "sched/deadline: Reset the deadline and the runtime with the parameters" resets them for a task with no parameters. For a task with parameters, they are cleared with the parameters at its 0-lag time.

But the boosted task can be a SCHED_DEADLINE task itself, when the waiter has an earlier deadline. It stays in the class at its deboost. rt_mutex_setprio() only resets dl.pi_se. enqueue_dl_entity() keeps a deadline that is ahead. So a task that was refilled keeps the waiter's runtime and deadline after the unlock. A task that sched_setattr() makes SCHED_DEADLINE while boosted ends its boost the same way.

In one period, the task can run what the waiter left on top of its own runtime. Other deadline tasks can miss deadlines.

Fix this by recording that refill in a new flag, dl_donor_refill. If the boost ends in the class with the flag set, start a new period at the deboost. The next enqueue is too late for a task blocked on another
rt_mutex: the chain walk copies its deadline into its waiter first.

The task can still hold a lock that another deadline task waits on. The new deadline can be later than that waiter's. rt_mutex_setprio() then boosts the task again.

A task that was not refilled keeps its runtime and its deadline. They are those of its own reservation. A new period there would give it a full runtime at every contended unlock.

The Sashiko AI review of the fourth posting found the sched_setattr() case. Four cases of deadline_bw_test, added later in this series, test this fix: deboost_in_class_resets_period, deboost_blocked_keeps_order, deboost_after_donor_refill and deboost_keeps_own_runtime.

In deboost_after_donor_refill, an owner of 5ms every 100ms runs 8ms with the lock. Its donor is a task of 2ms every 10ms. A deboost that tests the runtime against dl_runtime, in place of the flag, misses this
refill: it leaves less than dl_runtime. The owner then held less than 1ms after the unlock, in 3 guests of 3. With the flag, it holds its own 5ms.

Fixes 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
---
 include/linux/sched.h   |  6 ++++++
 kernel/sched/core.c     | 16 ++++++++++++---
 kernel/sched/deadline.c | 43 +++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h    | 10 ++++++++++
 kernel/sched/syscalls.c |  2 +-
 5 files changed, 73 insertions(+), 4 deletions(-)
include/linux/sched.h +6 -0
index e4f6323d7855..96b498f79484 100644
@@ -683,6 +683,11 @@ struct sched_dl_entity {
 	 * @dl_overrun tells if the task asked to be informed about runtime
 	 * overruns.
 	 *
+	 * @dl_donor_refill tells if a boosted task had its runtime refilled
+	 * from the parameters of its donor. Its runtime and deadline are
+	 * then not those of its own reservation. The end of the boost
+	 * clears it.
+	 *
 	 * @dl_server tells if this is a server entity.
 	 *
 	 * @dl_server_active tells if the dlserver is active(started).
@@ -711,6 +716,7 @@ struct sched_dl_entity {
 	unsigned int			dl_yielded        : 1;
 	unsigned int			dl_non_contending : 1;
 	unsigned int			dl_overrun	  : 1;
+	unsigned int			dl_donor_refill   : 1;
 	unsigned int			dl_server         : 1;
 	unsigned int			dl_server_active  : 1;
 	unsigned int			dl_defer	  : 1;
kernel/sched/core.c +13 -3
index 5ed660f099a5..a22df8b43a1a 100644
@@ -7834,16 +7834,26 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 				p->dl.pi_se = pi_task->dl.pi_se;
 				scope->flags |= ENQUEUE_REPLENISH;
 			} else {
-				p->dl.pi_se = &p->dl;
+				dl_deboost(&p->dl);
+				/*
+				 * dl_deboost() can start a new period. Its
+				 * deadline can then be after the top waiter's.
+				 * Boost the task again then.
+				 */
+				if (pi_task && dl_prio(pi_task->prio) &&
+				    dl_entity_preempt(&pi_task->dl, &p->dl)) {
+					p->dl.pi_se = pi_task->dl.pi_se;
+					scope->flags |= ENQUEUE_REPLENISH;
+				}
 			}
 		} else if (rt_prio(prio)) {
 			if (dl_prio(oldprio))
-				p->dl.pi_se = &p->dl;
+				dl_drop_boost(&p->dl);
 			if (oldprio < prio)
 				scope->flags |= ENQUEUE_HEAD;
 		} else {
 			if (dl_prio(oldprio))
-				p->dl.pi_se = &p->dl;
+				dl_drop_boost(&p->dl);
 			if (rt_prio(oldprio))
 				p->rt.timeout = 0;
 		}
kernel/sched/deadline.c +43 -0

84 lines not on this page · raw message

kernel/sched/sched.h +10 -0
index 92134ce326a4..d87296abec4c 100644
@@ -356,6 +356,16 @@ extern int  sched_dl_global_validate(void);
 extern void sched_dl_do_global(void);
 extern int  sched_dl_overflow(struct task_struct *p, int policy, const struct sched_attr *attr);
 extern void __setparam_dl(struct task_struct *p, const struct sched_attr *attr);
+#ifdef CONFIG_RT_MUTEXES
+extern void dl_deboost(struct sched_dl_entity *dl_se);
+
+/* End the boost of @dl_se. The caller holds the rq lock of its task. */
+static inline void dl_drop_boost(struct sched_dl_entity *dl_se)
+{
+	dl_se->pi_se = dl_se;
+	dl_se->dl_donor_refill = 0;
+}
+#endif
 extern void __getparam_dl(struct task_struct *p, struct sched_attr *attr, unsigned int flags);
 extern bool __checkparam_dl(const struct sched_attr *attr);
 extern bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr);
kernel/sched/syscalls.c +1 -1
index 9b04e77297ae..f346176f1ba1 100644
@@ -310,7 +310,7 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
 	 * the class. Drop its boost then, as rt_mutex_setprio() does.
 	 */
 	if (!dl_prio(newprio))
-		p->dl.pi_se = &p->dl;
+		dl_drop_boost(&p->dl);
 }
 #else /* !CONFIG_RT_MUTEXES */
 static inline void __setscheduler_dl_pi(int newprio, int policy,
Signature · 1 line
2.47.3
#29 lore raw

PATCH v7 12/40 sched/deadline: Replenish a throttled task boosted while asleep

In reply to Mathieu Desnoyers

A deadline task can be throttled as it blocks, with an rt_mutex held. Its replenishment timer is then armed. A deadline waiter can boost the task while it sleeps.

Commit feff2e65efd8 ("sched/deadline: Unthrottle PI boosted threads while enqueuing") lets a boost override the throttle. enqueue_task_dl() lifts the throttle of a boosted task, and dl_task_timer() ignores a boosted task. This covers a task that is enqueued while boosted. But a boost of a sleeping task does not enqueue it.

T is a SCHED_DEADLINE task that holds the rt_mutex L. W is a SCHED_DEADLINE task with an earlier deadline:

T W T's timer

uses up its runtime, sleeps
dl_throttled = 1
start_dl_timer()
pthread_mutex_timedlock(L)
rt_mutex_setprio(T, W)
T sleeps: no enqueue
dl_task_timer()
T is boosted: returns
times out
rt_mutex_setprio(T, NULL)
wakes up
enqueue_dl_entity()
dl_throttled: waits for the timer

The timer has already fired. T would never run again, not even to die of SIGKILL. Every later waiter on L would hang too. This was found by reading.

Fix this by returning early in dl_task_timer() only for a boosted task that is queued. A boosted task that sleeps then takes the existing path for a throttled task that is not queued: it is replenished.

The refill reads the parameters of the donor, from the timer. So this relies on two earlier patches. "sched/deadline: Do not replenish a boost from cleared parameters" keeps the refill from looping on cleared parameters. "rtmutex: Continue the chain walk when a waiter's deadline donor changes" keeps the donor pointer from going stale. After a deboost in the class, "sched/deadline: Reset the donor's runtime at a deboost in the class" starts a period of the task's own reservation.

The Sashiko AI review of the sixth posting of this series found this.

Fixes feff2e65efd8 ("sched/deadline: Unthrottle PI boosted threads while enqueuing")
---
 kernel/sched/deadline.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
kernel/sched/deadline.c +6 -3
index 989e7e7d3f8f..2b5a2a43addf 100644
@@ -1319,10 +1319,13 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
 	}
 
 	/*
-	 * The task might have been boosted by someone else and might be in the
-	 * boosting/deboosting path, its not throttled.
+	 * A boost overrides the throttle. enqueue_task_dl() lifts it when the
+	 * boost enqueues the task, or when the task wakes up boosted. So a
+	 * queued task needs nothing here. A boost of a sleeping task does not
+	 * enqueue it, and it can end before the wakeup. Nothing would lift the
+	 * throttle then. So let a sleeping task reach the !queued case below.
 	 */
-	if (is_dl_boosted(dl_se))
+	if (is_dl_boosted(dl_se) && task_on_rq_queued(p))
 		goto unlock;
 
 	/*
Signature · 1 line
2.47.3
#32 lore raw

PATCH v7 13/40 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 the third posting found the two cases with the 0-lag time ahead. deadline_bw_test, added later in this series, tests this in pi_former_owner_asleep and deboost_released_resets_period.

---
 kernel/sched/deadline.c | 8 ++++++++
 1 file changed, 8 insertions(+)
kernel/sched/deadline.c +8 -0
index 2b5a2a43addf..67cb1b1abbb8 100644
@@ -3640,6 +3640,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
#34 lore raw

PATCH v7 14/40 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 f346176f1ba1..8c72e751ff4e 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
#35 lore raw

PATCH v7 15/40 sched/deadline: Keep departing bandwidth across a root domain rebuild

In reply to Mathieu Desnoyers

A task that leaves SCHED_DEADLINE, or dies, keeps its bandwidth in total_bw until its 0-lag time. This keeps admission control on the safe side. Then inactive_task_timer() removes it from the root domain of the task's CPU. Two things break this:

- A rebuild of the accounting clears every root domain, then adds back the deadline tasks of the cpusets. It misses a task that left SCHED_DEADLINE, or a dead one. Their bandwidth is dropped, and the timer removes it again.
- A task that left SCHED_DEADLINE can also move to another root domain. The timer then takes total_bw from that one, which never had it.

Either way, a root domain admits deadline tasks beyond its capacity until the next rebuild.

Fix this with dl_departed_list. A departing task goes on it with the CPU it is on. A rebuild puts its bandwidth back in that CPU's root domain. The timer removes it from there, and so does sched_dl_overflow() for a task that returns to SCHED_DEADLINE.

Priority inheritance can boost a departed task back into the class, after it moved to another root domain. The boost cancels the timer and takes the task off the list. Keep the CPU recorded then. When the boost ends, the bandwidth is taken from the root domain that counts it, not from the one the task runs in. The pi_departed_moved case of deadline_bw_test, added later in this series, tests this.

A rebuild still drops the bandwidth of a task whose CPU is inactive, or that dies during the rebuild. Each task records a count of the rebuilds, dl_bw_gen, with its bandwidth. The timer removes nothing if a rebuild dropped the bandwidth since.

Make dl_cookie and dl_bw_visited() static: only deadline.c uses them.

deadline_rebuild_test, added later in this series, fails every time on v7.3 and v7.4-rc2 kernels. A one-CPU partition root admits two tasks of 600ms every second there, where it has room for one. It passes with this patch.

Fixes 387e31300b57 ("sched/deadline: Fix the update of the total -deadline utilization")
Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
---
 include/linux/sched.h          |  16 +++
 include/linux/sched/deadline.h |   5 +-
 kernel/cgroup/cpuset.c         |  11 +-
 kernel/sched/deadline.c        | 254 +++++++++++++++++++++++++++++----
 4 files changed, 249 insertions(+), 37 deletions(-)
include/linux/sched.h +16 -0
index 96b498f79484..063e49690658 100644
@@ -740,6 +740,22 @@ struct sched_dl_entity {
 	 */
 	struct hrtimer			inactive_timer;
 
+	/*
+	 * A task that leaves SCHED_DEADLINE, or dies, before its "0-lag
+	 * time" keeps its bandwidth in its root domain until the inactive
+	 * timer removes it. Meanwhile, @dl_departed_node links the task on
+	 * the list that a rebuild of the root domains' accounting reads.
+	 * @dl_departed_cpu is a CPU of the root domain that counts the
+	 * bandwidth. It stays recorded while priority inheritance boosts the
+	 * task back into the class. Otherwise @dl_departed_cpu is -1.
+	 *
+	 * @dl_bw_gen is the value of dl_bw_gen when the bandwidth was last
+	 * counted. If a rebuild dropped it since, there is nothing to remove.
+	 */
+	struct list_head		dl_departed_node;
+	int				dl_departed_cpu;
+	unsigned int			dl_bw_gen;
+
 	/*
 	 * Bits for DL-server functionality. Also see the comment near
 	 * dl_server_update().
include/linux/sched/deadline.h +1 -4
index 273538200a44..bdf39ac1d43d 100644
@@ -32,7 +32,7 @@ static inline bool dl_time_before(u64 a, u64 b)
 struct root_domain;
 extern void dl_add_task_root_domain(struct task_struct *p);
 extern void dl_clear_root_domain(struct root_domain *rd);
-extern void dl_clear_root_domain_cpu(int cpu);
+extern void dl_clear_root_domains(void);
 /*
  * Return whether moving DL task @p to @new_mask requires moving DL
  * bandwidth accounting between root domains. This helper is specific to
@@ -43,9 +43,6 @@ extern void dl_clear_root_domain_cpu(int cpu);
 extern bool dl_task_needs_bw_move(struct task_struct *p,
 				  const struct cpumask *new_mask);
 
-extern u64 dl_cookie;
-extern bool dl_bw_visited(int cpu, u64 cookie);
-
 static inline bool dl_server(struct sched_dl_entity *dl_se)
 {
 	return dl_se->dl_server;
kernel/cgroup/cpuset.c +2 -9
index 3219f927c35e..4159abfbbbb5 100644
@@ -985,21 +985,14 @@ void dl_rebuild_rd_accounting(void)
 {
 	struct cpuset *cs = NULL;
 	struct cgroup_subsys_state *pos_css;
-	int cpu;
-	u64 cookie = ++dl_cookie;
 
 	lockdep_assert_cpuset_lock_held();
 	lockdep_assert_cpus_held();
 	lockdep_assert_held(&sched_domains_mutex);
 
-	rcu_read_lock();
-
-	for_each_possible_cpu(cpu) {
-		if (dl_bw_visited(cpu, cookie))
-			continue;
+	dl_clear_root_domains();
 
-		dl_clear_root_domain_cpu(cpu);
-	}
+	rcu_read_lock();
 
 	cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
 
kernel/sched/deadline.c +230 -24

349 lines not on this page · raw message

Signature · 1 line
2.47.3
#36 lore raw

PATCH v7 16/40 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 and random_mix. The Sashiko AI review of the first posting 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 063e49690658..33e2d9492aa2 100644
@@ -711,6 +711,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;
@@ -724,6 +728,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 ddc92cf719ac..05be328571e9 100644
@@ -415,18 +415,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
@@ -495,6 +512,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);
 }
 
@@ -2885,6 +2910,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);
 }
@@ -4275,6 +4305,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
#37 lore raw

PATCH v7 17/40 sched/deadline: Rebuild the root domains' accounting from the task list

In reply to Mathieu Desnoyers

A rebuild of the root domains, as on CPU hotplug, clears their deadline accounting. dl_rebuild_rd_accounting() then adds back the deadline tasks of each cpuset. Without CONFIG_CPUSETS, it is a stub. So the first hotplug drops every deadline task's bandwidth, and their releases wrap total_bw around. In testing, a root domain admitted 9 tasks of 10ms every 100ms before a hotplug with deadline sleepers, and none after.

With cpusets, the rebuild skips a cpuset whose nr_deadline_tasks is 0. This count spares suspend and resume a costly walk of all tasks. An attach moves it by a tally taken in cpuset_can_attach(). A task that leaves the class between the tally and the move is taken off the old cpuset twice. Its count can then reach 0 with a deadline task in it. Every rebuild would then drop that task's bandwidth.

Fix both by walking the task list, with or without cpusets. The walk finds every deadline task, so the count and its hooks go. It holds tasklist_lock for reading, so fork and exit wait meanwhile. It takes the pi_lock of deadline tasks only. The walk that the count avoided took the pi_lock of every task. It leaves out an exited task with a dl_bw of 0. It also leaves out a zombie whose bandwidth an earlier rebuild dropped, as dl_clear_root_domains() does.

The walk visits every thread, and a suspend or a resume runs one rebuild for each CPU. So keep one count for the whole system,
dl_nr_bw_tasks: the number of tasks whose dl_bw is not 0. __setparam_dl() and __dl_clear_params() are the only places that change the dl_bw of a task, and they update the count. With a count of 0, the rebuild does not walk the task list, as Juri Lelli suggested.

In testing, a 64-vCPU guest held 10000 threads and no deadline task. A rebuild took 0.7 to 1.2 ms without the count, and 0.03 ms with it.

Without cpusets, a new dl_accounting_mutex keeps admissions out of a rebuild, as cpuset_mutex does with them.

Three hotplug cases of deadline_bw_test, added later in this series, fail without cpusets. With this patch, its five hotplug cases pass, in 4 VMs. Its death_zombie_hotplug case tests the zombie. The Sashiko AI reviews of v3, and of v4 before posting, found the wrong count and the exited tasks. Its review of v4 found the zombie.

Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
---
 include/linux/cpuset.h          |   9 --
 include/linux/sched/deadline.h  |  16 ++++
 kernel/cgroup/cgroup.c          |   3 -
 kernel/cgroup/cpuset-internal.h |   6 +-
 kernel/cgroup/cpuset.c          |  67 +-------------
 kernel/sched/deadline.c         | 154 ++++++++++++++++++++++++++------
 kernel/sched/syscalls.c         |  14 +--
 kernel/sched/topology.c         |   8 ++
 8 files changed, 163 insertions(+), 114 deletions(-)
include/linux/cpuset.h +0 -9
index 914983387e95..db1cc2fc0324 100644
@@ -72,8 +72,6 @@ extern int cpuset_init(void);
 extern void cpuset_init_smp(void);
 extern void cpuset_force_rebuild(void);
 extern void cpuset_update_active_cpus(void);
-extern void inc_dl_tasks_cs(struct task_struct *task);
-extern void dec_dl_tasks_cs(struct task_struct *task);
 extern void cpuset_lock(void);
 extern void cpuset_unlock(void);
 extern void lockdep_assert_cpuset_lock_held(void);
@@ -129,7 +127,6 @@ static inline int cpuset_do_page_mem_spread(void)
 
 extern bool current_cpuset_is_being_rebound(void);
 
-extern void dl_rebuild_rd_accounting(void);
 extern void rebuild_sched_domains(void);
 
 extern void cpuset_print_current_mems_allowed(void);
@@ -194,8 +191,6 @@ static inline void cpuset_update_active_cpus(void)
 	partition_sched_domains(1, NULL, NULL);
 }
 
-static inline void inc_dl_tasks_cs(struct task_struct *task) { }
-static inline void dec_dl_tasks_cs(struct task_struct *task) { }
 static inline void cpuset_lock(void) { }
 static inline void cpuset_unlock(void) { }
 static inline void lockdep_assert_cpuset_lock_held(void) { }
@@ -273,10 +268,6 @@ static inline bool current_cpuset_is_being_rebound(void)
 	return false;
 }
 
-static inline void dl_rebuild_rd_accounting(void)
-{
-}
-
 static inline void rebuild_sched_domains(void)
 {
 	guard(cpus_read_lock)();
include/linux/sched/deadline.h +16 -0
index bdf39ac1d43d..60be226699bb 100644
@@ -33,6 +33,22 @@ struct root_domain;
 extern void dl_add_task_root_domain(struct task_struct *p);
 extern void dl_clear_root_domain(struct root_domain *rd);
 extern void dl_clear_root_domains(void);
+extern void dl_rebuild_rd_accounting(void);
+/*
+ * Keep a rebuild of the root domains' accounting and an admission of
+ * bandwidth from running at the same time. With cpusets, cpuset_mutex
+ * does it, since every rebuild comes from the cpuset code. Without
+ * cpusets, dl_accounting_lock() takes a mutex of its own.
+ */
+#ifdef CONFIG_CPUSETS
+static inline void dl_accounting_lock(void) { }
+static inline void dl_accounting_unlock(void) { }
+static inline void lockdep_assert_dl_accounting_held(void) { }
+#else
+extern void dl_accounting_lock(void);
+extern void dl_accounting_unlock(void);
+extern void lockdep_assert_dl_accounting_held(void);
+#endif
 /*
  * Return whether moving DL task @p to @new_mask requires moving DL
  * bandwidth accounting between root domains. This helper is specific to
kernel/cgroup/cgroup.c +0 -3
index a284225f8dc9..2cfa770c2dcb 100644
@@ -7240,9 +7240,6 @@ static void do_cgroup_task_dead(struct task_struct *tsk)
 	if (thread_group_leader(tsk) && atomic_read(&tsk->signal->live))
 		list_add_tail(&tsk->cg_list, &cset->dying_tasks);
 
-	if (dl_task(tsk))
-		dec_dl_tasks_cs(tsk);
-
 	WARN_ON_ONCE(cgroup_task_frozen(tsk));
 	if (unlikely(!(tsk->flags & PF_KTHREAD) &&
 		     test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
kernel/cgroup/cpuset-internal.h +1 -5
index 1ba94ffaff9d..bf847953c78d 100644
@@ -166,11 +166,7 @@ struct cpuset {
 	 */
 	bool remote_partition_updating;
 
-	/*
-	 * number of SCHED_DEADLINE tasks attached to this cpuset, so that we
-	 * know when to rebuild associated root domain bandwidth information.
-	 */
-	atomic_t nr_deadline_tasks;
+	/* Number of SCHED_DEADLINE tasks the attach in progress moves here. */
 	int nr_migrate_dl_tasks;
 	/* DL bandwidth that needs destination reservation for this attach. */
 	u64 sum_migrate_dl_bw;
kernel/cgroup/cpuset.c +1 -66

91 lines not on this page · raw message

kernel/sched/deadline.c +128 -26

250 lines not on this page · raw message

kernel/sched/syscalls.c +9 -5
index 8c72e751ff4e..4c013caa2471 100644
@@ -568,6 +568,7 @@ int __sched_setscheduler(struct task_struct *p,
 	if (pi && (dl_policy(policy) || dl_policy(p->policy))) {
 		cpuset_locked = true;
 		cpuset_lock();
+		dl_accounting_lock();
 	}
 
 	/*
@@ -596,9 +597,7 @@ int __sched_setscheduler(struct task_struct *p,
 	 * 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.
+	 * one in the class: its bandwidth went at its last schedule.
 	 */
 	if ((dl_policy(policy) || dl_task(p)) && p->exit_state) {
 		retval = -ESRCH;
@@ -669,6 +668,7 @@ int __sched_setscheduler(struct task_struct *p,
 		policy = oldpolicy = -1;
 		task_rq_unlock(rq, p, &rf);
 		if (cpuset_locked) {
+			dl_accounting_unlock();
 			cpuset_unlock();
 			cpuset_locked = false;
 		}
@@ -779,8 +779,10 @@ int __sched_setscheduler(struct task_struct *p,
 	task_rq_unlock(rq, p, &rf);
 
 	if (pi) {
-		if (cpuset_locked)
+		if (cpuset_locked) {
+			dl_accounting_unlock();
 			cpuset_unlock();
+		}
 		rt_mutex_adjust_pi(p);
 	}
 
@@ -792,8 +794,10 @@ int __sched_setscheduler(struct task_struct *p,
 
 unlock:
 	task_rq_unlock(rq, p, &rf);
-	if (cpuset_locked)
+	if (cpuset_locked) {
+		dl_accounting_unlock();
 		cpuset_unlock();
+	}
 	return retval;
 }
 
kernel/sched/topology.c +8 -0
index 9d3a1b8dd393..35e56a45c238 100644
@@ -3528,7 +3528,15 @@ static void partition_sched_domains_locked(int ndoms_new, cpumask_var_t doms_new
 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
 			     struct sched_domain_attr *dattr_new)
 {
+	/*
+	 * The root domains attached here count no task's bandwidth until
+	 * dl_rebuild_rd_accounting() at the end. No admission of bandwidth may
+	 * run meanwhile. With cpusets, the callers hold cpuset_mutex, which
+	 * keeps admissions out. Without cpusets, dl_accounting_lock() does it.
+	 */
+	dl_accounting_lock();
 	sched_domains_mutex_lock();
 	partition_sched_domains_locked(ndoms_new, doms_new, dattr_new);
 	sched_domains_mutex_unlock();
+	dl_accounting_unlock();
 }
Signature · 1 line
2.47.3
#38 lore raw

PATCH v7 18/40 sched/deadline: Record the root domain holding a task's bandwidth

In reply to Mathieu Desnoyers

Admission, moves and releases of a deadline task's bandwidth find the root domain that counts it from the CPU the task is on. That CPU can be in another root domain. Two cases show it.

Commit 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets") moves a deadline task's bandwidth in two halves. cpuset_can_attach() reserves it in the destination. set_cpus_allowed_dl() frees it in the root domain of the task's runqueue. Since commit 5dd74441cbf4 ("cgroup/cpuset: Reserve DL bandwidth only for root-domain moves"), both halves move nothing when that root domain overlaps the destination. But a sleeping task stays on the CPU it last ran on. So a sleeping task moved to a partition and back leaves its bandwidth in the partition:

admin task T

makes P a partition root of CPU 3
CPU 3 is now in root domain B
CPUs 0-2 are in root domain A
sched_setattr(SCHED_DEADLINE)
A: total_bw += bw of T
runs on CPU 0, then sleeps
echo T > P/cgroup.procs
cpuset_can_attach()
dl_task_needs_bw_move(): true,
A does not overlap P
B: total_bw += bw of T
set_cpus_allowed_dl()
dl_task_needs_bw_move(): true
A: total_bw -= bw of T
still asleep on CPU 0
echo T > cgroup.procs of the root cgroup
cpuset_can_attach()
dl_task_needs_bw_move(): false,
A overlaps the root cpuset
set_cpus_allowed_dl()
dl_task_needs_bw_move(): false
kill -9 T
wakes up on a CPU of A exits
A: total_bw -= bw of T

B keeps the bandwidth of T. A does not count T while T is in A, so A admits beyond its capacity. After T exits, the total_bw of A is short by the bandwidth of T, and can underflow.

The second case needs no move:

1. A deadline task T sleeps on a CPU of root domain A.
2. That CPU goes offline, and joins the default root domain.
3. The rebuild counts T in A, the root domain of its cpuset.
4. sched_setattr() takes the sleeping T out of SCHED_DEADLINE.
5. The release takes the bandwidth from the root domain of the CPU T is on: the default one.

A keeps the bandwidth of T until the next rebuild, and refuses deadline tasks that would fit.

The first case was reproduced on v7.4-rc2. The second needs the earlier patches of this series: without "sched/deadline: Release the bandwidth of a task that leaves the class asleep", nothing releases the bandwidth of that sleeping task. The hotplug_sleeper_switched case of deadline_bw_test, added later in this series, tests it. Without this patch and with the CPU still offline, A admitted 63 tasks of 10% where it had room for 66, in 3 guests of 3.

Fix this by recording, in dl_bw_cpu, a CPU of the root domain that counts the bandwidth. The record replaces dl_departed_cpu. It is used as follows:
- Each site that counts the bandwidth sets the record.
- Each release or move reads it. The release clears it.
- If dl_bw_gen shows that a rebuild dropped the bandwidth, nothing is taken back. set_cpus_allowed_dl() makes that test under dl_departed_lock, so that a rebuild cannot change dl_bw_gen meanwhile.
- A move skips a bandwidth of 0, and does not update its record. So sched_dl_overflow() uses the CPU the task is on for it. The move_zero_bw case of deadline_bw_test, added later in this series, tests this.
- A rebuild drops departed bandwidth whose CPU is inactive. So a departing task records the CPU it departs from, if that CPU is active and in the same root domain.

The affinity check of sched_setaffinity() reads the record too. A task moved asleep is still on a CPU of the root domain it left. Testing that root domain let a new mask take the task out of the one that counts it. The affinity_moved_asleep case tests this.

A move now leaves out a sugov kthread and a task boosted into the class with no bandwidth of its own. The rebuild leaves them out too: no root domain counts theirs. A move would take a sugov kthread's bandwidth from a root domain that never held it.

Weiheng Qiu reported the moved sleeper, and Juri Lelli analysed it. His fix, linked below, took the first active CPU of the task's mask. A mask can have none during CPU hotplug. Tip dropped the fix after a sugov kthread hit its BUG_ON() there. The Sashiko AI reviews of this series found the other cases.

Fixes 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets")
---
 include/linux/sched.h   |  10 +-
 kernel/sched/deadline.c | 247 +++++++++++++++++++++++++++-------------
 kernel/sched/syscalls.c |  11 +-
 3 files changed, 187 insertions(+), 81 deletions(-)
include/linux/sched.h +6 -4
index 33e2d9492aa2..4a1cb869facc 100644
@@ -750,15 +750,17 @@ struct sched_dl_entity {
 	 * time" keeps its bandwidth in its root domain until the inactive
 	 * timer removes it. Meanwhile, @dl_departed_node links the task on
 	 * the list that a rebuild of the root domains' accounting reads.
-	 * @dl_departed_cpu is a CPU of the root domain that counts the
-	 * bandwidth. It stays recorded while priority inheritance boosts the
-	 * task back into the class. Otherwise @dl_departed_cpu is -1.
+	 * Otherwise that node is empty.
+	 *
+	 * @dl_bw_cpu is a CPU of the root domain that counts the bandwidth,
+	 * or -1. Each site that counts the bandwidth sets it. Each site that
+	 * removes or moves the bandwidth reads it.
 	 *
 	 * @dl_bw_gen is the value of dl_bw_gen when the bandwidth was last
 	 * counted. If a rebuild dropped it since, there is nothing to remove.
 	 */
 	struct list_head		dl_departed_node;
-	int				dl_departed_cpu;
+	int				dl_bw_cpu;
 	unsigned int			dl_bw_gen;
 
 	/*
kernel/sched/deadline.c +171 -76

459 lines not on this page · raw message

kernel/sched/syscalls.c +10 -1
index 4c013caa2471..306cd8d32173 100644
@@ -1185,6 +1185,8 @@ SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
 
 int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
 {
+	unsigned int cpu;
+
 	/*
 	 * If the task isn't a deadline task or admission control is
 	 * disabled then we don't care about affinity changes.
@@ -1204,9 +1206,16 @@ int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
 	 * if admission test is enabled, we only admit -deadline
 	 * tasks allowed to run on all the CPUs in the task's
 	 * root_domain.
+	 *
+	 * That is the root domain that counts the bandwidth of the task:
+	 * the one of the CPU recorded with it. A task moved asleep to
+	 * another cpuset is still on a CPU of the root domain it left. A
+	 * bandwidth of 0 is counted nowhere, and no move updates its
+	 * record: use the CPU the task is on.
 	 */
+	cpu = READ_ONCE(p->dl.dl_bw) ? dl_task_root_domain_cpu(p) : task_cpu(p);
 	guard(rcu)();
-	if (!cpumask_subset(task_rq(p)->rd->span, mask))
+	if (!cpumask_subset(cpu_rq(cpu)->rd->span, mask))
 		return -EBUSY;
 
 	return 0;
Signature · 1 line
2.47.3
#41 lore raw

PATCH v7 19/40 sched/deadline: Leave a dying task out of a rebuild of the accounting

In reply to Mathieu Desnoyers

A rebuild of the root domains' accounting takes the pi_lock of each deadline task, not its rq lock. A dying task past its 0-lag time releases its bandwidth at its last schedule. It holds its rq lock there, not its pi_lock. Then it clears dl_bw. The rebuild can find the task between the two steps.

In this diagram, T is a deadline task that exits on CPU 0 past its 0-lag time. bw is its dl_bw. CPU 1 rebuilds the accounting:

CPU 0 (T) CPU 1 (rebuild)

do_task_dead(): TASK_DEAD, under pi_lock
__schedule(): T's rq lock taken

    task_non_contending(T)
      dl_task_release_bw(T)
        total_bw -= bw
        dl_bw_gen recorded
        record cleared
                                             dl_rebuild_rd_accounting()
                                               dl_clear_root_domains()
                                                 dl_bw_gen++
                                                 total_bw reset
                                               dl_add_task_root_domain(T)
                                                 T's pi_lock taken
                                                 dl_bw != 0, dl_bw_gen old
                                                 total_bw += bw
      __dl_clear_params(T): dl_bw = 0

dl_bw_gen does not help, since the release came before the rebuild. The rebuild would count a bandwidth that nothing releases again. The root domain would then refuse deadline tasks it has room for, until the next rebuild.

Fix this with the record of the bandwidth, dl_bw_cpu. The release clears it under dl_departed_lock, which the walk holds. So leave out a dead task with no record. A dead task with a record has not reached its last schedule. The walk counts it as a live task. That schedule then releases the bandwidth, or puts the task on the departed list. A dead task on the departed list keeps its bandwidth until its timer, and the rebuild counts it as before.

The Sashiko AI review of v2 of this series found this window. Its review of v4 found a gap in the first version of this fix. That version also left out a task between TASK_DEAD and its last schedule, with its 0-lag time ahead.

This patch completes "sched/deadline: Rebuild the root domains' accounting from the task list". The walk of that patch finds exiting tasks, which the cpuset iterator skipped. The fix needs the record that "sched/deadline: Record the root domain holding a task's bandwidth" adds. The three go to stable together.

Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
---
 kernel/sched/deadline.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
kernel/sched/deadline.c +11 -0
index 01fbbd02cf8d..779acb9836dc 100644
@@ -3787,6 +3787,17 @@ void dl_add_task_root_domain(struct task_struct *p)
 		if (recorded < 0 || !cpu_active(recorded))
 			goto unlock;
 		cpu = recorded;
+	} else if (READ_ONCE(p->__state) == TASK_DEAD && p->dl.dl_bw_cpu < 0) {
+		/*
+		 * Count nothing for a dead task with no record. Its last
+		 * schedule released the bandwidth under its rq lock, and has
+		 * not cleared dl_bw yet. The release clears the record under
+		 * dl_departed_lock, which this walk holds. A dead task with a
+		 * record has not reached its last schedule. Count it as a
+		 * live task. That schedule then releases what the walk
+		 * counted, or puts the task on the departed list.
+		 */
+		goto unlock;
 	}
 	rq = cpu_rq(cpu);
 	dl_b = &rq->rd->dl_bw;
Signature · 1 line
2.47.3
#42 lore raw

PATCH v7 20/40 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 a22df8b43a1a..c77cae5d1be1 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 d87296abec4c..fd6d36b6b1e2 100644
@@ -2982,6 +2982,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 306cd8d32173..4f47b17151ed 100644
@@ -1238,11 +1238,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)
@@ -1271,6 +1267,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
#43 lore raw

PATCH v7 21/40 sched/deadline: Move a task's bandwidth only where room was made

In reply to Mathieu Desnoyers

Commit 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets") moves a deadline task's bandwidth in two halves. cpuset_can_attach() reserves it in the destination root domain. set_cpus_allowed_dl() then frees it in the source, when the task's affinity changes. Its comment relies on the first half: "We already made space for us in the destination domain".

But set_cpus_allowed_dl() runs on every change of affinity. It frees the bandwidth whenever the new mask leaves the task's root domain, with or without a reservation. sched_setaffinity() gets there too, if the task's cpuset spans two root domains. With isolcpus="domain", any cpuset that is not a partition root can hold isolated CPUs and other CPUs, which are in two root domains. With admission control on, __sched_setaffinity() refuses such a mask. With sched_rt_runtime_us at -1, nothing refuses it. The bandwidth is then freed in the source and added nowhere: no root domain counts it any more. The destination would underflow when the task leaves.

Fix this by flagging the affinity changes that come with a reservation, as SCA_DL_BW_RESERVED. cpuset_attach_task() sets it, through the new set_cpus_allowed_bw_reserved(). set_cpus_allowed_dl() moves the bandwidth only with the flag. Without it, the bandwidth stays where it is counted, until the next rebuild of the accounting counts it anew. The flag also skips the early exit of __set_cpus_allowed_ptr_locked() for a mask that does not change. The task may already have that mask from a change that moved no bandwidth, such as a sched_setaffinity() without admission control.

The attach still flags a task that sched_setattr() made a deadline task after cpuset_can_attach(), with nothing reserved for it. "sched: Make deadline policy and affinity changes wait for a cpuset attach" fixes that.

No case of deadline_bw_test fails before this patch and passes with it. no_admission_affinity_moves, added later in this series, covers this path together with "sched/deadline: Move a task's bandwidth to the root domain it runs in".

Fixes 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets")
---
 include/linux/sched.h   |  2 ++
 kernel/cgroup/cpuset.c  | 13 ++++++++++++-
 kernel/sched/core.c     | 26 +++++++++++++++++++++++++-
 kernel/sched/deadline.c | 14 +++++++++-----
 kernel/sched/sched.h    |  2 ++
 5 files changed, 50 insertions(+), 7 deletions(-)
include/linux/sched.h +2 -0
index 4a1cb869facc..dee4d4df624c 100644
@@ -1972,6 +1972,8 @@ extern void set_cpus_allowed_force(struct task_struct *p, const struct cpumask *
  * Return: zero if successful, or a negative error code
  */
 extern int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask);
+extern int set_cpus_allowed_bw_reserved(struct task_struct *p,
+					const struct cpumask *new_mask);
 extern int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, int node);
 extern void release_user_cpus_ptr(struct task_struct *p);
 extern int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask);
kernel/cgroup/cpuset.c +12 -1
index 7628cf77bdfd..194a438e25c3 100644
@@ -3261,6 +3261,7 @@ static cpumask_var_t cpus_attach;
 
 static void cpuset_attach_task(struct cpuset *cs, struct task_struct *task)
 {
+	bool reserved = false;
 	struct mm_struct *mm;
 
 	lockdep_assert_cpuset_lock_held();
@@ -3270,11 +3271,21 @@ static void cpuset_attach_task(struct cpuset *cs, struct task_struct *task)
 	else
 		cpumask_andnot(cpus_attach, task_cpu_possible_mask(task),
 			       subpartitions_cpus);
+	/*
+	 * cpuset_reserve_dl_bw() made room in @cs for the bandwidth of the
+	 * deadline tasks that cpuset_can_attach() counted. Flag the move, so
+	 * that the bandwidth of this task moves with it.
+	 */
+	if (dl_task(task) && dl_task_needs_bw_move(task, cs->effective_cpus))
+		reserved = true;
 	/*
 	 * can_attach beforehand should guarantee that this doesn't
 	 * fail.  TODO: have a better way to handle failure here
 	 */
-	WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
+	if (reserved)
+		WARN_ON_ONCE(set_cpus_allowed_bw_reserved(task, cpus_attach));
+	else
+		WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
 
 	if (cpuset_v2() && !attach_ctx.mems_updated)
 		return;
kernel/sched/core.c +25 -1
index c77cae5d1be1..2a964286a7cd 100644
@@ -3207,7 +3207,15 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
 	}
 
 	if (!(ctx->flags & SCA_MIGRATE_ENABLE)) {
-		if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) {
+		/*
+		 * A move with SCA_DL_BW_RESERVED must reach
+		 * set_cpus_allowed_dl(), even if the mask does not change.
+		 * @p may have this mask from a change that moved no
+		 * bandwidth, such as sched_setaffinity() without admission
+		 * control.
+		 */
+		if (cpumask_equal(&p->cpus_mask, ctx->new_mask) &&
+		    !(ctx->flags & SCA_DL_BW_RESERVED)) {
 			if (ctx->flags & SCA_USER)
 				swap(p->user_cpus_ptr, ctx->user_mask);
 			goto out;
@@ -3280,6 +3288,22 @@ int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
 }
 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
 
+/*
+ * Like set_cpus_allowed_ptr(), for a caller that has made room for the
+ * deadline bandwidth of @p in the root domain of @new_mask. Move that
+ * bandwidth there with @p. Return 0 on success, or a negative error
+ * code.
+ */
+int set_cpus_allowed_bw_reserved(struct task_struct *p, const struct cpumask *new_mask)
+{
+	struct affinity_context ac = {
+		.new_mask  = new_mask,
+		.flags     = SCA_DL_BW_RESERVED,
+	};
+
+	return __set_cpus_allowed_ptr(p, &ac);
+}
+
 /*
  * Change a given task's CPU affinity to the intersection of its current
  * affinity mask and @subset_mask, writing the resulting mask to @new_mask.
kernel/sched/deadline.c +9 -5
index 779acb9836dc..aba03fd6b381 100644
@@ -3622,12 +3622,16 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 	WARN_ON_ONCE(!dl_task(p));
 
 	/*
-	 * Migrating a SCHED_DEADLINE task between exclusive
-	 * cpusets (different root_domains) entails a bandwidth
-	 * update. We already made space for us in the destination
-	 * domain (see cpuset_can_attach()).
+	 * Migrating a SCHED_DEADLINE task between exclusive cpusets
+	 * (different root_domains) entails a bandwidth update. Move the
+	 * bandwidth only if the caller made room for it in the destination,
+	 * as SCA_DL_BW_RESERVED says. Only cpuset_attach_task() sets it.
+	 * Otherwise, the bandwidth stays where it is counted, until the next
+	 * rebuild of the accounting. Moving it without room would leave no
+	 * root domain counting it.
 	 */
-	if (dl_task_needs_bw_move(p, ctx->new_mask)) {
+	if ((ctx->flags & SCA_DL_BW_RESERVED) &&
+	    dl_task_needs_bw_move(p, ctx->new_mask)) {
 		unsigned int src_cpu = dl_task_root_domain_cpu(p);
 		struct dl_bw *src_dl_b = &cpu_rq(src_cpu)->rd->dl_bw;
 		unsigned int cpu;
kernel/sched/sched.h +2 -0
index fd6d36b6b1e2..9e3ca69abc36 100644
@@ -2983,6 +2983,8 @@ extern struct task_struct *pick_task_idle(struct rq *rq, struct rq_flags *rf);
 #define SCA_MIGRATE_ENABLE	0x04
 #define SCA_USER		0x08
 #define SCA_DL_CHECK		0x10
+/* The caller made room for the deadline bandwidth in the new root domain. */
+#define SCA_DL_BW_RESERVED	0x20
 
 extern void update_group_capacity(struct sched_domain *sd, int cpu);
 
Signature · 1 line
2.47.3
#44 lore raw

PATCH v7 22/40 cgroup/cpuset: Wait for an attach before rebuilding the sched domains

In reply to Mathieu Desnoyers

cpuset_can_attach() reserves the bandwidth of the deadline tasks it moves in the destination root domain. cpuset_attach() moves their bandwidth later, on the strength of that reservation.

Commit 75f7a25ec6bb ("cgroup/cpuset: Prevent race between task attach and cpuset state change") lets cpuset_attach() rely on what cpuset_can_attach() set up. The writes of cpus, mems and cpus.partition wait for an attach in progress, in wait_attach_done_lock(). CPU hotplug cannot run in between either: it takes cpus_write_lock, and the attach holds cpus_read_lock throughout.

But a rebuild of the sched domains does not wait. A write of sched_rt_runtime_us and the energy model rebuild them through rebuild_sched_domains(). The cgroup v1 writes of sched_load_balance and sched_relax_domain_level, and hk_sd_workfn(), use cpuset_full_lock().

In this example, a rebuild drops the reservation. T is a deadline task asleep in root domain R. Thread A moves T to a partition root P, which has a root domain of its own. Thread B writes sched_rt_runtime_us:

A B

cpuset_can_attach()
takes cpuset_mutex
cpuset_reserve_dl_bw()
P's total_bw += T's bandwidth
drops cpuset_mutex
rebuild_sched_domains()
takes cpuset_mutex dl_rebuild_rd_accounting()
clears R's and P's total_bw counts T in R (not moved yet)
drops cpuset_mutex
cpuset_attach()
takes cpuset_mutex
cpuset_attach_task(T)
set_cpus_allowed_dl(T)
R's total_bw -= T's bandwidth
records a CPU of P

P now lacks the bandwidth of T, and admits deadline tasks beyond its capacity. When T leaves P, P's total_bw underflows. In testing, the race left a destination admitting 3 tasks of 10% too many, or P admitting no task at all.

Fix this by waiting for an attach in progress in rebuild_sched_domains_cpuslocked() and in cpuset_full_lock(). The latter then takes its locks in the order of the writes of cpus and cpus.partition. A rebuild from CPU hotplug finds no attach in progress. The online, offline and kill of a cpuset never wait: they hold cgroup_mutex, which the attach holds throughout.

The move_vs_rebuild case of deadline_bw_test, added later in this series, tests this race. Without this patch, it fails in 5 of 8 VMs with 8 CPUs. With it, the case passes in 8 of 8. The next patch needs this wait too: without it, it would give back a reservation that a rebuild dropped already.

Found by the Sashiko AI reviews of v2 (the race) and v3 (the cgroup v1 writes) of this series.

Fixes 2ef269ef1ac0 ("cgroup/cpuset: Free DL BW in case can_attach() fails")
---
 kernel/cgroup/cpuset.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
kernel/cgroup/cpuset.c +13 -3
index 194a438e25c3..51b6be460794 100644
@@ -296,17 +296,20 @@ void lockdep_assert_cpuset_lock_held(void)
 	lockdep_assert_held(&cpuset_mutex);
 }
 
+static void wait_attach_done_lock(void) __acquires(&cpuset_mutex);
+
 /**
  * cpuset_full_lock - Acquire full protection for cpuset modification
  *
  * Takes both CPU hotplug read lock (cpus_read_lock()) and cpuset mutex
- * to safely modify cpuset data.
+ * to safely modify cpuset data. Waits for an attach in progress before
+ * it takes cpuset mutex.
  */
 void cpuset_full_lock(void)
 {
 	mutex_lock(&cpuset_top_mutex);
 	cpus_read_lock();
-	mutex_lock(&cpuset_mutex);
+	wait_attach_done_lock();
 }
 
 void cpuset_full_unlock(void)
@@ -1005,7 +1008,14 @@ void rebuild_sched_domains_locked(void)
 
 static void rebuild_sched_domains_cpuslocked(void)
 {
-	mutex_lock(&cpuset_mutex);
+	/*
+	 * Wait for an attach in progress. cpuset_can_attach() has reserved
+	 * the deadline bandwidth of the moving tasks in their new root
+	 * domain, and cpuset_attach() moves it on the strength of that
+	 * reservation. A rebuild of the accounting in between would drop
+	 * the reservation.
+	 */
+	wait_attach_done_lock();
 	rebuild_sched_domains_locked();
 	mutex_unlock(&cpuset_mutex);
 }
Signature · 1 line
2.47.3
#45 lore raw

PATCH v7 23/40 sched: Make deadline policy and affinity changes wait for a cpuset attach

In reply to Mathieu Desnoyers

__sched_setscheduler() takes cpuset_mutex for a change that involves SCHED_DEADLINE. Commit 710da3c8ea7d ("sched/core: Prevent race condition between cpuset and __sched_setscheduler()") added that lock. It keeps the cpuset code from changing the root domains while the deadline admission test runs.

But a cpuset attach drops cpuset_mutex between cpuset_can_attach() and cpuset_attach(). A sched_setattr() can run in between. Take a process in the root cgroup. It has deadline threads, and a thread T that is not a deadline task. The process is moved into a partition root P:

echo PID > P/cgroup.procs sched_setattr(T, SCHED_DEADLINE)

cpuset_can_attach()
lock cpuset_mutex
reserve room in P for the deadline
threads: T is not one of them
unlock cpuset_mutex
lock cpuset_mutex admit T in the root domain it
is still in
unlock cpuset_mutex
cpuset_attach()
lock cpuset_mutex
move T to P, where nothing is
reserved for it
unlock cpuset_mutex

The attach still moves the bandwidth of T. It is freed in the root domain T left, and P has no room reserved to count it. No root domain counts it any more, and P can admit deadline tasks beyond its capacity.

In testing, P was a one-CPU partition root, which admits 95%. The process had two sleeping deadline threads of 30% each, and sched_setattr() made T a deadline task of 40%. The move and the sched_setattr() both succeeded, with no room in P for the three. With threads of 20% and a T of 30%, P then admitted five more tasks of 10%, where it had room for two.

Fix this by taking cpuset_mutex in __sched_setscheduler() only when no attach is in progress. cpuset_partition_write() and cpuset_hotplug_update_tasks() already wait for an attach that way. A deadline policy change then comes before the attach, and is part of its reservation, or after it.

With this patch, and no room in P for the three, the two never both succeed. If the sched_setattr() comes first, the move is refused with EBUSY. If it comes after, T has its new CPUs and has not run on them. The call is then refused with EPERM, as for any sleeping task moved to another partition.

sched_setaffinity() on a deadline task can run in between as well. A later patch of this series reserves the bandwidth of the task on one CPU of its new affinity, and records that CPU with the task. It is "cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to". A new affinity in between could leave that CPU out. cpuset_attach() would then move no bandwidth, and the task would stay counted in the root domain it left. So sched_setaffinity() waits the same way when the task is a deadline task.

sched_setaffinity() tests the policy with no lock, before it decides to wait. A sched_setattr() can make the task a deadline task right after that test. So test the policy again under the runqueue lock, where the mask changes. If the task is a deadline task there and the caller did not wait, the call starts over, and waits. The new SCA_DL_NOWAIT flag asks for that test. After a race with a cpuset update, __sched_setaffinity() sets the mask a second time, within the cpuset. That second change waits for an attach too, so that the test cannot skip it.

For user-space, these calls now wait until a cpuset attach in progress ends:

- sched_setattr() and sched_setscheduler() on a deadline task
- sched_setattr() that makes a task a deadline task
- sched_setaffinity() on a deadline task

The attach can be the move of any process. The wait is not
interruptible: a signal does not end it. Outside that window, the results of these calls are unchanged.

Three cases of deadline_bw_test, added later in this series, test this. move_became_deadline and move_became_deadline_no_room fail without this patch. move_affinity_changed fails once the bandwidth is reserved on one CPU, if sched_setaffinity() does not wait.

A fourth case, move_affinity_became_deadline, covers the second test of the policy. Its window is a few instructions wide. A delay added after the first test, for testing only, widens it. The case then fails without the second test in 3 guests of 3. It passes with it.

Fixes 710da3c8ea7d ("sched/core: Prevent race condition between cpuset and __sched_setscheduler()")
---
 include/linux/cpuset.h  |  2 ++
 kernel/cgroup/cpuset.c  | 11 +++++++++
 kernel/sched/core.c     | 10 ++++++++
 kernel/sched/sched.h    |  2 ++
 kernel/sched/syscalls.c | 54 ++++++++++++++++++++++++++++++++++-------
 5 files changed, 70 insertions(+), 9 deletions(-)
include/linux/cpuset.h +2 -0
index db1cc2fc0324..5d0c01a25354 100644
@@ -73,6 +73,7 @@ extern void cpuset_init_smp(void);
 extern void cpuset_force_rebuild(void);
 extern void cpuset_update_active_cpus(void);
 extern void cpuset_lock(void);
+extern void cpuset_lock_no_attach(void);
 extern void cpuset_unlock(void);
 extern void lockdep_assert_cpuset_lock_held(void);
 extern void cpuset_cpus_allowed_locked(struct task_struct *p, struct cpumask *mask);
@@ -192,6 +193,7 @@ static inline void cpuset_update_active_cpus(void)
 }
 
 static inline void cpuset_lock(void) { }
+static inline void cpuset_lock_no_attach(void) { }
 static inline void cpuset_unlock(void) { }
 static inline void lockdep_assert_cpuset_lock_held(void) { }
 
kernel/cgroup/cpuset.c +11 -0
index 51b6be460794..ce9c57617f49 100644
@@ -378,6 +378,17 @@ static void wait_attach_done_lock(void)
 	}
 }
 
+/**
+ * cpuset_lock_no_attach - Acquire cpuset_mutex with no task attach in progress
+ *
+ * A task attach drops cpuset_mutex between cpuset_can_attach() and
+ * cpuset_attach(). Use this to keep a change out of that window.
+ */
+void cpuset_lock_no_attach(void)
+{
+	wait_attach_done_lock();
+}
+
 static inline void check_insane_mems_config(nodemask_t *nodes)
 {
 	if (!cpusets_insane_config() &&
kernel/sched/core.c +10 -0
index 2a964286a7cd..52c291de384e 100644
@@ -3195,6 +3195,16 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
 		goto out;
 	}
 
+	/*
+	 * sched_setaffinity() tested the policy with no lock, and did not
+	 * wait for a cpuset attach in progress. @p became a deadline task
+	 * since: let the caller wait and try again.
+	 */
+	if ((ctx->flags & SCA_DL_NOWAIT) && task_has_dl_policy(p)) {
+		ret = -EAGAIN;
+		goto out;
+	}
+
 	/*
 	 * Check under the same lock that __sched_setscheduler() holds for
 	 * its admission test, so that p cannot become SCHED_DEADLINE
kernel/sched/sched.h +2 -0
index 9e3ca69abc36..2087ad70c56e 100644
@@ -2985,6 +2985,8 @@ extern struct task_struct *pick_task_idle(struct rq *rq, struct rq_flags *rf);
 #define SCA_DL_CHECK		0x10
 /* The caller made room for the deadline bandwidth in the new root domain. */
 #define SCA_DL_BW_RESERVED	0x20
+/* The caller did not wait for a cpuset attach: -EAGAIN for a deadline task. */
+#define SCA_DL_NOWAIT		0x40
 
 extern void update_group_capacity(struct sched_domain *sd, int cpu);
 
kernel/sched/syscalls.c +45 -9

83 lines not on this page · raw message

Signature · 1 line
2.47.3
#48 lore raw

PATCH v7 24/40 cgroup/cpuset: Give back the bandwidth an attach did not move

In reply to Mathieu Desnoyers

Commit 2ef269ef1ac0 ("cgroup/cpuset: Free DL BW in case can_attach() fails") reserves the bandwidth of an attach as one sum. cpuset_can_attach() adds up the bandwidth of the deadline tasks it moves. Once all tasks pass their checks, it reserves the sum in the destination root domain. If another controller refuses the attach, cpuset_cancel_attach() frees the sum. If the attach goes through, the move of each task uses its part of the sum.

But a task can leave SCHED_DEADLINE between cpuset_can_attach() and cpuset_attach(). The previous patch makes sched_setattr() wait for the attach. sysrq-n does not wait: it cannot sleep. The task then moves no bandwidth. Its part of the reservation stays in the destination's total_bw, until the next rebuild of the accounting. The destination can then refuse deadline tasks that would fit.

Fix this by keeping the tally of what the attach moves, in sum_moved_dl_bw. Once the attach is through, give back what it did not move.

set_cpus_allowed_dl() decides the move under the runqueue lock. cpuset_attach_task() does not hold it. So the tally counts what set_cpus_allowed_dl() reports in the affinity context.

The random_mix case of deadline_bw_test, added later in this series, found the bug. It could no longer lower a fair server in a partition root with no room left.

The move_normalized case, added with that test, fires sysrq-n while a process with a sleeping deadline thread of 30% moves into a one-CPU partition root. Without this patch, the partition kept the 30% in 3 guests of 3. It admitted 6 tasks of 10% where it had room for 9.

Fixes 2ef269ef1ac0 ("cgroup/cpuset: Free DL BW in case can_attach() fails")
---
 include/linux/sched.h           |  3 ++-
 kernel/cgroup/cpuset-internal.h |  2 ++
 kernel/cgroup/cpuset.c          | 30 +++++++++++++++++++++++++-----
 kernel/sched/core.c             | 12 ++++++++----
 kernel/sched/deadline.c         |  4 ++++
 kernel/sched/sched.h            |  2 ++
 6 files changed, 43 insertions(+), 10 deletions(-)
include/linux/sched.h +2 -1
index dee4d4df624c..471cd27894ff 100644
@@ -1973,7 +1973,8 @@ extern void set_cpus_allowed_force(struct task_struct *p, const struct cpumask *
  */
 extern int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask);
 extern int set_cpus_allowed_bw_reserved(struct task_struct *p,
-					const struct cpumask *new_mask);
+					const struct cpumask *new_mask,
+					u64 *moved);
 extern int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, int node);
 extern void release_user_cpus_ptr(struct task_struct *p);
 extern int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask);
kernel/cgroup/cpuset-internal.h +2 -0
index bf847953c78d..93aa46d76b04 100644
@@ -170,6 +170,8 @@ struct cpuset {
 	int nr_migrate_dl_tasks;
 	/* DL bandwidth that needs destination reservation for this attach. */
 	u64 sum_migrate_dl_bw;
+	/* The part of sum_migrate_dl_bw moved. The rest is given back. */
+	u64 sum_moved_dl_bw;
 	/*
 	 * CPU used for temporary DL bandwidth allocation during attach;
 	 * -1 if no DL bandwidth was allocated in the current attach.
kernel/cgroup/cpuset.c +25 -5
index ce9c57617f49..2f39c3d12550 100644
@@ -3140,10 +3140,24 @@ static void clear_attach_data(struct llist_head *head, bool cancel)
 	llist_for_each_entry_safe(cs, next, lnode, attach_node) {
 		init_llist_node(&cs->attach_node);
 		if (cs->nr_migrate_dl_tasks) {
-			if (cancel && cs->dl_bw_cpu >= 0)
-				dl_bw_free(cs->dl_bw_cpu, cs->sum_migrate_dl_bw);
+			/*
+			 * Give back the bandwidth the attach did not move.
+			 * If the attach is cancelled, that is all of the
+			 * reservation. Otherwise, it is what no move used,
+			 * such as the part for a task that left
+			 * SCHED_DEADLINE. The class it left releases its own
+			 * bandwidth, from the root domain that counts it.
+			 */
+			if (cs->dl_bw_cpu >= 0) {
+				u64 bw = cancel ? cs->sum_migrate_dl_bw :
+					 cs->sum_migrate_dl_bw - cs->sum_moved_dl_bw;
+
+				if (bw)
+					dl_bw_free(cs->dl_bw_cpu, bw);
+			}
 			cs->nr_migrate_dl_tasks = 0;
 			cs->sum_migrate_dl_bw = 0;
+			cs->sum_moved_dl_bw = 0;
 			cs->dl_bw_cpu = -1;
 		}
 	}
@@ -3303,10 +3317,16 @@ static void cpuset_attach_task(struct cpuset *cs, struct task_struct *task)
 	 * can_attach beforehand should guarantee that this doesn't
 	 * fail.  TODO: have a better way to handle failure here
 	 */
-	if (reserved)
-		WARN_ON_ONCE(set_cpus_allowed_bw_reserved(task, cpus_attach));
-	else
+	if (reserved) {
+		u64 moved;
+
+		/* Count what the move reports it moved. */
+		WARN_ON_ONCE(set_cpus_allowed_bw_reserved(task, cpus_attach,
+							  &moved));
+		cs->sum_moved_dl_bw += moved;
+	} else {
 		WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
+	}
 
 	if (cpuset_v2() && !attach_ctx.mems_updated)
 		return;
kernel/sched/core.c +8 -4
index 52c291de384e..229b7bfa9634 100644
@@ -3301,17 +3301,21 @@ EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
 /*
  * Like set_cpus_allowed_ptr(), for a caller that has made room for the
  * deadline bandwidth of @p in the root domain of @new_mask. Move that
- * bandwidth there with @p. Return 0 on success, or a negative error
- * code.
+ * bandwidth there with @p, and set @moved to the bandwidth moved, 0
+ * if none. Return 0 on success, or a negative error code.
  */
-int set_cpus_allowed_bw_reserved(struct task_struct *p, const struct cpumask *new_mask)
+int set_cpus_allowed_bw_reserved(struct task_struct *p,
+				 const struct cpumask *new_mask, u64 *moved)
 {
 	struct affinity_context ac = {
 		.new_mask  = new_mask,
 		.flags     = SCA_DL_BW_RESERVED,
 	};
+	int ret;
 
-	return __set_cpus_allowed_ptr(p, &ac);
+	ret = __set_cpus_allowed_ptr(p, &ac);
+	*moved = ac.dl_bw_moved;
+	return ret;
 }
 
 /*
kernel/sched/deadline.c +4 -0
index aba03fd6b381..79c99e3bc156 100644
@@ -3629,6 +3629,9 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 	 * Otherwise, the bandwidth stays where it is counted, until the next
 	 * rebuild of the accounting. Moving it without room would leave no
 	 * root domain counting it.
+	 *
+	 * Report in @ctx the bandwidth moved. The caller made its own test
+	 * without the runqueue lock, so it must count only what this reports.
 	 */
 	if ((ctx->flags & SCA_DL_BW_RESERVED) &&
 	    dl_task_needs_bw_move(p, ctx->new_mask)) {
@@ -3657,6 +3660,7 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 		cpu = cpumask_any_and(ctx->new_mask, cpu_active_mask);
 		p->dl.dl_bw_cpu = cpu < nr_cpu_ids ? (int)cpu : -1;
 		p->dl.dl_bw_gen = dl_bw_gen;
+		ctx->dl_bw_moved = p->dl.dl_bw;
 	}
 
 	set_cpus_allowed_common(p, ctx);
kernel/sched/sched.h +2 -0
index 2087ad70c56e..661da2b5c278 100644
@@ -2688,6 +2688,8 @@ extern const u32		sched_prio_to_wmult[40];
 struct affinity_context {
 	const struct cpumask	*new_mask;
 	struct cpumask		*user_mask;
+	/* Out: the deadline bandwidth moved to the new root domain. */
+	u64			dl_bw_moved;
 	unsigned int		flags;
 };
 
Signature · 1 line
2.47.3
#49 lore raw

PATCH v7 25/40 cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to

In reply to Mathieu Desnoyers

Commit 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets") moves a deadline task's bandwidth in two halves. cpuset_can_attach() reserves it in the destination. set_cpus_allowed_dl() frees it in the source when the task's affinity changes. The reservation goes to the root domain of the first active CPU of the destination cpuset. So cpuset_can_attach() treats the cpuset as one root domain.

But a cpuset can span more than one root domain. With isolcpus=domain, the root cpuset holds the isolated CPUs, which are in the default root domain. A task also keeps the affinity set by sched_setaffinity(). Its new CPUs can then all be in a root domain that got no reservation. The task runs there, and its bandwidth is reserved in the other root domain.

Take a machine with CPUs 0-4, booted with isolcpus=domain,1,2. P is a partition root of CPU 4. A deadline task T, pinned to CPUs 1-2, is moved into P and back to the root cgroup:

total_bw of the root domain of
admin, task T CPUs 0, 3 CPUs 1, 2 CPU 4 (P)

sched_setaffinity(T, CPUs 1-2)
sched_setattr(T, SCHED_DEADLINE) + bw
echo T > P/cgroup.procs
cpuset_can_attach()
reserves on CPU 4 + bw
set_cpus_allowed_dl()
frees where recorded, CPU 1 - bw
records CPU 4
T runs on CPU 4
echo T > cgroup.procs of the root
cpuset_can_attach()
reserves on CPU 0 + bw
__set_cpus_allowed_ptr()
keeps T's affinity: CPUs 1-2
set_cpus_allowed_dl()
frees where recorded, CPU 4 - bw
records CPU 1
T runs on CPU 1
T exits

    releases where recorded, CPU 1                 - bw
                                       ---------   ---------   ---------
  left after T exits                   + bw        - bw        0

T ran in the root domain of CPUs 1 and 2 without being counted there. In testing, the total_bw of that root domain went below zero when T died. It then refused every deadline task, until the next rebuild of the accounting.

Fix this by reserving the bandwidth on the CPU that the move records with the task. The new dl_task_bw_reserve_cpu() works out that CPU and records it with the task. It is the CPU the task is on, if the task can stay there. Else it is the first active CPU of the new mask, a housekeeping one if any. The rebuild of the accounting makes the same choice, later in this series. cpuset_can_attach() reserves the bandwidth per such CPU, and refuses with EBUSY as before. cpuset_attach_task() moves the bandwidth to the CPU recorded, and does not work it out again:
the task may have run on another CPU since. cpuset_attach() gives back the rest.

The record is a new field of the task, dl_bw_resv_cpu. cpuset_attach_task() moves the bandwidth of a task only if the task has that record. Juri Lelli suggested to track the tasks that cpuset_can_attach() counts. A task it did not count cannot use the room made for another task.

A new mask can also span both root domains. A running task would then go to the CPU that cpumask_any_and_distribute() picks. A sleeping one would wake up where select_fallback_rq() picks. Either CPU can be in the root domain without the reservation. So __set_cpus_allowed_ptr_locked() takes the CPU with the reservation, if cpumask_any_and_distribute() picked a CPU of the other root domain. A sleeping task gets the CPU chosen as its wakeup CPU.

A new mask that still holds an active CPU of the root domain counting the task moves no bandwidth at the attach. The task can still land in the other root domain, if it must leave its CPU. A later patch of this series moves the bandwidth there, without a check for room. It is "sched/deadline: Move a task's bandwidth to the root domain it runs in".

The sums are kept per CPU, not per cpuset: one cpuset can need room in two root domains. One set of sums is enough, since cgroup_mutex lets one attach run at a time. guarantee_active_cpus() now takes the cpuset to start from.

Later in this series, deadline_bw_test gets four cases for this:
move_isolated, move_isolated_refused, move_isolated_asleep and move_spanning. Without this patch, all four fail with isolcpus=domain,1,2. With isolcpus=domain,0,1, move_isolated, move_spanning and six other move cases fail. The case move_back_cpu_offline tests a mask that holds an offline CPU.

Fixes 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets")
---
 include/linux/sched.h           |   8 +-
 include/linux/sched/deadline.h  |  15 ++-
 kernel/cgroup/cpuset-internal.h |  12 --
 kernel/cgroup/cpuset.c          | 216 +++++++++++++++++++-------------
 kernel/sched/core.c             |  27 +++-
 kernel/sched/deadline.c         | 133 ++++++++++++++++----
 kernel/sched/sched.h            |   2 +
 kernel/sched/syscalls.c         |   5 +-
 8 files changed, 282 insertions(+), 136 deletions(-)
include/linux/sched.h +7 -1
index 471cd27894ff..2f2f59402f09 100644
@@ -758,10 +758,16 @@ struct sched_dl_entity {
 	 *
 	 * @dl_bw_gen is the value of dl_bw_gen when the bandwidth was last
 	 * counted. If a rebuild dropped it since, there is nothing to remove.
+	 *
+	 * @dl_bw_resv_cpu is a CPU of the root domain where a cpuset attach
+	 * in progress reserved room for the bandwidth, or -1.
+	 * cpuset_can_attach() sets it, and cpuset_attach() moves the
+	 * bandwidth there.
 	 */
 	struct list_head		dl_departed_node;
 	int				dl_bw_cpu;
 	unsigned int			dl_bw_gen;
+	int				dl_bw_resv_cpu;
 
 	/*
 	 * Bits for DL-server functionality. Also see the comment near
@@ -1974,7 +1980,7 @@ extern void set_cpus_allowed_force(struct task_struct *p, const struct cpumask *
 extern int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask);
 extern int set_cpus_allowed_bw_reserved(struct task_struct *p,
 					const struct cpumask *new_mask,
-					u64 *moved);
+					int cpu, u64 *moved);
 extern int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, int node);
 extern void release_user_cpus_ptr(struct task_struct *p);
 extern int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask);
include/linux/sched/deadline.h +9 -6
index 60be226699bb..cbb7cd71db58 100644
@@ -50,14 +50,17 @@ extern void dl_accounting_unlock(void);
 extern void lockdep_assert_dl_accounting_held(void);
 #endif
 /*
- * Return whether moving DL task @p to @new_mask requires moving DL
- * bandwidth accounting between root domains. This helper is specific to
- * DL bandwidth move accounting semantics and is shared by
- * cpuset_can_attach() and set_cpus_allowed_dl() so both paths use the
- * same source root-domain test.
+ * Return the CPU that a move of DL task @p to the CPUs of @new_mask
+ * records with its DL bandwidth. Return -1 if the bandwidth stays in the
+ * root domain that counts it. Like the move, keep the CPUs within the
+ * affinity set by the user. cpuset_can_attach() reserves the bandwidth in
+ * the root domain of that CPU. cpuset_attach_task() then moves it there,
+ * and set_cpus_allowed_dl() makes the same test.
  */
-extern bool dl_task_needs_bw_move(struct task_struct *p,
+extern int dl_task_bw_reserve_cpu(struct task_struct *p,
 				  const struct cpumask *new_mask);
+extern int dl_task_bw_reserved_cpu(struct task_struct *p);
+extern void dl_task_bw_unreserve(struct task_struct *p);
 
 static inline bool dl_server(struct sched_dl_entity *dl_se)
 {
kernel/cgroup/cpuset-internal.h +0 -12
index 93aa46d76b04..a83443dfb788 100644
@@ -166,18 +166,6 @@ struct cpuset {
 	 */
 	bool remote_partition_updating;
 
-	/* Number of SCHED_DEADLINE tasks the attach in progress moves here. */
-	int nr_migrate_dl_tasks;
-	/* DL bandwidth that needs destination reservation for this attach. */
-	u64 sum_migrate_dl_bw;
-	/* The part of sum_migrate_dl_bw moved. The rest is given back. */
-	u64 sum_moved_dl_bw;
-	/*
-	 * CPU used for temporary DL bandwidth allocation during attach;
-	 * -1 if no DL bandwidth was allocated in the current attach.
-	 */
-	int dl_bw_cpu;
-
 	/* Invalid partition error code, not lock protected */
 	enum prs_errcode prs_err;
 
kernel/cgroup/cpuset.c +132 -84

342 lines not on this page · raw message

kernel/sched/core.c +23 -4
index 229b7bfa9634..e9f80407f75b 100644
@@ -3250,6 +3250,22 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
 		goto out;
 	}
 
+	/*
+	 * The caller made room for the deadline bandwidth of @p in the root
+	 * domain of ctx->dl_bw_cpu. The new mask can span two root domains:
+	 * keep @p in that one. Also wake a sleeping @p up on dest_cpu, since
+	 * select_fallback_rq() could pick a CPU of the other one.
+	 */
+	if ((ctx->flags & SCA_DL_BW_RESERVED) &&
+	    cpumask_test_cpu(ctx->dl_bw_cpu, cpu_valid_mask) &&
+	    cpumask_test_cpu(ctx->dl_bw_cpu, ctx->new_mask)) {
+		if (!cpumask_test_cpu(dest_cpu,
+				      cpu_rq(ctx->dl_bw_cpu)->rd->span))
+			dest_cpu = ctx->dl_bw_cpu;
+		if (!task_on_rq_queued(p))
+			p->wake_cpu = dest_cpu;
+	}
+
 	do_set_cpus_allowed(p, ctx);
 
 	return affine_move_task(rq, p, rf, dest_cpu, ctx->flags);
@@ -3300,15 +3316,18 @@ EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
 
 /*
  * Like set_cpus_allowed_ptr(), for a caller that has made room for the
- * deadline bandwidth of @p in the root domain of @new_mask. Move that
- * bandwidth there with @p, and set @moved to the bandwidth moved, 0
- * if none. Return 0 on success, or a negative error code.
+ * deadline bandwidth of @p in the root domain of @cpu. If the move records
+ * @cpu with that bandwidth, move the bandwidth there with @p. Set @moved
+ * to the bandwidth moved, 0 if none. Return 0 on success, or a negative
+ * error code.
  */
 int set_cpus_allowed_bw_reserved(struct task_struct *p,
-				 const struct cpumask *new_mask, u64 *moved)
+				 const struct cpumask *new_mask, int cpu,
+				 u64 *moved)
 {
 	struct affinity_context ac = {
 		.new_mask  = new_mask,
+		.dl_bw_cpu = cpu,
 		.flags     = SCA_DL_BW_RESERVED,
 	};
 	int ret;
kernel/sched/deadline.c +106 -27

166 lines not on this page · raw message

kernel/sched/sched.h +2 -0
index 661da2b5c278..3cc287785b91 100644
@@ -2690,6 +2690,8 @@ struct affinity_context {
 	struct cpumask		*user_mask;
 	/* Out: the deadline bandwidth moved to the new root domain. */
 	u64			dl_bw_moved;
+	/* In, with SCA_DL_BW_RESERVED: the CPU the caller made room on. */
+	int			dl_bw_cpu;
 	unsigned int		flags;
 };
 
kernel/sched/syscalls.c +3 -2
index 4aa3ccbff320..241dedd2aaac 100644
@@ -1339,8 +1339,9 @@ long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
 	/*
 	 * Wait for a cpuset attach in progress before changing the affinity
 	 * of a deadline task. cpuset_can_attach() reserved the bandwidth of
-	 * the task for the CPUs it moves to, and cpuset_attach() moves it
-	 * there. A new affinity in between could change those CPUs.
+	 * the task on one CPU, and recorded that CPU with the task.
+	 * cpuset_attach() moves the bandwidth there. A new affinity in
+	 * between could leave that CPU out, and the bandwidth would not move.
 	 *
 	 * The policy is tested here with no lock. A task that becomes a
 	 * deadline task after this test is found under its runqueue lock,
Signature · 1 line
2.47.3
#50 lore raw

PATCH v7 26/40 sched/deadline: Make a rebuild count a task in the root domain it runs in

In reply to Mathieu Desnoyers

A rebuild of the accounting counts each deadline task on the first active CPU of its cpuset. Commit 318e18ed22e8 ("sched/deadline: Walk up cpuset hierarchy to decide root domain when hot-unplug") made this choice. It relies on the bandwidth check to keep such a CPU active. This guess would go wrong in three ways:

- A cpuset, like the root one, can hold CPUs isolated by isolcpus="domain" beside housekeeping CPUs. If an isolated CPU comes first, the task would be counted in the default root domain. Its own root domain would then be short of that bandwidth.
- A task confined to isolated CPUs can see them all go offline. The rebuild would then find no active CPU, and hit its BUG_ON().
- dl_task_offline_migration() moves a throttled task, with its bandwidth, off CPUs that went offline. The rebuild would count it in its cpuset, not where it moved.

In the first and third cases, a root domain would admit deadline tasks beyond its capacity.

Fix this by choosing the CPU in this order:

1. The CPU the task is on, if it is active and in the task's mask. A mask can hold CPUs of two root domains, for instance after select_fallback_rq() widened it. Also the CPU the task is queued on out of its mask, if it is active and recorded with the bandwidth. Without admission control, dl_task_offline_migration() can put a throttled task there. It runs there until it blocks.
2. dl_bw_cpu, the CPU recorded with the bandwidth, if it is active and in the mask. A task moved asleep is not on its new CPUs yet.
3. The first active CPU of the mask, a housekeeping one if any.
4. With no active CPU in the mask: dl_bw_cpu if it is active, else an active CPU of the cpuset.

The mask of the task comes before its cpuset. A partition change sets the task masks before its rebuild, and the housekeeping mask after.

Leave out a task with no active CPU, instead of the BUG_ON(). dl_bw_gen then keeps its release from removing anything. dl_task_offline_migration() counts it again when it moves it.

A task that select_fallback_rq() moves to another root domain still runs where its bandwidth is not counted. The next patch moves the bandwidth with it.

The Sashiko AI reviews of v1 to v4 found these cases.

Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
Fixes 318e18ed22e8 ("sched/deadline: Walk up cpuset hierarchy to decide root domain when hot-unplug")
---
 kernel/sched/deadline.c | 88 +++++++++++++++++++++++++++++++++++------
 1 file changed, 77 insertions(+), 11 deletions(-)
kernel/sched/deadline.c +77 -11
index a9b8bd019d4b..9ff79141c630 100644
@@ -927,14 +927,20 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 			__dl_sub(dl_b, p->dl.dl_bw,
 				 cpumask_weight(src_rq->rd->span));
 			raw_spin_unlock(&dl_b->lock);
-
-			dl_b = &later_rq->rd->dl_bw;
-			raw_spin_lock(&dl_b->lock);
-			__dl_add(dl_b, p->dl.dl_bw,
-				 cpumask_weight(later_rq->rd->span));
-			raw_spin_unlock(&dl_b->lock);
 		}
+		/*
+		 * Count the bandwidth in the root domain the task moves to.
+		 * Do it also when a rebuild left the task out, for want of an
+		 * active CPU. A rebuild that reaches the task after this finds
+		 * its dl_bw_gen current, and leaves it alone.
+		 */
+		dl_b = &later_rq->rd->dl_bw;
+		raw_spin_lock(&dl_b->lock);
+		__dl_add(dl_b, p->dl.dl_bw,
+			 cpumask_weight(later_rq->rd->span));
+		raw_spin_unlock(&dl_b->lock);
 		p->dl.dl_bw_cpu = later_rq->cpu;
+		p->dl.dl_bw_gen = dl_bw_gen;
 	}
 
 	set_task_cpu(p, later_rq->cpu);
@@ -3820,6 +3826,60 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
 	cpuset_cpus_allowed_locked(p, cpus);
 }
 
+/*
+ * Return a CPU of the root domain where a rebuild of the accounting should
+ * count the bandwidth of @p, or nr_cpu_ids if there is none.
+ *
+ * Prefer the CPU @p is on, if it is active and in the mask of @p. The
+ * task runs, or wakes up, in the root domain of that CPU. A mask can hold
+ * CPUs of two root domains: housekeeping CPUs and CPUs isolated by
+ * isolcpus="domain". When every CPU of a mask goes offline,
+ * select_fallback_rq() can widen it to both. It moves no bandwidth.
+ * Prefer that CPU also if @p is queued there, out of its mask, and the
+ * CPU is the one recorded. Without admission control,
+ * dl_task_offline_migration() can put a throttled task and its bandwidth
+ * on any active CPU. The task runs there until it blocks.
+ *
+ * Else prefer the CPU recorded with the bandwidth, if it is active and in
+ * the mask. It is in the root domain that admitted the bandwidth, or that
+ * its last move put it in. A task moved asleep is still on a CPU of the
+ * root domain it left, out of its mask. Else take the first active CPU of
+ * the mask, a housekeeping one if there is one. A task on isolated CPUs
+ * that all went offline can have no active CPU at all.
+ */
+static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
+{
+	struct cpumask *msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
+	int recorded = p->dl.dl_bw_cpu;
+	unsigned int cpu;
+
+	/*
+	 * Look at the mask of the task first. A change of the cpusets sets
+	 * the mask of each task before its rebuild. The housekeeping mask
+	 * that dl_get_task_effective_cpus() reads is updated after it. If no
+	 * CPU of the mask is active, take the CPU recorded if it is active.
+	 * dl_task_offline_migration() moved the task there, or an earlier
+	 * rebuild counted it there. Else ask the cpuset.
+	 */
+	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
+	cpu = task_cpu(p);
+	if (cpumask_test_cpu(cpu, msk) ||
+	    (cpu == recorded && cpu_active(cpu) && task_on_rq_queued(p)))
+		return cpu;
+	if (cpumask_empty(msk)) {
+		if (recorded >= 0 && cpu_active(recorded))
+			return recorded;
+		dl_get_task_effective_cpus(p, msk);
+		cpumask_and(msk, msk, cpu_active_mask);
+	} else if (recorded >= 0 && cpumask_test_cpu(recorded, msk)) {
+		return recorded;
+	}
+	cpu = cpumask_first_and(msk, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
+	if (cpu < nr_cpu_ids)
+		return cpu;
+	return cpumask_first(msk);
+}
+
 /* From dl_rebuild_rd_accounting(), under the locks it asserts. */
 void dl_add_task_root_domain(struct task_struct *p)
 {
@@ -3827,7 +3887,6 @@ void dl_add_task_root_domain(struct task_struct *p)
 	struct rq *rq;
 	struct dl_bw *dl_b;
 	unsigned int cpu;
-	struct cpumask *msk;
 
 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
 	/*
@@ -3842,10 +3901,17 @@ void dl_add_task_root_domain(struct task_struct *p)
 		return;
 	}
 
-	msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
-	dl_get_task_effective_cpus(p, msk);
-	cpu = cpumask_first_and(cpu_active_mask, msk);
-	BUG_ON(cpu >= nr_cpu_ids);
+	cpu = dl_task_rebuild_cpu(p);
+	if (cpu >= nr_cpu_ids) {
+		/*
+		 * No active CPU can count the bandwidth of this task. Leave it
+		 * out of this rebuild. dl_bw_gen then keeps its release from
+		 * removing anything. A later rebuild, or
+		 * dl_task_offline_migration(), counts it again.
+		 */
+		raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
+		return;
+	}
 
 	raw_spin_lock(&dl_departed_lock);
 	/*
Signature · 1 line
2.47.3
#53 lore raw

PATCH v7 27/40 sched/deadline: Move a task's bandwidth to the root domain it runs in

In reply to Mathieu Desnoyers

When a CPU goes offline, select_fallback_rq() picks a new CPU for a deadline task asleep on it. balance_push() moves a queued task the same way. The new CPU can be in another root domain. With isolcpus="domain", the isolated CPUs are in the default root domain. A cpuset that is not a partition can hold CPUs of both root domains.

Commit 59d06cea1198 ("sched/deadline: Fix bandwidth accounting at all levels after offline migration") fixed this for a throttled task. dl_task_offline_migration() moves its bandwidth with it. A task that select_fallback_rq() places still moves no bandwidth. So it runs in a root domain that does not count its bandwidth, until the next rebuild. That root domain can admit deadline tasks beyond its capacity.

Fix this in migrate_task_rq_dl(). The CPU recorded with the bandwidth gives the root domain that counts it. If the new CPU is in another root domain, move the bandwidth there. Record the new CPU. As dl_task_offline_migration() does, add the bandwidth even without room, since the task runs there. Add it also if a rebuild left the task out. Do not move it to a CPU that is not active. A migration-disabled task can wake up on a CPU that goes offline. That CPU is in the default root domain by then. The task leaves it before it runs anywhere else.

Compare the root domains, not the CPU the task leaves. That CPU can still be in the mask when select_fallback_rq() picks a CPU of the other root domain. A task can also wake up on its CPU with no migration while another root domain counts its bandwidth. A cpuset move or a rebuild can move the bandwidth while the task sleeps. A change of the mask can then give that CPU back. So task_woken_dl() makes the same check.

Both checks read the record without dl_departed_lock, so a move inside a root domain takes no lock. dl_task_move_bw() checks again under dl_departed_lock. Its caller holds the pi_lock or the rq lock of the task. Together, the two locks keep the record stable.

Move no bandwidth while the sched domains are rebuilt. The CPUs then change root domains one by one. Two CPUs can be in different root domains only because one of them was attached to its new root domain first. The rebuild of the accounting that follows counts the task. dl_bw_rebuild_begin() opens this window in partition_sched_domains_locked(). dl_rebuild_rd_accounting() closes it.

Move no bandwidth for a task blocked on a mutex while it is migrated. Proxy execution queues such a task on the CPU of the mutex owner, which can be in another root domain. The task does not run there. It goes back when it is woken. proxy_set_task_cpu() does not call migrate_task_rq_dl() today. A proxy execution fix makes it do so, as set_task_cpu() does [1]. If the task then wakes up in another root domain, the wake-up moves the bandwidth.

These cases of deadline_bw_test, added later in this series, fail without this patch:
- hotplug_fallback, hotplug_fallback_moved and
hotplug_fallback_in_mask: a task woken on an isolated CPU stays counted in the housekeeping root domain.
- no_admission_affinity_moves: without admission control, a task given an affinity of one isolated CPU stays counted in the housekeeping root domain.

This follows the Sashiko AI reviews of v4 and v5.

[1] https://lore.kernel.org/all/[email protected]/

Fixes 59d06cea1198 ("sched/deadline: Fix bandwidth accounting at all levels after offline migration")
---
 include/linux/sched/deadline.h |   1 +
 kernel/sched/deadline.c        | 152 ++++++++++++++++++++++++++++++---
 kernel/sched/topology.c        |   3 +
 3 files changed, 144 insertions(+), 12 deletions(-)
include/linux/sched/deadline.h +1 -0
index cbb7cd71db58..bdabd54af729 100644
@@ -33,6 +33,7 @@ struct root_domain;
 extern void dl_add_task_root_domain(struct task_struct *p);
 extern void dl_clear_root_domain(struct root_domain *rd);
 extern void dl_clear_root_domains(void);
+extern void dl_bw_rebuild_begin(void);
 extern void dl_rebuild_rd_accounting(void);
 /*
  * Keep a rebuild of the root domains' accounting and an admission of
kernel/sched/deadline.c +140 -12

211 lines not on this page · raw message

kernel/sched/topology.c +3 -0
index 35e56a45c238..9ec5f38afd28 100644
@@ -3430,6 +3430,9 @@ static void partition_sched_domains_locked(int ndoms_new, cpumask_var_t doms_new
 		n = ndoms_new;
 	}
 
+	/* dl_rebuild_rd_accounting() ends it. */
+	dl_bw_rebuild_begin();
+
 	/* Destroy deleted domains: */
 	for (i = 0; i < ndoms_cur; i++) {
 		for (j = 0; j < n && !new_topology; j++) {
Signature · 1 line
2.47.3
#56 lore raw

PATCH v7 28/40 sched/deadline: Keep a task in the root domain that counts its bandwidth

In reply to Mathieu Desnoyers

The root domain that admits a deadline task counts its bandwidth. The mask of the task can hold CPUs of another root domain. With isolcpus="domain", the isolated CPUs are in the default root domain. A cpuset that is not a partition root can hold isolated and housekeeping CPUs.

The code that picks a CPU for a task does not look at the root domain that counts it:

- select_fallback_rq() and dl_task_offline_migration() pick a CPU when the CPU of the task goes offline.
- __set_cpus_allowed_ptr_locked() picks one when the mask changes.
- select_task_rq_dl() can leave a task on the CPU it slept on, which can be in the other root domain.
- dl_task_rebuild_cpu() picks the CPU that a rebuild counts a task with. It prefers the CPU the task is on, then a housekeeping CPU.

Each can take the task, or its bandwidth, to the other root domain while its own root domain still has a CPU for it. The bandwidth then moves with no admission test, and the root domain it arrives in can exceed its limit.

Add dl_task_bw_span(), which returns the CPUs of the root domain that counts a task. Make each of these places try one of those CPUs first. After a rebuild the root domains are new, and the CPU recorded with the bandwidth can be offline. So dl_task_rebuild_cpu() cannot use the root domain. It looks at the kind of the CPU recorded, housekeeping or isolated. It prefers a CPU of the mask of the same kind.

The CPU recorded can be the one going offline. Its root domain still counts the task until the rebuild attaches that CPU to the default root domain. So dl_task_bw_span() still returns that root domain until then. This covers the common case: a task that runs on the CPU when it goes offline, which balance_push() moves.

dl_task_bw_span() returns NULL while the sched domains are rebuilt. The CPUs then change root domains one by one. A housekeeping CPU passes through the default root domain, which holds the isolated CPUs. Its span would send a housekeeping task to an isolated CPU. So inside a rebuild, the CPU is picked as it was before this patch. If that CPU is in the other root domain, the next wakeup brings the task back.

A known limit remains. A wakeup can pick its CPU inside a rebuild, and be queued after the rebuild. Its bandwidth can then still move to the other root domain, with no admission test. This was found by reading, not reproduced.

A task with no CPU left in its root domain still moves, and its bandwidth with it. The next two patches refuse the changes that lead to that.

The case hotplug_keeps_root_domain of deadline_bw_test, added later in this series, tests this. A cpuset holds two isolated CPUs and two housekeeping CPUs, H and K. A deadline task counted in the housekeeping root domain sleeps on H. Then H goes offline. The task must wake up on K. Without this patch it woke up on an isolated CPU: CPU 0, in a guest with isolcpus=domain,0,1.

These cases test the other paths:
- hotplug_spinner_keeps: a running task whose CPU goes offline;
- hotplug_waking_keeps: a task that wakes up often, at the offline;
- hotplug_isolated_keeps: the same, for a task counted on the isolated side;
- rebuild_waking_keeps: a wakeup inside a rebuild. It fails in most runs if dl_task_bw_span() does not return NULL there. That needs isolcpus=domain,0,1.

Fixes 332ac17ef5bf ("sched/deadline: Add bandwidth management for SCHED_DEADLINE tasks")
---
 kernel/sched/core.c     |  38 ++++++++++
 kernel/sched/deadline.c | 156 +++++++++++++++++++++++++++++++++-------
 kernel/sched/sched.h    |   1 +
 3 files changed, 171 insertions(+), 24 deletions(-)
kernel/sched/core.c +38 -0
index e9f80407f75b..dc270a23179d 100644
@@ -3264,6 +3264,23 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
 			dest_cpu = ctx->dl_bw_cpu;
 		if (!task_on_rq_queued(p))
 			p->wake_cpu = dest_cpu;
+	} else {
+		const struct cpumask *span = dl_task_bw_span(p);
+		unsigned int cpu = nr_cpu_ids;
+
+		/*
+		 * No room was made for @p in another root domain. Keep @p
+		 * in the root domain that counts its bandwidth, if the new
+		 * mask holds one of its CPUs.
+		 */
+		if (span && !cpumask_test_cpu(dest_cpu, span))
+			cpu = cpumask_first_and_and(cpu_valid_mask,
+						    ctx->new_mask, span);
+		if (cpu < nr_cpu_ids) {
+			dest_cpu = cpu;
+			if (!task_on_rq_queued(p))
+				p->wake_cpu = dest_cpu;
+		}
 	}
 
 	do_set_cpus_allowed(p, ctx);
@@ -3668,8 +3685,21 @@ static int select_fallback_rq(int cpu, struct task_struct *p)
 	int nid = cpu_to_node(cpu);
 	const struct cpumask *nodemask = NULL;
 	enum { cpuset, possible, fail } state = cpuset;
+	const struct cpumask *span;
 	int dest_cpu;
 
+	/*
+	 * Keep a deadline task in the root domain that counts its
+	 * bandwidth, if one of its CPUs is allowed and online.
+	 */
+	span = dl_task_bw_span(p);
+	if (span) {
+		for_each_cpu_and(dest_cpu, span, p->cpus_ptr) {
+			if (is_cpu_allowed(p, dest_cpu))
+				return dest_cpu;
+		}
+	}
+
 	/*
 	 * If the node that the CPU is on has been offlined, cpu_to_node()
 	 * will return -1. There is no CPU on the node, and we should
@@ -3686,6 +3716,14 @@ static int select_fallback_rq(int cpu, struct task_struct *p)
 	}
 
 	for (;;) {
+		/* The mask is wider now: look again in that root domain. */
+		if (span && state != cpuset) {
+			for_each_cpu_and(dest_cpu, span, p->cpus_ptr) {
+				if (is_cpu_allowed(p, dest_cpu))
+					goto out;
+			}
+		}
+
 		/* Any allowed, online CPU? */
 		for_each_cpu(dest_cpu, p->cpus_ptr) {
 			if (!is_cpu_allowed(p, dest_cpu))
kernel/sched/deadline.c +132 -24

222 lines not on this page · raw message

kernel/sched/sched.h +1 -0
index 3cc287785b91..f80ea5541b3f 100644
@@ -371,6 +371,7 @@ extern bool __checkparam_dl(const struct sched_attr *attr);
 extern bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr);
 extern int  dl_cpuset_cpumask_can_shrink(const struct cpumask *cur, const struct cpumask *trial);
 extern int  dl_bw_deactivate(int cpu);
+extern const struct cpumask *dl_task_bw_span(struct task_struct *p);
 extern s64 dl_scaled_delta_exec(struct rq *rq, struct sched_dl_entity *dl_se, s64 delta_exec);
 /*
  * SCHED_DEADLINE supports servers (nested scheduling) with the following
Signature · 1 line
2.47.3
#59 lore raw

PATCH v7 29/40 sched/deadline: Keep the last CPU a task has in its root domain

In reply to Mathieu Desnoyers

dl_bw_deactivate() refuses to take a CPU offline when the rest of its root domain cannot hold the deadline bandwidth counted there. It also keeps the last CPU of a root domain that counts a deadline task. That test comes from commit d4742f6ed7ea ("sched/deadline: Correctly account for allocated bandwidth during hotplug").

That test looks at the root domain, not at the mask of each task. With isolcpus="domain", a cpuset that is not a partition root can hold one housekeeping CPU and some isolated CPUs. A deadline task in it can be counted in the housekeeping root domain. When that housekeeping CPU goes offline, the root domain keeps its other CPUs, so the offline is accepted. But the task has only isolated CPUs left. It runs in the default root domain, which did not admit it. Its bandwidth follows with no admission test, and the default root domain can exceed its limit.

Refuse the offline with EBUSY in that case. Walk the deadline tasks counted in the root domain of the CPU. Refuse if one of them has CPUs left to run on, but none in that root domain. Skip the walk if no task holds a bandwidth. A task whose mask holds no other CPU gets the CPUs of an ancestor of its cpuset: add cpuset_cpus_allowed_without() to tell which. Like __set_cpus_allowed_ptr(), it keeps them within the affinity set by the user, if they intersect. Skip a dead task: it runs no more.

Do not refuse during a suspend. It takes the CPUs offline with the tasks frozen, and the resume puts them back. Do not refuse without admission control either: there is no limit to exceed.

An administrator who needs the CPU offline can first give the cpuset of the task another CPU of that root domain. The offline is then accepted, and the task wakes up on that CPU: the hotplug_keeps_root_domain case tests this. The administrator can also turn admission control off, by writing -1 to /proc/sys/kernel/sched_rt_runtime_us.

The walk cannot miss a task. sched_setattr() only makes a deadline task of a task whose mask holds its whole root domain. sched_setaffinity() only gives a deadline task such a mask. A mask also gets smaller by a cpuset change or a cpuset move, and both exclude CPU hotplug.

For user-space, the refused offline is a write of 0 to /sys/devices/system/cpu/cpuN/online that fails with EBUSY. An offline that leaves each deadline task a CPU in its root domain is accepted as before.

The case hotplug_last_refused of deadline_bw_test, added later in this series, tests this. Without this patch the offline is accepted. The cases hotplug_user_mask_refused and hotplug_dead_accepted test the affinity set by the user and a dead task.

Fixes d4742f6ed7ea ("sched/deadline: Correctly account for allocated bandwidth during hotplug")
---
 include/linux/cpuset.h  |  9 +++++++
 kernel/cgroup/cpuset.c  | 26 ++++++++++++++++++
 kernel/sched/deadline.c | 60 ++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 94 insertions(+), 1 deletion(-)
include/linux/cpuset.h +9 -0
index 5d0c01a25354..68849539cc8b 100644
@@ -79,6 +79,8 @@ extern void lockdep_assert_cpuset_lock_held(void);
 extern void cpuset_cpus_allowed_locked(struct task_struct *p, struct cpumask *mask);
 extern void cpuset_cpus_allowed(struct task_struct *p, struct cpumask *mask);
 extern bool cpuset_cpus_allowed_fallback(struct task_struct *p);
+extern void cpuset_cpus_allowed_without(struct task_struct *p, int cpu,
+					struct cpumask *mask);
 extern int cpuset_num_cpus(struct cgroup *cgroup);
 extern nodemask_t cpuset_mems_allowed(struct task_struct *p);
 #define cpuset_current_mems_allowed (current->mems_allowed)
@@ -214,6 +216,13 @@ static inline bool cpuset_cpus_allowed_fallback(struct task_struct *p)
 	return false;
 }
 
+static inline void cpuset_cpus_allowed_without(struct task_struct *p, int cpu,
+					       struct cpumask *mask)
+{
+	cpumask_and(mask, task_cpu_possible_mask(p), cpu_active_mask);
+	cpumask_clear_cpu(cpu, mask);
+}
+
 static inline int cpuset_num_cpus(struct cgroup *cgroup)
 {
 	return num_online_cpus();
kernel/cgroup/cpuset.c +26 -0
index 7bdb9e21a7ed..3ccd61a37d30 100644
@@ -4312,6 +4312,32 @@ void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
 	spin_unlock_irqrestore(&callback_lock, flags);
 }
 
+/*
+ * Set @pmask to the active CPUs that the cpuset of @tsk gives it once @cpu
+ * is offline: those of the nearest ancestor that keeps one. Leave it empty
+ * if there is none. As cpuset_update_tasks_cpumask() does, keep the CPUs
+ * possible for @tsk. As __set_cpus_allowed_ptr() does, keep those of the
+ * affinity the user set, if one is left. The caller holds the CPU hotplug
+ * lock for writing, which keeps the cpusets and their tasks as they are.
+ * It holds the pi_lock of @tsk, which keeps its user affinity.
+ */
+void cpuset_cpus_allowed_without(struct task_struct *tsk, int cpu,
+				 struct cpumask *pmask)
+{
+	struct cpuset *cs;
+
+	guard(rcu)();
+	for (cs = task_cs(tsk); cs; cs = parent_cs(cs)) {
+		cpumask_and(pmask, cs->effective_cpus, cpu_active_mask);
+		cpumask_clear_cpu(cpu, pmask);
+		if (!cpumask_empty(pmask))
+			break;
+	}
+	cpumask_and(pmask, pmask, task_cpu_possible_mask(tsk));
+	if (tsk->user_cpus_ptr && cpumask_intersects(pmask, tsk->user_cpus_ptr))
+		cpumask_and(pmask, pmask, tsk->user_cpus_ptr);
+}
+
 /**
  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
  * @tsk: pointer to task_struct with which the scheduler is struggling
kernel/sched/deadline.c +59 -1

68 lines not on this page · raw message

Signature · 1 line
2.47.3
#62 lore raw

PATCH v7 30/40 cgroup/cpuset: Refuse to take a deadline task out of its root domain

In reply to Mathieu Desnoyers

A cpuset attach asks the destination root domain for room before it moves a deadline task there. A change of the CPUs of a cpuset asks nothing. validate_change() only checks that a partition root keeps enough capacity for its deadline bandwidth. That check comes from commit f82f80426f7a ("sched/deadline: Ensure that updates to exclusive cpusets don't break AC").

With isolcpus="domain", a cpuset that is not a partition root can hold housekeeping CPUs and isolated CPUs, which are in two root domains. Two changes can take every CPU of one root domain away from that cpuset:

- a write to cpuset.cpus, of that cpuset or of an ancestor;
- a partition root that takes those CPUs, when it is created or when it grows.

A deadline task counted in that root domain then runs in the other one, which did not admit it. Its bandwidth follows with no admission test, and that root domain can exceed its limit.

Refuse both:

- A write to cpuset.cpus fails with EBUSY, and changes nothing. The cpuset.cpus file of cgroup v1 gets the same check.
- The write that makes the partition root, or makes it grow, still succeeds. cpuset makes the partition root invalid. For a "root" partition, cpuset.cpus.partition then reads "root invalid (Deadline task would leave its root domain)".

A task goes to another root domain by a move to another cpuset, which asks for room.

A change that leaves each deadline task a CPU in its root domain is accepted as before.

The check follows __set_cpus_allowed_ptr(). That keeps the new mask within the affinity set by the user, if they intersect. So a mask that grows can also take a task out of its root domain, and it is checked too. Changes that cannot fail are not checked: a partition that is disabled or becomes invalid, and a CPU that comes online.

dl_task_keeps_root_domain() tells whether a new mask keeps a task in the root domain that counts it. Without admission control it accepts any mask: there is no limit to exceed. An administrator who needs the change can turn admission control off, by writing -1 to /proc/sys/kernel/sched_rt_runtime_us.

The cases mask_out_refused and partition_takes_refused of deadline_bw_test, added later in this series, test this. Without this patch the write is accepted and the partition root is valid. These cases test the other paths:
- partition_takes_fallback_refused: the CPUs of an ancestor;
- mask_grows_refused: a mask that grows;
- partition_swap_refused: a partition root that takes and gives CPUs in one change;
- partition_refused_no_warn: a refusal with no warning.

Fixes f82f80426f7a ("sched/deadline: Ensure that updates to exclusive cpusets don't break AC")
---
 include/linux/sched/deadline.h  |   2 +
 kernel/cgroup/cpuset-internal.h |   1 +
 kernel/cgroup/cpuset.c          | 219 +++++++++++++++++++++++++++++++-
 kernel/sched/deadline.c         |  25 ++++
 4 files changed, 244 insertions(+), 3 deletions(-)
include/linux/sched/deadline.h +2 -0
index bdabd54af729..67426834a9a4 100644
@@ -62,6 +62,8 @@ extern int dl_task_bw_reserve_cpu(struct task_struct *p,
 				  const struct cpumask *new_mask);
 extern int dl_task_bw_reserved_cpu(struct task_struct *p);
 extern void dl_task_bw_unreserve(struct task_struct *p);
+extern bool dl_task_keeps_root_domain(struct task_struct *p,
+				      const struct cpumask *new_mask);
 
 static inline bool dl_server(struct sched_dl_entity *dl_se)
 {
kernel/cgroup/cpuset-internal.h +1 -0
index a83443dfb788..8fe0225704eb 100644
@@ -36,6 +36,7 @@ enum prs_errcode {
 	PERR_ACCESS,
 	PERR_REMOTE,
 	PERR_ISOPARENT,
+	PERR_DLTASK,
 };
 
 /* bits in struct cpuset flags field */
kernel/cgroup/cpuset.c +216 -3

280 lines not on this page · raw message

kernel/sched/deadline.c +25 -0
index 47264640de14..ff559f2729fb 100644
@@ -5091,6 +5091,31 @@ int dl_bw_deactivate(int cpu)
 	return ret;
 }
 
+/*
+ * Return false if @p has CPUs in the root domain that counts its
+ * bandwidth and @new_mask holds none of them. A cpuset refuses such a
+ * mask: only a move to another cpuset makes room in another root domain.
+ * Like __set_cpus_allowed_ptr(), keep @new_mask within the affinity set by
+ * the user, if they intersect.
+ */
+bool dl_task_keeps_root_domain(struct task_struct *p,
+			       const struct cpumask *new_mask)
+{
+	const struct cpumask *span;
+
+	if (!dl_bandwidth_enabled() || !task_has_dl_policy(p))
+		return true;
+	/* pi_lock also protects p->user_cpus_ptr. */
+	guard(raw_spinlock_irqsave)(&p->pi_lock);
+	guard(rcu)();
+	span = dl_task_bw_span(p);
+	if (!span || !cpumask_intersects(span, p->cpus_ptr))
+		return true;
+	if (p->user_cpus_ptr && cpumask_intersects(new_mask, p->user_cpus_ptr))
+		return cpumask_intersects_and(span, new_mask, p->user_cpus_ptr);
+	return cpumask_intersects(span, new_mask);
+}
+
 int dl_bw_alloc(int cpu, u64 dl_bw)
 {
 	return dl_bw_manage(dl_bw_req_alloc, cpu, dl_bw);
Signature · 1 line
2.47.3
#63 lore raw

PATCH v7 31/40 sched/deadline: Cancel the replenishment timer with the parameters

In reply to Mathieu Desnoyers

A task that leaves SCHED_DEADLINE has its parameters cleared at its 0-lag time. Its replenishment timer can still be armed then. If the task comes back and throttles before that timer fires, start_dl_timer() does not restart it, since it is queued. The replenishment would then come at the period of the reservation the task left. Too early, it would give the task runtime it has not earned. Too late, it would delay the task by up to a period.

Commit a649f237db18 ("sched,dl: Fix sched class hopping CBS hole") armed the replenishment timer when a task leaves the class. The timer then reset the task if it was still out. Commit 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization") moved that reset to the inactive timer, at the 0-lag time. Nothing cancels the replenishment timer there.

The timer of a throttled task fires at its next period, which can come after the 0-lag time:
- A task that yielded is throttled with runtime left. Its 0-lag time comes before its deadline.
- A constrained-deadline task that overran by little reaches its 0-lag time before the end of its period.

Fix this by cancelling the timer where the parameters are cleared. This includes task_non_contending(). switched_from_dl() calls it to release the bandwidth of a task that leaves asleep past its 0-lag time. A constrained task that overran as it blocked has the timer armed there too.

The Sashiko AI review of the first posting of this series found this. It has no reproducer.

Fixes 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization")
---
 kernel/sched/deadline.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/sched/deadline.c +2 -0
index ff559f2729fb..b9268c52935d 100644
@@ -694,6 +694,7 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 				if (dl_task && READ_ONCE(p->__state) == TASK_DEAD)
 					sub_rq_bw(dl_se, &rq->dl);
 				dl_task_release_bw(p);
+				cancel_replenish_timer(dl_se);
 				__dl_clear_params(dl_se);
 			}
 		}
@@ -2518,6 +2519,7 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 		}
 
 		dl_task_release_bw(p);
+		cancel_replenish_timer(dl_se);
 		__dl_clear_params(dl_se);
 
 		goto unlock;
Signature · 1 line
2.47.3
#64 lore raw

PATCH v7 32/40 sched/deadline: Count the bandwidth a boosted task is given

In reply to Mathieu Desnoyers

sched_setattr(SCHED_DEADLINE) on a sleeping task that priority inheritance boosted into the class leaves the new bandwidth out of this_bw. switched_to_dl() does not run, since the task is in the class already. sched_dl_overflow() changes this_bw only for a task of the deadline policy. When the task wakes up, __add_running_bw() warns:

	WARN_ON_ONCE(dl_rq->running_bw > dl_rq->this_bw);

When the task leaves the runqueue, this_bw would stay short by that bandwidth, and skew GRUB reclaiming on that CPU.

Fix this by changing this_bw in __setparam_dl(), which every task that gains deadline parameters goes through. If no runqueue counts the bandwidth of the task, dl_change_utilization() now adds the new one. It now also runs when the bandwidth does not change. It then returns early, so that a sleeping task keeps its running_bw and its inactive timer.

A sugov kthread given a reservation of its own now has its bandwidth counted in this_bw. It reaches dl_change_utilization(), so the WARN_ON_ONCE() for SCHED_FLAG_SUGOV there goes. sched_dl_overflow() returned early for an unchanged bandwidth, even if no root domain counts it. That is the case for such a kthread, and for a task that a rebuild left out. Admit such a bandwidth as new. Without room, that fails with EBUSY. The Sashiko AI review of the third posting found this early return.

A reproducer shows the warning, and this_bw unchanged by the change. With this patch, this_bw takes the new bandwidth, and nothing warns.

Fixes 8fd27231c330 ("sched/deadline: Track the "total rq utilization" too")
---
 kernel/sched/deadline.c | 54 ++++++++++++++++++++++++++++++++---------
 1 file changed, 43 insertions(+), 11 deletions(-)
kernel/sched/deadline.c +43 -11
index b9268c52935d..0b3005948313 100644
@@ -573,22 +573,37 @@ void cancel_inactive_timer(struct sched_dl_entity *dl_se)
 	cancel_dl_timer(dl_se, &dl_se->inactive_timer);
 }
 
+/*
+ * Make the runqueue of a sleeping task count @new_bw as the bandwidth of
+ * the task. Do nothing for a queued task. The dequeue and the enqueue
+ * around the change of its parameters update this_bw.
+ */
 static void dl_change_utilization(struct task_struct *p, u64 new_bw)
 {
-	WARN_ON_ONCE(p->dl.flags & SCHED_FLAG_SUGOV);
+	struct sched_dl_entity *dl_se = &p->dl;
+	struct rq *rq = task_rq(p);
 
 	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.
+	 * No runqueue counts the bandwidth of the task. Add the new one to
+	 * this runqueue, so that add_rq_bw() adds nothing later. A task that
+	 * enters the class asleep comes here, and so does a special entity
+	 * given a reservation of its own. So does a task waking up on
+	 * another CPU: task_cpu() already points at the CPU it wakes on.
 	 */
-	if (!p->dl.dl_bw_oncpu)
+	if (!dl_se->dl_bw_oncpu) {
+		__add_rq_bw(new_bw, &rq->dl);
+		dl_se->dl_bw_oncpu = 1;
+		return;
+	}
+
+	/* Same bandwidth: leave running_bw and the inactive timer alone. */
+	if (new_bw == dl_se->dl_bw)
 		return;
 
-	dl_rq_change_utilization(task_rq(p), &p->dl, new_bw);
+	dl_rq_change_utilization(rq, dl_se, new_bw);
 }
 
 static void __dl_clear_params(struct sched_dl_entity *dl_se);
@@ -4677,10 +4692,6 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	if (attr->sched_flags & SCHED_FLAG_SUGOV)
 		return 0;
 
-	/* !deadline task may carry old deadline bandwidth */
-	if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
-		return 0;
-
 	/*
 	 * Change the bandwidth of a deadline task where it is counted: in
 	 * the root domain of the CPU recorded with it. A task moved asleep
@@ -4695,6 +4706,16 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	 */
 	counted = task_has_dl_policy(p) && p->dl.dl_bw_cpu >= 0 &&
 		  p->dl.dl_bw_gen == dl_bw_gen;
+
+	/*
+	 * !deadline task may carry old deadline bandwidth. The same
+	 * bandwidth needs no admission if it is counted. If it is not, admit
+	 * it as new below. A special entity given a reservation of its own
+	 * has no bandwidth counted, nor has a task that a rebuild left out.
+	 */
+	if (new_bw == p->dl.dl_bw && counted)
+		return 0;
+
 	cpu = counted && p->dl.dl_bw ? p->dl.dl_bw_cpu : task_cpu(p);
 	dl_b = dl_bw_of(cpu);
 
@@ -4724,7 +4745,6 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 		if (counted)
 			__dl_sub(dl_b, p->dl.dl_bw, cpus);
 		__dl_add(dl_b, new_bw, cpus);
-		dl_change_utilization(p, new_bw);
 		err = 0;
 	} else if (!dl_policy(policy) && task_has_dl_policy(p)) {
 		/*
@@ -4774,8 +4794,20 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 void __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
 {
 	struct sched_dl_entity *dl_se = &p->dl;
+	u64 period = attr->sched_period ?: attr->sched_deadline;
 	bool held;
 
+	/*
+	 * Change the bandwidth that the runqueue counts here, with the
+	 * parameters. A task that priority inheritance boosted into the
+	 * class is in it already, so switched_to_dl() does not run for it.
+	 *
+	 * A special entity has no bandwidth on a runqueue. Test the flags
+	 * of the request, since those of the entity are still the old ones.
+	 */
+	if (!(attr->sched_flags & SCHED_FLAG_SUGOV))
+		dl_change_utilization(p, to_ratio(period, attr->sched_runtime));
+
 	held = dl_se_holds_bw(dl_se);
 	dl_se->dl_runtime = attr->sched_runtime;
 	dl_se->dl_deadline = attr->sched_deadline;
Signature · 1 line
2.47.3
#65 lore raw

PATCH v7 33/40 sched/deadline: Start a period for a task that enters the class blocked

In reply to Mathieu Desnoyers

Commit fb00aca47440 ("rtmutex: Turn the plist into an rb-tree") sorts the waiters of an rt_mutex by priority. For deadline tasks, "the one with the earliest deadline wins". A waiter takes the deadline of its task.

A task can enter the class while it waits on an rt_mutex. sched_setattr() can make it SCHED_DEADLINE. A priority inheritance boost can also put it in the class, if it owns another rt_mutex. switched_to_dl() leaves a task that is not queued to its wakeup. But the chain walk reads the deadline first, and copies it into the waiter. A task new to the class has a deadline of 0.

So the waiter goes before every other deadline waiter. It takes the rt_mutex first, whatever their deadlines. Those waiters can then miss their deadlines. It also boosts a deadline owner whose own deadline is earlier.

Fix this by starting a new period in switched_to_dl() for a task that waits on an rt_mutex, if its deadline has passed. The period uses the reservation the task runs on: its own, or the copy a boost made. This is what setup_new_dl_entity() does at an enqueue. At the wakeup, update_dl_entity() then checks that period as for any wakeup.

A new donor of a task with no parameters of its own needs the same. For a queued task, the enqueue of the boost starts a period from the new donor. For a blocked task, dl_boost_blocked() starts it at the boost.

The setattr_blocked_keeps_order and boost_blocked_keeps_order cases of deadline_bw_test, added later in this series, test this. Both fail on v7.4-rc2 and on the series without this patch. The triage of the Sashiko AI review of the fifth posting found the bug.

Fixes fb00aca47440 ("rtmutex: Turn the plist into an rb-tree")
---
 kernel/sched/core.c     |  2 ++
 kernel/sched/deadline.c | 42 +++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h    |  1 +
 3 files changed, 45 insertions(+)
kernel/sched/core.c +2 -0
index dc270a23179d..2d3409a1a12a 100644
@@ -7939,6 +7939,8 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 			     dl_entity_preempt(&pi_task->dl, &p->dl))) {
 				p->dl.pi_se = pi_task->dl.pi_se;
 				scope->flags |= ENQUEUE_REPLENISH;
+				if (!scope->queued)
+					dl_boost_blocked(p);
 			} else {
 				dl_deboost(&p->dl);
 				/*
kernel/sched/deadline.c +42 -0

66 lines not on this page · raw message

kernel/sched/sched.h +1 -0
index f80ea5541b3f..717ced2bb487 100644
@@ -358,6 +358,7 @@ extern int  sched_dl_overflow(struct task_struct *p, int policy, const struct sc
 extern void __setparam_dl(struct task_struct *p, const struct sched_attr *attr);
 #ifdef CONFIG_RT_MUTEXES
 extern void dl_deboost(struct sched_dl_entity *dl_se);
+extern void dl_boost_blocked(struct task_struct *p);
 
 /* End the boost of @dl_se. The caller holds the rq lock of its task. */
 static inline void dl_drop_boost(struct sched_dl_entity *dl_se)
Signature · 1 line
2.47.3
#68 lore raw

PATCH v7 34/40 sched/deadline: Cap the runtime left of a constrained task at dl_runtime

In reply to Mathieu Desnoyers

sched_setattr() can change the parameters of a SCHED_DEADLINE task. The task keeps its runtime and its absolute deadline: the new parameters take effect at the next period. At the next wakeup, update_dl_entity() checks the runtime left against the new parameters.

For a constrained task, that check uses the density, dl_runtime / dl_deadline. Commit 2317d5f1c349 ("sched/deadline: Use deadline instead of period when calculating overflow") made dl_entity_overflow() compare with it: "We care about if the runtime can make its deadline, not its period." Commit 3effcb4247e7 ("sched/deadline: Use the revised wakeup rule for suspending constrained dl tasks") then cut the runtime of a constrained task that overflows to density * laxity. Both bound the runtime by dl_runtime only while the deadline is at most dl_deadline ahead.

A change to a shorter dl_deadline breaks that. The old deadline can be farther ahead. The check then keeps more runtime than the new dl_runtime, or computes more. For example, take a task of 50ms every 100ms with 49ms left. Changed to 8ms in 20ms every 100ms, it would wake with 39.6ms. It would then run far more than its new runtime in this period. Admission control already counts the new, smaller bandwidth. So other deadline tasks could miss their deadlines.

An implicit task is not affected. Its check compares with its bandwidth, which bounds the runtime for any deadline.

Fix this by keeping no more than dl_runtime before the check, for a constrained task. A boosted task runs on the parameters of its donor, and is left alone. The runtime is signed and can be negative there, so compare it as signed.

The cases change_constrained_new_params and wake_constrained_new_params of deadline_bw_test, added later in this series, test this. The first changes a running task, the second a sleeping one. Both fail without this patch.

The Sashiko AI review of the sixth posting of this series found this.

Fixes 2317d5f1c349 ("sched/deadline: Use deadline instead of period when calculating overflow")
Fixes 3effcb4247e7 ("sched/deadline: Use the revised wakeup rule for suspending constrained dl tasks")
---
 kernel/sched/deadline.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
kernel/sched/deadline.c +19 -0
index 90b17969554b..1a07f4109cc5 100644
@@ -1389,6 +1389,25 @@ static void update_dl_entity(struct sched_dl_entity *dl_se)
 {
 	struct rq *rq = rq_of_dl_se(dl_se);
 
+	/*
+	 * The checks below compare the runtime left with the density,
+	 * dl_runtime / dl_deadline. That bounds the runtime by dl_runtime
+	 * only while the deadline is at most dl_deadline ahead. After a
+	 * change to a shorter dl_deadline, the deadline can be farther
+	 * ahead, and the runtime left larger than dl_runtime. A constrained
+	 * task would then run more than dl_runtime in a period. Keep no
+	 * more than dl_runtime.
+	 *
+	 * An implicit task is checked against its bandwidth, which holds
+	 * for any deadline. A boosted task runs on the parameters of its
+	 * donor. Leave both alone.
+	 *
+	 * The runtime is signed, and can be negative here.
+	 */
+	if (!dl_is_implicit(dl_se) && !is_dl_boosted(dl_se) &&
+	    dl_se->runtime > (s64)dl_se->dl_runtime)
+		dl_se->runtime = dl_se->dl_runtime;
+
 	if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
 	    dl_entity_overflow(dl_se, rq_clock(rq))) {
 
Signature · 1 line
2.47.3
#69 lore raw

PATCH v7 35/40 sched/deadline: Check the runtime of a task that comes back runnable

In reply to Mathieu Desnoyers

Commit a649f237db18 ("sched,dl: Fix sched class hopping CBS hole") keeps the runtime and the deadline of a task that leaves SCHED_DEADLINE. A task that comes back before its deadline goes on with them. So leaving the class and coming back gives no new runtime.

But the task can come back with new parameters. If it is asleep, its wakeup checks the runtime left against them, with dl_entity_overflow(). If it is runnable, enqueue_dl_entity() starts a new period only if the deadline has passed. The runtime left is not checked.

So a task can come back with a smaller runtime, and still run on the old one. Admission control counts only the new one. Juri Lelli found this case. On v7.4-rc2, a task of 50ms every 100ms came back through SCHED_OTHER with 10ms every 100ms. It ran 39ms of the next 100ms.

Fix this by applying the wakeup rule to a task that enters the class runnable, with update_dl_entity(). It starts a new period, or reduces the runtime of a constrained task, if the runtime left does not fit the new parameters. The task gets no more than a wakeup would give it.

The return_running_new_params case of deadline_bw_test, added later in this series, tests this. It fails on v7.4-rc2 and passes with this patch. The return_asleep_new_params case tests the wakeup, and passes on both.

Fixes a649f237db18 ("sched,dl: Fix sched class hopping CBS hole")
---
 kernel/sched/deadline.c | 8 ++++++++
 1 file changed, 8 insertions(+)
kernel/sched/deadline.c +8 -0
index 1a07f4109cc5..b650c37ae561 100644
@@ -2834,6 +2834,14 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 		update_dl_entity(dl_se);
 	} else if (flags & ENQUEUE_REPLENISH) {
 		replenish_dl_entity(dl_se);
+	} else if ((flags & ENQUEUE_CLASS) && !is_dl_boosted(dl_se)) {
+		/*
+		 * The task enters the class runnable. It may come back before
+		 * its deadline, with the runtime left from older parameters.
+		 * Check that runtime against the new parameters, as a wakeup
+		 * does.
+		 */
+		update_dl_entity(dl_se);
 	} else if ((flags & ENQUEUE_MOVE) &&
 		   !is_dl_boosted(dl_se) &&
 		   dl_time_before(dl_se->deadline, rq_clock(rq_of_dl_se(dl_se)))) {
Signature · 1 line
2.47.3
#70 lore raw

PATCH v7 36/40 sched/deadline: Check the runtime of a task whose parameters change

In reply to Mathieu Desnoyers

Commit 40767b0dc768 ("sched/deadline: Fix deadline parameter modification handling") lets new parameters take effect at the next period. So sched_setattr() cannot give a task a fresh runtime.

But admission control counts the new bandwidth at once. When a task shrinks its reservation, the runtime left from the old one is not checked against the new one. A comment in sched_dl_overflow() names the gap: the old bandwidth should stay counted until the 0-lag time.

So a running task can shrink its reservation, and still run on the old one. Other tasks can meanwhile be admitted into the bandwidth it gave back. On v7.4-rc2, a task of 50ms every 100ms changed to 10ms every 100ms. It ran 39ms of the next 100ms.

Fix this by applying the wakeup rule after a change of parameters, as the previous patch does for a task that enters the class. __setparam_dl() marks a change of the runtime, the deadline or the period. The next enqueue then calls update_dl_entity(). It starts a new period, or reduces the runtime of a constrained task, if the runtime left does not fit. The task gets no more than a wakeup would give it. A boosted task runs on the parameters of its donor. So it keeps the mark until an enqueue after its deboost.
A larger reservation still takes effect at the next period.

The enqueue flags cannot tell a change of parameters: a cgroup move also uses ENQUEUE_MOVE. Without the mark, a task that waited behind others could fail the check, and get a later deadline for no reason.

The change_running_new_params case of deadline_bw_test, added later in this series, tests this. change_boosted_new_params tests a task that changes its parameters while boosted. Both fail on v7.4-rc2 and pass with this patch.

Fixes 40767b0dc768 ("sched/deadline: Fix deadline parameter modification handling")
---
 include/linux/sched.h   |  5 +++++
 kernel/sched/deadline.c | 26 +++++++++++++++++++++-----
 2 files changed, 26 insertions(+), 5 deletions(-)
include/linux/sched.h +5 -0
index 2f2f59402f09..5bb41f350936 100644
@@ -715,6 +715,10 @@ struct sched_dl_entity {
 	 * @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.
+	 *
+	 * @dl_new_params tells if sched_setattr() changed the runtime, the
+	 * deadline or the period. The next enqueue that is not boosted checks
+	 * the runtime left against them, and clears it.
 	 */
 	unsigned int			dl_throttled      : 1;
 	unsigned int			dl_yielded        : 1;
@@ -729,6 +733,7 @@ struct sched_dl_entity {
 	unsigned int			dl_defer_idle     : 1;
 	unsigned int			dl_bw_attached    : 1;
 	unsigned int			dl_bw_oncpu       : 1;
+	unsigned int			dl_new_params     : 1;
 
 	/*
 	 * Bandwidth enforcement timer. Each -deadline task has its
kernel/sched/deadline.c +21 -5
index b650c37ae561..f1d259df8f2a 100644
@@ -2785,7 +2785,16 @@ static void __dequeue_dl_entity(struct sched_dl_entity *dl_se)
 static void
 enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 {
+	bool new_params = dl_se->dl_new_params;
+
 	WARN_ON_ONCE(on_dl_rq(dl_se));
+	/*
+	 * A boosted task runs on the parameters of its donor. Keep the mark
+	 * until an enqueue checks the runtime against its own: the one at
+	 * the deboost, or at a wakeup.
+	 */
+	if (!is_dl_boosted(dl_se))
+		dl_se->dl_new_params = 0;
 
 	update_stats_enqueue_dl(dl_rq_of_se(dl_se), dl_se, flags);
 
@@ -2834,12 +2843,13 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 		update_dl_entity(dl_se);
 	} else if (flags & ENQUEUE_REPLENISH) {
 		replenish_dl_entity(dl_se);
-	} else if ((flags & ENQUEUE_CLASS) && !is_dl_boosted(dl_se)) {
+	} else if (((flags & ENQUEUE_CLASS) || new_params) &&
+		   !is_dl_boosted(dl_se)) {
 		/*
-		 * The task enters the class runnable. It may come back before
-		 * its deadline, with the runtime left from older parameters.
-		 * Check that runtime against the new parameters, as a wakeup
-		 * does.
+		 * The task enters the class, or its parameters change, while
+		 * it is runnable. It may have runtime left from older
+		 * parameters. Check that runtime against the new parameters,
+		 * as a wakeup does.
 		 */
 		update_dl_entity(dl_se);
 	} else if ((flags & ENQUEUE_MOVE) &&
@@ -4866,6 +4876,11 @@ void __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
 	u64 period = attr->sched_period ?: attr->sched_deadline;
 	bool held;
 
+	if (attr->sched_runtime != dl_se->dl_runtime ||
+	    attr->sched_deadline != dl_se->dl_deadline ||
+	    period != dl_se->dl_period)
+		dl_se->dl_new_params = 1;
+
 	/*
 	 * Change the bandwidth that the runqueue counts here, with the
 	 * parameters. A task that priority inheritance boosted into the
@@ -4999,6 +5014,7 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se)
 	dl_se->dl_defer_running		= 0;
 	dl_se->dl_defer_armed		= 0;
 	dl_se->dl_bw_oncpu		= 0;
+	dl_se->dl_new_params		= 0;
 
 #ifdef CONFIG_RT_MUTEXES
 	dl_se->pi_se			= dl_se;
Signature · 1 line
2.47.3
#73 lore raw

PATCH v7 37/40 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 and random_mix cases. It checks that this_bw is back to its first value once their tasks are gone.

---
 kernel/sched/debug.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/sched/debug.c +2 -0
index e0d6cd3bd607..3dbe1d7d2d77 100644
@@ -1174,6 +1174,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
#74 lore raw

PATCH v7 38/40 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 four 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     | 1089 +++++++++++++++++
 5 files changed, 1100 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 +1089 -0

1,089 lines not on this page · raw message

Signature · 1 line
2.47.3
#77 lore raw

PATCH v7 39/40 selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild

In reply to Mathieu Desnoyers

A task that leaves SCHED_DEADLINE, or dies, keeps its bandwidth until its 0-lag time. No selftest checks what happens to this bandwidth meanwhile.

Add deadline_rebuild_test, with three cases. In each case, a task of 400ms every second runs 380ms, then leaves SCHED_DEADLINE. Its 0-lag time is then about 570ms ahead. P is a partition root of one CPU. Before the 0-lag time:
- dies_before_rebuild: the task exits in P. Then a second partition root is made, which rebuilds the accounting of every root domain.
- switched_out_before_rebuild: the same, but the task switches to SCHED_OTHER and sleeps in P.
- moved_after_switch_out: the task switches to SCHED_OTHER outside P. Then it moves into P and dies there.

After the 0-lag time, P must admit one task of 600ms every second, and refuse a second one with EBUSY. A kernel with the bug removes the bandwidth from P's root domain at the 0-lag time. But the rebuild dropped it already, or P never had it. total_bw then wraps around, and P admits both tasks.

The test skips without root, 3 CPUs, the cgroup v2 cpuset controller or deadline admission control. Admission control is off when sched_rt_runtime_us is -1.

On v7.4-rc2, in 8-CPU VMs, the three cases fail. "sched/deadline: Keep departing bandwidth across a root domain rebuild" fixes them. With the whole series, the three cases pass, with and without PREEMPT_RT.

---
 .../selftests/sched/deadline/.gitignore       |   1 +
 .../testing/selftests/sched/deadline/Makefile |   2 +-
 tools/testing/selftests/sched/deadline/config |   2 +
 .../sched/deadline/deadline_rebuild_test.c    | 497 ++++++++++++++++++
 4 files changed, 501 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
tools/testing/selftests/sched/deadline/.gitignore +1 -0
index 9f203c455b91..bf7dd0da81a9 100644
@@ -1 +1,2 @@
 deadline_switch_test
+deadline_rebuild_test
tools/testing/selftests/sched/deadline/Makefile +1 -1
index 3f4dc1ec6119..f3a1d1746d22 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_rebuild_test
 
 include ../../lib.mk
tools/testing/selftests/sched/deadline/config +2 -0
index 3a3a7285a708..a711e8af46bf 100644
@@ -1 +1,3 @@
+CONFIG_CGROUPS=y
+CONFIG_CPUSETS=y
 CONFIG_MAGIC_SYSRQ=y
tools/testing/selftests/sched/deadline/deadline_rebuild_test.c new file +497 -0

497 lines not on this page · raw message

Signature · 1 line
2.47.3
#78 lore raw

PATCH v7 40/40 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 104 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
- what can happen during a cpuset move: a rebuild of the sched domains, a policy change, an affinity change, a wakeup, the death of a thread, a refusal by another controller
- deaths, sched_yield() and runtime overruns
- a stopped task and a frozen task
- bandwidth reclaiming and fair server changes
- CPU hotplug, also with admission control turned off
- sched_setaffinity() racing with sched_setattr()
- parameter changes while a task wakes on another CPU (params_waking)
- a random mix of all of the above, with affinity changes (random_mix)

The comment above each case gives its scenario. params_waking and random_mix also compare the this_bw of their CPUs, which "sched/debug:
Show the deadline bandwidth of each runqueue" prints. Four cases follow reproducers of Juri Lelli's sched-deadline-tests: stopped_switched_out, hotplug_sleeper_switched, hotplug_no_admission_pinned 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. Twenty-three cases need CPUs isolated by isolcpus=domain. move_cancelled needs CONFIG_RT_GROUP_SCHED. move_normalized fires sysrq-n, which changes the whole system, so it needs DEADLINE_TEST_SYSRQ=1. 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 up to the patch before its fix, and passes from the fix:
- overrun_caught and stopped_switched_out: "sched/deadline: Release the bandwidth of a task that leaves the class asleep"
- hotplug_departed and hotplug_no_admission_pinned: "sched/deadline:
Keep departing bandwidth across a root domain rebuild". Before it, the second one fails in part of the runs.
- move_asleep, move_non_contending, move_died, move_woken and
move_woken_full: "sched/deadline: Record the root domain holding a task's bandwidth"
- affinity_vs_setattr: "sched/deadline: Check SCHED_DEADLINE affinity under the rq lock"
- params_keep_class_change: "sched: Refuse SCHED_FLAG_KEEP_PARAMS that would change the policy or the class"

On v7.4-rc2, in 8 VMs of 8 CPUs, 35 cases fail in every VM. overrun_caught fails in part of the runs. The same holds on tip sched/urgent, the base of this series. The 35 cases are:

  affinity_vs_setattr              move_affinity_changed
  boost_blocked_keeps_order        move_asleep
  boosted_owner_policy             move_back_cpu_offline
  change_boosted_new_params        move_became_deadline
  change_constrained_new_params    move_became_deadline_no_room
  change_running_new_params        move_died
  death_zombie_hotplug             move_non_contending
  death_zombie_switched            move_vs_rebuild
  deboost_after_donor_refill       move_woken
  deboost_in_class_resets_period   move_woken_full
  deboost_released_resets_period   params_keep_boosted
  deboost_resets_period            params_keep_class_change
  hotplug_departed                 pi_departed_moved
  hotplug_no_admission_pinned      pi_former_owner_asleep
  hotplug_sleeper_switched         random_mix
  move_affinity_became_deadline    return_running_new_params
  setattr_blocked_keeps_order      stopped_switched_out

wake_constrained_new_params

28 cases skip there. 25 lack what they need. hotplug_refused and hotplug_server cannot set up their state. move_normalized was not run:
on v7.4-rc2, sysrq-n leaves cpuset_mutex locked, which "sched: Take cpuset_mutex for a deadline policy change only with pi" fixes.

With the whole series, every case passes wherever it runs, PREEMPT_RT included. The twenty-three isolcpus cases ran 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 |    2 +
 .../sched/deadline/deadline_bw_test.c         | 9597 +++++++++++++++++
 .../testing/selftests/sched/deadline/settings |    1 +
 5 files changed, 9602 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 bf7dd0da81a9..42f6b2945e96 100644
@@ -1,2 +1,3 @@
 deadline_switch_test
 deadline_rebuild_test
+deadline_bw_test
tools/testing/selftests/sched/deadline/Makefile +1 -1
index f3a1d1746d22..15f1e96a21e6 100644
@@ -3,6 +3,6 @@
 CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES)
 LDLIBS += -lpthread
 
-TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test
+TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test deadline_bw_test
 
 include ../../lib.mk
tools/testing/selftests/sched/deadline/config +2 -0
index a711e8af46bf..b19db0c962e0 100644
@@ -1,3 +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 +9597 -0

2,985 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.

#7 lore raw

Re: [PATCH v7 05/40] sched/deadline: Refuse dl_server debugfs writes while the rq is offline

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/debug: sched_server_write_common() misses CPU deactivation window --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/debug: sched_server_write_common() misses CPU deactivation window
--

commit 6c51bc6b398f0bfbd0028d2f5672f277e0ab2db8
Author: Mathieu Desnoyers <[email protected]>

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

This commit replaces the cpu_online() check in sched_server_write_common() with an !rq->online check to reject dl_server debugfs writes while a runqueue is offline during CPU hotplug transitions.

Quoted 11 lines
kernel/sched/debug.c +2 -1
index e6a3b516c703b..e0d6cd3bd607d 100644
@@ -410,7 +410,15 @@ 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

kernel/sched/debug.c static ssize_t sched_server_write_common(struct file *filp, const char __user *u · line 424

Quoted 10 lines
kernel/sched/debug.c +7 -0
+		 * 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.
+		 */
+		if (!rq->online)
 			return -EBUSY;
 
 		update_rq_clock(rq);

[Severity: Medium]
Does checking only !rq->online still leave a window during CPU deactivation where cpu_active(cpu) is already false while rq->online is still set?

In sched_cpu_deactivate(), set_cpu_active(cpu, false) clears the CPU from cpu_active_mask before synchronize_rcu(), and sched_set_rq_offline() sets rq->online = 0 only after synchronize_rcu() completes:

CPU0 CPU1
sched_cpu_deactivate(cpu)
set_cpu_active(cpu, false)
synchronize_rcu()

                                  sched_server_write_common()
                                    guard(rq_lock_irqsave)(rq)
                                    if (!rq->online)  // still 1
                                    dl_server_apply_params()
                                      cpus = dl_bw_cpus(cpu);
                                    dl_server_start()
  sched_set_rq_offline(rq, cpu)
    rq->online = 0

Because dl_bw_cpus(cpu) and dl_bw_capacity(cpu) intersect rq->rd->span with cpu_active_mask, they already exclude the deactivating CPU before cpuset_cpu_inactive() rebuilds the root domain. If the CPU was the only active CPU in its root domain (for example, a single-CPU cpuset partition), dl_bw_cpus(cpu) is 0 while rq->online is still 1. Even when N - 1 active CPUs remain in the root domain, dl_b->total_bw still counts all N servers while __dl_overflow(), __dl_sub(), and __dl_add() account against N - 1 CPUs, and dl_server_start() re-enqueues the server on the deactivating runqueue after balance_push_set(cpu, true).

Checking (!rq->online || !cpu_active(cpu_of(rq))) under rq_lock_irqsave would close both the activation and deactivation windows.

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

Re: [PATCH v7 09/40] rtmutex: Continue the chain walk when a waiter's deadline donor changes

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] rtmutex: premature chain walk stop in rt_mutex_adjust_prio_chain() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] rtmutex: premature chain walk stop in rt_mutex_adjust_prio_chain()
--

commit 9c99e3811a419d96fcdd59dd7a4617c1edc67678
Author: Mathieu Desnoyers <[email protected]>

rtmutex: Continue the chain walk when a waiter's deadline donor changes

This commit records the task's deadline donor in struct rt_mutex_waiter and checks it in rt_waiter_up_to_date() so that priority inheritance chain walks continue when a blocked task's deadline donor changes without changing its sort keys.

Quoted 4 lines
kernel/locking/rtmutex.c +0 -0
index 5a9534c715b84..c78dfe9c93fc5 100644

[ ... ]

Quoted 6 lines
kernel/locking/rtmutex.c +1 -1
@@ -824,12 +841,13 @@ static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
 
 	/*
 	 * If the waiter priority is the same as the task priority
-	 * then there is no further priority adjustment necessary.  If
+	 * then there is no further priority adjustment necessary. The

kernel/locking/rtmutex.c static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task, · line 853

Quoted 10 lines
kernel/locking/rtmutex.c +2 -1
+	 * task must also pass on the same deadline donor.  If
 	 * deadlock detection is off, we stop the chain walk. If its
 	 * enabled we continue, but stop the requeueing in the chain
 	 * walk.
 	 */
-	if (rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task))) {
+	if (rt_waiter_up_to_date(waiter, task)) {
 		if (!detect_deadlock)
 			goto out_unlock_pi;
 		else

[Severity: High]
Can rt_mutex_adjust_prio_chain() still stop one lock too early at the preceding top_waiter != task_top_pi_waiter(task) check when a task holds two locks and its top PI waiter switches from one lock to the other?

Consider the commit message setup where O (SCHED_OTHER) holds L2, M (SCHED_OTHER) holds L1 and L1' and blocks on L2, W (SCHED_DEADLINE, earlier deadline) blocks on L1', and Z (SCHED_DEADLINE, later deadline) blocks on L1, so both M and O have dl.pi_se = &W->dl. If W switches to SCHED_OTHER via sched_setscheduler() -> rt_mutex_adjust_pi(W), the first iteration of rt_mutex_adjust_prio_chain() demotes W's waiter on L1' in M->pi_waiters, making Z's waiter on L1 the new task_top_pi_waiter(M) and updating M->dl.pi_se = &Z->dl, while step [12] records L1's top waiter:

kernel/locking/rtmutex.c:rt_mutex_adjust_prio_chain() {
    ...
	if (top_waiter) {
		if (!task_has_pi_waiters(task))
			goto out_unlock_pi;
		if (top_waiter != task_top_pi_waiter(task)) {
			if (!detect_deadlock)
				goto out_unlock_pi;
    ...
	top_waiter = rt_mutex_top_waiter(lock);
}

On the next iteration at M, top_waiter is still W's waiter on L1' while task_top_pi_waiter(M) is Z's waiter on L1, so the walk exits at goto out_unlock_pi before reaching rt_waiter_up_to_date(waiter, task). O->dl.pi_se remains &W->dl, and once W unblocks and exits, O's next replenish_dl_entity() reads W's freed task_struct (use-after-free).

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

Re: [PATCH v7 12/40] sched/deadline: Replenish a throttled task boosted while asleep

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: dl_task_timer() refills sleeping boosted task from donor --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: dl_task_timer() refills sleeping boosted task from donor
--

commit 2a5083dbbf5a615c669ceffa5d4cba59162262f3
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Replenish a throttled task boosted while asleep

This commit changes dl_task_timer() to return early for a boosted task only when it is queued on the runqueue, allowing a sleeping boosted task to fall through and be replenished when its deadline timer fires.

Quoted 11 lines
kernel/sched/deadline.c +1 -2
index 989e7e7d3f8f1..2b5a2a43addfd 100644
@@ -1319,10 +1319,13 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
 	}
 
 	/*
-	 * The task might have been boosted by someone else and might be in the
-	 * boosting/deboosting path, its not throttled.
+	 * A boost overrides the throttle. enqueue_task_dl() lifts it when the

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

Quoted 10 lines
kernel/sched/deadline.c +5 -1
+	 * boost enqueues the task, or when the task wakes up boosted. So a
+	 * queued task needs nothing here. A boost of a sleeping task does not
+	 * enqueue it, and it can end before the wakeup. Nothing would lift the
+	 * throttle then. So let a sleeping task reach the !queued case below.
 	 */
-	if (is_dl_boosted(dl_se))
+	if (is_dl_boosted(dl_se) && task_on_rq_queued(p))
 		goto unlock;
 
 	/*

[Severity: Medium]
Does letting a sleeping boosted task fall through to replenish_dl_entity() corrupt its CBS accounting by refilling its pre-boost deficit from the donor's reservation parameters?

A task only sets dl_throttled and arms dl_timer while unboosted, so when dl_task_timer() fires while p is still asleep, p has never executed under the boost and dl_se->runtime and dl_se->deadline still reflect p's own pre-sleep reservation. However, replenish_dl_entity() reads runtime, deadline, and period from pi_of(dl_se):

kernel/sched/deadline.c:replenish_dl_entity() {
	...
	if (dl_se->runtime <= 0)
		dl_note_donor_refill(dl_se);

	while (dl_se->runtime <= 0) {
		dl_se->deadline += period;
		dl_se->runtime += runtime;
	}
	...
}

Because dl_note_donor_refill() sets dl_se->dl_donor_refill, if the donor times out and deboosts p before wakeup, dl_deboost() resets dl_se->deadline and dl_se->runtime to a full new period, forgiving any runtime overrun p owed before going to sleep.

If p instead wakes up while still boosted after overrunning its own budget, the while loop above pays off p's overrun in multiples of the donor's smaller runtime and period, which can push p's boosted deadline several donor periods into the future. For a constrained-deadline task whose dl_timer fires at dl_next_period(dl_se), adding a donor's shorter dl_period to p's earlier dl_se->deadline can leave dl_se->deadline behind rq_clock(rq) and falsely trigger the "sched: DL replenish lagged too much" warning. If the donor left SCHED_DEADLINE and had its parameters cleared before dl_task_timer() runs, the !runtime branch in replenish_dl_entity() skips dl_note_donor_refill() and the deadline update because dl_se->dl_deadline is non-zero, leaving p's expired deadline in the past after dl_deboost(). Finally, if p changed policy while sleeping and boosted, refilling from the donor before 0-lag time leaves donor-derived runtime and deadline on p when rt_mutex_setprio() drops the boost via dl_drop_boost().

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

Re: [PATCH v7 11/40] sched/deadline: Reset the donor's runtime at a deboost in the class

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: rt_mutex_setprio() skips dl_deboost() on donor change - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: rt_mutex_setprio() skips dl_deboost() on donor change
- [Medium] sched/deadline: donor runtime kept when leaving dl_sched_class
- [Low] sched/deadline: missing dl_note_donor_refill() on cleared donor in replenish_dl_entity()
--

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

sched/deadline: Reset the donor's runtime at a deboost in the class

This commit adds a dl_donor_refill flag to record when a boosted task has its runtime replenished from a donor's reservation, and starts a new period from the task's own parameters when the boost ends in the deadline class.

[ ... ]

Quoted 11 lines
kernel/sched/core.c +2 -1
index 5ed660f099a55..a22df8b43a1a7 100644
@@ -7834,16 +7834,26 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 				p->dl.pi_se = pi_task->dl.pi_se;
 				scope->flags |= ENQUEUE_REPLENISH;
 			} else {
-				p->dl.pi_se = &p->dl;
+				dl_deboost(&p->dl);
+				/*

kernel/sched/core.c void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) · line 7848

Quoted 10 lines
kernel/sched/core.c +9 -0
+				 * dl_deboost() can start a new period. Its
+				 * deadline can then be after the top waiter's.
+				 * Boost the task again then.
+				 */
+				if (pi_task && dl_prio(pi_task->prio) &&
+				    dl_entity_preempt(&pi_task->dl, &p->dl)) {
+					p->dl.pi_se = pi_task->dl.pi_se;
+					scope->flags |= ENQUEUE_REPLENISH;
+				}
 			}

[Severity: Medium]
Can a SCHED_DEADLINE task skip dl_deboost(&p->dl) here when switching from one deadline donor to another?

In rt_mutex_setprio(), the outer if statement tests dl_entity_preempt(&pi_task->dl, &p->dl) before calling dl_deboost(&p->dl). When p was refilled from a previous donor W1, p->dl.deadline holds W1's postponed deadline rather than p's own reservation deadline. If p unlocks W1's lock while another deadline waiter W2 is queued on a lock held by p, and W2->dl.deadline is earlier than W1's postponed deadline, the outer check takes the first branch and skips dl_deboost(&p->dl).

Because p->dl.dl_deadline is non-zero and p->dl.runtime is still positive from W1's refill, ENQUEUE_REPLENISH in replenish_dl_entity() does not reset p->dl.runtime or p->dl.deadline either. p then keeps W1's leftover runtime and postponed deadline, even if p's own new-period deadline would have been earlier than W2->dl.deadline.

Calling dl_deboost(&p->dl) unconditionally when dl_prio(p->normal_prio) before testing whether pi_task preempts &p->dl would compare pi_task against p's own reservation.

kernel/sched/core.c void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) · line 7859

Quoted 13 lines
kernel/sched/core.c +2 -2
 		} else if (rt_prio(prio)) {
 			if (dl_prio(oldprio))
-				p->dl.pi_se = &p->dl;
+				dl_drop_boost(&p->dl);
 			if (oldprio < prio)
 				scope->flags |= ENQUEUE_HEAD;
 		} else {
 			if (dl_prio(oldprio))
-				p->dl.pi_se = &p->dl;
+				dl_drop_boost(&p->dl);
 			if (rt_prio(oldprio))
 				p->rt.timeout = 0;
 		}

[Severity: Medium]
Does a task that still has SCHED_DEADLINE parameters (p->dl.dl_runtime != 0) keep the donor's refilled runtime and deadline when leaving the deadline class at deboost?

A task can have p->dl.dl_runtime != 0 and p->dl.dl_donor_refill == 1 while leaving dl_sched_class (for example, if it changed its policy away from SCHED_DEADLINE while boosted and then unlocks, or if it left SCHED_DEADLINE before its 0-lag time and was boosted and refilled before inactive_timer fired). When it leaves dl_sched_class, sched_change_begin() runs switched_from_dl() before dl_drop_boost(&p->dl) clears dl_donor_refill:

kernel/sched/deadline.c:switched_from_dl() {
	if (task_on_rq_queued(p) && p->dl.dl_runtime)
		task_non_contending(&p->dl, false);
	...
	if (!p->dl.dl_runtime) {
		p->dl.deadline = 0;
		p->dl.runtime = 0;
	}
}

Because p->dl.dl_runtime is non-zero, switched_from_dl() passes the donor's refilled runtime and deadline to task_non_contending(), which mixes them with p's own dl_period and dl_runtime to compute zerolag_time. If the donor's remaining runtime makes zerolag_time negative, task_non_contending() clears p's parameters immediately and lets p re-enter SCHED_DEADLINE with a fresh budget in the same period; otherwise, p retains the donor's runtime and deadline if it returns to SCHED_DEADLINE before inactive_timer fires.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index d6d2657dcddd6..989e7e7d3f8f1 100644

[ ... ]

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

Quoted 8 lines
kernel/sched/deadline.c +1 -0
@@ -832,6 +869,7 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 		if (!dl_se->dl_deadline) {
 			dl_se->deadline = rq_clock(rq);
 			dl_se->runtime = 0;
+			dl_note_donor_refill(dl_se);
 		}
 		if (dl_se->runtime < 0 || dl_se->dl_yielded)
 			dl_se->runtime = 0;

[Severity: Low]
In this cleared-donor fallback (!runtime || !deadline || !period), should dl_note_donor_refill(dl_se) also be called when dl_se->dl_deadline is non-zero?

If a boosted SCHED_DEADLINE task hits this path when its runtime is exhausted or after sched_yield(), replenish_dl_entity() zeroes dl_se->runtime and clears dl_se->dl_throttled without setting dl_donor_refill. A subsequent dl_deboost() then leaves the task in the class with runtime == 0, dl_throttled == 0, and its old deadline.

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

Re: [PATCH v7 10/40] sched/deadline: Reset the deadline and the runtime with the parameters

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: donor runtime kept in switched_from_dl() when dl_runtime != 0 --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: donor runtime kept in switched_from_dl() when dl_runtime != 0
--

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

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

This commit resets a deadline entity's dynamic deadline and 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 its next entry into the class starts a new period.

Quoted 7 lines
kernel/sched/deadline.c +0 -0
index 71b1c155c2424..d6d2657dcddd6 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);

kernel/sched/deadline.c static void switched_from_dl(struct rq *rq, struct task_struct *p) · line 3580

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

[Severity: Medium]
Can a task deboosting via switched_from_dl() still retain a donor's deadline and runtime when p->dl.dl_runtime is non-zero?

If a SCHED_DEADLINE task holding an rt_mutex contended by a deadline waiter changes policy to SCHED_OTHER, __setscheduler_dl_pi() keeps it boosted in dl_sched_class with its non-zero p->dl.dl_runtime while setting p->dl.pi_se to the donor. When its runtime is replenished while boosted, replenish_dl_new_period() refills p->dl.deadline and p->dl.runtime from the donor's reservation.

At unlock, rt_mutex_setprio() invokes switched_from_dl() before calling dl_drop_boost(&p->dl). Because p->dl.dl_runtime is non-zero, switched_from_dl() skips resetting p->dl.deadline and p->dl.runtime, and task_non_contending() computes zerolag_time by mixing the donor's dynamic deadline and runtime with p's static dl_period and dl_runtime. If the donor's runtime makes zerolag_time negative, task_non_contending() clears p's bandwidth and parameters before its true 0-lag time; otherwise, p keeps the donor's runtime and can consume it on top of its own reservation if it re-enters SCHED_DEADLINE before the inactive timer fires.

Commits "sched/deadline: Reset the donor's runtime at a deboost in the class" and "sched/deadline: Check the runtime of a task whose parameters change" later in this series handle deboosts that stay in dl_sched_class, but do not cover leaving dl_sched_class via switched_from_dl() with non-zero p->dl.dl_runtime.

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

Re: [PATCH v7 18/40] sched/deadline: Record the root domain holding a task's bandwidth

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: __sched_setscheduler() checks task_rq(p) root domain --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: __sched_setscheduler() checks task_rq(p) root domain
--

commit 889f3e0f3403117f479bd558c00411593ac35a7e
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Record the root domain holding a task's bandwidth

This commit replaces dl_departed_cpu with dl_bw_cpu in struct sched_dl_entity to record a CPU of the root domain that accounts for a deadline task's bandwidth across admissions, moves, rebuilds, and releases.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 8e8c62c574d55..01fbbd02cf8d0 100644

[ ... ]

Quoted 20 lines
kernel/sched/deadline.c +16 -0
@@ -4213,6 +4280,23 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
 		return 0;
 
+	/*
+	 * Change the bandwidth of a deadline task where it is counted: in
+	 * the root domain of the CPU recorded with it. A task moved asleep
+	 * has not run there yet, so the CPU it is on can be elsewhere. No
+	 * bandwidth is counted if a rebuild dropped it, or if the task
+	 * enters the class. A runtime below about a millionth of the period
+	 * gives a bandwidth of 0. It counts for nothing, and no move updates
+	 * its record. In these three cases, the root domain of the CPU the
+	 * task is on takes the new bandwidth. The caller holds cpuset_mutex,
+	 * or dl_accounting_mutex without cpusets, so no rebuild runs
+	 * meanwhile.
+	 */
+	counted = task_has_dl_policy(p) && p->dl.dl_bw_cpu >= 0 &&
+		  p->dl.dl_bw_gen == dl_bw_gen;
+	cpu = counted && p->dl.dl_bw ? p->dl.dl_bw_cpu : task_cpu(p);
+	dl_b = dl_bw_of(cpu);

[ ... ]

Quoted 21 lines
kernel/sched/syscalls.c +6 -0
index 4c013caa24713..306cd8d32173b 100644
@@ -1185,6 +1185,8 @@ SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
 
 int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
 {
+	unsigned int cpu;
+
 	/*
 	 * If the task isn't a deadline task or admission control is
 	 * disabled then we don't care about affinity changes.
@@ -1204,9 +1206,16 @@ int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
 	 * if admission test is enabled, we only admit -deadline
 	 * tasks allowed to run on all the CPUs in the task's
 	 * root_domain.
+	 *
+	 * That is the root domain that counts the bandwidth of the task:
+	 * the one of the CPU recorded with it. A task moved asleep to
+	 * another cpuset is still on a CPU of the root domain it left. A

kernel/sched/syscalls.c int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask) · line 1221

Quoted 10 lines
kernel/sched/syscalls.c +4 -1
+	 * bandwidth of 0 is counted nowhere, and no move updates its
+	 * record: use the CPU the task is on.
 	 */
+	cpu = READ_ONCE(p->dl.dl_bw) ? dl_task_root_domain_cpu(p) : task_cpu(p);
 	guard(rcu)();
-	if (!cpumask_subset(task_rq(p)->rd->span, mask))
+	if (!cpumask_subset(cpu_rq(cpu)->rd->span, mask))
 		return -EBUSY;
 
 	return 0;

[Severity: Medium]
Should __sched_setscheduler() also use the root domain recorded in p->dl.dl_bw_cpu rather than rq->rd when validating a deadline task's root domain span and dl_bw.bw?

kernel/sched/syscalls.c:__sched_setscheduler() {
	...
		if (dl_bandwidth_enabled() && dl_policy(policy) &&
				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
			cpumask_t *span = rq->rd->span;

			if (!cpumask_subset(span, &p->cpus_mask) ||
			    rq->rd->dl_bw.bw == 0) {
				retval = -EPERM;
				goto unlock;
			}
		}
	...
}

When a sleeping SCHED_DEADLINE task is moved to another exclusive cpuset partition (or its CPU goes offline into the default root domain), p->cpus_mask and p->dl.dl_bw_cpu reflect the root domain holding its bandwidth, while rq (task_rq(p)) remains in the old root domain. Because rq->rd->span is not a subset of p->cpus_mask, __sched_setscheduler() rejects sched_setattr() parameter updates on that task with -EPERM before reaching the moved-sleeper handling in sched_dl_overflow().

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

Re: [PATCH v7 23/40] sched: Make deadline policy and affinity changes wait for a cpuset attach

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched: stale cpumask before cpuset_lock_no_attach() in __sched_setaffinity() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched: stale cpumask before cpuset_lock_no_attach() in __sched_setaffinity()
--

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

sched: Make deadline policy and affinity changes wait for a cpuset attach

This commit introduces cpuset_lock_no_attach() and uses it in __sched_setscheduler() and sched_setaffinity() so that deadline policy and affinity changes wait until any in-progress cpuset task attach finishes.

Quoted 4 lines
kernel/sched/syscalls.c +0 -0
index 4f47b17151ed9..4aa3ccbff320f 100644

[ ... ]

Quoted 12 lines
kernel/sched/syscalls.c +5 -1
@@ -1271,9 +1276,21 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)
 		/*
 		 * The cpuset mask must win here, as it does when
 		 * cpuset_update_tasks_cpumask() sets it on a deadline task.
+		 *
+		 * A sched_setattr() may have made @p a deadline task since
+		 * the first call. SCA_DL_NOWAIT would then skip this second
+		 * call. Wait for a cpuset attach in progress instead, as
+		 * sched_setaffinity() does for a deadline task.
 		 */
 		ctx->flags &= ~SCA_DL_CHECK;
-		__set_cpus_allowed_ptr(p, ctx);

kernel/sched/syscalls.c int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx) · line 1295

Quoted 10 lines
kernel/sched/syscalls.c +8 -0
+		if (ctx->flags & SCA_DL_NOWAIT) {
+			ctx->flags &= ~SCA_DL_NOWAIT;
+			cpuset_lock_no_attach();
+			__set_cpus_allowed_ptr(p, ctx);
+			cpuset_unlock();
+		} else {
+			__set_cpus_allowed_ptr(p, ctx);
+		}
 		retval = -EINVAL;
 	}

[Severity: Medium]
Can this second __set_cpus_allowed_ptr() call apply a stale new_mask after cpuset_lock_no_attach() sleeps?

In __sched_setaffinity(), when the concurrent cpuset update recovery path (!cpumask_subset(new_mask, cpus_allowed)) is entered with SCA_DL_NOWAIT set, cpuset_cpus_allowed(p, cpus_allowed) and new_mask are computed before cpuset_lock_no_attach() is called:

kernel/sched/syscalls.c:__sched_setaffinity() {
    ...
	cpuset_cpus_allowed(p, cpus_allowed);
	if (!cpumask_subset(new_mask, cpus_allowed)) {
		cpumask_copy(new_mask, cpus_allowed);
		if (unlikely((ctx->flags & SCA_USER) && ctx->user_mask)) {
			bool empty = !cpumask_and(new_mask, new_mask,
						  ctx->user_mask);

			if (empty)
				cpumask_copy(new_mask, cpus_allowed);
		}
    ...
}

If p becomes a SCHED_DEADLINE task after the first __set_cpus_allowed_ptr() call and a cpuset attach or update runs before cpuset_lock_no_attach() acquires cpuset_mutex, new_mask is not recomputed under cpuset_mutex:

CPU0 CPU1
sched_setaffinity(p)
!task_has_dl_policy(p)
__sched_setaffinity(p, &ac)

    __set_cpus_allowed_ptr()
    cpuset_cpus_allowed()
    cpumask_copy(new_mask, ...)
                                  sched_setattr(p, SCHED_DEADLINE)
                                  cgroup_procs_write() -> cpuset_attach()
                                    moves p and DL bw to new partition P
    cpuset_lock_no_attach()
    __set_cpus_allowed_ptr()
      sets p->cpus_mask to stale new_mask  <-- wrong CPUs for p's DL bw

Because SCA_DL_CHECK is cleared before the second __set_cpus_allowed_ptr() call, p's affinity is overwritten with the pre-attach cpuset mask while its deadline bandwidth remains accounted in P's root domain.

In addition, if css_set_move_task() moves p to the destination cpuset before cpuset_cpus_allowed() is read while attach_ctx.in_progress is still set, waiting in cpuset_lock_no_attach() delays restoring p->user_cpus_ptr from ctx->user_mask until after cpuset_attach_task() has already run using the un-restored p->user_cpus_ptr from the first __set_cpus_allowed_ptr() call, and then applies new_mask intersected with the old ctx->user_mask without SCA_DL_CHECK, narrowing the deadline task's affinity below its root domain span.

Recomputing cpus_allowed and new_mask after acquiring cpuset_lock_no_attach() (or holding cpuset_lock_no_attach() before reading cpus_allowed on the recovery path) would ensure the mask matches the post-attach cpuset state.

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

Re: [PATCH v7 38/40] selftests/sched: Add a test of SCHED_DEADLINE policy round trips

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] selftests/sched: 64 KiB FILLER_STACK fails pthread_attr_setstacksize() - [Low] selftests/sched…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] selftests/sched: 64 KiB FILLER_STACK fails pthread_attr_setstacksize()
- [Low] selftests/sched: missing sem_destroy() and pipe leak in deadline_switch_test
--

commit 84b080b4abc565be69cf0d196565fbf11ac9aa91
Author: Mathieu Desnoyers <[email protected]>

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

This commit adds a new sched/deadline selftest covering SCHED_DEADLINE policy round trips to SCHED_OTHER and back, as well as sysrq-n normalization with deadline tasks and priority-inheritance lock owners.

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

[ ... ]

Quoted 2 lines
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +2 -0
+static int test_sysrq_boosted_owner(int normalized)
+{

[ ... ]

Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +5 -0
+	if (sem_init(&owner_locked, 0, 0) || sem_init(&owner_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		ret = KSFT_FAIL;
+		goto out;
+	}

[ ... ]

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +8 -0
+out:
+	close(fd);
+	pthread_mutex_destroy(&pi_lock);
+	return ret;
+}
+
+#define FILLERS		2048
+#define FILLER_STACK	(64 * 1024)

[ ... ]

Quoted 2 lines
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +2 -0
+static int test_sysrq_running_owner(int normalized)
+{

[ ... ]

tools/testing/selftests/sched/deadline/deadline_switch_test.c line 977

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +10 -0
+	fill = calloc(FILLERS, sizeof(*fill));
+	if (!fill || pipe(filler_pipe) || sem_init(&owner_locked, 0, 0) ||
+	    sem_init(&filler_ready, 0, 0) || sem_init(&waiter_go, 0, 0) ||
+	    pthread_attr_init(&fa) || pthread_attr_setstacksize(&fa, FILLER_STACK)) {
+		ksft_print_msg("setup: %s\n", strerror(errno));
+		free(fill);
+		close(fd);
+		pthread_mutex_destroy(&pi_lock);
+		return KSFT_FAIL;
+	}

[Severity: Medium]
Does pthread_attr_setstacksize(&fa, FILLER_STACK) fail with EINVAL on architectures where PTHREAD_STACK_MIN is larger than 64 KiB, such as arm64 and powerpc64 (128 KiB)? That causes test_sysrq_running_owner() to fail during setup on those architectures.

Also, pthread_attr_init() and pthread_attr_setstacksize() return an error number directly without setting errno, so strerror(errno) reports a stale errno (typically "Success"), and this error path returns without closing filler_pipe or destroying fa.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_switch_test.c line 1056

Quoted 13 lines
tools/testing/selftests/sched/deadline/deadline_switch_test.c new file +13 -0
+out:
+	close(filler_pipe[1]);
+	for (i = 0; i < started; i++)
+		if (join(fill[i]))
+			ret = KSFT_FAIL;
+	close(filler_pipe[0]);
+	sched_setaffinity(0, sizeof(old), &old);
+	pthread_attr_destroy(&fa);
+	free(fill);
+	close(fd);
+	pthread_mutex_destroy(&pi_lock);
+	return ret;
+}

[Severity: Low]
Should test_sysrq_boosted_owner() and test_sysrq_running_owner() call sem_destroy() on owner_locked, owner_go, filler_ready, and waiter_go during cleanup? Without sem_destroy(&owner_locked) in test_sysrq_boosted_owner(), test_sysrq_running_owner() calls sem_init() on an already initialized owner_locked semaphore, which is undefined behavior in POSIX.

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

Re: [PATCH v7 27/40] sched/deadline: Move a task's bandwidth to the root domain it runs in

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: dl_bw_rebuilding() drops bw moves during rebuild task walk - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: dl_bw_rebuilding() drops bw moves during rebuild task walk
- [Medium] sched/deadline: migrate_task_rq_dl() drops bw move for mutex-blocked tasks
- [Medium] sched/deadline: dl_task_move_bw() moves departed bw of PI-boosted tasks
--

commit 00a2592b3e4a7ff7a78ebc503a680dacf59e846b
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Move a task's bandwidth to the root domain it runs in

This commit moves a deadline task's bandwidth to the root domain of its new CPU in migrate_task_rq_dl() and task_woken_dl() when it differs from the root domain that currently counts it, while suppressing moves during sched domain rebuilds and proxy execution migrations.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 9ff79141c6306..6c6a4d9cd0548 100644

[ ... ]

Quoted 54 lines
kernel/sched/deadline.c +49 -1
@@ -2930,11 +2968,86 @@ select_task_rq_dl(struct task_struct *p, int cpu, int flags)
 	return cpu;
 }
 
-static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unused)
+/*
+ * Return true if the root domain of @cpu may not count the bandwidth of
+ * @p. Either another root domain counts it, or a rebuild left @p out.
+ * Test without dl_departed_lock, so that a move inside a root domain
+ * takes no lock. dl_task_move_bw() tests again under it.
+ *
+ * Return false if @cpu is not active. A migration-disabled task can wake
+ * up on a CPU that goes offline, after it joined the default root domain.
+ * Keep the bandwidth where it is counted. balance_push() moves the task
+ * off that CPU once it enables migration, or its next wakeup does once
+ * the CPU is offline. That migration moves the bandwidth if needed.
+ *
+ * Return false while the sched domains are rebuilt. The CPUs then move
+ * to their new root domains one by one. That alone can make the two root
+ * domains differ. The rebuild of the accounting
+ * that follows counts @p.
+ */
+static bool dl_task_bw_elsewhere(struct task_struct *p, int cpu)
+{
+	int bw_cpu = READ_ONCE(p->dl.dl_bw_cpu);
+
+	if (bw_cpu < 0 || !p->dl.dl_bw || !cpu_active(cpu) || dl_bw_rebuilding())
+		return false;
+	return READ_ONCE(p->dl.dl_bw_gen) != READ_ONCE(dl_bw_gen) ||
+	       cpu_rq(bw_cpu)->rd != cpu_rq(cpu)->rd;
+}
+
+/*
+ * Move the bandwidth of @p to the root domain of @new_cpu. Count it there
+ * also if a rebuild left @p out. Add it even without room, since @p runs
+ * there. The caller holds the rq lock of @p, or its pi_lock for a wakeup.
+ */
+static void dl_task_move_bw(struct task_struct *p, int new_cpu)
+{
+	struct dl_bw *dl_b;
+	int cpu;
+
+	if (dl_entity_is_special(&p->dl) || !p->dl.dl_bw)
+		return;
+
+	guard(raw_spinlock)(&dl_departed_lock);
+	cpu = p->dl.dl_bw_cpu;
+	if (cpu < 0 || dl_bw_rebuilding())
+		return;
+	if (p->dl.dl_bw_gen == dl_bw_gen) {
+		if (cpu_rq(cpu)->rd == cpu_rq(new_cpu)->rd)
+			return;
+		dl_b = dl_bw_of(cpu);
+		raw_spin_lock(&dl_b->lock);

kernel/sched/deadline.c select_task_rq_dl(struct task_struct *p, int cpu, int flags) · line 3029

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+		__dl_sub(dl_b, p->dl.dl_bw, dl_bw_cpus(cpu));
+		raw_spin_unlock(&dl_b->lock);
+	}
+	dl_b = dl_bw_of(new_cpu);
+	raw_spin_lock(&dl_b->lock);
+	__dl_add(dl_b, p->dl.dl_bw, dl_bw_cpus(new_cpu));
+	raw_spin_unlock(&dl_b->lock);
+	p->dl.dl_bw_cpu = new_cpu;
+	p->dl.dl_bw_gen = dl_bw_gen;
+}

[Severity: Medium]
Can dl_task_move_bw() move the departing bandwidth of a non-deadline task that was PI-boosted back into the deadline class?

When a task leaves SCHED_DEADLINE before its 0-lag time, switched_from_dl() arms inactive_timer and leaves p->dl.dl_bw and p->dl.dl_bw_cpu set in the original root domain. As a non-deadline task (!task_has_dl_policy(p)), it can move to another root domain without admission control, and if it is then PI-boosted by a deadline waiter before its 0-lag time, switched_to_dl() cancels the inactive timer and takes it off dl_departed_list while keeping the original dl_bw_cpu recorded.

Because neither dl_task_bw_elsewhere() nor dl_task_move_bw() checks task_has_dl_policy(p), waking or migrating the boosted task in the new root domain subtracts p->dl.dl_bw from the original root domain before its 0-lag time and adds that unreserved bandwidth to the new root domain.

Quoted 10 lines
kernel/sched/deadline.c +6 -0
+
+static void migrate_task_rq_dl(struct task_struct *p, int new_cpu)
 {
 	struct rq_flags rf;
 	struct rq *rq;
 
+	/*
+	 * The new CPU can be in another root domain than the one that counts
+	 * the bandwidth. A mask can hold CPUs of two root domains, and
+	 * select_fallback_rq() can widen it. Move the bandwidth there, as

kernel/sched/deadline.c select_task_rq_dl(struct task_struct *p, int cpu, int flags) · line 3049

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 * dl_task_offline_migration() does for a throttled task.
+	 *
+	 * Not for a task that is blocked on a mutex and only queued for
+	 * proxy execution. It does not run on the new CPU, so its bandwidth
+	 * stays in its root domain. If its wake-up then picks a CPU of another
+	 * root domain, the bandwidth moves at that time.
+	 */
+	if (unlikely(dl_task_bw_elsewhere(p, new_cpu)) &&
+	    !(p->is_blocked && task_on_rq_migrating(p)))
+		dl_task_move_bw(p, new_cpu);

[Severity: Medium]
Does skipping dl_task_move_bw() when p->is_blocked && task_on_rq_migrating(p) also drop the bandwidth move for normal queued migrations of mutex-blocked tasks under CONFIG_SCHED_PROXY_EXEC?

When a mutex-blocked task (p->is_blocked == 1) is migrated across root domains by move_queued_task() or move_queued_task_locked() (for example from __balance_push_cpu_stop() during CPU hotplug or push_dl_task()), deactivate_task() sets p->on_rq = TASK_ON_RQ_MIGRATING and set_task_cpu() updates both p->cpu and p->wake_cpu to new_cpu:

kernel/sched/core.c:move_queued_task() {
	...
	deactivate_task(rq, p, DEQUEUE_NOCLOCK);
	set_task_cpu(p, new_cpu);
	...
	activate_task(rq, p, 0);
}

When the mutex is unlocked, try_to_wake_up() sees p->on_rq == TASK_ON_RQ_QUEUED and takes ttwu_runnable():

kernel/sched/core.c:ttwu_runnable() {
	...
	if (p->is_blocked) {
		if (p->se.sched_delayed)
			enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED);
		if (proxy_needs_return(rq, p))
			return 0;
	}
	...
	ttwu_do_wakeup(p);
	return 1;
}

Because task_cpu(p) == p->wake_cpu, proxy_needs_return() returns false and ttwu_runnable() finishes the wakeup in place without calling migrate_task_rq_dl() or task_woken_dl(), leaving p's bandwidth counted in the old root domain.

[ ... ]

Quoted 13 lines
kernel/sched/deadline.c +3 -1
@@ -4068,8 +4192,10 @@ void dl_rebuild_rd_accounting(void)
 	 * a resume run one for each CPU. A task gets a bandwidth under the
 	 * locks this rebuild holds, so the count cannot leave 0 meanwhile.
 	 */
-	if (!atomic_read(&dl_nr_bw_tasks))
+	if (!atomic_read(&dl_nr_bw_tasks)) {
+		dl_bw_rebuild_end();
 		return;
+	}
 
 	read_lock(&tasklist_lock);
 	for_each_process_thread(g, p) {

kernel/sched/deadline.c void dl_rebuild_rd_accounting(void) · line 4213

Quoted 5 lines
kernel/sched/deadline.c +1 -0
@@ -4083,6 +4209,7 @@ void dl_rebuild_rd_accounting(void)
 			dl_add_task_root_domain(p);
 	}
 	read_unlock(&tasklist_lock);
+	dl_bw_rebuild_end();
 }

[Severity: Medium]
Can keeping dl_bw_rebuilding() true until the end of the tasklist walk drop bandwidth moves for tasks that dl_add_task_root_domain() has already visited?

During CPU deactivation, tasks are woken via select_fallback_rq() or pushed by __balance_push_cpu_stop() while dl_rebuild_rd_accounting() walks for_each_process_thread() under read_lock(&tasklist_lock):

CPU0 CPU1
partition_sched_domains_locked()
dl_bw_rebuild_begin()
...
dl_rebuild_rd_accounting()

    dl_clear_root_domains()
    read_lock(&tasklist_lock)
    for_each_process_thread(g, p)
      dl_add_task_root_domain(p)
        /* counts p in RD_A (or skips
         * p if cpu >= nr_cpu_ids) */
                                        try_to_wake_up(p)
                                          select_fallback_rq() -> cpu in RD_B
                                          set_task_cpu(p, new_cpu)
                                            migrate_task_rq_dl(p, new_cpu)
                                              dl_task_bw_elsewhere()
                                                dl_bw_rebuilding() == true
                                                --> returns false (bw not moved)
      /* still visiting later tasks */
    read_unlock(&tasklist_lock)
    dl_bw_rebuild_end()

Once dl_add_task_root_domain(p) releases p->pi_lock, p can wake up or migrate to an active CPU in another root domain before the walk finishes. Because dl_bw_rebuilding() is still true, migrate_task_rq_dl() and task_woken_dl() ignore the move, leaving p's bandwidth counted in RD_A (or uncounted if dl_task_rebuild_cpu(p) returned nr_cpu_ids).

In addition, when dl_task_bw_elsewhere() runs under rq->__lock without p->pi_lock, it reads bw_cpu = READ_ONCE(p->dl.dl_bw_cpu) before checking dl_bw_rebuilding() and READ_ONCE(dl_bw_gen), whereas dl_add_task_root_domain() updates p->dl.dl_bw_cpu and p->dl.dl_bw_gen under p->pi_lock and dl_departed_lock, so dl_task_bw_elsewhere() can compare cpu_rq(bw_cpu)->rd using a stale bw_cpu read from before the rebuild ended.

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

Re: [PATCH v7 26/40] sched/deadline: Make a rebuild count a task in the root domain it runs in

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: dl_task_rebuild_cpu() uses recorded CPU outside task cpuset - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: dl_task_rebuild_cpu() uses recorded CPU outside task cpuset
- [Medium] sched/deadline: dl_task_rebuild_cpu() fallback reads stale HK_TYPE_DOMAIN
--

commit 5f53c9545c6d42e90c32f229213e080ced9acb3f
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Make a rebuild count a task in the root domain it runs in

This commit introduces dl_task_rebuild_cpu() to select an active CPU in the root domain where a deadline task runs during root domain bandwidth rebuilds, and leaves out tasks with no active CPU until offline migration or a later rebuild places them.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index a9b8bd019d4ba..9ff79141c6306 100644

[ ... ]

Quoted 37 lines
kernel/sched/deadline.c +33 -0
@@ -3820,6 +3826,60 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
 	cpuset_cpus_allowed_locked(p, cpus);
 }
 
+/*
+ * Return a CPU of the root domain where a rebuild of the accounting should
+ * count the bandwidth of @p, or nr_cpu_ids if there is none.
+ *
+ * Prefer the CPU @p is on, if it is active and in the mask of @p. The
+ * task runs, or wakes up, in the root domain of that CPU. A mask can hold
+ * CPUs of two root domains: housekeeping CPUs and CPUs isolated by
+ * isolcpus="domain". When every CPU of a mask goes offline,
+ * select_fallback_rq() can widen it to both. It moves no bandwidth.
+ * Prefer that CPU also if @p is queued there, out of its mask, and the
+ * CPU is the one recorded. Without admission control,
+ * dl_task_offline_migration() can put a throttled task and its bandwidth
+ * on any active CPU. The task runs there until it blocks.
+ *
+ * Else prefer the CPU recorded with the bandwidth, if it is active and in
+ * the mask. It is in the root domain that admitted the bandwidth, or that
+ * its last move put it in. A task moved asleep is still on a CPU of the
+ * root domain it left, out of its mask. Else take the first active CPU of
+ * the mask, a housekeeping one if there is one. A task on isolated CPUs
+ * that all went offline can have no active CPU at all.
+ */
+static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
+{
+	struct cpumask *msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
+	int recorded = p->dl.dl_bw_cpu;
+	unsigned int cpu;
+
+	/*
+	 * Look at the mask of the task first. A change of the cpusets sets
+	 * the mask of each task before its rebuild. The housekeeping mask
+	 * that dl_get_task_effective_cpus() reads is updated after it. If no
+	 * CPU of the mask is active, take the CPU recorded if it is active.
+	 * dl_task_offline_migration() moved the task there, or an earlier

kernel/sched/deadline.c static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp · line 3871

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 * rebuild counted it there. Else ask the cpuset.
+	 */
+	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
+	cpu = task_cpu(p);
+	if (cpumask_test_cpu(cpu, msk) ||
+	    (cpu == recorded && cpu_active(cpu) && task_on_rq_queued(p)))
+		return cpu;
+	if (cpumask_empty(msk)) {
+		if (recorded >= 0 && cpu_active(recorded))
+			return recorded;

[Severity: Medium]
Can returning recorded here without checking the task's cpuset charge the bandwidth to a newly created partition that no longer contains the task?

Suppose a sleeping task in top_cpuset has user_cpus_ptr restricted via sched_setaffinity() to CPUs 0 and 1, and both go offline while CPUs 2 and 3 remain online. The hotplug rebuild sees an empty msk, falls back to dl_get_task_effective_cpus(), and records CPU 2 in p->dl.dl_bw_cpu.

If CPU 2 is then moved into a new cpuset partition root, cpuset_update_tasks_cpumask() updates top_cpuset tasks with possible_mask & ~subpartitions_cpus. Because __set_cpus_allowed_ptr() intersects that mask with p->user_cpus_ptr ({0, 1}), p->cpus_mask stays {0, 1} and msk remains empty. This check then sees CPU 2 is still active and returns it, counting the top_cpuset task's bandwidth in the new partition on CPU 2 instead of top_cpuset on CPU 3.

kernel/sched/deadline.c static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp · line 3881

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+		dl_get_task_effective_cpus(p, msk);
+		cpumask_and(msk, msk, cpu_active_mask);
+	} else if (recorded >= 0 && cpumask_test_cpu(recorded, msk)) {
+		return recorded;
+	}
+	cpu = cpumask_first_and(msk, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
+	if (cpu < nr_cpu_ids)
+		return cpu;
+	return cpumask_first(msk);
+}

[Severity: Medium]
Does calling dl_get_task_effective_cpus() here read a stale HK_TYPE_DOMAIN mask during cpuset partition transitions?

dl_get_task_effective_cpus() checks housekeeping_cpumask(HK_TYPE_DOMAIN):

kernel/sched/deadline.c:dl_get_task_effective_cpus() {
	hk_msk = housekeeping_cpumask(HK_TYPE_DOMAIN);
	if (housekeeping_enabled(HK_TYPE_DOMAIN)) {
		if (!cpumask_intersects(p->cpus_ptr, hk_msk)) {
			cpumask_andnot(cpus, cpu_active_mask, hk_msk);
			return;
		}
	}
}

HK_TYPE_DOMAIN excludes both boot-time isolcpus=domain CPUs and runtime isolated cpuset partitions, and cpuset_update_sd_hk_unlock() rebuilds root domain accounting before housekeeping_update() refreshes HK_TYPE_DOMAIN. If a task is confined to an offline isolcpus=domain CPU (so msk is empty and recorded is inactive) when a runtime isolated partition on another CPU transitions to root or member, cpu_active_mask & ~hk_msk still includes that partition's CPU. dl_add_task_root_domain() will then charge the task's bandwidth to that root domain and record the CPU in p->dl.dl_bw_cpu.

Should dl_get_task_effective_cpus() use HK_TYPE_DOMAIN_BOOT to match dl_task_rebuild_cpu()?

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

Re: [PATCH v7 28/40] sched/deadline: Keep a task in the root domain that counts its bandwidth

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: missing wake_cpu update in __set_cpus_allowed_ptr_locked() - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: missing wake_cpu update in __set_cpus_allowed_ptr_locked()
- [Medium] sched/deadline: wrong root domain in dl_task_offline_migration() on rebuild
- [Medium] sched/deadline: missing READ_ONCE() on dl_bw_cpu in dl_task_rebuild_cpu()
--

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

sched/deadline: Keep a task in the root domain that counts its bandwidth

This commit adds dl_task_bw_span() and updates CPU selection paths for SCHED_DEADLINE tasks to prefer CPUs in the root domain that accounts for the task's bandwidth.

Quoted 16 lines
kernel/sched/core.c +8 -0
index e9f80407f75be..dc270a23179d5 100644
@@ -3264,6 +3264,23 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
 			dest_cpu = ctx->dl_bw_cpu;
 		if (!task_on_rq_queued(p))
 			p->wake_cpu = dest_cpu;
+	} else {
+		const struct cpumask *span = dl_task_bw_span(p);
+		unsigned int cpu = nr_cpu_ids;
+
+		/*
+		 * No room was made for @p in another root domain. Keep @p
+		 * in the root domain that counts its bandwidth, if the new
+		 * mask holds one of its CPUs.

kernel/sched/core.c static int __set_cpus_allowed_ptr_locked(struct task_struct *p, · line 3284

Quoted 10 lines
kernel/sched/core.c +9 -0
+		 */
+		if (span && !cpumask_test_cpu(dest_cpu, span))
+			cpu = cpumask_first_and_and(cpu_valid_mask,
+						    ctx->new_mask, span);
+		if (cpu < nr_cpu_ids) {
+			dest_cpu = cpu;
+			if (!task_on_rq_queued(p))
+				p->wake_cpu = dest_cpu;
+		}
 	}

[Severity: Medium]
Does this leave p->wake_cpu stale when cpumask_any_and_distribute() already picked a dest_cpu inside span?

When cpumask_test_cpu(dest_cpu, span) is true, cpu stays at nr_cpu_ids and p->wake_cpu is not updated for a sleeping task. Because affine_move_task() does not move sleeping tasks, p->wake_cpu remains on the old CPU (such as an offlining housekeeping CPU during cpuset_hotplug_update_tasks()). If p then wakes up during the subsequent sched domain rebuild while dl_task_bw_span(p) returns NULL, select_task_rq() and select_fallback_rq() can place p on an isolated CPU in def_root_domain and move its bandwidth without admission control.

Updating p->wake_cpu whenever span is non-NULL and dest_cpu is in span (and !task_on_rq_queued(p)) would avoid this.

[ ... ]

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 6c6a4d9cd0548..e5f77d3c5fa03 100644

[ ... ]

Quoted 26 lines
kernel/sched/deadline.c +13 -0
@@ -901,18 +903,36 @@ static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq);
 
 static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p)
 {
+	const struct cpumask *span;
 	struct rq *later_rq = NULL;
 	struct dl_bw *dl_b;
 
 	later_rq = find_lock_later_rq(p, rq);
+	/*
+	 * find_lock_later_rq() looks in the root domain of @rq. Once @rq is
+	 * offline, a rebuild attaches it to def_root_domain. That root domain
+	 * may not count @p. Do not take @p out of the root domain that counts
+	 * it while @p has an active CPU there.
+	 */
+	span = dl_task_bw_span(p);
+	if (later_rq && span && !cpumask_test_cpu(later_rq->cpu, span) &&
+	    cpumask_first_and_and(cpu_active_mask, p->cpus_ptr, span) < nr_cpu_ids) {
+		double_unlock_balance(rq, later_rq);
+		later_rq = NULL;
+	}
 	if (!later_rq) {
 		int cpu;
 
 		/*
 		 * If we cannot preempt any rq, fall back to pick any

kernel/sched/deadline.c static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq); · line 935

Quoted 10 lines
kernel/sched/deadline.c +7 -2
-		 * online CPU:
+		 * online CPU. Try the root domain that counts @p first.
 		 */
-		cpu = cpumask_any_and(cpu_active_mask, p->cpus_ptr);
+		cpu = nr_cpu_ids;
+		if (span)
+			cpu = cpumask_first_and_and(cpu_active_mask,
+						    p->cpus_ptr, span);
+		if (cpu >= nr_cpu_ids)
+			cpu = cpumask_any_and(cpu_active_mask, p->cpus_ptr);

[Severity: Medium]
Can dl_task_offline_migration() still move a throttled task and its bandwidth into def_root_domain when dl_task_timer() fires during a sched domain rebuild?

CPU0 CPU1 (<hardirq>)
sched_cpu_deactivate(H)
sched_set_rq_offline(rq_H)
cpuset_cpu_inactive(H)

    partition_sched_domains_locked()
      dl_bw_rebuild_begin()
      detach_destroy_domains()
        cpu_attach_domain(def_rd, H)
                                         dl_task_timer(p)
                                           dl_task_offline_migration(rq_H, p)
                                             find_lock_later_rq() -> iso_rq
                                             dl_task_bw_span(p) -> NULL
                                             p->dl.dl_bw_cpu = iso_rq->cpu
      dl_rebuild_rd_accounting()
        dl_add_task_root_domain(p)
          dl_task_rebuild_cpu(p) -> iso_rq->cpu

While dl_bw_rebuild_seq is odd, rq_H is already attached to def_root_domain, so find_lock_later_rq() searches def_root_domain (or cpumask_any_and() picks the first active CPU in p->cpus_ptr, which can be an isolated CPU). Because dl_task_bw_span(p) returns NULL during the rebuild, the check above does not reject the isolated later_rq.

Unlike migrate_task_rq_dl() and task_woken_dl(), which skip moving bandwidth while dl_bw_rebuilding() is true, dl_task_offline_migration() then unconditionally subtracts p->dl.dl_bw from src_rq->rd->dl_bw (which can underflow total_bw before dl_clear_root_domains() runs), adds it to def_root_domain, and overwrites p->dl.dl_bw_cpu with the isolated CPU. Both the rebuild and later wakeups then treat def_root_domain as the root domain that counts p.

[ ... ]

Quoted 27 lines
kernel/sched/deadline.c +12 -4
@@ -3987,17 +4075,37 @@ static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
 	 */
 	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
 	cpu = task_cpu(p);
-	if (cpumask_test_cpu(cpu, msk) ||
-	    (cpu == recorded && cpu_active(cpu) && task_on_rq_queued(p)))
+	if (cpu == recorded && cpu_active(cpu) && task_on_rq_queued(p))
 		return cpu;
 	if (cpumask_empty(msk)) {
 		if (recorded >= 0 && cpu_active(recorded))
 			return recorded;
 		dl_get_task_effective_cpus(p, msk);
 		cpumask_and(msk, msk, cpu_active_mask);
-	} else if (recorded >= 0 && cpumask_test_cpu(recorded, msk)) {
-		return recorded;
 	}
+	/*
+	 * Keep the bandwidth where it was counted: with the housekeeping
+	 * CPUs, or with the CPUs that isolcpus="domain" isolates. The root
+	 * domains are new, and the CPU recorded can be offline. So prefer a
+	 * CPU of the mask of the same kind as the CPU recorded: housekeeping
+	 * or not.
+	 */
+	if (recorded >= 0) {
+		const struct cpumask *hk = housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT);
+		bool rec_hk = cpumask_test_cpu(recorded, hk);
+		unsigned int same;

kernel/sched/deadline.c static unsigned int dl_task_rebuild_cpu(struct task_struct *p) · line 4106

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+
+		if (cpumask_test_cpu(cpu, msk) && cpumask_test_cpu(cpu, hk) == rec_hk)
+			return cpu;
+		if (cpumask_test_cpu(recorded, msk))
+			return recorded;
+		for_each_cpu(same, msk) {
+			if (cpumask_test_cpu(same, hk) == rec_hk)
+				return same;
+		}
+	}

[Severity: Medium]
Should p->dl.dl_bw_cpu be read with READ_ONCE() when initializing recorded in dl_task_rebuild_cpu()?

dl_add_task_root_domain() calls dl_task_rebuild_cpu(p) while holding only p->pi_lock, before acquiring dl_departed_lock. Concurrently, a dying deadline task in its final __schedule() holds rq->lock and dl_departed_lock (not p->pi_lock) and can write p->dl.dl_bw_cpu = -1 via task_non_contending() -> dl_task_release_bw(). Because recorded is loaded with a plain read and used after calling housekeeping_cpumask(), the compiler is free to reload p->dl.dl_bw_cpu after the recorded >= 0 check and pass -1 to cpumask_test_cpu().

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

Re: [PATCH v7 29/40] sched/deadline: Keep the last CPU a task has in its root domain

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] cgroup/cpuset: missing descendant cpus_allowed filter in cpuset_cpus_allowed_without() - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] cgroup/cpuset: missing descendant cpus_allowed filter in cpuset_cpus_allowed_without()
- [Medium] cgroup/cpuset: filter by task_cpu_possible_mask() in cpuset_cpus_allowed_without()
--

commit 119af82ab355761f9fade868df0ef32c60b9344b
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Keep the last CPU a task has in its root domain

This commit refuses to take a CPU offline with -EBUSY when doing so would leave a SCHED_DEADLINE task with runnable CPUs only outside the root domain that accounts for its bandwidth.

Quoted 19 lines
kernel/cgroup/cpuset.c +11 -0
index 7bdb9e21a7edb..3ccd61a37d302 100644
@@ -4312,6 +4312,32 @@ void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
 	spin_unlock_irqrestore(&callback_lock, flags);
 }
 
+/*
+ * Set @pmask to the active CPUs that the cpuset of @tsk gives it once @cpu
+ * is offline: those of the nearest ancestor that keeps one. Leave it empty
+ * if there is none. As cpuset_update_tasks_cpumask() does, keep the CPUs
+ * possible for @tsk. As __set_cpus_allowed_ptr() does, keep those of the
+ * affinity the user set, if one is left. The caller holds the CPU hotplug
+ * lock for writing, which keeps the cpusets and their tasks as they are.
+ * It holds the pi_lock of @tsk, which keeps its user affinity.
+ */
+void cpuset_cpus_allowed_without(struct task_struct *tsk, int cpu,
+				 struct cpumask *pmask)

kernel/cgroup/cpuset.c void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask) · line 4335

Quoted 10 lines
kernel/cgroup/cpuset.c +10 -0
+{
+	struct cpuset *cs;
+
+	guard(rcu)();
+	for (cs = task_cs(tsk); cs; cs = parent_cs(cs)) {
+		cpumask_and(pmask, cs->effective_cpus, cpu_active_mask);
+		cpumask_clear_cpu(cpu, pmask);
+		if (!cpumask_empty(pmask))
+			break;
+	}

[Severity: Medium]
Does cpuset_cpus_allowed_without() return an overly wide mask when it walks past an intermediate ancestor to find remaining active CPUs?

During cgroup v2 hotplug, compute_effective_cpumask() propagates effective_cpus top-down, intersecting each descendant's configured cpus_allowed with its parent's new effective_cpus and only inheriting the parent's mask when that intersection is empty:

kernel/cgroup/cpuset.c:compute_effective_cpumask() {
	has_cpus = cpumask_and(new_cpus, cs->cpus_allowed, parent->effective_cpus);
	if (!has_cpus && is_in_v2_mode())
		cpumask_copy(new_cpus, parent->effective_cpus);
}

Consider a system with isolcpus=domain,0 and housekeeping CPUs 1-2, where parent P has cpus_allowed = {1} and child C has cpus_allowed = {0, 1} (giving C effective_cpus = {1}). When CPU 1 is taken offline, walking up from C skips P (which becomes empty) and returns top_cpuset's remaining active CPUs {0, 2}. dl_task_leaves_span() sees CPU 2 in the housekeeping root domain span {1, 2} and allows the offline. However, once P inherits {0, 2} from top_cpuset, C computes cpus_allowed & P->effective_cpus = {0, 1} & {0, 2} = {0}, moving the deadline task and its bandwidth onto isolated CPU 0 in def_root_domain without admission control.

kernel/cgroup/cpuset.c void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask) · line 4336

Quoted 1 line
kernel/cgroup/cpuset.c +1 -0
+	cpumask_and(pmask, pmask, task_cpu_possible_mask(tsk));

[Severity: Medium]
Can intersecting pmask with task_cpu_possible_mask(tsk) after the ancestor loop leave pmask empty when an ancestor has possible CPUs for tsk?

On asymmetric arm64 systems where a 32-bit deadline task can only run on a subset of CPUs, task_cs(tsk)->effective_cpus may retain active 64-bit-only CPUs after the outgoing 32-bit CPU is cleared. The loop then stops at task_cs(tsk), and intersecting with task_cpu_possible_mask(tsk) afterward produces an empty pmask. dl_task_leaves_span() treats an empty msk as false and allows the last 32-bit CPU in the task's root domain to go offline, after which guarantee_active_cpus() (which filters by task_cpu_possible_mask(tsk) before testing each ancestor) walks up to an ancestor with a 32-bit CPU in another root domain and moves the task's bandwidth there without admission control.

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

Re: [PATCH v7 36/40] sched/deadline: Check the runtime of a task whose parameters change

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: boosted task with !dl_donor_refill runs on old runtime - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: boosted task with !dl_donor_refill runs on old runtime
- [Medium] sched/deadline: dl_new_params deferred past dl_deboost() breaks PI re-boost
- [Medium] sched/deadline: update_dl_entity() on dl_new_params mixes old and new params
--

commit 707d1303811b0425863d63e123b53368955b72a6
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Check the runtime of a task whose parameters change

This commit adds a dl_new_params flag to struct sched_dl_entity so that when sched_setattr() modifies a deadline task's runtime, deadline, or period, the next non-boosted enqueue calls update_dl_entity() to check the remaining runtime against the new parameters.

Quoted 8 lines
kernel/sched/deadline.c +0 -0
index b650c37ae5615..f1d259df8f2a0 100644
@@ -2785,7 +2785,16 @@ static void __dequeue_dl_entity(struct sched_dl_entity *dl_se)
 static void
 enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 {

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

Quoted 10 lines
kernel/sched/deadline.c +9 -0
+	bool new_params = dl_se->dl_new_params;
+
 	WARN_ON_ONCE(on_dl_rq(dl_se));
+	/*
+	 * A boosted task runs on the parameters of its donor. Keep the mark
+	 * until an enqueue checks the runtime against its own: the one at
+	 * the deboost, or at a wakeup.
+	 */
+	if (!is_dl_boosted(dl_se))
+		dl_se->dl_new_params = 0;

[Severity: Medium]
Can a boosted SCHED_DEADLINE task with !dl_se->dl_donor_refill keep running on its old reservation's remaining runtime after sched_setattr() shrinks its parameters?

When a SCHED_DEADLINE task with dl_se->runtime > 0 is boosted by an earlier-deadline waiter, replenish_dl_entity() does not refill it from the donor and leaves dl_se->dl_donor_refill at 0:

kernel/sched/deadline.c:replenish_dl_entity() {
    ...
	if (dl_se->runtime <= 0)
		dl_note_donor_refill(dl_se);

	while (dl_se->runtime <= 0) {
		dl_se->deadline += period;
		dl_se->runtime += runtime;
	}
    ...
}

Because the task is still consuming its own remaining runtime rather than the donor's, deferring dl_new_params whenever is_dl_boosted(dl_se) is true lets the task consume the old larger runtime while holding the lock, even though sched_dl_overflow() has already released the old bandwidth in the root domain for other deadline tasks to use.

Quoted 9 lines
kernel/sched/deadline.c +2 -2
@@ -2834,12 +2843,13 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 		update_dl_entity(dl_se);
 	} else if (flags & ENQUEUE_REPLENISH) {
 		replenish_dl_entity(dl_se);
-	} else if ((flags & ENQUEUE_CLASS) && !is_dl_boosted(dl_se)) {
+	} else if (((flags & ENQUEUE_CLASS) || new_params) &&
+		   !is_dl_boosted(dl_se)) {
 		/*
-		 * The task enters the class runnable. It may come back before

kernel/sched/deadline.c enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags) · line 2855

Quoted 10 lines
kernel/sched/deadline.c +4 -3
-		 * its deadline, with the runtime left from older parameters.
-		 * Check that runtime against the new parameters, as a wakeup
-		 * does.
+		 * The task enters the class, or its parameters change, while
+		 * it is runnable. It may have runtime left from older
+		 * parameters. Check that runtime against the new parameters,
+		 * as a wakeup does.
 		 */
 		update_dl_entity(dl_se);
 	} else if ((flags & ENQUEUE_MOVE) &&

[Severity: Medium]
When a boosted task with dl_new_params set and !dl_se->dl_donor_refill is deboosted in rt_mutex_setprio(), does deferring update_dl_entity() until enqueue_dl_entity() miss the post-deboost re-boost check?

In rt_mutex_setprio(), dl_deboost(&p->dl) only updates p->dl.deadline when dl_se->dl_donor_refill is set, and immediately checks whether the task must be boosted again by the remaining top waiter:

kernel/sched/core.c:rt_mutex_setprio() {
    ...
				dl_deboost(&p->dl);
				/*
				 * dl_deboost() can start a new period. Its
				 * deadline can then be after the top waiter's.
				 * Boost the task again then.
				 */
				if (pi_task && dl_prio(pi_task->prio) &&
				    dl_entity_preempt(&pi_task->dl, &p->dl)) {
					p->dl.pi_se = pi_task->dl.pi_se;
					scope->flags |= ENQUEUE_REPLENISH;
				}
    ...
}

Because update_dl_entity() only runs later in sched_change_end() -> enqueue_task_dl() -> enqueue_dl_entity(), dl_entity_preempt() compares pi_task->dl against p->dl.deadline before update_dl_entity() advances p->dl.deadline to a new period, leaving p unboosted with a deadline later than its top waiter. If p is blocked on another rt_mutex (!scope->queued) when deboosted, enqueue_dl_entity() does not run at all, so the priority inheritance chain walk propagates p's stale deadline.

[Severity: Medium]
Can calling update_dl_entity() on dl_new_params mix the previous period's dynamic state with the newly written static parameters when switching between constrained and implicit deadlines?

If a running task started its current period with a constrained deadline (dl_deadline < dl_period) and calls sched_setattr() to switch to an implicit deadline (dl_deadline == dl_period), __setparam_dl() overwrites dl_se->dl_deadline and dl_se->dl_period before enqueue_dl_entity() runs. When dl_entity_overflow() then triggers in update_dl_entity(), !dl_is_implicit(dl_se) is now false:

kernel/sched/deadline.c:update_dl_entity() {
    ...
		if (unlikely((!dl_is_implicit(dl_se) ||
			      (dl_se->dl_defer && dl_se->dl_defer_running)) &&
			     !dl_time_before(dl_se->deadline, rq_clock(rq)) &&
			     !is_dl_boosted(dl_se))) {
			update_dl_revised_wakeup(dl_se, rq);
			return;
		}

		dl_se->dl_defer_running = 0;
		replenish_dl_new_period(dl_se, rq);
    ...
}

Instead of capping the runtime via update_dl_revised_wakeup(), update_dl_entity() calls replenish_dl_new_period() and grants a full fresh runtime before the constrained reservation's period or 0-lag time has elapsed. Conversely, if a runnable task whose old deadline has already passed switches to a constrained deadline, dl_check_constrained_dl() at the top of enqueue_dl_entity() computes dl_next_period() from the old dl_se->deadline and the new dl_deadline/dl_period, throttles the task, and returns before update_dl_entity() can start a new period.

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

Re: [PATCH v7 33/40] sched/deadline: Start a period for a task that enters the class blocked

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: unstarted period when sleeping task has !dl_task_pi_blocked() - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: unstarted period when sleeping task has !dl_task_pi_blocked()
- [Medium] sched/deadline: sched_setattr() on PI-boosted blocked task skips period update
--

commit 5f0fe1e32222b5c48a70b881608ff3bc4a90abf3
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Start a period for a task that enters the class blocked

This commit starts a deadline period in switched_to_dl() and dl_boost_blocked() when a task blocked on an rt_mutex enters the deadline class or receives a new donor so its waiter does not sort with a deadline of 0.

Quoted 5 lines
kernel/sched/deadline.c +0 -0
index 0b30059483136..90b17969554bf 100644

kernel/sched/deadline.c void dl_deboost(struct sched_dl_entity *dl_se) · line 133

Quoted 9 lines
kernel/sched/deadline.c +6 -0
@@ -125,6 +125,12 @@ void dl_deboost(struct sched_dl_entity *dl_se)
 	}
 	dl_drop_boost(dl_se);
 }
+
+/* Return true if @p waits on an rt_mutex. The caller holds its pi_lock. */
+static inline bool dl_task_pi_blocked(struct task_struct *p)
+{
+	return p->pi_blocked_on;
+}

[Severity: Medium]
Can gating replenish_dl_new_period() on dl_task_pi_blocked(p) still leave p->dl.deadline at 0 when a sleeping task participates in rt_mutex priority inheritance before waking up?

A non-deadline task sleeping in futex_wait_requeue_pi() on uaddr1 has !task_on_rq_queued(p) and p->pi_blocked_on == NULL. If it enters dl_sched_class while sleeping on uaddr1 (via sched_setattr() or a PI boost on another rt_mutex it owns), dl_task_pi_blocked(p) is false, so both switched_to_dl() and dl_boost_blocked() leave p->dl.deadline at 0. A subsequent FUTEX_CMP_REQUEUE_PI then calls rt_mutex_start_proxy_lock() -> task_blocks_on_rt_mutex() without waking p, queueing its waiter on uaddr2 with a deadline of 0 ahead of all real deadline waiters.

Similarly, if a task holding an rt_mutex sleeps in a non-rt_mutex syscall (p->pi_blocked_on == NULL) and sched_setattr() makes it SCHED_DEADLINE, p->dl.deadline remains 0 while dl_prio(p->normal_prio) becomes true. If an earlier-deadline waiter then blocks on that rt_mutex before p wakes up, rt_mutex_setprio() evaluates dl_entity_preempt(&pi_task->dl, &p->dl) against deadline 0, which returns false and fails to boost p.

[ ... ]

Quoted 7 lines
kernel/sched/deadline.c +3 -0
@@ -4483,6 +4514,17 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 	if (!task_on_rq_queued(p)) {
 		add_rq_bw(&p->dl, &rq->dl);
 
+		/*
+		 * A task that waits on an rt_mutex cannot wait for its wakeup.
+		 * The chain walk sorts its waiter by its deadline first. A task

kernel/sched/deadline.c static void switched_to_dl(struct rq *rq, struct task_struct *p) · line 4529

Quoted 10 lines
kernel/sched/deadline.c +8 -0
+		 * new to the class has a deadline of 0, which goes before every
+		 * real one. Start a new period now, as setup_new_dl_entity()
+		 * does at an enqueue.
+		 */
+		if (dl_task_pi_blocked(p) && !p->dl.dl_throttled &&
+		    dl_time_before(p->dl.deadline, rq_clock(rq)))
+			replenish_dl_new_period(&p->dl, rq);
+
 		return;
 	}

[Severity: Medium]
What happens when sched_setattr() changes the policy of a task blocked on an rt_mutex that is already in dl_sched_class due to a PI boost?

Because prev_class and next_class are both &dl_sched_class, __sched_setscheduler() does not set DEQUEUE_CLASS, so switched_to_dl() does not run:

kernel/sched/syscalls.c:__setscheduler_dl_pi() {
	if (dl_prio(newprio) && !dl_policy(policy)) {
		struct task_struct *pi_task = rt_mutex_get_top_task(p);

		if (pi_task) {
			p->dl.pi_se = pi_task->dl.pi_se;
			scope->flags |= ENQUEUE_REPLENISH;
		}
	}

...
}

When sched_setattr() gives such a blocked task its own SCHED_DEADLINE reservation with an earlier deadline than its donor's, __setscheduler_dl_pi() does nothing because dl_policy(policy) is true, and prio_changed_dl() returns early because !task_on_rq_queued(p). Neither p->dl.deadline nor p->dl.pi_se is updated, so rt_mutex_adjust_pi() sees rt_waiter_up_to_date(waiter, p) and stops without re-sorting p's waiter or propagating the earlier deadline down the lock chain.

Conversely, when a blocked task leaves SCHED_DEADLINE (!dl_policy(policy)) while remaining boosted in dl_sched_class (dl_prio(newprio)), setting ENQUEUE_REPLENISH in __setscheduler_dl_pi() has no effect while !scope->queued because dl_boost_blocked() is not called.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=33
maintainer Reviewed-by on v7 4/40
#5 lore raw

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

In reply to Mathieu Desnoyers

Hello,

Quoted 33 lines · 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.

Quoted 6 lines

With this patch, the reproducer survives 20 rounds with no warning.

Fixes daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks")

---

Thanks,
Juri

maintainer Reviewed-by on v7 5/40
#9 lore raw

Re: [PATCH v7 05/40] sched/deadline: Refuse dl_server debugfs writes while the rq is offline

In reply to Mathieu Desnoyers

Hello,

Quoted 22 lines · 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.

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.

Quoted 7 lines

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

---

Thanks,
Juri

maintainer Reviewed-by on v7 8/40
#14 lore raw

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

In reply to Mathieu Desnoyers

Hello,

Quoted 41 lines · 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

Quoted 11 lines

Fix this by reading the inherited runtime, deadline and period once, and by not refilling from cleared ones. They are cleared under the waiter's rq lock, not the owner's. So test all three. The owner stays runnable. It gets no runtime. A negative runtime is reset to 0: the owner's own reservation does not pay for the boost. An owner with no parameters of its own gets a deadline of now. A deadline of 0 would mark its dl_rq as empty. The wakeup of a boosted task already gives that deadline when its donor is cleared. The owner runs until the chain walk deboosts it, or until it releases the lock. That also covers sysrq-n:
normalize_rt_tasks() changes the waiter without a chain walk. The warning stays for an entity that is not boosted.

The above paragraph is a bit hard to decipher. :)

Maybe something like the below?

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

Quoted 10 lines

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 the third posting found the lockup. Juri Lelli suggested this fix in place of a larger one.

Also for other changelogs, I am not sure this kind of info adds much, as I fear it will be hard to track down in history anyway.

Quoted 6 lines
Fixes a5e7be3b28a2 ("sched/deadline: Clear dl_entity params when setscheduling to different class")

---

For the implementation,

Thanks,
Juri

#8 lore raw

Re: [PATCH v7 05/40] sched/deadline: Refuse dl_server debugfs writes while the rq is offline

In reply to [email protected]
Quoted 3 lines

Does checking only !rq->online still leave a window during CPU deactivation where cpu_active(cpu) is already false while rq->online is still set?

Yes. On v6 I answered that the rq->online test would stay as it is. The next version adds the cpu_active() test you suggest. The refusal then covers the whole deactivation, so the window is gone.

On the way up, cpu_active() is set before rq->online. So the extra test changes nothing there.

A write in that window left no wrong state in v7. The rebuild at the end of sched_cpu_deactivate() resets total_bw and extra_bw. But the comment says the refusal covers the whole offline, and now it does.

This was checked by reading, not reproduced.

Thanks,

Mathieu

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

Re: [PATCH v7 10/40] sched/deadline: Reset the deadline and the runtime with the parameters

In reply to [email protected]
Quoted 2 lines

Can a task deboosting via switched_from_dl() still retain a donor's deadline and runtime when p->dl.dl_runtime is non-zero?

Yes, and upstream does the same. This is known. The v7 cover letter lists it under "Not changed". At a deboost, the 0-lag time of a task comes from the deadline and runtime of the boost.

It cannot be fixed without the deadline and runtime the task had before the boost. Nothing stores them. A new period of its own at that point gives a 0-lag time of about now. That releases the bandwidth at once.

Quoted 3 lines

otherwise, p keeps the donor's runtime and can consume it on top of its own reservation if it re-enters SCHED_DEADLINE before the inactive timer fires.

That return is checked. Patches 35 and 36 check the runtime left against the task's own parameters, as a wakeup does. A runtime that does not fit starts a new period.

The cover letter of the next version states this point more clearly under "Not changed". All of this was checked by reading.

Thanks,

Mathieu

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

Re: [PATCH v7 09/40] rtmutex: Continue the chain walk when a waiter's deadline donor changes

In reply to [email protected]
Quoted 4 lines

Can rt_mutex_adjust_prio_chain() still stop one lock too early at the preceding top_waiter != task_top_pi_waiter(task) check when a task holds two locks and its top PI waiter switches from one lock to the other?

Yes, thanks. I checked it by reading. The walk stops at M, at the top-waiter test, and never reaches the donor test of this patch. So O keeps W as its donor.

The test dates from the first rtmutex code, commit 23f78d4a03c5. With RT priorities only, it stops the walk the same way. O then stays boosted to W's old priority until it unlocks L2.

Quoted 2 lines

O->dl.pi_se remains &W->dl, and once W unblocks and exits, O's next replenish_dl_entity() reads W's freed task_struct (use-after-free).

Not in this exact sequence. W is the top waiter of L1', so its timeout walks from M. The donor test of this patch sends that walk on to O.

A third waiter on L1' gives the use after free. X is a SCHED_FIFO task. After W's policy change, X's waiter on L1' sorts before W's. O, M, W and Z are as in your setup:

O M W Z X

locks L2 locks L1 and L1'
blocks on L1'
M->dl.pi_se = &W->dl
blocks on L2
O->dl.pi_se = &W->dl
blocks on L1
sched_setscheduler(SCHED_OTHER)
rt_mutex_adjust_pi(W)
M->dl.pi_se = &Z->dl
walk at M: L1' is not M's top
stops
blocks on L1'
walk stops at M
times out on L1'
not the top waiter: no walk
exits

O's next refill then reads W's freed task_struct. Before W exits, O keeps the boost of a task that has left SCHED_DEADLINE.

The next version adds a patch after this one, "rtmutex: Continue the walk when the owner's top waiter changes lock". It removes the top_waiter != task_top_pi_waiter() test. The next test, the one this patch extends, already stops the walk for a waiter that is up to date. An out of date waiter is now requeued, and the walk goes on. Its changelog has the diagram above.

Two new test cases cover it, without the exit. In pi_chain_top_moves_rt, W and Z have RT priorities. On v7, O kept W's priority in each of 14 runs. With the next version, O follows Z in each of 14 runs. In pi_chain_top_moves, they are deadline tasks. A deadline task that shares O's CPU lost one of its periods on v7, in each of 8 runs. It did not with the next version, in 8 runs.

Two more points, both found by reading.

With the test gone, more walks go on. Patch 33 started a new period for a blocked task at each boost, even with the same donor. Its waiter was then out of date again after each step. In a ww_mutex cycle, the walk could run until max_lock_depth. In the next version, patch 33 starts a new period only when the donor changes.

A narrower window remains. The old donor can leave as a waiter that is not the top one while a walk is in flight. It starts no walk. The owners further down keep it until the walk in flight reaches them. The donor pointer holds no reference on the donor, so no change to this test can close it. The cover letter widens its known limit to this case.

Thanks,

Mathieu

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

Re: [PATCH v7 11/40] sched/deadline: Reset the donor's runtime at a deboost in the class

In reply to [email protected]
Quoted 2 lines

Can a SCHED_DEADLINE task skip dl_deboost(&p->dl) here when switching from one deadline donor to another?

Yes, while the boost lasts. The first branch does not clear dl_donor_refill. The flag set by the first donor's refill stays set while the second donor boosts the task. At the last unlock, rt_mutex_setprio(p, NULL) takes the else branch. There, dl_deboost() starts a new period. So the task keeps nothing of the first donor after the boost.

During the second boost, the task keeps the deadline and runtime it has, as upstream does. Its own new period could indeed be earlier. But a dl_deboost() at each change of top waiter would give the task a full runtime of its own each time. A task whose top waiter changes often would then exceed its bandwidth. So this is left as is. The cover letter of the next version lists it under "Not changed".

Quoted 3 lines

Does a task that still has SCHED_DEADLINE parameters (p->dl.dl_runtime != 0) keep the donor's refilled runtime and deadline when leaving the deadline class at deboost?

This is the same point as on patch 10. It is known, and upstream does the same. A return to SCHED_DEADLINE before the inactive timer is checked against the task's own parameters, by patches 35 and 36. The cover letter of the next version states it more clearly under "Not changed".

Quoted 3 lines

In this cleared-donor fallback (!runtime || !deadline || !period), should dl_note_donor_refill(dl_se) also be called when dl_se->dl_deadline is non-zero?

No, this is intended, as answered on v6. The task has parameters of its own. It keeps its own deadline, with no runtime left: an exhausted period. After the deboost, the next update_curr_dl() throttles it until its next period, as for any task that used up its runtime. Setting the flag would make dl_deboost() start a new period. That would be a second full runtime in the same period.

All three points were checked by reading.

Thanks,

Mathieu

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

Re: [PATCH v7 12/40] sched/deadline: Replenish a throttled task boosted while asleep

In reply to [email protected]
Quoted 3 lines

Does letting a sleeping boosted task fall through to replenish_dl_entity() corrupt its CBS accounting by refilling its pre-boost deficit from the donor's reservation parameters?

No, it does what the boost of a queued task does. I checked it by reading. When a throttled task that is queued gets boosted, rt_mutex_setprio() sets ENQUEUE_REPLENISH. replenish_dl_entity() then refills it from the donor's parameters, with the same loop. That is upstream behaviour. The timer now gives the sleeping task the same refill. Before this patch, the sleeping task was not refilled at all. It hung.

Quoted 2 lines

dl_deboost() resets dl_se->deadline and dl_se->runtime to a full new period, forgiving any runtime overrun p owed before going to sleep.

The overrun of a throttled task is the delay of the overrun detection, up to a tick. A queued task boosted while throttled gets the same. Without the flag, the task would keep the donor's runtime after the boost.

Quoted 3 lines

the while loop above pays off p's overrun in multiples of the donor's smaller runtime and period, which can push p's boosted deadline several donor periods into the future.

The same loop runs for a queued throttled task at its boost. It is how the base pays an overrun while boosted.

Quoted 1 line

and falsely trigger the "sched: DL replenish lagged too much" warning.

That message is printed once per boot. The code then starts a new period. The queued case can print it too.

Quoted 5 lines

If the donor left SCHED_DEADLINE and had its parameters cleared before dl_task_timer() runs, the !runtime branch in replenish_dl_entity() skips dl_note_donor_refill() and the deadline update because dl_se->dl_deadline is non-zero, leaving p's expired deadline in the past after dl_deboost().

That early return clears the throttle, which is what this patch needs. The task keeps its own past deadline until its wakeup starts a new period. A sleeping deadline task keeps the deadline of its last period in general. The cover letter of the next version lists that under "Not changed".

Quoted 4 lines

Finally, if p changed policy while sleeping and boosted, refilling from the donor before 0-lag time leaves donor-derived runtime and deadline on p when rt_mutex_setprio() drops the boost via dl_drop_boost().

This is the known 0-lag point of patch 10. The cover letter lists it under "Not changed".

Thanks,

Mathieu

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

Re: [PATCH v7 18/40] sched/deadline: Record the root domain holding a task's bandwidth

In reply to [email protected]
Quoted 3 lines

Should __sched_setscheduler() also use the root domain recorded in p->dl.dl_bw_cpu rather than rq->rd when validating a deadline task's root domain span and dl_bw.bw?

This repeats a point from v6, and the answer is the same. That EPERM is the baseline's affinity check. This series does not change it. It is a gate only. The admission test is sched_dl_overflow(), and it uses the recorded CPU. So the gate can refuse wrongly, but it never admits wrongly.

Patch 23 needs the refusal. sched_setattr() can make a task a deadline task right after a cpuset move. That task has no recorded CPU yet. The CPU it is on is the only one the check can use.

The hotplug case is the same check, with the same effect. Once the task has run on its new CPUs, its parameters can be changed as usual.

The v7 cover letter lists this under "Not changed" for the partition move. The next version widens that line to a task asleep on a CPU that went offline. All of this was checked by reading.

Thanks,

Mathieu

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

Re: [PATCH v7 23/40] sched: Make deadline policy and affinity changes wait for a cpuset attach

In reply to [email protected]
Quoted 2 lines

Can this second __set_cpus_allowed_ptr() call apply a stale new_mask after cpuset_lock_no_attach() sleeps?

Yes, thanks. The restore reads the cpuset mask with no lock. That is upstream code. But this patch sleeps between that read and the write, and an attach can move the task meanwhile. The next version takes cpuset_lock_no_attach() first. It then reads the cpuset mask again and builds the restore mask under that lock. Every writer of a cpuset mask holds cpuset_mutex, so the mask stays valid until the call.

Quoted 5 lines

In addition, if css_set_move_task() moves p to the destination cpuset before cpuset_cpus_allowed() is read while attach_ctx.in_progress is still set, waiting in cpuset_lock_no_attach() delays restoring p->user_cpus_ptr from ctx->user_mask until after cpuset_attach_task() has already run

This does not change the result. A cpuset attach intersects the mask with the user mask of the task, with or without this patch. So the task gets the cpuset mask and the old user mask, as if the old user mask had been put back first. The bandwidth stays in the root domain the attach
reserved: cpuset_can_attach() and cpuset_attach() saw the same user mask. Keeping the restore after the attach is the reason for the wait.

Both points were checked by reading. Neither was reproduced.

Thanks,

Mathieu

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

Re: [PATCH v7 26/40] sched/deadline: Make a rebuild count a task in the root domain it runs in

In reply to [email protected]
Quoted 3 lines

Can returning recorded here without checking the task's cpuset charge the bandwidth to a newly created partition that no longer contains the task?

Yes, thanks. The record can name a CPU that a partition root took since. With no active CPU in the mask, the next version asks the cpuset first. It keeps the CPU recorded only if the cpuset holds it.

The early return covered two cases. A task that dl_task_offline_migration() moved to that CPU is queued there. The test before it already catches that task. A task that an earlier rebuild counted there keeps the record if its cpuset holds the CPU. A task asleep wakes up through select_fallback_rq(), on a CPU of its cpuset. So the cpuset is where it runs.

This was found by reading. A new test case, rebuild_record_taken, shows it. A partition root takes the CPU recorded with a sleeping task. On v7 the partition counts the task, which then wakes up outside it. With the next version the task is counted where it wakes up. That held in each of 7 runs on both.

Quoted 2 lines

Does calling dl_get_task_effective_cpus() here read a stale HK_TYPE_DOMAIN mask during cpuset partition transitions?

Yes. Upstream reads it there too, for every task. This patch only reaches it for a task with no active CPU in its mask. With admission control on, patch 29 refuses the offline that leads there. The next version reads HK_TYPE_DOMAIN_BOOT in dl_get_task_effective_cpus(), as the rest of the series does. A task whose mask holds only CPUs isolated at boot runs in def_root_domain, whatever the partitions do.

This was checked by reading, not reproduced.

Thanks,

Mathieu

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

Re: [PATCH v7 27/40] sched/deadline: Move a task's bandwidth to the root domain it runs in

In reply to [email protected]
Quoted 2 lines

Can dl_task_move_bw() move the departing bandwidth of a non-deadline task that was PI-boosted back into the deadline class?

Yes, and this is intended. A departed task boosted back is in the class. A rebuild counts it where it runs, like any deadline task (see switched_to_dl()). The move does the same thing at the wakeup.

The bandwidth is moved, not released. One root domain counts it at any time. If the boost ends before the 0-lag time, the task goes back on the departed list with the new record. Its inactive timer then releases the bandwidth there. The move has no check for room. That is a known limit, which the cover letter lists for this patch. This was checked by reading.

Quoted 4 lines

Does skipping dl_task_move_bw() when p->is_blocked && task_on_rq_migrating(p) also drop the bandwidth move for normal queued migrations of mutex-blocked tasks under CONFIG_SCHED_PROXY_EXEC?

Yes, thanks. On this base, proxy_set_task_cpu() does not call migrate_task_rq_dl(). So the check guarded no proxy migration. It only skipped the ordinary migrations of a blocked task.

With admission control on, I found no such migration that crosses root domains. sched_setaffinity() must keep the span, patch 28 keeps the task in it, and a cpuset attach moves the bandwidth itself. With admission control off, sched_setaffinity() can cross. The bandwidth then stays behind until the task sleeps and wakes, or migrates again.

The next version removes the check. It stays in the proxy execution RFC, in the patch that makes a proxy migration call migrate_task_rq(). That series also wakes a blocked deadline task through the full path, which moves the bandwidth. This was checked by reading, not reproduced.

Quoted 3 lines

Can keeping dl_bw_rebuilding() true until the end of the tasklist walk drop bandwidth moves for tasks that dl_add_task_root_domain() has already visited?

Yes. The message says the rebuild that follows counts the task. That holds only for a task the walk has not reached yet.

The root domains are final once the walk starts. So the next version ends the rebuild window in dl_clear_root_domains(). A flag, dl_bw_walking, then covers the walk of the task list. A helper, dl_bw_move_blocked(p), blocks a move in two cases:
- the sched domains are being rebuilt;
- the walk runs and has not counted p yet (p has an old dl_bw_gen).
The walk then counts p where it is. A task the walk already counted moves its bandwidth again. The walk and a wakeup both hold the pi_lock of the task, so they are ordered.

This moves the boundary of the known limit of patch 28. A wakeup can pick its CPU before the walk reaches the task, and be queued after the walk counted it. Its bandwidth then moves with no check for room. The cover letter and the message of patch 28 state this.

Quoted 3 lines

In addition, when dl_task_bw_elsewhere() runs under rq->__lock without p->pi_lock, it reads bw_cpu = READ_ONCE(p->dl.dl_bw_cpu) before checking dl_bw_rebuilding() and READ_ONCE(dl_bw_gen)

That lockless test is only a hint. dl_task_move_bw() reads the record again under dl_departed_lock. A stale read can only skip a move. The next wakeup or migration tests again. I left it.

Both points were checked by reading. Neither was reproduced.

Thanks,

Mathieu

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

Re: [PATCH v7 28/40] sched/deadline: Keep a task in the root domain that counts its bandwidth

In reply to [email protected]
Quoted 2 lines

Does this leave p->wake_cpu stale when cpumask_any_and_distribute() already picked a dest_cpu inside span?

Yes. The stale wake_cpu matters only for a wakeup during the rebuild of the sched domains. Outside it, select_task_rq_dl() prefers the span. The cover letter lists the rebuild case as a known limit of this patch.

The next version still sets wake_cpu for a sleeping task whose new mask keeps its CPU in the span, as you suggest. That narrows the window. It does not close it: during a rebuild, find_later_rq() can still look in another root domain. This was checked by reading.

Quoted 3 lines

Can dl_task_offline_migration() still move a throttled task and its bandwidth into def_root_domain when dl_task_timer() fires during a sched domain rebuild?

Yes, thanks. Upstream makes the same move. But with this series, the walk then counted the task on the isolated CPU, and kept it there. And the cover letter says no bandwidth moves during the rebuild.

The next version uses the same test as migrate_task_rq_dl() and task_woken_dl(), dl_bw_move_blocked(p). So dl_task_offline_migration() moves no root domain bandwidth while the sched domains are rebuilt, or before the walk counted the task. The bandwidth of the runqueue still moves, since it follows the task. The walk counts the task on the side of its record, and its next wakeup brings it back. The task itself may still run on the isolated CPU until it blocks. That is the known limit of this patch.

This was checked by reading, not reproduced.

Quoted 2 lines

Should p->dl.dl_bw_cpu be read with READ_ONCE() when initializing recorded in dl_task_rebuild_cpu()?

Yes. The last schedule of a dying task can clear the record while the walk holds only the pi_lock. The walk checks again under dl_departed_lock, so the race is harmless. But the value must be read once. The next version uses READ_ONCE(), in patch 26, where this line comes from.

Thanks,

Mathieu

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

Re: [PATCH v7 29/40] sched/deadline: Keep the last CPU a task has in its root domain

In reply to [email protected]
Quoted 2 lines

Does cpuset_cpus_allowed_without() return an overly wide mask when it walks past an intermediate ancestor to find remaining active CPUs?

Yes, thanks. cgroup v2 computes the CPUs from the top down. The walk up skipped a parent that then inherits wider CPUs. The next version starts from the nearest valid partition root, or the top cpuset, that keeps an active CPU. It then works down to the cpuset of the task with effective_cpus_below(), as compute_effective_cpumask() does. Patch 30 already used that helper for cpuset writes. It moves into this patch. cgroup v1 keeps the walk up.

This was found by reading. A new test case, hotplug_nested_refused, tests it. On v7 the offline is accepted, and the task wakes up on an isolated CPU. With the next version it fails with EBUSY. That held in each of 6 runs on both.

Quoted 3 lines

Can intersecting pmask with task_cpu_possible_mask(tsk) after the ancestor loop leave pmask empty when an ancestor has possible CPUs for tsk?

Yes. The possible mask must come before the empty test. The path is select_fallback_rq(), though. The cpuset update fails on an empty mask and leaves the mask alone. The wakeup then tries cpuset.cpus, then task_cpu_fallback_mask(). Patch 28 makes each step prefer a CPU of the span. So the bandwidth leaves only if none of those CPUs is in the span.

The next version stops the walk at a cpuset with a CPU the task can run on. If none is left, select_fallback_rq() picks the CPU, with the change described below. The check now predicts that change too. This was checked by reading. I have no asymmetric arm64 system to test on.

A second read of this patch found a related gap. At an offline, select_fallback_rq() runs before the cpuset update. A runnable deadline task on the outgoing CPU is pushed away then. The fallback uses cpuset.cpus, then the housekeeping CPUs. These are not the CPUs that this patch predicts. So a running task could leave its root domain while the offline was accepted.

A new test case, hotplug_fallback_running, shows it. A deadline task with a 2ms period runs on the outgoing CPU. On v7, the task left its root domain in every run (8 runs). The next version changes select_fallback_rq() in patch 28. When it would widen the mask out of the root domain of the task, the task gets the CPUs of that root domain instead. The cpuset update that follows sets the real mask. With that change, the case passed in each run where it was not skipped.

Thanks,

Mathieu

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

Re: [PATCH v7 33/40] sched/deadline: Start a period for a task that enters the class blocked

In reply to [email protected]
Quoted 3 lines

Can gating replenish_dl_new_period() on dl_task_pi_blocked(p) still leave p->dl.deadline at 0 when a sleeping task participates in rt_mutex priority inheritance before waking up?

Yes, as on v6. Both cases are real, and upstream. But deadline 0 is one case of a wider behaviour. A deadline task that sleeps keeps the deadline of its last period. After a long sleep, that deadline is far in the past. It sorts first at a requeue_pi, and it blocks the boost of a sleeping owner, as 0 does. This happens with or without a class change.

This patch fixes the case where the task already waits on the rt_mutex when it enters the class. Refreshing the deadline of a sleeping task in the rt_mutex paths would be a separate change. The cover letter of the next version lists this under "Not changed". This was checked again by reading.

Quoted 3 lines

What happens when sched_setattr() changes the policy of a task blocked on an rt_mutex that is already in dl_sched_class due to a PI boost?

The class does not change, so switched_to_dl() does not run. The waiter keeps the deadline that the boost gave it. But a sleeping deadline task starts its own period only at its wakeup. This is the same wider behaviour as in the first point. At the deboost, the task starts a period of its own. Upstream left a deadline of 0 here.

Quoted 5 lines

Conversely, when a blocked task leaves SCHED_DEADLINE (!dl_policy(policy)) while remaining boosted in dl_sched_class (dl_prio(newprio)), setting ENQUEUE_REPLENISH in __setscheduler_dl_pi() has no effect while !scope->queued because dl_boost_blocked() is not called.

dl_boost_blocked() would do nothing there. It only acts for a task with no parameters of its own. A task that leaves the class keeps its parameters and its deadline until its 0-lag time. A queued task boosted back does the same. The new donor still reaches the next owner: pi_se changed, so the chain walk goes on.

Both points were checked by reading.

Apart from these points, the next version changes this patch. A blocked task starts a new period only when its donor changes. The reply on patch 9 says why.

Thanks,

Mathieu

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

Re: [PATCH v7 36/40] sched/deadline: Check the runtime of a task whose parameters change

In reply to [email protected]
Quoted 3 lines

Can a boosted SCHED_DEADLINE task with !dl_se->dl_donor_refill keep running on its old reservation's remaining runtime after sched_setattr() shrinks its parameters?

Yes, but its own runtime does not limit it while it is boosted. A boosted task is never throttled. When its runtime runs out, update_curr_dl_se() enqueues it with ENQUEUE_REPLENISH, and replenish_dl_entity() refills it from the donor. A smaller runtime would only bring the donor refill sooner. The CPU time during the boost is the same. This is the inheritance design of 2d3d891d3344.

At the deboost, the runtime left is checked against the new parameters. An implicit task keeps it only if it fits the new bandwidth until the deadline. Patch 34 caps a constrained task at the new dl_runtime. That is what a wakeup gives.

You are right that the comment is loose. Without a refill, the task runs on its own runtime first. The next version says "A boosted task is refilled from its donor."

Quoted 3 lines

When a boosted task with dl_new_params set and !dl_se->dl_donor_refill is deboosted in rt_mutex_setprio(), does deferring update_dl_entity() until enqueue_dl_entity() miss the post-deboost re-boost check?

Yes, thanks. Patch 11 resets the donor refill in dl_deboost() for this exact reason: the re-boost test and the chain walk read the deadline before the enqueue. This patch left the check of the new parameters to the enqueue. So the test read a deadline the check could still move. And a blocked task was not checked before the chain walk.

The next version does the check in dl_deboost(), after dl_drop_boost(), when the mark is set. The re-boost test then sees the result. A throttled task is left to its replenishment, as at the enqueue.

A new test case, deboost_new_params_reboost, shows it. An owner shrinks its parameters while boosted, and its donor times out. A deadline waiter with an earlier deadline remains. On v7 the owner is not boosted again and is throttled: its 20ms of work took 400ms in each of 40 runs. With the next version it took about 20ms in each of 40 runs.

Quoted 3 lines

Can calling update_dl_entity() on dl_new_params mix the previous period's dynamic state with the newly written static parameters when switching between constrained and implicit deadlines?

The first case gives the wakeup rule. A sleeping task changed the same way, and woken at the same time, gets the same new period upstream.

It also gives no more than without this patch. Without it, the task keeps its old runtime and deadline. dl_next_period() reads the new parameters. So the timer refills the task with the new runtime at its old deadline. The task then gets a little more than with this patch.

The excess is the run of the old reservation before the change. sched_dl_overflow() gives that bandwidth back at once. Its XXX comment says the old bandwidth should stay until the 0-lag time. The message of this patch names that gap. It is not changed here.

In the second case, dl_check_constrained_dl() runs on every enqueue upstream, including the one of sched_setattr(). This patch does not move it. The task is throttled the same way on v7.4-rc2.

Both cases were checked by reading.

Thanks,

Mathieu

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

Re: [PATCH v7 38/40] selftests/sched: Add a test of SCHED_DEADLINE policy round trips

In reply to [email protected]
Quoted 3 lines

Does pthread_attr_setstacksize(&fa, FILLER_STACK) fail with EINVAL on architectures where PTHREAD_STACK_MIN is larger than 64 KiB, such as arm64 and powerpc64 (128 KiB)?

Yes, thanks. The case then fails in its setup on those architectures. deadline_bw_test.c raises its stack to PTHREAD_STACK_MIN. This test missed it. The next version raises FILLER_STACK the same way.

Quoted 4 lines

Also, pthread_attr_init() and pthread_attr_setstacksize() return an error number directly without setting errno, so strerror(errno) reports a stale errno (typically "Success"), and this error path returns without closing filler_pipe or destroying fa.

Right. The next version splits the setup, so each step prints its own error. It prints the error number that pthread_attr_*() return. The error paths now free what the setup made.

Quoted 3 lines

Should test_sysrq_boosted_owner() and test_sysrq_running_owner() call sem_destroy() on owner_locked, owner_go, filler_ready, and waiter_go during cleanup?

Yes. No thread uses owner_locked when the second case initializes it again, so it is harmless in practice. But POSIX leaves it undefined. The next version destroys the semaphores at the end of both cases.

Both points were checked by reading.

Thanks,

Mathieu

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

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

In reply to Juri Lelli
Quoted 3 lines · Juri Lelli

The above paragraph is a bit hard to decipher. :)

Maybe something like the below?

Yes, thanks. The next version takes your text as is.

Quoted 2 lines

Also for other changelogs, I am not sure this kind of info adds much, as I fear it will be hard to track down in history anyway.

Agreed. The next version drops the sentences that name the review that found a bug, in all the changelogs. The credits to people stay.

Quoted 3 lines

For the implementation,

Thanks!

Mathieu

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

Re: [PATCH v7 05/40] sched/deadline: Refuse dl_server debugfs writes while the rq is offline

In reply to Juri Lelli
Quoted 1 line · Juri Lelli

Thanks! The next version adds one test here. The Sashiko review of v7 noted that cpu_active() is cleared before rq->online on the way down. So the patch now refuses a write if either is off:

        if (!rq->online || !cpu_active(cpu_of(rq)))
                return -EBUSY;

I kept your tag, with a note below the --- that it was on the v7 code. Tell me if you would rather I drop it.

Mathieu

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

Re: [PATCH v7 09/40] rtmutex: Continue the chain walk when a waiter's deadline donor changes

In reply to Mathieu Desnoyers

Hello,

On 17/11/26 09:10, Mathieu Desnoyers wrote:

...

Quoted 3 lines

Fix this by recording the donor in the waiter with the sort keys, in waiter_update_prio(). rt_waiter_up_to_date() compares both. The walk and rt_mutex_adjust_pi() use it. A new donor then takes the walk on to the

...

Quoted 4 lines
 kernel/locking/rtmutex.c        | 22 ++++++++++++++++++++--
 kernel/locking/rtmutex_api.c    |  2 +-
 kernel/locking/rtmutex_common.h |  3 +++
 3 files changed, 24 insertions(+), 3 deletions(-)

Thanks for confirming the Sashiko finding and for the plan in your reply [1]. As you note there, a window remains however the walk is changed, because the donor pointer holds no reference on the donor. So I have to wonder (and ask for Peter, Thomas, etc opinion) if we'd rather not keep extending the chain walk for DEADLINE PI, which is known broken and proxy execution is going to replace anyway, and leave rtmutex.c alone.

It looks like what we lack is memory safety, apart from accurate PI. It's an hack after another, but how about having the owner pin its donor
instead: take a reference on the task behind dl.pi_se whenever it is set to another task's entity, and drop it when pi_se changes (rt_mutex_setprio() and __setscheduler_dl_pi() are the only writers). The donor then stays allocated at most for the owner's critical section; its parameters may be stale or cleared meanwhile, which replenish_dl_entity() already copes with after patch 8; and the owner may keep running on a stale donor, which is no worse than today's DEADLINE PI. Thoughts?

Not against doing "the more right thing" of course. Just evaluating alternatives.

Thanks,
Juri

[1] https://lore.kernel.org/all/[email protected]/

maintainer
#16 lore raw

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

In reply to Mathieu Desnoyers
Quoted 5 lines · Mathieu Desnoyers
Quoted 3 lines · Juri Lelli

The above paragraph is a bit hard to decipher. :)

Maybe something like the below?

Quoted 7 lines

Yes, thanks. The next version takes your text as is.

Quoted 2 lines

Also for other changelogs, I am not sure this kind of info adds much, as I fear it will be hard to track down in history anyway.

Agreed. The next version drops the sentences that name the review that found a bug, in all the changelogs. The credits to people stay.

Hummm, now that you say it, crediting Sashiko for findings might be worthwhile (for usefulness statistics etc), though.

#17 lore raw

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

Quoted 2 lines · Juri Lelli

Hummm, now that you say it, crediting Sashiko for findings might be worthwhile (for usefulness statistics etc), though.

Agreed. Documentation/process/generated-content.rst also asks for it:
"if a tool was used to find a problem addressed by a change, that should be noted in the changelog". The next version keeps the credit, without the number of the posting. For this patch:

The Sashiko AI review of this series found the lockup.

Thanks,

Mathieu

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

Re: [PATCH v7 09/40] rtmutex: Continue the chain walk when a waiter's deadline donor changes

In reply to Juri Lelli
Quoted 10 lines · Juri Lelli

So I have to
wonder (and ask for Peter, Thomas, etc opinion) if we'd rather not keep extending the chain walk for DEADLINE PI, which is known broken and proxy execution is going to replace anyway, and leave rtmutex.c alone.

It looks like what we lack is memory safety, apart from accurate PI. It's an hack after another, but how about having the owner pin its donor
instead: take a reference on the task behind dl.pi_se whenever it is set to another task's entity, and drop it when pi_se changes (rt_mutex_setprio() and __setscheduler_dl_pi() are the only writers).

I like it. It closes the use after free in every case, also the window that no change to the walk can close. I checked two points in the code.

The writers: rt_mutex_setprio() and __setscheduler_dl_pi() set pi_se to a donor. dl_drop_boost() resets it to the task's own entity. dl_deboost() calls it. One helper can do all of them: drop the reference on the old donor, take one on the new one. The task behind pi_se is the owner of that entity, which can be a donor further up the chain. A task that exits while boosted needs its reference dropped too.

The locks: these writers hold the rq lock. put_task_struct() is safe there. It frees the task through call_rcu(), also on PREEMPT_RT.

Then patch 9 is no longer needed for memory safety. I would drop it. The owner keeps running on a stale donor until the next walk, as today.

The new patch after this one in the planned next version is a different case. Its subject is "rtmutex: Continue the walk when the owner's top waiter changes lock". It fixes a bug of RT priorities from 2006: an owner stays boosted to the priority of a waiter that left the chain. pi_chain_top_moves_rt shows it without any deadline task. I would keep it, Cc'd to the locking maintainers, or send it on its own.

I will wait for Peter's and Thomas' opinion before I change the series.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer Reviewed-by on v7 13/40
#33 lore raw

Re: [PATCH v7 13/40] sched/deadline: Release the bandwidth of a task that leaves the class asleep

In reply to Mathieu Desnoyers

Hello,

Quoted 49 lines · 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 the third posting found the two cases with the 0-lag time ahead. deadline_bw_test, added later in this series, tests this in pi_former_owner_asleep and deboost_released_resets_period.

Quoted 7 lines

---

Thanks,
Juri

maintainer
#79 lore raw
In reply to Mathieu Desnoyers

Hello,

Quoted 3 lines · Mathieu Desnoyers

Hi Ingo, Juri,

This series fixes 36 bugs of SCHED_DEADLINE. Most of them are in its

...

Thanks again for all the work on this!

So, I feel we are making progress, but the set keeps growing/changing.

While we spend more time on the "upper half" of it, would it maybe make sense to split the lowest part so that foundation fixes can start to be merged. I'm thinking 1-8, 10, 13, 14, 16, 20, 37 (37 is not a fix but harmless). Not all associated test will pass of course, which is not super nice, but we know they pass with the complete set and can maybe come later.

Just a thought, happy to continue iterating over the complete set.

Thanks,
Juri

#80 lore raw
Quoted 6 lines · Juri Lelli

While we spend more time on the "upper half" of it, would it maybe make sense to split the lowest part so that foundation fixes can start to be merged. I'm thinking 1-8, 10, 13, 14, 16, 20, 37 (37 is not a fix but harmless). Not all associated test will pass of course, which is not super nice, but we know they pass with the complete set and can maybe come later.

Good idea. As we discussed on IRC, I am taking these 14 patches as they are.

They apply on tip sched/urgent as they are. Each one builds alone. The kernel builds without warnings with PREEMPT_RT, without cpusets, and with RT group scheduling.

I would rather not leave failing tests in the tree. So I split the tests too. The first series adds deadline_switch_test with its 5 cases, and deadline_bw_test with 47 of its 112 cases. They pass in every one of 25 VMs, PREEMPT_RT included, with no kernel warning. On v7.4-rc2, 10 of them fail, one of them in part of the runs only.

The other cases test the fixes left out. They come with them in the second series. As you suggested, the two PI cases of 13 move there too:
pi_former_owner_asleep and deboost_released_resets_period. asleep_round_trip tests 13 without PI.

One case gets worse with these patches. pi_chain_top_moves passes on v7.4-rc2, and fails with them in every run. A bisect points at 13. The owner keeps a deadline task that left the class as its donor, and another deadline task gets too little CPU time. The case passes again with 9 and a new rtmutex fix of the next version. So it moves to the second series with them. Until they land, the cover letter of the first series lists this as a known limit.

One more result on v7.4-rc2. In one VM, hotplug_server crashed the kernel with a divide error in inactive_task_timer(). The message of 4 gives that path as found by reading. 4 fixes it.

I will post these 14 patches with the split tests as their own series. The rest will follow as the next version of this series, on top of it.

Thanks,

Mathieu

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