Skip to contentSkip to conversation

sched/deadline: bandwidth accounting fixes and selftests

PATCH Superseded Mathieu Desnoyers 2 participants 59 messages Nov 16 – Nov 17

Subsystems (6)

v6 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

v6 cover sched/deadline: bandwidth accounting fixes and selftests

Hi Ingo, Juri,

This series fixes 33 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 33.

Three of the bugs take the kernel down (patches 4, 8 and 24). 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 18 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 19 changes. Take it by whichever route you prefer.

Patch 1 of v5, also Andrea's, is upstream. It is
commit f7141257dd67 ("sched/core: Fix cpuset_mutex double unlock in __sched_setscheduler()"), and is dropped here.

Juri, Ingo dropped your four fixes from sched/urgent after the first one crashed Marek Szyprowski's hotplug test. They are here:
- 1/4 is patch 16. It does not use the task's mask, which can have no active CPU during hotplug.
- 2/4 is patch 11, without its double release. It does not carry your Signed-off-by, which is yours to add back.
- 3/4 is patch 1.
- 4/4 is patch 12, extended.
Marek found v2 fixed on the board that crashed.

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

Patches 16, 17 and 19 to 28 go together. 16 records the root domain that counts a task's bandwidth. 17 and 19 to 25 fix the rebuild, attach and migration paths that the record exposes. 26 to 28 keep a task in the root domain that counts it, as long as that root domain has a CPU for it. Patch 30 completes patch 14. Patch 34
shows this_bw in sched_debug. Patches 35 to 37 add 96 cases in tools/testing/selftests/sched/deadline, as Juri suggested.

Peter, patch 23 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 21 touches __sched_setscheduler() and sched_setaffinity(). A change of a deadline task waits there for a cpuset attach in progress. Patch 26 touches select_fallback_rq() and __set_cpus_allowed_ptr_locked() for deadline tasks.

Waiman, patches 27 and 28 add refusals that only isolcpus="domain" can trigger. They apply when a change would leave a deadline task no CPU in the root domain that counts it. 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. The message of each patch named states its own.

- Patch 13: 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 25: 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.
- Patches 26 to 28: 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 27 and 28 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.

Testing
=======

The 96 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 thirteen isolcpus cases run in the fourth group. There, three cases that need 4 CPUs that are not isolated skip. Four of the thirteen also run in the fifth group. move_cancelled runs only in the last group.

On v7.4-rc1, 32 cases of deadline_bw_test fail in 8 guests of 8 vCPUs, as patch 37 lists. overrun_caught and hotplug_sleeper_switched fail in 7 guests of 8, the others in every guest. The three cases of deadline_rebuild_test fail there too, and so do throttled_round_trip and asleep_round_trip of deadline_switch_test. The sysrq cases were not run on v7.4-rc1: sysrq-n leaves cpuset_mutex locked there, which patch 6 fixes.

Each case added in v5 or v6 for a fix fails without that fix. Each fix names the cases that test it, and patch 37 lists the rest. There are three exceptions:
- deboost_blocked_keeps_order passes on v7.4-rc1, and fails on v5.
- return_asleep_new_params passes everywhere. It covers the wakeup path that patches 32 and 33 copy.
- deboost_keeps_own_runtime passes with and without the flag of patch
10. It checks that a task keeps the runtime of its own reservation.

Two of the new cases pass on v7.4-rc1 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 11, 13 and 20, a kernel built with the series up to that patch confirms the claim of its message. Each of the 37 patches builds alone. The whole series also builds without CONFIG_CPUSETS, with PREEMPT_RT and with CONFIG_RT_GROUP_SCHED.

Not tested: cgroup v1 cpusets, threaded cgroups (every move is a write to cgroup.procs), the sched_ext server, and CPUs of unequal capacity.

Patch 8 has no selftest. A 300ms debug delay before rt_mutex_adjust_pi() locks up the series without patch 8, but not with it. A stress test switches the waiter in and out of the class. The series runs it for 600 seconds, with and without PREEMPT_RT.

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 v5. Each finding was checked against the code first.

Changes since v5
================

- Rebased on tip sched/urgent ec6f6731538e. Patch 1 of v5 is upstream, so it is dropped and the patches are renumbered.
- Patch 8 is the smaller fix Juri suggested. replenish_dl_entity() reads the inherited parameters once, and does not refill from a runtime of 0. The owner runs on until the chain walk deboosts it. The series no longer touches the rt_mutex code. So it no longer needs v2 of "locking/rtmutex: priority inheritance fixes and tests", and applies on tip sched/urgent alone. Patches 10 and 11 are rebased on the new patch 8.
- Patch 9: the comment of __dl_clear_params() says that it also resets the deadline and the runtime.
- Patch 11 calls task_non_contending() for a task that leaves the class asleep, as Juri suggested. The code is shorter and does the same.
- Patch 10: in v5 the deboost tested the runtime against dl_runtime. A task that its donor refilled could pass that test with a runtime and a deadline that were not its own. The refill is now recorded in a flag, dl_donor_refill. The deboost starts a new period when the flag is set, and keeps the runtime and the deadline otherwise. Two new cases test this: deboost_after_donor_refill and deboost_keeps_own_runtime.
- The Fixes: tags of patch 24 also name 318e18ed22e8. Its subject says what the rebuild does: it counts a task in the root domain it runs in.
- Patch 16: the second case of its message needs no pin and no change of admission control. hotplug_sleeper_switched now checks the accounting while the CPU is still offline, and fails without the patch. Bringing the CPU back rebuilt the accounting, and hid the bandwidth left behind.
- Fixes from the Sashiko review of v5:
- 10: the deboost starts the new period at once. A task blocked on another rt_mutex kept a deadline of 0. Its waiter then went first. If the new period ends after the top waiter's deadline, the task is boosted again.
- 16: sched_setaffinity() checks the root domain that counts the task. A departing task records the CPU it departs from.
- 19: an attach that reserved the bandwidth moves it, even if the mask does not change.
- 24: a simpler test of the recorded CPU. The behaviour is the same.
- 25: the bandwidth also moves at a wakeup with no migration. The test compares root domains, not the CPU the task leaves. New subject.
- Patch 13 (13 in v5), from Juri's review:
- A departed task keeps the CPU recorded when priority inheritance boosts it back into the class. In v5, the end of the boost took the bandwidth from the root domain the task ran in. Patch 16 hid this at the end of the series. The new case pi_departed_moved tests it.
- Two comments are Juri's: what dl_bw_gen dates, and why a rebuild drops the bandwidth of a departed task whose CPU is inactive.
- Patches 15 to 17 (15 to 17 in v5), from Juri's review:
- 15: the rebuild does not walk the task list when no task holds a deadline bandwidth. A new count, dl_nr_bw_tasks, tells it. A suspend and a resume run one rebuild for each CPU. In a 64-vCPU guest with 10000 threads and no deadline task, a rebuild took 0.7 to 1.2 ms without the count. It takes 0.03 ms with it. Patch 27 uses the count too.
- 16: set_cpus_allowed_dl() tests dl_bw_gen under dl_departed_lock.
- 17: the message says that the patch completes patch 15 and needs

    patch 16.

- New patch 18, by Andrea Parri, posted on its own on 2026-11-05. It moves the affinity check of a deadline task under the runqueue lock. It adds SCA_DL_CHECK as 0x10, so SCA_DL_BW_RESERVED of patch 19 stays 0x20. Patch 19 is rebased on it. The new case affinity_vs_setattr tests it.
- New patch 21, and patches 22 and 23 (20 and 21 in v5), from Juri's review. In v5, a task could become a deadline task between cpuset_can_attach() and cpuset_attach(). Nothing was reserved for it. It could use the room reserved for the other tasks, and their bandwidth stayed behind.
- New patch 21: sched_setattr() and sched_setaffinity() of a deadline task wait for an attach in progress. The change then comes before the attach, and is part of its reservation, or after it. sched_setaffinity() tests the policy with no lock before it decides to wait. So the policy is tested again under the runqueue lock. The call starts over if a sched_setattr() made the task a deadline task meanwhile. The wait is not interruptible.
- Patch 22 comes after that wait. Only sysrq-n can then take a task out of the class between the two halves of an attach. The patch gives back the part of the reservation that no task used. The new case move_normalized tests it.
- Patch 23: cpuset_can_attach() records, with each task it counts, the CPU the room was reserved on. Juri suggested to track the counted tasks. cpuset_attach_task() moves the bandwidth of a task only if the task has that record. It moves it to that CPU, and does not compute the CPU again. A task that wakes up during the attach and runs on another CPU no longer misses its reservation. A wakeup needs no wait. During the attach, the root domain the task leaves still counts its bandwidth. The destination has room reserved for it.
- Seven new cases test this: move_became_deadline, move_became_deadline_no_room, move_affinity_changed, move_affinity_became_deadline, move_woken, move_woken_full and move_cancelled.
- Six more new cases:
- move_died and frozen_moved_switched: a thread killed during a move, and a task frozen by the cgroup freezer.
- Four follow reproducers of Juri's sched-deadline-tests:
stopped_switched_out, hotplug_sleeper_switched, hotplug_no_admission_pinned and pi_chain_two_owners.
- random_mix also changes the affinity of its tasks.
- New patches 26 to 28. With isolcpus="domain", a cpuset can hold CPUs of two root domains. A deadline task could go from one to the other with no cpuset attach. A CPU offline or a cpuset that lost CPUs could do it. Patch 25 then moved its bandwidth with no check for room.
- Patch 26: a CPU of the root domain that counts the task is tried first, wherever a CPU is picked for it.
- Patch 27: a CPU offline fails with EBUSY if it takes the last CPU a deadline task has in that root domain.
- Patch 28: a cpuset change that leaves a deadline task no CPU in that root domain is refused. A write to cpuset.cpus fails with EBUSY. cpuset makes a partition root invalid.
- Four new cases test this: hotplug_keeps_root_domain, hotplug_last_refused, mask_out_refused (was mask_back_asleep) and partition_takes_refused. The three hotplug_fallback cases now fail if the task wakes up in the other root domain. no_admission_affinity_moves tests patch 25 with admission control off.
- Patches 2, 3, 6, 14, 17, 20, 29 and 30 have Juri's Reviewed-by. Patches 7 and 9 have his Acked-by.
- Not in this series: the single list of accounted tasks that Juri suggested in his review of patch 13 of v5. I tried it. It removes dl_bw_gen and the walk of the task list. But the rebuild then runs with interrupts disabled for its whole length. In a 64-vCPU guest, that was 0.15ms with 1000 deadline tasks and 1.2ms with 10000. Today it is less than 0.1ms at a time. I left it out for that reason.
- New patch 31: a task that enters the class while it waits on an rt_mutex gets a deadline. Before, its waiter was sorted with a deadline of 0, ahead of every real one. Upstream has this bug. The triage of the Sashiko review of v5 found it.
- Six new selftest cases test these fixes. They fail on v5.
- Patch 2's comment names the use of SCHED_FLAG_KEEP_PARAMS on a deadline task: a change of its utilization clamps (Juri Lelli).
- Patch 5 of v5 is split in two, as Juri asked. 4 removes the division by zero. 5 refuses the debugfs write in the hotplug windows. Each has its own Fixes: tag.
- Patch 6 has clearer comments on its two policy checks, and an unlikely() (Juri Lelli).
- New patches 32 and 33, for the case Juri pointed out in v5. A task kept the runtime left from its old parameters when it came back to the class runnable. A runnable task that changed its parameters kept it too. Both now get the check a wakeup does. Upstream has these bugs. Three new cases test them.
- Patch 23's message says what an attach without a reservation does.
- Patch 37 (29 in v5) said that 13 cases fail on v7.4-rc1. That count left out two cases added in v5. A new run of the 89 cases gives 32, and the message lists them. The message is a third of its length: it no longer repeats what each fix says about its own cases.
- v5 reported three upstream problems found with isolcpus=domain. Waiman Long answered them; see the v5 cover. The tests avoid them.

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.
- The EPERM of a sleeping task moved to another partition is the baseline's affinity check.
- An attach whose mask keeps a CPU of the task's root domain reserves nothing. The task then stays in that root domain.

Based on tip sched/urgent, ec6f6731538e.

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 (35):
sched: Refuse SCHED_FLAG_KEEP_PARAMS that would change the policy or
the class
sched/deadline: Do not admit bandwidth for parameters that are kept
sched: Let a task boosted by a deadline waiter change its policy sched/deadline: Do not divide by zero active CPUs of a root domain sched/deadline: Refuse dl_server debugfs writes while the rq is
offline
sched: Take cpuset_mutex for a deadline policy change only with pi sched/deadline: Do not lose a throttled task switched out and back sched/deadline: Do not replenish a boost from cleared parameters sched/deadline: Reset the deadline and the runtime with the parameters sched/deadline: Reset the donor's runtime at a deboost in the class 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: 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                |   38 +-
 kernel/cgroup/cgroup.c                        |    3 -
 kernel/cgroup/cpuset-internal.h               |   15 +-
 kernel/cgroup/cpuset.c                        |  496 +-
 kernel/sched/core.c                           |  124 +-
 kernel/sched/deadline.c                       | 1157 ++-
 kernel/sched/debug.c                          |   12 +-
 kernel/sched/sched.h                          |   20 +
 kernel/sched/syscalls.c                       |  163 +-
 kernel/sched/topology.c                       |    8 +
 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         | 8101 +++++++++++++++++
 .../sched/deadline/deadline_rebuild_test.c    |  497 +
 .../sched/deadline/deadline_switch_test.c     |  808 ++
 .../testing/selftests/sched/deadline/settings |    1 +
 20 files changed, 11218 insertions(+), 305 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 v6 1/37 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-rc1, 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 v6 2/37 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 v6 3/37 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-rc1. 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 v6 4/37 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-rc1, a loop of such writes oopses at the first offline and online:

  Oops: divide error: 0000 [#1] SMP NOPTI
  RIP: 0010:dl_server_apply_params+0x335/0x380
  Call Trace:
   sched_server_write_common.isra.0+0x1c0/0x260
   full_proxy_write+0x58/0x90
   vfs_write+0xcb/0x550

By reading, two other paths would divide by zero:
- inactive_task_timer(), for a task that left SCHED_DEADLINE or died, if its CPU went offline.
- sched_setattr(SCHED_DEADLINE) on a task asleep on an offline CPU, with admission control off.

Fix this by changing total_bw alone when the root domain has no active CPU.

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

Fixes daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks")
---
 kernel/sched/deadline.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/sched/deadline.c +9 -2
index dfae08625342..b614d5fc1a1a 100644
@@ -189,18 +189,25 @@ void __dl_update(struct dl_bw *dl_b, s64 bw)
 	}
 }
 
+/*
+ * Spread a change of total_bw over the extra_bw of the active CPUs of the
+ * root domain. @cpus is their number. With no active CPU, as can happen
+ * during CPU hotplug, change total_bw alone.
+ */
 static inline
 void __dl_sub(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
 {
 	dl_b->total_bw -= tsk_bw;
-	__dl_update(dl_b, (s32)tsk_bw / cpus);
+	if (cpus)
+		__dl_update(dl_b, (s32)tsk_bw / cpus);
 }
 
 static inline
 void __dl_add(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
 {
 	dl_b->total_bw += tsk_bw;
-	__dl_update(dl_b, -((s32)tsk_bw / cpus));
+	if (cpus)
+		__dl_update(dl_b, -((s32)tsk_bw / cpus));
 }
 
 static inline bool
Signature · 1 line
2.47.3
#5 lore raw

PATCH v6 5/37 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-rc1, 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
#6 lore raw

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

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 20746e8301600abc34772d08e7fcdc3dbeb36656
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 9 lines
kernel/sched/debug.c +0 -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)))

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

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

[Severity: Medium]
Can a debugfs write still slip through during sched_cpu_deactivate() after cpu_active(cpu) is cleared?

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()
                                    dl_server_start()
  sched_set_rq_offline(rq, cpu)
    rq->online = 0

During the synchronize_rcu() window, rq->online is still 1 and the root domain has not yet been rebuilt by cpuset_cpu_inactive(), but cpu_active(cpu) is already false. In dl_server_apply_params(), dl_bw_cpus(cpu) and dl_bw_capacity(cpu) weight rd->span against cpu_active_mask, so they exclude the deactivating CPU while dl_b->total_bw still includes its server bandwidth. If this was the last active CPU in its root domain, cpus and cap are 0; if other active CPUs remain, __dl_overflow() checks N servers against N - 1 CPUs' capacity and __dl_sub() / __dl_add() miscalculate extra_bw across N - 1 CPUs. dl_server_start() also re-enqueues the server on the deactivating runqueue after balance_push_set(cpu, true).

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

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

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

Quoted 2 lines

Can a debugfs write still slip through during sched_cpu_deactivate() after cpu_active(cpu) is cleared?

Yes, it can pass in that window. It leaves no wrong state, though.

Quoted 3 lines

if other active CPUs remain, __dl_overflow() checks N servers against N - 1 CPUs' capacity and __dl_sub() / __dl_add() miscalculate extra_bw across N - 1 CPUs.

The test against the N - 1 CPUs that remain is the safe side. dl_bw_deactivate() just made the same test. __dl_update() spreads extra_bw over the active CPUs only, so the divisor matches the CPUs it updates. With no active CPU left, any bandwidth above 0 is refused.

The rebuild at the end of sched_cpu_deactivate() then resets total_bw and extra_bw. So the write lasts until the end of the same call.

Quoted 2 lines

dl_server_start() also re-enqueues the server on the deactivating runqueue after balance_push_set(cpu, true).

The rq is still online there. Any fair enqueue on that CPU starts the server in the same window.

So the planned next version keeps the rq->online test as it is.

Thanks,

Mathieu

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

PATCH v6 6/37 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-rc1, 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, last CPU#3:
   ...
   #3: ffffffff83006098 (tasklist_lock){.+.+}-{3:3}, at: normalize_rt_tasks+0x34/0x150

A sched_setattr(SCHED_DEADLINE) after it never returned, in 2 VMs of 2. The sysrq_normalize case of deadline_switch_test, added later in this series, tests this with DEADLINE_TEST_SYSRQ=1. It passes with this series.

Fixes 111cd11bbc54 ("sched/cpuset: Bring back cpuset_mutex")
---
 kernel/sched/syscalls.c | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
kernel/sched/syscalls.c +23 -3
index cb115aa9b0b3..9b04e77297ae 100644
@@ -561,9 +561,11 @@ int __sched_setscheduler(struct task_struct *p,
 
 	/*
 	 * SCHED_DEADLINE bandwidth accounting relies on stable cpusets
-	 * information.
+	 * information. Do not take cpuset_mutex when pi is unset: the
+	 * caller is normalize_rt_tasks(), which holds tasklist_lock and
+	 * cannot sleep.
 	 */
-	if (dl_policy(policy) || dl_policy(p->policy)) {
+	if (pi && (dl_policy(policy) || dl_policy(p->policy))) {
 		cpuset_locked = true;
 		cpuset_lock();
 	}
@@ -643,7 +645,13 @@ int __sched_setscheduler(struct task_struct *p,
 		}
 	}
 
-	/* Re-check policy now with rq lock held: */
+	/*
+	 * The caller gave no policy (SETPARAM_POLICY): the request was
+	 * derived from an unlocked read of p->policy above. If the task
+	 * changed policy since, re-derive the request from scratch, and
+	 * release cpuset_mutex: the re-derived request re-decides whether
+	 * it is needed.
+	 */
 	if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
 		policy = oldpolicy = -1;
 		task_rq_unlock(rq, p, &rf);
@@ -654,6 +662,18 @@ int __sched_setscheduler(struct task_struct *p,
 		goto recheck;
 	}
 
+	/*
+	 * The caller gave an explicit policy, so the request needs no
+	 * re-derivation (oldpolicy is -1 above). But the decision to
+	 * take cpuset_mutex used the same unlocked read: the task
+	 * entered SCHED_DEADLINE since, and the change below would take
+	 * it out of the class. Retry to take the mutex.
+	 */
+	if (unlikely(pi && !cpuset_locked && task_has_dl_policy(p))) {
+		task_rq_unlock(rq, p, &rf);
+		goto recheck;
+	}
+
 	oldprio = p->prio;
 
 	newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
Signature · 1 line
2.47.3
#9 lore raw

PATCH v6 7/37 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-rc1. 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
#10 lore raw

PATCH v6 8/37 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 parameters once, and by not refilling from a runtime of 0. The owner stays runnable. Its deadline stays where it was. It 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.

A 300ms debug delay before rt_mutex_adjust_pi() locks up v7.4-rc1 in 8-CPU VMs, but not a kernel with this patch.

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 | 28 +++++++++++++++++++++++-----
 1 file changed, 23 insertions(+), 5 deletions(-)
kernel/sched/deadline.c +23 -5
index e4d7cbf4861d..c4ea51059941 100644
@@ -807,8 +807,26 @@ 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. Refilling from a runtime of 0 would loop
+	 * forever. Leave the entity runnable instead: the walk deboosts it,
+	 * or its task releases the lock.
+	 */
+	if (unlikely(!runtime)) {
+		WARN_ON_ONCE(!is_dl_boosted(dl_se));
+		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 +840,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 +854,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
#11 lore raw

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

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: torn donor parameter reads in replenish_dl_entity() - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: torn donor parameter reads in replenish_dl_entity()
- [Medium] sched/deadline: unreset negative runtime in replenish_dl_entity()
- [Medium] sched/deadline: zero deadline in replenish_dl_entity() on initial boost
--

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

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

This commit avoids an infinite loop in replenish_dl_entity() when a boosted entity's donor has left SCHED_DEADLINE and had its parameters cleared before the priority inheritance chain walk deboosts the owner.

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

Quoted 12 lines
kernel/sched/deadline.c +4 -0
index e4d7cbf4861de..c4ea510599415 100644
@@ -807,8 +807,26 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 {
 	struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
 	struct rq *rq = rq_of_dl_rq(dl_rq);
+	struct sched_dl_entity *pi_se = pi_of(dl_se);
+	u64 runtime = READ_ONCE(pi_se->dl_runtime);
+	u64 deadline = READ_ONCE(pi_se->dl_deadline);
+	u64 period = READ_ONCE(pi_se->dl_period);

[Severity: Medium]
Can replenish_dl_entity() observe a non-zero runtime alongside a zeroed deadline or period when racing with __dl_clear_params()?

__dl_clear_params() zeroes dl_runtime, dl_deadline and dl_period in that same order under the donor's rq lock without ordering barriers:

CPU0 (boosted owner) CPU1 (donor)
replenish_dl_entity()
runtime = READ_ONCE(pi_se->dl_runtime)

                                  inactive_task_timer()
                                    __dl_clear_params()
                                      dl_se->dl_runtime = 0
                                      dl_se->dl_deadline = 0
                                      dl_se->dl_period = 0

deadline = READ_ONCE(pi_se->dl_deadline) <-- reads 0
period = READ_ONCE(pi_se->dl_period) <-- reads 0

Because only !runtime is checked below, replenish_dl_entity() proceeds with runtime > 0 and deadline == 0 or period == 0. A boosted non-deadline task gets dl_se->deadline set to rq_clock(rq) + 0, while a boosted SCHED_DEADLINE task has runtime added in the while (dl_se->runtime <= 0) loop without advancing dl_se->deadline. If dl_se->deadline is then in the past, the lag check emits a false "sched: DL replenish lagged too much" warning and calls replenish_dl_new_period(), which re-reads pi_of(dl_se)->dl_deadline and pi_of(dl_se)->dl_runtime directly and sets dl_se->runtime to 0.

Quoted 6 lines
kernel/sched/deadline.c +5 -1
-	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

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

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 * read each of them once. Refilling from a runtime of 0 would loop
+	 * forever. Leave the entity runnable instead: the walk deboosts it,
+	 * or its task releases the lock.
+	 */
+	if (unlikely(!runtime)) {
+		WARN_ON_ONCE(!is_dl_boosted(dl_se));
+		dl_se->dl_yielded = 0;
+		dl_se->dl_throttled = 0;
+		return;
+	}

[Severity: Medium]
Does returning here without resetting dl_se->runtime leave the entity with an accumulating negative runtime?

When a boosted task exhausts its runtime after the donor's parameters are cleared, dl_se->runtime remains <= 0 across this early return. Every subsequent tick in update_curr_dl_se() subtracts delta_exec from dl_se->runtime, sees dl_runtime_exceeded(dl_se), sets dl_se->dl_overrun (sending repeated SIGXCPU signals if SCHED_FLAG_DL_OVERRUN is enabled), and re-enters enqueue_task_dl() -> replenish_dl_entity().

With the follow-up commit "sched/deadline: Reset the donor's runtime at a deboost in the class", this return also happens before dl_note_donor_refill(dl_se). If a SCHED_DEADLINE owner had not been refilled from the donor before the donor's parameters were cleared, dl_donor_refill stays 0 and dl_deboost() does not reset dl_se->runtime; when dl_se->deadline is still in the future at deboost, the negative runtime is charged against the owner's own periods on its next replenish, or pushes zerolag_time past dl_se->deadline in task_non_contending() if the owner blocks first.

[Severity: Medium]
Can this early return also leave dl_se->deadline at 0 when a runnable non-deadline task is first boosted into SCHED_DEADLINE?

When rt_mutex_setprio() boosts a runnable non-deadline task whose dl_se->deadline is 0, it sets ENQUEUE_REPLENISH and calls enqueue_task_dl() -> enqueue_dl_entity() -> replenish_dl_entity(). If the donor's parameters were already cleared (for example after normalize_rt_tasks(), or before a multi-hop PI chain walk finishes deboosting an intermediate lock owner), replenish_dl_entity() returns here before the dl_se->dl_deadline == 0 branch initializes dl_se->deadline.

__enqueue_dl_entity() then calls inc_dl_deadline() with deadline == 0:

kernel/sched/deadline.c:inc_dl_deadline() {
	if (dl_rq->earliest_dl.curr == 0 ||
	    dl_time_before(deadline, dl_rq->earliest_dl.curr)) {
		if (dl_rq->earliest_dl.curr == 0)
			cpupri_set(&rq->rd->cpupri, rq->cpu, CPUPRI_HIGHER);
		dl_rq->earliest_dl.curr = deadline;
		cpudl_set(&rq->rd->cpudl, rq->cpu, deadline);
	}
}

Because dl_rq->earliest_dl.curr == 0 is the sentinel for an empty dl_rq, enqueuing a subsequent deadline task with a later deadline overwrites dl_rq->earliest_dl.curr and cpudl, hiding earlier deadlines on this rq from cross-CPU deadline balancing.

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

PATCH v6 9/37 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-rc1, 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 c4ea51059941..dd48f74412b8 100644
@@ -3557,6 +3557,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).
@@ -3972,7 +3982,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)
 {
@@ -3983,6 +3994,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
#13 lore raw

PATCH v6 10/37 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 | 37 +++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h    | 10 ++++++++++
 kernel/sched/syscalls.c |  2 +-
 5 files changed, 67 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 +37 -0
index dd48f74412b8..1f3da0e0a698 100644
@@ -93,6 +93,38 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return pi_of(dl_se) != dl_se;
 }
+
+/*
+ * Record that @dl_se had its runtime refilled from the parameters of its
+ * donor, if it is boosted.
+ */
+static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
+{
+	if (is_dl_boosted(dl_se))
+		dl_se->dl_donor_refill = 1;
+}
+
+/*
+ * End the boost of @dl_se, whose task stays in the class. If the boost
+ * refilled its runtime from the donor's parameters, start a new period
+ * now. The next enqueue is too late for a task blocked on another
+ * rt_mutex: the chain walk copies its deadline into its waiter node
+ * first. Without a refill, the task keeps the runtime and the deadline
+ * of its own reservation.
+ *
+ * The caller holds the rq lock and the pi_lock of the task, and has
+ * updated the rq clock.
+ */
+void dl_deboost(struct sched_dl_entity *dl_se)
+{
+	struct rq *rq = rq_of_dl_se(dl_se);
+
+	if (dl_se->dl_donor_refill) {
+		dl_se->deadline = rq_clock(rq) + dl_se->dl_deadline;
+		dl_se->runtime = dl_se->dl_runtime;
+	}
+	dl_drop_boost(dl_se);
+}
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -734,6 +766,7 @@ static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 	/* for non-boosted task, pi_of(dl_se) == dl_se */
 	dl_se->deadline = rq_clock(rq) + pi_of(dl_se)->dl_deadline;
 	dl_se->runtime = pi_of(dl_se)->dl_runtime;
+	dl_note_donor_refill(dl_se);
 
 	/*
 	 * If it is a deferred reservation, and the server
@@ -842,11 +875,15 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 	    (dl_se->dl_defer_armed && dl_entity_overflow(dl_se, rq_clock(rq)))) {
 		dl_se->deadline = rq_clock(rq) + deadline;
 		dl_se->runtime = runtime;
+		dl_note_donor_refill(dl_se);
 	}
 
 	if (dl_se->dl_yielded && dl_se->runtime > 0)
 		dl_se->runtime = 0;
 
+	if (dl_se->runtime <= 0)
+		dl_note_donor_refill(dl_se);
+
 	/*
 	 * We keep moving the deadline away until we get some
 	 * available runtime for the entity. This ensures correct
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
#14 lore raw

Re: [PATCH v6 10/37] sched/deadline: Reset the donor's runtime at a deboost in the class

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [Medium] sched/deadline: implicit declaration of dl_note_donor_refill() - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [Medium] sched/deadline: implicit declaration of dl_note_donor_refill()
- [Medium] sched/deadline: rt_mutex_setprio() skips dl_deboost() on donor change
- [Medium] sched/deadline: donor runtime kept when leaving dl_sched_class
- [Medium] sched/deadline: missing dl_note_donor_refill() on cleared donor
- [Low] sched/deadline: __dl_clear_params() fails to clear dl_donor_refill
--

commit 25ef3546a7248ed2f828d8c39dc34ecf7474dcc4
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 struct sched_dl_entity to track when a priority-inherited SCHED_DEADLINE task has been replenished from its donor's reservation, resetting its period on in-class deboost.

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]
When a SCHED_DEADLINE task was refilled from an earlier donor and now switches to a new top waiter pi_task, doesn't the outer dl_entity_preempt(&pi_task->dl, &p->dl) check compare pi_task against the old donor's postponed deadline before dl_deboost() can reset p->dl to its own reservation?

If the first donor's refill pushed p->dl.deadline past pi_task->dl.deadline, rt_mutex_setprio() takes the first branch and skips dl_deboost(). Because p->dl.dl_deadline is non-zero and p->dl.runtime > 0, replenish_dl_entity() leaves the first donor's remaining runtime and postponed deadline in place after the unlock. Calling dl_deboost(&p->dl) unconditionally when dl_prio(p->normal_prio) before testing dl_entity_preempt(&pi_task->dl, &p->dl) would reset the period first and then boost from the new waiter if needed.

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]
What happens if a task with its own deadline parameters (p->dl.dl_runtime != 0) is refilled from a donor and then leaves dl_sched_class at deboost, for instance after changing its policy via sched_setattr() while boosted (or being boosted again before its 0-lag timer fires)?

sched_change_begin() runs switched_from_dl() before dl_drop_boost() clears dl_donor_refill, and switched_from_dl() only resets deadline and runtime when !p->dl.dl_runtime:

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

task_non_contending() then computes zerolag_time from the donor's refilled deadline and runtime combined with p's own dl_period and dl_runtime. If the donor's remaining runtime makes zerolag_time negative, task_non_contending() immediately clears p's parameters even though p already exhausted its own budget in this period; otherwise p keeps the donor's runtime and deadline with dl_donor_refill cleared if it returns to SCHED_DEADLINE before the inactive timer fires.

Quoted 33 lines
kernel/sched/deadline.c +25 -0
index dd48f74412b87..1f3da0e0a698c 100644
@@ -93,6 +93,38 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return pi_of(dl_se) != dl_se;
 }
+
+/*
+ * Record that @dl_se had its runtime refilled from the parameters of its
+ * donor, if it is boosted.
+ */
+static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
+{
+	if (is_dl_boosted(dl_se))
+		dl_se->dl_donor_refill = 1;
+}
+
+/*
+ * End the boost of @dl_se, whose task stays in the class. If the boost
+ * refilled its runtime from the donor's parameters, start a new period
+ * now. The next enqueue is too late for a task blocked on another
+ * rt_mutex: the chain walk copies its deadline into its waiter node
+ * first. Without a refill, the task keeps the runtime and the deadline
+ * of its own reservation.
+ *
+ * The caller holds the rq lock and the pi_lock of the task, and has
+ * updated the rq clock.
+ */
+void dl_deboost(struct sched_dl_entity *dl_se)
+{
+	struct rq *rq = rq_of_dl_se(dl_se);

kernel/sched/deadline.c static inline bool is_dl_boosted(struct sched_dl_entity *dl_se) · line 130

Quoted 10 lines
kernel/sched/deadline.c +7 -0
+
+	if (dl_se->dl_donor_refill) {
+		dl_se->deadline = rq_clock(rq) + dl_se->dl_deadline;
+		dl_se->runtime = dl_se->dl_runtime;
+	}
+	dl_drop_boost(dl_se);
+}
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {

[Severity: Medium]
Does this break the build when CONFIG_RT_MUTEXES is disabled? dl_note_donor_refill() is defined inside #ifdef CONFIG_RT_MUTEXES with no stub in the #else branch, but replenish_dl_new_period() and replenish_dl_entity() call it unconditionally.

[ ... ]

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

Quoted 13 lines
kernel/sched/deadline.c +4 -0
@@ -842,11 +875,15 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 	    (dl_se->dl_defer_armed && dl_entity_overflow(dl_se, rq_clock(rq)))) {
 		dl_se->deadline = rq_clock(rq) + deadline;
 		dl_se->runtime = runtime;
+		dl_note_donor_refill(dl_se);
 	}
 
 	if (dl_se->dl_yielded && dl_se->runtime > 0)
 		dl_se->runtime = 0;
 
+	if (dl_se->runtime <= 0)
+		dl_note_donor_refill(dl_se);
+

[Severity: Medium]
Should the early return when !runtime earlier in replenish_dl_entity() also call dl_note_donor_refill(dl_se)?

kernel/sched/deadline.c:replenish_dl_entity() {
	if (unlikely(!runtime)) {
		WARN_ON_ONCE(!is_dl_boosted(dl_se));
		dl_se->dl_yielded = 0;
		dl_se->dl_throttled = 0;
		return;
	}
}

When a donor leaves the class and its parameters are cleared before the lock owner is deboosted, this path keeps the owner runnable after it exhausted its runtime, and update_curr_dl_se() continues driving dl_se->runtime negative. Without dl_donor_refill set, dl_deboost() will not start a new period and the boosted execution is charged against the owner's own reservation (or leaves deadline at 0 if the owner entered SCHED_DEADLINE while boosted).

Quoted 8 lines
kernel/sched/sched.h +0 -0
index 92134ce326a49..d87296abec4c2 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);

kernel/sched/sched.h extern int sched_dl_global_validate(void); · line 368

Quoted 10 lines
kernel/sched/sched.h +10 -0
+#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

[Severity: Low]
Should __dl_clear_params() also clear dl_donor_refill (or call dl_drop_boost()) instead of only setting dl_se->pi_se = dl_se?

kernel/sched/deadline.c:__dl_clear_params() {
...

	dl_se->dl_defer_running		= 0;
	dl_se->dl_defer_armed		= 0;
#ifdef CONFIG_RT_MUTEXES
	dl_se->pi_se			= dl_se;

#endif
}

If a task forks while boosted and refilled by a donor, dup_task_struct() copies dl_donor_refill = 1 into the child and __sched_fork() -> init_dl_entity() -> __dl_clear_params() leaves it set, which would cause an unintended period reset if the child later becomes SCHED_DEADLINE and passes through dl_deboost().

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

Re: [PATCH v6 10/37] sched/deadline: Reset the donor's runtime at a deboost in the class

Quoted 5 lines

If the first donor's refill pushed p->dl.deadline past pi_task->dl.deadline, rt_mutex_setprio() takes the first branch and skips dl_deboost(). Because p->dl.dl_deadline is non-zero and p->dl.runtime > 0, replenish_dl_entity() leaves the first donor's remaining runtime and postponed deadline in place after the unlock.

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 unlock, rt_mutex_setprio(p, NULL) takes the else branch. There, dl_deboost() starts a new period. So the task does not keep the first donor's values after the unlock.

A dl_deboost() at each change of top waiter would give the task a full runtime of its own reservation each time.

Quoted 2 lines

task_non_contending() then computes zerolag_time from the donor's refilled deadline and runtime combined with p's own dl_period and dl_runtime.

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

Quoted 3 lines

otherwise p keeps the donor's runtime and deadline
with dl_donor_refill cleared if it returns to SCHED_DEADLINE before the inactive timer fires.

On that return, patches 32 and 33 check the runtime left against the task's own parameters, as a wakeup does. Only dl_deboost() reads the flag, and the task is not boosted then.

Quoted 1 line

Does this break the build when CONFIG_RT_MUTEXES is disabled?

Yes. Fixed in the planned next version.

Quoted 2 lines

Should the early return when !runtime earlier in replenish_dl_entity() also call dl_note_donor_refill(dl_se)?

Only where the early return starts a period from the donor. The planned next version changes that early return in patch 8. It adds no runtime, and resets a negative runtime to 0. It gives a deadline of now to an owner with no parameters of its own, and notes a refill there. An owner with parameters keeps its own deadline and runtime. Setting the flag for it would give it a second full runtime in the same period.

Quoted 2 lines

Should __dl_clear_params() also clear dl_donor_refill (or call dl_drop_boost()) instead of only setting dl_se->pi_se = dl_se?

Yes. Fixed in the planned next version.

Thanks,

Mathieu

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

PATCH v6 11/37 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 1f3da0e0a698..09188a28b3a1 100644
@@ -3620,6 +3620,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
#17 lore raw

PATCH v6 12/37 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
#18 lore raw

PATCH v6 13/37 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-rc1 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
#19 lore raw

PATCH v6 14/37 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 cbdfa0793703..6444c4550936 100644
@@ -411,18 +411,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
@@ -491,6 +508,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);
 }
 
@@ -2865,6 +2890,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);
 }
@@ -4254,6 +4284,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
#20 lore raw

PATCH v6 15/37 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
#21 lore raw

PATCH v6 16/37 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-rc1. 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
#22 lore raw

Re: [PATCH v6 16/37] sched/deadline: Record the root domain holding a task's bandwidth

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 685fb9b4f51b7675ac0c8a518174590afd51eb14
Author: Mathieu Desnoyers <[email protected]>

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

This commit records in dl_bw_cpu a CPU of the root domain that accounts for a deadline task's bandwidth, and updates bandwidth moves, releases, parameter changes, and affinity checks to consult that recorded root domain instead of task_rq(p)->rd.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index ccd6426811b9e..44db625bffc32 100644

[ ... ]

Quoted 20 lines
kernel/sched/deadline.c +16 -0
@@ -4193,6 +4260,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 check the root domain of the recorded dl_bw_cpu instead of rq->rd?

While sched_dl_overflow() and dl_task_check_affinity() are updated to look up the root domain via dl_bw_cpu for a task moved while asleep, __sched_setscheduler() still checks rq = task_rq(p) before calling sched_dl_overflow():

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, p->cpus_mask is updated to the destination cpuset while task_rq(p) stays in the old root domain. Because the old rq->rd->span is disjoint from p->cpus_mask, sched_setattr() fails here with -EPERM before reaching sched_dl_overflow().

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

Re: [PATCH v6 16/37] sched/deadline: Record the root domain holding a task's bandwidth

Quoted 2 lines

Should __sched_setscheduler() also check the root domain of the recorded dl_bw_cpu instead of rq->rd?

Thanks. That EPERM is the baseline's affinity check. The cover letter lists it under "Not changed". It refuses the call, so nothing is counted wrongly.

The check also matters when sched_setattr() makes a task a deadline task during a cpuset move. Patch 21 covers that case ("sched: Make deadline policy and affinity changes wait for a cpuset attach"). That task has no CPU recorded yet. So the root domain of the CPU it is on is the only one the check can use.

Once the task has run on its new CPUs, its parameters can be changed as usual.

Thanks,

Mathieu

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

PATCH v6 17/37 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 44db625bffc3..75fc9314da67 100644
@@ -3767,6 +3767,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
#25 lore raw

PATCH v6 18/37 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
#26 lore raw

PATCH v6 19/37 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 75fc9314da67..1825ca22d422 100644
@@ -3602,12 +3602,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
#27 lore raw

PATCH v6 20/37 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
#28 lore raw

PATCH v6 21/37 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.

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 | 40 ++++++++++++++++++++++++++++++++--------
 5 files changed, 57 insertions(+), 8 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 +32 -8
index 4f47b17151ed..70b364b4f82d 100644
@@ -564,10 +564,15 @@ int __sched_setscheduler(struct task_struct *p,
 	 * information. Do not take cpuset_mutex when pi is unset: the
 	 * caller is normalize_rt_tasks(), which holds tasklist_lock and
 	 * cannot sleep.
+	 *
+	 * Wait for a task attach in progress. cpuset_can_attach() reserved
+	 * the bandwidth of the deadline tasks it saw, and cpuset_attach()
+	 * moves them. A task that enters or leaves the class in between
+	 * would not match that reservation.
 	 */
 	if (pi && (dl_policy(policy) || dl_policy(p->policy))) {
 		cpuset_locked = true;
-		cpuset_lock();
+		cpuset_lock_no_attach();
 		dl_accounting_lock();
 	}
 
@@ -1289,6 +1294,7 @@ long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
 	struct affinity_context ac;
 	struct cpumask *user_mask;
 	int retval;
+	bool dl;
 
 	CLASS(find_get_task, p)(pid);
 	if (!p)
@@ -1318,13 +1324,31 @@ long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
 		return -ENOMEM;
 	}
 
-	ac = (struct affinity_context){
-		.new_mask  = in_mask,
-		.user_mask = user_mask,
-		.flags     = SCA_USER,
-	};
-
-	retval = __sched_setaffinity(p, &ac);
+	/*
+	 * 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 policy is tested here with no lock. A task that becomes a
+	 * deadline task after this test is found under its runqueue lock,
+	 * with SCA_DL_NOWAIT. Wait and try again then.
+	 */
+	for (;;) {
+		dl = task_has_dl_policy(p);
+		ac = (struct affinity_context){
+			.new_mask  = in_mask,
+			.user_mask = user_mask,
+			.flags     = SCA_USER | (dl ? 0 : SCA_DL_NOWAIT),
+		};
+		if (dl)
+			cpuset_lock_no_attach();
+		retval = __sched_setaffinity(p, &ac);
+		if (dl)
+			cpuset_unlock();
+		if (dl || retval != -EAGAIN)
+			break;
+	}
 	kfree(ac.user_mask);
 
 	return retval;
Signature · 1 line
2.47.3
#29 lore raw

Re: [PATCH v6 21/37] sched: Make deadline policy and affinity changes wait for a cpuset attach

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched: broken cpuset rollback in __sched_setaffinity() with SCA_DL_NOWAIT --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched: broken cpuset rollback in __sched_setaffinity() with SCA_DL_NOWAIT
--

commit 9d195b268d19186fd430b17e56b76c3ac49f0d39
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 SCA_DL_NOWAIT so that SCHED_DEADLINE policy changes in __sched_setscheduler() and affinity changes in sched_setaffinity() wait for an in-progress cpuset attach to finish.

Quoted 25 lines
kernel/sched/core.c +10 -0
index 2a964286a7cd0..52c291de384e7 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/syscalls.c +0 -0
index 4f47b17151ed9..70b364b4f82dd 100644

[ ... ]

Quoted 29 lines
kernel/sched/syscalls.c +18 -7
@@ -1318,13 +1324,31 @@ long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
 		return -ENOMEM;
 	}
 
-	ac = (struct affinity_context){
-		.new_mask  = in_mask,
-		.user_mask = user_mask,
-		.flags     = SCA_USER,
-	};
-
-	retval = __sched_setaffinity(p, &ac);
+	/*
+	 * 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 policy is tested here with no lock. A task that becomes a
+	 * deadline task after this test is found under its runqueue lock,
+	 * with SCA_DL_NOWAIT. Wait and try again then.
+	 */
+	for (;;) {
+		dl = task_has_dl_policy(p);
+		ac = (struct affinity_context){
+			.new_mask  = in_mask,
+			.user_mask = user_mask,
+			.flags     = SCA_USER | (dl ? 0 : SCA_DL_NOWAIT),
+		};
+		if (dl)

kernel/sched/syscalls.c long sched_setaffinity(pid_t pid, const struct cpumask *in_mask) · line 1354

Quoted 10 lines
kernel/sched/syscalls.c +7 -0
+			cpuset_lock_no_attach();
+		retval = __sched_setaffinity(p, &ac);
+		if (dl)
+			cpuset_unlock();
+		if (dl || retval != -EAGAIN)
+			break;
+	}
 	kfree(ac.user_mask);
 
 	return retval;

[Severity: Medium]
Can SCA_DL_NOWAIT cause the cpuset race rollback in __sched_setaffinity() to fail and leave p->cpus_mask and p->user_cpus_ptr un-restored?

When p is initially not a deadline task, sched_setaffinity() passes SCA_DL_NOWAIT without holding cpuset_mutex. If the first __set_cpus_allowed_ptr() succeeds while a concurrent cpuset update narrows cpus_allowed and another thread changes p to SCHED_DEADLINE, the recovery path in __sched_setaffinity() clears SCA_DL_CHECK but leaves SCA_DL_NOWAIT set:

kernel/sched/syscalls.c:__sched_setaffinity() {
    ...
	cpuset_cpus_allowed(p, cpus_allowed);
	if (!cpumask_subset(new_mask, cpus_allowed)) {
    ...
		ctx->flags &= ~SCA_DL_CHECK;
		__set_cpus_allowed_ptr(p, ctx);
		retval = -EINVAL;
	}
    ...
}

CPU0 CPU1
sched_setaffinity(p)
dl = false (SCA_DL_NOWAIT set)
__sched_setaffinity(p, &ac)

    cpuset_cpus_allowed(p, ...)
    __set_cpus_allowed_ptr(p, ctx)
      sets p->cpus_mask = new_mask
      swaps p->user_cpus_ptr
        with ctx->user_mask
                                      cpuset narrows p's cpus_allowed
                                      sched_setattr(p, SCHED_DEADLINE)
    cpuset_cpus_allowed(p, ...)
    !cpumask_subset(new_mask, ...)
    ctx->flags &= ~SCA_DL_CHECK
    __set_cpus_allowed_ptr(p, ctx)
      SCA_DL_NOWAIT && dl_policy
      returns -EAGAIN (ignored)  <-- rollback skipped
    returns -EINVAL

kfree(ac.user_mask)

Because the second __set_cpus_allowed_ptr() aborts with -EAGAIN and its return value is ignored, p->cpus_mask is left containing CPUs outside the task's cpuset cpus_allowed, and the rejected user_mask remains installed in p->user_cpus_ptr while the previous user_cpus_ptr is freed.

Clearing SCA_DL_NOWAIT alongside SCA_DL_CHECK before the recovery __set_cpus_allowed_ptr() call would allow the rollback to complete.

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

PATCH v6 22/37 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 1825ca22d422..5503820c5b26 100644
@@ -3609,6 +3609,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)) {
@@ -3637,6 +3640,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
#31 lore raw

PATCH v6 23/37 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 a 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.

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          | 209 +++++++++++++++++++-------------
 kernel/sched/core.c             |  27 ++++-
 kernel/sched/deadline.c         | 128 ++++++++++++++-----
 kernel/sched/sched.h            |   2 +
 kernel/sched/syscalls.c         |   5 +-
 8 files changed, 270 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 +125 -84

329 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 +101 -27

161 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 70b364b4f82d..59d78ae6b9fd 100644
@@ -1327,8 +1327,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
#32 lore raw

Re: [PATCH v6 23/37] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] sched/deadline: unmasked offline CPUs in __dl_task_bw_move_cpu() span check - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] sched/deadline: unmasked offline CPUs in __dl_task_bw_move_cpu() span check
- [Medium] cgroup/cpuset: stale dl_bw_resv_cpu left when cpuset_attach() skips task loop
--

commit 1fc4cfdda6a5d5f5e22bff0342024fd03d578a7c
Author: Mathieu Desnoyers <[email protected]>

cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to

This commit reserves and moves a deadline task's bandwidth using the specific destination CPU recorded in task->dl.dl_bw_resv_cpu during cpuset_can_attach(), keeping per-CPU reservation sums in cpuset_dl_bw so that attaches to cpusets spanning multiple root domains account bandwidth in the root domain where the task actually runs.

Quoted 4 lines
kernel/cgroup/cpuset.c +0 -0
index 2f39c3d12550e..0d55f092d9cbb 100644

[ ... ]

Quoted 29 lines
kernel/cgroup/cpuset.c +14 -9
@@ -3236,15 +3258,20 @@ static int cpuset_can_attach(struct cgroup_taskset *tset)
 				goto out_unlock;
 		}
 
-		if (dl_task(task)) {
-			/*
-			 * Count all migrating DL tasks for cpuset task accounting.
-			 * Only tasks that need a root-domain bandwidth move
-			 * contribute to sum_migrate_dl_bw.
-			 */
-			cs->nr_migrate_dl_tasks++;
-			if (dl_task_needs_bw_move(task, cs->effective_cpus))
-				cs->sum_migrate_dl_bw += task->dl.dl_bw;
+		if (!dl_task(task))
+			continue;
+		/*
+		 * Sum the bandwidth of the deadline tasks that move to another
+		 * root domain, per CPU that the move records. That CPU depends
+		 * on the CPUs the task gets. A cpuset can span more than one
+		 * root domain, and the affinity of a task can keep it in any
+		 * of them.
+		 */
+		cpuset_attach_cpus(cs, task, cpus_attach);
+		cpu = dl_task_bw_reserve_cpu(task, cpus_attach);
+		if (cpu >= 0) {
+			per_cpu_ptr(&cpuset_dl_bw, cpu)->sum += task->dl.dl_bw;
+			cpumask_set_cpu(cpu, dl_attach_cpus);
 		}
 	}

[ ... ]

kernel/cgroup/cpuset.c static void cpuset_attach(struct cgroup_taskset *tset) · line 3454

Quoted 12 lines
kernel/cgroup/cpuset.c +3 -2
@@ -3407,8 +3446,9 @@ static void cpuset_attach(struct cgroup_taskset *tset)
 		schedule_flush_migrate_mm();
 	cs->old_mems_allowed = attach_ctx.nodemask_to;
 out:
-	clear_attach_data(&src_cs_head, false);
-	clear_attach_data(&dst_cs_head, false);
+	clear_attach_data(&src_cs_head);
+	clear_attach_data(&dst_cs_head);
+	cpuset_free_dl_bw();
 	dec_attach_in_progress_locked();
 
 	mutex_unlock(&cpuset_mutex);

[Severity: Medium]
Does cpuset_attach() leave a stale task->dl.dl_bw_resv_cpu behind when it takes the !attach_ctx.cpus_updated && !attach_ctx.mems_updated fast path?

In cpuset_can_attach(), dl_task_bw_reserve_cpu() runs whenever oldcs != cs, even if oldcs and cs have identical effective_cpus and effective_mems (for example, when enabling +cpuset in cgroup.subtree_control or moving a task between v2 cgroups with the same effective masks). If the task's bandwidth is currently counted in another root domain, dl_task_bw_reserve_cpu() sets task->dl.dl_bw_resv_cpu = cpu. In cpuset_attach(), the fast path:

kernel/cgroup/cpuset.c:cpuset_attach() {
    ...
	if (cpuset_v2() && !attach_ctx.cpus_updated && !attach_ctx.mems_updated) {
		llist_for_each_entry(cs, dst_cs_head.first, attach_node)
			cs->old_mems_allowed = attach_ctx.nodemask_to;
		goto out;
	}
    ...
}

jumps past cpuset_attach_task() to out:, where cpuset_free_dl_bw() releases the reservation in cpuset_dl_bw, but dl_task_bw_unreserve() is never called on the tasks in tset.

If that task is later part of a v2 threaded subtree attach where oldcs == cs for this thread while another thread in the taskset has oldcs != cs and cpus_updated == true, cpuset_can_attach() skips this task, and cpuset_attach_task() consumes the stale dl_bw_resv_cpu. That moves the task's bandwidth without a destination reservation and adds moved to per_cpu(cpuset_dl_bw, cpu).moved, corrupting the root domain accounting and underflowing b->sum - b->moved in cpuset_free_dl_bw().

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 5503820c5b26c..b43106a590256 100644

[ ... ]

Quoted 14 lines
kernel/sched/deadline.c +6 -2
@@ -3657,10 +3676,64 @@ bool dl_task_needs_bw_move(struct task_struct *p,
 	 * their bandwidth: dl_add_task_root_domain() leaves them out.
 	 */
 	if (!dl_task(p) || dl_entity_is_special(&p->dl) || !p->dl.dl_bw)
-		return false;
+		return -1;
 
 	cpu = dl_task_root_domain_cpu(p);
-	return !cpumask_intersects(cpu_rq(cpu)->rd->span, new_mask);
+	if (cpumask_intersects(cpu_rq(cpu)->rd->span, new_mask))
+		return -1;
+	/*
+	 * A task moved asleep is still on a CPU of the root domain it left.
+	 * If the new mask holds that CPU, the task wakes up there.

kernel/sched/deadline.c bool dl_task_needs_bw_move(struct task_struct *p, · line 3696

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 */
+	cpu = task_cpu(p);
+	if (cpu_active(cpu) && cpumask_test_cpu(cpu, new_mask))
+		return cpu;
+	cpu = cpumask_first_and_and(new_mask, cpu_active_mask,
+				    housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
+	if (cpu >= nr_cpu_ids)
+		cpu = cpumask_any_and(new_mask, cpu_active_mask);
+	return cpu < nr_cpu_ids ? (int)cpu : -1;
+}

[Severity: High]
Can offline CPUs in def_root_domain.span cause __dl_task_bw_move_cpu() to falsely return -1 when attaching a task to top_cpuset?

Every offline possible CPU is attached to def_root_domain (in sched_init() and detach_destroy_domains()), as are CPUs isolated via isolcpus=domain or isolated cpuset partitions. When a task is attached to top_cpuset, cpuset_attach_cpus() sets new_mask to task_cpu_possible_mask(task) & ~subpartitions_cpus, which includes all offline possible CPUs.

Because cpumask_intersects(cpu_rq(cpu)->rd->span, new_mask) does not mask against cpu_active_mask, any system with an offline CPU in cpu_possible_mask will see def_root_domain.span intersect new_mask on that offline CPU (unless filtered out by p->user_cpus_ptr). Moving a deadline task whose bandwidth is in def_root_domain back to top_cpuset will then return -1 here, skipping both the destination reservation and the bandwidth move out of def_root_domain.

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

PATCH v6 24/37 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.
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 | 83 +++++++++++++++++++++++++++++++++++------
 1 file changed, 72 insertions(+), 11 deletions(-)
kernel/sched/deadline.c +72 -11
index b43106a59025..c765a403014a 100644
@@ -923,14 +923,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);
@@ -3795,6 +3801,55 @@ 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.
+ *
+ * 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))
+		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)
 {
@@ -3802,7 +3857,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);
 	/*
@@ -3817,10 +3871,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
#34 lore raw

Re: [PATCH v6 24/37] sched/deadline: Make a rebuild count a task in the root domain it runs in

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: dl_task_rebuild_cpu() misaccounts offline-migrated task --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: dl_task_rebuild_cpu() misaccounts offline-migrated task
--

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

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

This commit updates root-domain deadline bandwidth rebuilding to select the CPU where a deadline task's bandwidth is counted based on the task's current CPU, recorded dl_bw_cpu, active affinity mask, and cpuset, while skipping tasks that have no active CPU available.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index b43106a590256..c765a403014a2 100644

[ ... ]

Quoted 42 lines
kernel/sched/deadline.c +38 -0
@@ -3795,6 +3801,55 @@ 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.
+ *
+ * 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))
+		return cpu;
+	if (cpumask_empty(msk)) {
+		if (recorded >= 0 && cpu_active(recorded))
+			return recorded;

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

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]
Can dl_task_rebuild_cpu() count a task migrated by dl_task_offline_migration() in the wrong root domain once a CPU in p->cpus_mask comes back online?

When admission control is disabled and all CPUs in p->cpus_ptr are offline, dl_task_offline_migration() falls back to cpumask_any(cpu_active_mask) and moves a throttled task's bandwidth and runqueue placement to that fallback CPU without changing p->cpus_mask:

kernel/sched/deadline.c:dl_task_offline_migration() {
    ...
		cpu = cpumask_any_and(cpu_active_mask, p->cpus_ptr);
		if (cpu >= nr_cpu_ids) {
			...
			cpu = cpumask_any(cpu_active_mask);
		}
		later_rq = cpu_rq(cpu);
    ...
}

If p was pinned to a single offline CPU (p->nr_cpus_allowed == 1), it is not pushable and continues running and replenishing on the fallback CPU even after its original CPU comes back online. During the rebuild triggered by that cpu_up(), msk (&p->cpus_mask & cpu_active_mask) is no longer empty, and neither task_cpu(p) nor recorded (p->dl.dl_bw_cpu) is in msk. dl_task_rebuild_cpu() then returns a CPU from msk rather than task_cpu(p), accounting the bandwidth in the root domain of p->cpus_mask instead of the root domain where the task is still queued and running.

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

PATCH v6 25/37 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.

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.

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.

Fixes 59d06cea1198 ("sched/deadline: Fix bandwidth accounting at all levels after offline migration")
---
 kernel/sched/deadline.c | 92 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 81 insertions(+), 11 deletions(-)
kernel/sched/deadline.c +81 -11
index c765a403014a..35f40185953a 100644
@@ -2910,11 +2910,69 @@ 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.
+ */
+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)
+		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)
+		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);
+		__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;
+}
+
+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
+	 * dl_task_offline_migration() does for a throttled task.
+	 */
+	if (unlikely(dl_task_bw_elsewhere(p, new_cpu)))
+		dl_task_move_bw(p, new_cpu);
+
 	if (READ_ONCE(p->__state) != TASK_WAKING)
 		return;
 
@@ -3577,6 +3635,15 @@ static void pull_dl_task(struct rq *this_rq)
  */
 static void task_woken_dl(struct rq *rq, struct task_struct *p)
 {
+	/*
+	 * A task can wake up on the CPU it slept on, with no migration,
+	 * while another root domain counts its bandwidth. The bandwidth
+	 * moved while the task slept out of its mask, and the mask then got
+	 * that CPU back. Move the bandwidth to this root domain.
+	 */
+	if (unlikely(dl_task_bw_elsewhere(p, cpu_of(rq))))
+		dl_task_move_bw(p, cpu_of(rq));
+
 	if (!task_on_cpu(rq, p) &&
 	    !test_tsk_need_resched(rq->curr) &&
 	    p->nr_cpus_allowed > 1 &&
@@ -3612,9 +3679,10 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 	 * (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.
+	 * Otherwise, the bandwidth stays where it is counted, until the task
+	 * runs in another root domain (migrate_task_rq_dl(), task_woken_dl()),
+	 * or the next rebuild of the accounting. Freeing it here without room
+	 * would leave no root domain counting it.
 	 *
 	 * cpuset_can_attach() made room for @p in the root domain of
 	 * ctx->dl_bw_cpu, and recorded that CPU with @p. Move the bandwidth
@@ -3806,10 +3874,11 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
  * 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.
+ * task runs, or most often 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. A task that then runs in
+ * the other root domain takes its bandwidth along.
  *
  * 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
@@ -3876,8 +3945,8 @@ void dl_add_task_root_domain(struct task_struct *p)
 		/*
 		 * 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.
+		 * removing anything. A later rebuild counts it again. So does
+		 * the move of the task to an active CPU.
 		 */
 		raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
 		return;
@@ -4071,7 +4140,8 @@ void dl_clear_root_domains(void)
 	int cpu;
 
 	guard(raw_spinlock_irqsave)(&dl_departed_lock);
-	dl_bw_gen++;
+	/* dl_task_bw_elsewhere() reads it without the lock. */
+	WRITE_ONCE(dl_bw_gen, dl_bw_gen + 1);
 	for_each_possible_cpu(cpu) {
 		if (!dl_bw_visited(cpu, cookie))
 			dl_clear_root_domain(cpu_rq(cpu)->rd);
Signature · 1 line
2.47.3
#36 lore raw

Re: [PATCH v6 25/37] sched/deadline: Move a task's bandwidth to the root domain it runs in

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: missing cpu_active() check in dl_task_move_bw() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: missing cpu_active() check in dl_task_move_bw()
--

commit 1138754ab6e05269e8ea3d708fa33a8aa8f05601
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 target CPU during migration and wakeup if its bandwidth is currently counted in another root domain or was left out of a rebuild.

Quoted 47 lines
kernel/sched/deadline.c +38 -1
index c765a403014a2..35f40185953a3 100644
@@ -2910,11 +2910,69 @@ 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.
+ */
+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)
+		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)
+		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 2960

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 p->dl.dl_bw to def_root_domain and record an inactive CPU in p->dl.dl_bw_cpu when new_cpu is not active?

During CPU hot-unplug, sched_cpu_deactivate() clears the outgoing CPU from cpu_active_mask, attaches it to def_root_domain, and rebuilds root-domain accounting so a sleeping migration-disabled deadline task is counted on an active CPU in p->cpus_mask. If that task wakes up before sched_cpu_wait_empty() finishes, is_cpu_allowed() still permits the online outgoing CPU, so ttwu_do_activate() -> task_woken_dl() calls dl_task_move_bw() on it.

Because neither dl_task_bw_elsewhere() nor dl_task_move_bw() checks cpu_active(), this regression subtracts p->dl.dl_bw from the active root domain and moves it to def_root_domain, allowing the active root domain to admit deadline tasks beyond its capacity.

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

PATCH v6 26/37 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.

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.

Fixes 332ac17ef5bf ("sched/deadline: Add bandwidth management for SCHED_DEADLINE tasks")
---
 kernel/sched/core.c     | 38 +++++++++++++++++++++++
 kernel/sched/deadline.c | 69 +++++++++++++++++++++++++++++++++++++++--
 kernel/sched/sched.h    |  1 +
 3 files changed, 106 insertions(+), 2 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 +67 -2

104 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
#38 lore raw

Re: [PATCH v6 26/37] sched/deadline: Keep a task in the root domain that counts its bandwidth

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: dl_task_offline_migration() bypasses dl_task_bw_span() - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: dl_task_offline_migration() bypasses dl_task_bw_span()
- [Medium] sched/deadline: dl_task_bw_span() returns NULL for deactivating dl_bw_cpu
- [Low] sched/deadline: dead branch and fallback order in dl_task_rebuild_cpu()
--

commit a54933b747047e1dd4434be5e5299159be0de9fe
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 and dl_task_rebuild_cpu() to prefer CPUs in the root domain that counts a deadline task's bandwidth.

Quoted 13 lines
kernel/sched/deadline.c +1 -0
index 35f40185953a3..5294546786f12 100644
@@ -864,13 +864,19 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 
 	later_rq = find_lock_later_rq(p, rq);
 	if (!later_rq) {
+		const struct cpumask *span = dl_task_bw_span(p);
 		int cpu;
 
 		/*
 		 * If we cannot preempt any rq, fall back to pick any

kernel/sched/deadline.c static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p · line 879

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 find_lock_later_rq(p, rq) bypass the dl_task_bw_span(p) check and migrate p onto an isolated CPU in def_root_domain?

When a housekeeping CPU goes offline, detach_destroy_domains() attaches its runqueue to def_root_domain while dl_rebuild_rd_accounting() moves a throttled task's bandwidth to the new housekeeping root domain. When dl_task_timer() later fires on that offline CPU and calls dl_task_offline_migration(), find_later_rq() searches task_rq(p)->rd->cpudl, which is def_root_domain.cpudl:

kernel/sched/deadline.c:find_later_rq() {
    ...
	if (!cpudl_find(&task_rq(task)->rd->cpudl, task, later_mask))
		return -1;
    ...
}

With isolcpus=domain, isolated CPUs also belong to def_root_domain. If p->cpus_mask includes an isolated CPU that is free or running a later deadline in def_root_domain.cpudl, find_lock_later_rq() returns that isolated CPU's runqueue and skips the !later_rq fallback entirely, moving p and its bandwidth into def_root_domain without admission control.

[ ... ]

Quoted 16 lines
kernel/sched/deadline.c +12 -0
@@ -3669,6 +3690,29 @@ static unsigned int dl_task_root_domain_cpu(struct task_struct *p)
 	return cpu;
 }
 
+/*
+ * Return the CPUs of the root domain that counts the bandwidth of @p, or
+ * NULL if none does. The mask of @p can hold CPUs of another root domain,
+ * with isolcpus="domain". Where a CPU is picked for @p, a CPU of this
+ * root domain comes first: no other root domain admitted @p.
+ *
+ * The caller holds the pi_lock or the rq lock of @p. With interrupts
+ * off, the root domain is not freed.
+ */
+const struct cpumask *dl_task_bw_span(struct task_struct *p)
+{
+	int cpu;

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

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+
+	if (!task_has_dl_policy(p) || dl_entity_is_special(&p->dl) ||
+	    !p->dl.dl_bw)
+		return NULL;
+	cpu = READ_ONCE(p->dl.dl_bw_cpu);
+	if (cpu < 0 || !cpu_active(cpu) ||
+	    READ_ONCE(p->dl.dl_bw_gen) != READ_ONCE(dl_bw_gen))
+		return NULL;
+	return cpu_rq(cpu)->rd->span;
+}

[Severity: Medium]
Does rejecting !cpu_active(cpu) here cause dl_task_bw_span() to return NULL while a CPU is being deactivated?

In sched_cpu_deactivate(cpu), set_cpu_active(cpu, false) runs before balance_push_set(), synchronize_rcu(), and cpuset_cpu_inactive(), and cpuset_handle_hotplug() also calls cpuset_hotplug_update_tasks() before rebuild_sched_domains_cpuslocked() runs dl_rebuild_rd_accounting(). Throughout that window, cpu_rq(cpu)->rd still points to the root domain that counts p's bandwidth, but any task whose p->dl.dl_bw_cpu is the outgoing CPU gets dl_task_bw_span(p) == NULL. Tasks pushed by balance_push, updated by cpuset_hotplug_update_tasks(), or woken during deactivation can then be placed on an isolated CPU in def_root_domain and move their bandwidth there without admission control.

Quoted 18 lines
kernel/sched/deadline.c +14 -0
@@ -3903,6 +3947,27 @@ static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
 	 */
 	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
 	cpu = task_cpu(p);
+	/*
+	 * 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;
+
+		if (cpumask_test_cpu(cpu, msk) && cpumask_test_cpu(cpu, hk) == rec_hk)
+			return cpu;

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

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

[Severity: Low]
Because the new (recorded >= 0) block returns recorded whenever cpumask_test_cpu(recorded, msk) is true, the existing else-if branch right below this hunk is now unreachable:

kernel/sched/deadline.c:dl_task_rebuild_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;
	}
    ...
}

Also, when cpumask_empty(msk) is true and recorded is inactive, dl_get_task_effective_cpus(p, msk) refills msk after the kind-matching loop has already run, so the fallback at the end of the function will pick a housekeeping CPU even when recorded was an isolated CPU.

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

Re: [PATCH v6 26/37] sched/deadline: Keep a task in the root domain that counts its bandwidth

Quoted 2 lines

Can find_lock_later_rq(p, rq) bypass the dl_task_bw_span(p) check and migrate p onto an isolated CPU in def_root_domain?

Yes. After the rebuild, the offline rq is in def_root_domain, so the search only sees the isolated CPUs. The task and its bandwidth then move there with no admission test. The planned next version drops that result if the task still has an active CPU in its own root domain. It then takes the fallback, which prefers that root domain.

Quoted 2 lines

Does rejecting !cpu_active(cpu) here cause dl_task_bw_span() to return NULL while a CPU is being deactivated?

Yes. Until the rebuild, the root domain of that CPU still counts the task. The planned next version returns its span in that window. It returns NULL only for a housekeeping CPU that the rebuild already put in def_root_domain. The same holds the other way: a task counted on an isolated CPU that goes offline now stays on the isolated side.

A shorter window is left. The rebuild bumps dl_bw_gen before its walk reaches each task. In between, dl_task_bw_span() returns NULL for that task, and the CPU is picked without a preference. The window lasts one walk of the task list.

Quoted 3 lines

Because the new (recorded >= 0) block returns recorded whenever cpumask_test_cpu(recorded, msk) is true, the existing else-if branch right below this hunk is now unreachable:

Right. The planned next version drops the branch. It also refills the mask before the test of the kind of CPU.

Thanks,

Mathieu

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

PATCH v6 27/37 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.

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.

Fixes d4742f6ed7ea ("sched/deadline: Correctly account for allocated bandwidth during hotplug")
---
 include/linux/cpuset.h  |  9 +++++++
 kernel/cgroup/cpuset.c  | 20 +++++++++++++++
 kernel/sched/deadline.c | 56 ++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 84 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 +20 -0
index 0d55f092d9cb..ef5ad8e38f06 100644
@@ -4305,6 +4305,26 @@ 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. The caller holds the CPU hotplug lock for writing,
+ * which keeps the cpusets and their tasks as they are.
+ */
+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))
+			return;
+	}
+}
+
 /**
  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
  * @tsk: pointer to task_struct with which the scheduler is struggling
kernel/sched/deadline.c +55 -1

64 lines not on this page · raw message

Signature · 1 line
2.47.3
#41 lore raw

Re: [PATCH v6 27/37] sched/deadline: Keep the last CPU a task has in its root domain

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: missing affinity masks in dl_task_leaves_span() fallback - [Low] sched/deadline…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: missing affinity masks in dl_task_leaves_span() fallback
- [Low] sched/deadline: dl_task_leaves_span() rejects CPU offline for dead tasks
--

commit 48b62790717c3a90940a59e814da93b5ddf9ada9
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 deadline task with runnable CPUs only outside the root domain that accounts for its bandwidth.

Quoted 18 lines
kernel/sched/deadline.c +10 -0
index 5294546786f12..096c0ec55cdc2 100644
@@ -4896,9 +4896,63 @@ static int dl_bw_manage(enum dl_bw_request req, int cpu, u64 dl_bw)
 	return overflow ? -EBUSY : 0;
 }
 
+/*
+ * Return true if @p has CPUs to run on once @cpu is offline, but none in
+ * the root domain of @cpu, which counts its bandwidth.
+ */
+static bool dl_task_leaves_span(struct task_struct *p, int cpu,
+				const struct cpumask *span)
+{
+	struct cpumask *msk;
+
+	guard(raw_spinlock_irqsave)(&p->pi_lock);

kernel/sched/deadline.c static int dl_bw_manage(enum dl_bw_request req, int cpu, u64 dl_bw) · line 4918

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	if (dl_task_bw_span(p) != span)
+		return false;
+	msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
+	cpumask_and(msk, p->cpus_ptr, cpu_active_mask);
+	cpumask_clear_cpu(cpu, msk);
+	/* With no CPU left, the cpuset gives @p the CPUs of an ancestor. */
+	if (cpumask_empty(msk))
+		cpuset_cpus_allowed_without(p, cpu, msk);
+	return !cpumask_empty(msk) && !cpumask_intersects(msk, span);
+}

[Severity: Medium]
When msk is empty and dl_task_leaves_span() falls back to cpuset_cpus_allowed_without(), does it also need to restrict the inherited ancestor mask by p->user_cpus_ptr (when their intersection is non-empty) and task_cpu_possible_mask(p)?

When the CPU goes offline, cpuset_update_tasks_cpumask() updates the task via __set_cpus_allowed_ptr(), which intersects the new cpuset mask with p->user_cpus_ptr if they overlap:

kernel/sched/core.c:__set_cpus_allowed_ptr() {
    ...
	if (p->user_cpus_ptr &&
	    !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) &&
	    cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr))
		ctx->new_mask = rq->scratch_mask;
    ...
}

Suppose CPUs 0-1 are housekeeping CPUs in span and CPUs 2-3 are isolated (isolcpus=domain,2,3), and a task with user_cpus_ptr = {0, 2, 3} is moved into a child cpuset with cpuset.cpus = 0 under top_cpuset (0-3). Taking CPU 0 offline leaves msk empty, so cpuset_cpus_allowed_without() returns {1, 2, 3} from top_cpuset. Because dl_task_leaves_span() sees CPU 1 in msk & span, it allows the offline, after which __set_cpus_allowed_ptr() intersects {1, 2, 3} with user_cpus_ptr and restricts the task to {2, 3} in the default root domain without an admission check.

In addition, the CONFIG_CPUSETS implementation of cpuset_cpus_allowed_without() does not intersect cs->effective_cpus with task_cpu_possible_mask(tsk), unlike guarantee_active_cpus() and the !CONFIG_CPUSETS stub.

Quoted 17 lines
kernel/sched/deadline.c +17 -0
+
+/*
+ * Return true if @cpu is the last CPU that a deadline task can run on in
+ * the root domain that counts its bandwidth. With @cpu offline, the task
+ * would run in another root domain, which did not admit it. The mask of
+ * a task holds CPUs of two root domains only with isolcpus="domain".
+ *
+ * A suspend takes the CPUs offline with the tasks frozen, and the resume
+ * puts them back. Without admission control, there is no limit to exceed.
+ * Return false in both cases.
+ */
+static bool dl_cpu_last_of_task(int cpu)
+{
+	const struct cpumask *span;
+	struct task_struct *g, *p;
+
+	if (cpuhp_tasks_frozen || !dl_bandwidth_enabled())

kernel/sched/deadline.c static int dl_bw_manage(enum dl_bw_request req, int cpu, u64 dl_bw) · line 4945

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+		return false;
+	/* No task holds a bandwidth: do not walk the task list. */
+	if (!atomic_read(&dl_nr_bw_tasks))
+		return false;
+	guard(rcu)();
+	span = cpu_rq(cpu)->rd->span;
+	for_each_process_thread(g, p) {
+		if (task_has_dl_policy(p) && dl_task_leaves_span(p, cpu, span))
+			return true;
+	}

[Severity: Low]
Can this reject a CPU offline when p is an un-reaped exited task waiting for its 0-lag timer?

When a deadline task exits before its 0-lag time, task_non_contending() places it on dl_departed_list and arms inactive_timer while leaving p->policy and p->dl.dl_bw_cpu set. Until release_task() unhashes the task or inactive_timer fires, for_each_process_thread() still visits it and dl_task_leaves_span() returns true if the outgoing CPU was its only CPU in span, causing dl_bw_deactivate() to fail with -EBUSY even though a TASK_DEAD task will never run again or move its bandwidth to another root domain.

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

PATCH v6 28/37 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.

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.

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          | 179 +++++++++++++++++++++++++++++++-
 kernel/sched/deadline.c         |  19 ++++
 4 files changed, 198 insertions(+), 3 deletions(-)
include/linux/sched/deadline.h +2 -0
index cbb7cd71db58..d3796d874aa2 100644
@@ -61,6 +61,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 +176 -3

234 lines not on this page · raw message

kernel/sched/deadline.c +19 -0
index 096c0ec55cdc..61b50266468f 100644
@@ -4955,6 +4955,25 @@ 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.
+ */
+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;
+	guard(raw_spinlock_irqsave)(&p->pi_lock);
+	guard(rcu)();
+	span = dl_task_bw_span(p);
+	return !span || !cpumask_intersects(span, p->cpus_ptr) ||
+	       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
#43 lore raw

Re: [PATCH v6 28/37] cgroup/cpuset: Refuse to take a deadline task out of its root domain

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] cgroup/cpuset: excpus clobbered via tmp->new_cpus in remote_cpus_update() - [High] cgroup/cpuset…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] cgroup/cpuset: excpus clobbered via tmp->new_cpus in remote_cpus_update()
- [High] cgroup/cpuset: partition_xcpus_del() called on invalid partition in update_parent_effective_cpumask()
- [Medium] cgroup/cpuset: wrong descendant effective_cpus in dl_tasks_keep_without()
- [Medium] sched/deadline: user_cpus_ptr ignored in dl_task_keeps_root_domain()
- [Medium] cgroup/cpuset: dl_tasks_keep_root_domain() skips invalidated partitions
--

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

cgroup/cpuset: Refuse to take a deadline task out of its root domain

This commit rejects cpuset CPU mask updates and invalidates partition roots when the resulting effective CPUs would move a SCHED_DEADLINE task out of the root domain accounting its bandwidth without admission control.

Quoted 4 lines
kernel/cgroup/cpuset.c +0 -0
index ef5ad8e38f06f..5b4f7d4ef3ae2 100644

[ ... ]

Quoted 1 line
kernel/cgroup/cpuset.c +0 -0
@@ -1126,6 +1127,92 @@ static void update_partition_sd_lb(struct cpuset *cs, int old_prs)

[ ... ]

Quoted 33 lines
kernel/cgroup/cpuset.c +33 -0
+static bool dl_tasks_keep_without(struct cpuset *root, struct cpuset *part,
+				  const struct cpumask *xcpus, bool enable,
+				  struct cpumask *new_cpus)
+{
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp, *a;
+	bool keep = true;
+
+	rcu_read_lock();
+	cpuset_for_each_descendant_pre(cp, pos_css, root) {
+		if (cp == part || (cp != root && is_partition_valid(cp))) {
+			pos_css = css_rightmost_descendant(pos_css);
+			continue;
+		}
+		if (!cpumask_intersects(cp->effective_cpus, xcpus))
+			continue;
+		for (a = cp; ; a = parent_cs(a)) {
+			if (cpumask_andnot(new_cpus, a->effective_cpus, xcpus) ||
+			    a == root)
+				break;
+		}
+		keep = dl_tasks_keep_cpus(cp, new_cpus);
+		if (!keep)
+			break;
+	}
+	if (keep && enable) {
+		cpuset_for_each_descendant_pre(cp, pos_css, part) {
+			if (cp != part && is_partition_valid(cp)) {
+				pos_css = css_rightmost_descendant(pos_css);
+				continue;
+			}
+			if (cpumask_subset(cp->effective_cpus, xcpus))
+				continue;

kernel/cgroup/cpuset.c static void update_partition_sd_lb(struct cpuset *cs, int old_prs) · line 1214

Quoted 10 lines
kernel/cgroup/cpuset.c +10 -0
+			if (!cpumask_and(new_cpus, cp->effective_cpus, xcpus))
+				cpumask_copy(new_cpus, xcpus);
+			keep = dl_tasks_keep_cpus(cp, new_cpus);
+			if (!keep)
+				break;
+		}
+	}
+	rcu_read_unlock();
+	return keep;
+}

[Severity: Medium]
Can dl_tasks_keep_without() miscompute new_cpus for descendant cpusets and let a deadline task move to another root domain without admission control?

In the first loop, when cp loses all of its effective_cpus to xcpus and inherits from an ancestor a above parent_cs(cp), new_cpus is set to a->effective_cpus & ~xcpus without filtering top-down through the cpus_allowed masks of the cpusets between a and cp as compute_effective_cpumask() does. If root has effective_cpus {0, 1, 2} (0-1 housekeeping, 2 isolated), child P has cpus_allowed {0}, and grandchild C has cpus_allowed {2} (so C inherits effective_cpus {0}), a partition taking xcpus {0} tests C against root's {1, 2} and sees housekeeping CPU 1, whereas update_cpumasks_hier() gives P {1, 2} and gives C {2}, moving a deadline task in C into the isolated root domain.

In the second loop (when enable is true), cp's new mask is derived from cp->effective_cpus & xcpus instead of filtering xcpus & cpu_active_mask top-down through each descendant's cpus_allowed. Because enabling part switches its effective CPUs from cpus_allowed to effective_xcpus, a child C whose cpus_allowed only intersects part->exclusive_cpus previously inherited part->cpus_allowed, passes the cpumask_subset(cp->effective_cpus, xcpus) check if part->cpus_allowed is a subset of xcpus, and then switches to C->cpus_allowed once part is enabled; in addition, xcpus is not masked with cpu_active_mask, so offline CPUs in xcpus can match def_root_domain->span.

[ ... ]

kernel/cgroup/cpuset.c static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus, · line 1876

Quoted 10 lines
kernel/cgroup/cpuset.c +3 -0
@@ -1779,6 +1868,9 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 		else if (prstate_housekeeping_conflict(prs, PRS_ROOT,
 						       excpus, tmp->delmask))
 			WRITE_ONCE(cs->prs_err, PERR_HKEEPING);
+		else if (!dl_tasks_keep_without(&top_cpuset, cs, tmp->addmask,
+						false, tmp->new_cpus))
+			WRITE_ONCE(cs->prs_err, PERR_DLTASK);
 		if (cs->prs_err)
 			goto invalidate;
 	}

[Severity: High]
Does passing tmp->new_cpus to dl_tasks_keep_without() clobber excpus before it is copied to cs->effective_xcpus?

update_cpumasks_hier() calls remote_cpus_update() with excpus pointing to tmp->new_cpus:

kernel/cgroup/cpuset.c:update_cpumasks_hier() {
    ...
			compute_excpus(cp, tmp->new_cpus);
			...
			rcu_read_unlock();
			remote_cpus_update(cp, NULL, tmp->new_cpus, tmp);
			rcu_read_lock();
    ...
}

When a descendant remote partition gains exclusive CPUs during update_cpumasks_hier(), dl_tasks_keep_without() overwrites tmp->new_cpus with top_cpuset's remaining effective CPUs, and remote_cpus_update() then copies that clobbered mask from excpus into cs->effective_xcpus.

[ ... ]

Quoted 5 lines
kernel/cgroup/cpuset.c +1 -0
@@ -2013,6 +2109,15 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			deleting = false;
 			adding = cpumask_and(tmp->addmask,
 					     cs->effective_xcpus, parent->effective_xcpus);
+		} else if (deleting &&

kernel/cgroup/cpuset.c static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, · line 2122

Quoted 10 lines
kernel/cgroup/cpuset.c +8 -0
+			   !dl_tasks_keep_without(parent, cs, tmp->delmask,
+						  is_partition_invalid(cs),
+						  tmp->new_cpus)) {
+			/* As above: the partition becomes invalid. */
+			part_error = PERR_DLTASK;
+			deleting = false;
+			adding = cpumask_and(tmp->addmask,
+					     cs->effective_xcpus, parent->effective_xcpus);
 		}
 	} else {

[Severity: High]
Can setting adding here when is_partition_invalid(cs) is true call partition_xcpus_del() on an already-invalid partition?

An invalid local partition root (old_prs < 0) with cpuset.cpus.exclusive set keeps a non-empty cs->effective_xcpus even though those CPUs were not removed from parent->effective_cpus. When updating cpuset.cpus or cpuset.cpus.exclusive on that invalid partition takes the newmask branch and dl_tasks_keep_without() returns false, adding becomes true while old_prs < 0, so partition_xcpus_del(old_prs, parent, tmp->addmask) triggers WARN_ON_ONCE(old_prs < 0) and corrupts subpartitions_cpus, isolated_cpus, and parent->effective_cpus by releasing CPUs that cs never held. Guarding adding with is_partition_valid(cs) avoids releasing unowned CPUs.

[ ... ]

Quoted 1 line
kernel/cgroup/cpuset.c +0 -0
@@ -2496,6 +2604,66 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,

[ ... ]

Quoted 31 lines
kernel/cgroup/cpuset.c +26 -0
+static bool dl_tasks_keep_root_domain(struct cpuset *cs, struct cpuset *trialcs,
+				      struct cpumask *new_cpus)
+{
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp;
+	bool keep = true;
+
+	if (is_partition_valid(cs))
+		return true;
+	rcu_read_lock();
+	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
+		if (is_partition_valid(cp)) {
+			pos_css = css_rightmost_descendant(pos_css);
+			continue;
+		}
+		trial_effective_cpus(cp, cs, trialcs, new_cpus);
+		if (cpumask_subset(cp->effective_cpus, new_cpus))
+			continue;
+		keep = dl_tasks_keep_cpus(cp, new_cpus);
+		if (!keep)
+			break;
+	}
+	rcu_read_unlock();
+	return keep;
+}
+
 /**
  * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
  * @cs: the cpuset to consider
@@ -2528,6 +2696,11 @@ static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
 	if (alloc_tmpmasks(&tmp))

kernel/cgroup/cpuset.c static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs, · line 2706

Quoted 10 lines
kernel/cgroup/cpuset.c +5 -0
 		return -ENOMEM;
 
+	if (!dl_tasks_keep_root_domain(cs, trialcs, tmp.new_cpus)) {
+		free_tmpmasks(&tmp);
+		return -EBUSY;
+	}
+
 	/*
 	 * Check all the descendants in update_cpumasks_hier() if
 	 * effective_xcpus is to be changed.

[Severity: Medium]
What happens when a write to cpuset.cpus (or cpuset.cpus.exclusive) invalidates a valid partition root?

dl_tasks_keep_root_domain() runs before partition_cpus_change() and returns true immediately when is_partition_valid(cs) is true, and update_exclusive_cpumask() does not check dl_tasks_keep_root_domain() at all. If cs is a valid root partition on a housekeeping CPU containing a deadline task and a user writes a boot-isolated CPU to cs/cpuset.cpus, partition_cpus_change() invalidates cs (PERR_HKEEPING), and update_cpumasks_hier() recomputes cs->effective_cpus as a non-partition cpuset on the isolated CPU; dl_rebuild_rd_accounting() then adds the task's bandwidth to def_root_domain via dl_add_task_root_domain() without admission control.

Quoted 16 lines
kernel/sched/deadline.c +8 -0
index 096c0ec55cdc2..61b50266468f9 100644
@@ -4955,6 +4955,25 @@ 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.
+ */
+bool dl_task_keeps_root_domain(struct task_struct *p,
+			       const struct cpumask *new_mask)
+{

kernel/sched/deadline.c int dl_bw_deactivate(int cpu) · line 4975

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	const struct cpumask *span;
+
+	if (!dl_bandwidth_enabled() || !task_has_dl_policy(p))
+		return true;
+	guard(raw_spinlock_irqsave)(&p->pi_lock);
+	guard(rcu)();
+	span = dl_task_bw_span(p);
+	return !span || !cpumask_intersects(span, p->cpus_ptr) ||
+	       cpumask_intersects(span, new_mask);
+}

[Severity: Medium]
Should dl_task_keeps_root_domain() account for p->user_cpus_ptr the way __set_cpus_allowed_ptr() and dl_task_bw_reserve_cpu() do?

When cpuset_update_tasks_cpumask() calls set_cpus_allowed_ptr(task, new_cpus), __set_cpus_allowed_ptr() restricts new_cpus to new_cpus & p->user_cpus_ptr whenever their intersection is non-empty. Because dl_task_keeps_root_domain() tests span against new_mask directly (and dl_tasks_keep_root_domain() and dl_tasks_keep_without() skip cpusets where cpumask_subset(cp->effective_cpus, new_cpus) holds), a deadline task counted in housekeeping span {0, 1} whose p->user_cpus_ptr only intersects new_mask on isolated CPU {2} passes this check (or the subset check when widening effective_cpus from {0, 1} to {0, 1, 2}) and has its affinity restricted to {2} in the isolated root domain without admission control. Intersecting new_mask with p->user_cpus_ptr when cpumask_intersects(new_mask, p->user_cpus_ptr) is true and checking tasks even when new_cpus grows would match __set_cpus_allowed_ptr().

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

Re: [PATCH v6 28/37] cgroup/cpuset: Refuse to take a deadline task out of its root domain

Quoted 2 lines

Can dl_tasks_keep_without() miscompute new_cpus for descendant cpusets and let a deadline task move to another root domain without admission control?

Yes. Fixed in the planned next version: the new masks are computed from the top down, as update_cpumasks_hier() does.

Quoted 2 lines

Does passing tmp->new_cpus to dl_tasks_keep_without() clobber excpus before it is copied to cs->effective_xcpus?

Yes, and with no deadline task at all. update_cpumasks_hier() computes effective_xcpus again right after, so the wrong value does not last. Only update_sibling_cpumasks(), called in between, can see it. This is from reading: no test case showed a lasting effect. Fixed in the planned next version with a scratch mask of its own.

Quoted 2 lines

Can setting adding here when is_partition_invalid(cs) is true call partition_xcpus_del() on an already-invalid partition?

Yes. Fixed in the planned next version.

Quoted 2 lines

What happens when a write to cpuset.cpus (or cpuset.cpus.exclusive) invalidates a valid partition root?

Right, the task can then run in a root domain that did not admit it, as upstream does. The planned next version does not refuse this write, for two reasons.

The same move happens on paths that cannot fail:
- CPU hotplug;
- a child partition made invalid after its parent, in update_cpumasks_hier();
- a write of "member" to cpuset.cpus.partition.
A check on this write alone would not give a rule that holds.

The write path also cannot tell early whether the partition becomes invalid. validate_partition(), prstate_housekeeping_conflict() and update_parent_effective_cpumask() find that out, and the last one already changes the state. Refusing would mean splitting partition_cpus_change() into a compute step and an apply step. That is too much for a fix meant for stable.

The rebuild then counts the task where it runs. The cover letter of the planned next version lists this under "Not changed".

For cpuset.cpus.exclusive: on a cpuset that is not a partition root, the exclusive CPUs do not change effective_cpus. On a partition root, the change goes through update_parent_effective_cpumask() or remote_cpus_update(), which have the check.

Quoted 2 lines

Should dl_task_keeps_root_domain() account for p->user_cpus_ptr the way __set_cpus_allowed_ptr() and dl_task_bw_reserve_cpu() do?

Yes. Fixed in the planned next version, for masks that grow too.

Thanks,

Mathieu

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

PATCH v6 29/37 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 61b50266468f..72bafa46ae41 100644
@@ -650,6 +650,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);
 			}
 		}
@@ -2446,6 +2447,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
#46 lore raw

PATCH v6 30/37 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 72bafa46ae41..69a338c1526d 100644
@@ -529,22 +529,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);
@@ -4546,10 +4561,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
@@ -4564,6 +4575,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);
 
@@ -4593,7 +4614,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)) {
 		/*
@@ -4643,8 +4663,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
#47 lore raw

PATCH v6 31/37 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.

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-rc1 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/deadline.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
kernel/sched/deadline.c +22 -0
index 69a338c1526d..ffa8b946e804 100644
@@ -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;
+}
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -135,6 +141,11 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return false;
 }
+
+static inline bool dl_task_pi_blocked(struct task_struct *p)
+{
+	return false;
+}
 #endif /* !CONFIG_RT_MUTEXES */
 
 static inline u8 dl_get_type(struct sched_dl_entity *dl_se, struct rq *rq)
@@ -4352,6 +4363,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
+		 * 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;
 	}
 
Signature · 1 line
2.47.3
#48 lore raw

Re: [PATCH v6 31/37] sched/deadline: Start a period for a task that enters the class blocked

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: unstarted period in switched_to_dl() when !pi_blocked_on - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: unstarted period in switched_to_dl() when !pi_blocked_on
- [Medium] sched/deadline: switched_to_dl() skips period reset on boosted pre-0-lag task
- [Medium] sched/deadline: stale deadline on rt_mutex waiter when donor or policy changes
--

commit 97588bc2bebff0e4575bb7d4c8f530868b8856a3
Author: Mathieu Desnoyers <[email protected]>

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

This commit starts a new period in switched_to_dl() when a task blocked on an rt_mutex enters dl_sched_class with an expired deadline so that the rt_mutex waiter tree does not sort it with a deadline of 0.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 69a338c1526d0..ffa8b946e8047 100644

[ ... ]

Quoted 4 lines
kernel/sched/deadline.c +0 -0
@@ -4352,6 +4363,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);
 

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

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

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

While a task sleeps in futex_wait_requeue_pi() on a non-PI futex, p->pi_blocked_on is NULL. If sched_setattr() or a PI boost moves p into dl_sched_class there, switched_to_dl() leaves p->dl.deadline at 0, and a later FUTEX_CMP_REQUEUE_PI calls rt_mutex_start_proxy_lock() -> task_blocks_on_rt_mutex() without waking p, queuing its waiter ahead of all deadline waiters with deadline 0. Likewise, if a task holding an rt_mutex is switched to SCHED_DEADLINE while sleeping on a non-rt_mutex wait, p->dl.deadline stays 0 and rt_mutex_setprio() fails to boost p when a deadline waiter with an earlier deadline blocks on that rt_mutex (dl_entity_preempt(&pi_task->dl, &p->dl) is false against 0).

[Severity: Medium]
What happens when a task that left SCHED_DEADLINE before its 0-lag time is PI-boosted back into dl_sched_class while blocked on an rt_mutex?

switched_from_dl() preserves p->dl.deadline and p->dl.dl_throttled until inactive_timer fires. If p then blocks on an rt_mutex while holding another and is boosted back into dl_sched_class, enqueue_task_dl() is not called because p is not queued, and switched_to_dl() checks !p->dl.dl_throttled && dl_time_before(p->dl.deadline, rq_clock(rq)) without checking is_dl_boosted(&p->dl).

If p->dl.dl_throttled is still set, switched_to_dl() skips replenish_dl_new_period() and leaves p throttled with its expired deadline; if p->dl.dl_timer then fires while p is boosted, dl_task_timer() bails out on is_dl_boosted(dl_se) without clearing dl_throttled, which prevents enqueue_dl_entity() from queuing p after deboost. Even when p is not throttled, if its old pre-0-lag p->dl.deadline is still in the future, switched_to_dl() skips replenish_dl_new_period() and the chain walk sorts p using its abandoned reservation's deadline instead of the donor's.

[Severity: Medium]
Does starting a period in switched_to_dl() leave p->dl.deadline stale if the top PI donor on a blocked task changes while it remains in dl_sched_class?

If a non-deadline task p owns rt_mutex M1 and blocks on rt_mutex M2, an initial deadline waiter W1 on M1 moves p into dl_sched_class and switched_to_dl() sets p->dl.deadline from W1. If a second deadline waiter W2 with a much earlier deadline then blocks on M1, rt_mutex_setprio(p, W2) keeps prev_class == next_class == &dl_sched_class and sets p->dl.pi_se = W2->dl.pi_se with ENQUEUE_REPLENISH. Because p is not queued, sched_change_end() calls prio_changed_dl() instead of enqueue_task_dl() or switched_to_dl(), leaving p->dl.deadline at W1's later deadline. rt_mutex_adjust_prio_chain() then sees an unchanged waiter deadline and stops the chain walk on M2, and when p later wakes up, update_dl_entity() keeps W1's future deadline if dl_entity_overflow() is not triggered.

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

Re: [PATCH v6 31/37] sched/deadline: Start a period for a task that enters the class blocked

Quoted 3 lines

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

Both cases are real, and upstream. But a deadline of 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.

Quoted 4 lines

If p->dl.dl_throttled is still set, switched_to_dl() skips replenish_dl_new_period() and leaves p throttled with its expired deadline; if p->dl.dl_timer then fires while p is boosted, dl_task_timer() bails out on is_dl_boosted(dl_se) without clearing dl_throttled

Right, and upstream. The planned next version has a separate patch for
it: dl_task_timer() replenishes a boosted task that sleeps.

Quoted 4 lines

Even when p is not
throttled, if its old pre-0-lag p->dl.deadline is still in the future, switched_to_dl() skips replenish_dl_new_period() and the chain walk sorts p using its abandoned reservation's deadline instead of the donor's.

This is intended. A queued task boosted back keeps its deadline too. replenish_dl_entity() keeps the deadline and the runtime of a task with parameters of its own, while it has runtime left. The blocked task now gets the same. The task keeps its parameters until its 0-lag time, so that leaving the class and coming back gains nothing.

Quoted 2 lines

Does starting a period in switched_to_dl() leave p->dl.deadline stale if the top PI donor on a blocked task changes while it remains in dl_sched_class?

Yes. Fixed in the planned next version: a boost of a blocked task with no parameters of its own starts a period from the new donor.

Thanks,

Mathieu

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

PATCH v6 32/37 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-rc1, 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-rc1 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 ffa8b946e804..b47c13c8714d 100644
@@ -2723,6 +2723,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
#51 lore raw

Re: [PATCH v6 32/37] sched/deadline: Check the runtime of a task that comes back runnable

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: missed update_dl_entity() when setattr runs while PI-boosted --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: missed update_dl_entity() when setattr runs while PI-boosted
--

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

sched/deadline: Check the runtime of a task that comes back runnable

This commit calls update_dl_entity() when a runnable unboosted task enters SCHED_DEADLINE so its remaining runtime is checked against its new scheduling parameters.

Quoted 9 lines
kernel/sched/deadline.c +1 -0
index ffa8b946e8047..b47c13c8714d9 100644
@@ -2723,6 +2723,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)) {

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

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

[Severity: Medium]
Can a runnable task bypass update_dl_entity() when returning to SCHED_DEADLINE with smaller runtime if it is PI-boosted at the time of sched_setattr()?

If a SCHED_DEADLINE task switches to SCHED_OTHER before its 0-lag time and is then PI-boosted back into dl_sched_class by an rt_mutex waiter, replenish_dl_entity() sees non-zero dl_se->dl_deadline and positive dl_se->runtime, so dl_se->dl_donor_refill stays 0.

When sched_setattr() then returns the task to SCHED_DEADLINE with a smaller runtime while still boosted, __sched_setscheduler() sees prev_class == next_class == &dl_sched_class (so ENQUEUE_CLASS is not set) and is_dl_boosted(dl_se) is true, skipping update_dl_entity(). Even with commit "sched/deadline: Check the runtime of a task whose parameters change", enqueue_dl_entity() clears dl_se->dl_new_params unconditionally at the top while skipping the check because is_dl_boosted(dl_se) is true.

When the task later unlocks the rt_mutex, dl_deboost() sees dl_donor_refill == 0 and leaves the old larger dl_se->runtime intact:

kernel/sched/deadline.c:dl_deboost() {
	if (dl_se->dl_donor_refill) {
		dl_se->deadline = rq_clock(rq) + dl_se->dl_deadline;
		dl_se->runtime = dl_se->dl_runtime;
	}
	dl_drop_boost(dl_se);
}

Because the subsequent enqueue only passes ENQUEUE_MOVE with a future deadline, update_dl_entity() is never called, and the task runs on its old larger runtime while admission control only accounts for the new smaller bandwidth.

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

PATCH v6 33/37 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-rc1, 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 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. It fails on v7.4-rc1 and passes with this patch.

Fixes 40767b0dc768 ("sched/deadline: Fix deadline parameter modification handling")
---
 include/linux/sched.h   |  5 +++++
 kernel/sched/deadline.c | 20 +++++++++++++++-----
 2 files changed, 20 insertions(+), 5 deletions(-)
include/linux/sched.h +5 -0
index 2f2f59402f09..f40abe5b9ace 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 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 +15 -5
index b47c13c8714d..3b62ee43c209 100644
@@ -2674,7 +2674,10 @@ 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));
+	dl_se->dl_new_params = 0;
 
 	update_stats_enqueue_dl(dl_rq_of_se(dl_se), dl_se, flags);
 
@@ -2723,12 +2726,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) &&
@@ -4696,6 +4700,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
@@ -4828,6 +4837,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
#53 lore raw

Re: [PATCH v6 33/37] sched/deadline: Check the runtime of a task whose parameters change

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: dl_new_params cleared while boosted in enqueue_dl_entity() - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: dl_new_params cleared while boosted in enqueue_dl_entity()
- [Medium] sched/deadline: unchecked laxity in update_dl_entity() on dl_deadline shrink
--

commit b62a12a066a3a8cec83cd122301c3f7fcc56bd77
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 enqueue checks the remaining runtime against the new parameters via update_dl_entity().

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

Quoted 12 lines
kernel/sched/deadline.c +3 -0
index b47c13c8714d9..3b62ee43c2099 100644
@@ -2674,7 +2674,10 @@ 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));
+	dl_se->dl_new_params = 0;

[Severity: Medium]
Does clearing dl_se->dl_new_params unconditionally here lose the mark if the task is priority-inheritance boosted when sched_setattr() shrinks its reservation?

When is_dl_boosted(dl_se) is true, the new_params branch below is skipped (or on a wakeup while boosted, update_dl_entity() checks against pi_of(dl_se) rather than the task's own parameters). If the boost took no donor refill (dl_donor_refill == 0), dl_deboost() later leaves dl_se->runtime and dl_se->deadline intact, and the subsequent enqueue sees dl_se->dl_new_params == 0 and lets the task run on its old larger runtime after admission control already released the bandwidth difference.

Quoted 10 lines
kernel/sched/deadline.c +2 -1
 	update_stats_enqueue_dl(dl_rq_of_se(dl_se), dl_se, flags);
 
@@ -2723,12 +2726,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)) {
 		/*

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

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

[Severity: Medium]
Can update_dl_entity() leave or set dl_se->runtime above the new dl_se->dl_runtime when sched_setattr() shrinks dl_deadline to a constrained reservation while dl_se->deadline - rq_clock(rq) still exceeds the new dl_deadline?

Both dl_entity_overflow() and update_dl_revised_wakeup() assume that laxity = dl_se->deadline - rq_clock(rq) is at most dl_se->dl_deadline:

kernel/sched/deadline.c:update_dl_revised_wakeup() {
	u64 laxity = dl_se->deadline - rq_clock(rq);

	WARN_ON(dl_time_before(dl_se->deadline, rq_clock(rq)));

	dl_se->runtime = (dl_se->dl_density * laxity) >> BW_SHIFT;
}

For example, if a task running at 50ms/100ms/100ms has runtime = 30ms and laxity = 80ms when changed to 10ms/20ms/100ms (density 50%), dl_entity_overflow() sees 30ms / 80ms <= 10ms / 20ms and leaves runtime at 30ms; if changed instead at runtime = 49ms and laxity = 99ms to 8ms/20ms/100ms (density 40%), update_dl_revised_wakeup() sets dl_se->runtime to 39.6ms against an 8ms budget. Besides letting the task overrun the bandwidth it just gave back in sched_dl_overflow(), blocking with dl_se->runtime > dl_se->dl_runtime makes task_non_contending() compute a negative zerolag_time and drop running_bw or total_bw immediately.

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

PATCH v6 34/37 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
#55 lore raw

PATCH v6 35/37 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 four 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.

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 two sysrq cases run only with DEADLINE_TEST_SYSRQ set. They also need root and CONFIG_MAGIC_SYSRQ. sysrq_boosted_owner runs 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 sysrq_boosted_owner.

On v7.4-rc1, in 8-CPU VMs, three of the four 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.

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     | 808 ++++++++++++++++++
 5 files changed, 819 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 +808 -0

808 lines not on this page · raw message

Signature · 1 line
2.47.3
#56 lore raw

PATCH v6 36/37 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-rc1, 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
#57 lore raw

PATCH v6 37/37 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 89 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. Thirteen 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-rc1, in 8 VMs of 8 CPUs, 32 cases fail. 30 fail in every VM. overrun_caught and hotplug_sleeper_switched each failed in 7 VMs of 8. The 32 cases are:

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

18 cases skip there. 15 lack what they need. hotplug_refused and hotplug_server cannot set up their state. move_normalized was not run:
on v7.4-rc1, 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 thirteen 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         | 8101 +++++++++++++++++
 .../testing/selftests/sched/deadline/settings |    1 +
 5 files changed, 8106 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 +8101 -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.

#58 lore raw

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

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] selftests/sched: unconditional cpu_up() and hotplug check in fallback_case() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] selftests/sched: unconditional cpu_up() and hotplug check in fallback_case()
--

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

selftests/sched: Add a test of SCHED_DEADLINE bandwidth accounting

This commit adds deadline_bw_test to test SCHED_DEADLINE bandwidth accounting across priority inheritance, parameter changes, cpuset moves, deaths, yields, runtime overruns, reclaiming, fair servers, and CPU hotplug.

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

[ ... ]

Quoted 23 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +23 -0
+static int fallback_case(enum fb_mode mode)
+{
+	int in_b = mode == FB_LAST_H || mode == FB_PART_H || mode == FB_STAY_K;
+	int off_cpu;
+	int on_h = mode == FB_ON_H || mode == FB_MASK_H || in_b;
+	int no_offline = mode == FB_MASK_H || mode == FB_LAST_H || mode == FB_PART_H;
+	char cg_q[PATH_MAX];
+	int on_i1 = mode == FB_ON_I1;
+	char cg_b[PATH_MAX], cg_c[PATH_MAX], path[PATH_MAX + 32], buf[256], one[16];
+	long long def0, hk0, def_off = 0, hk_off = 0, def_ref, hk_ref, def, hk, bw;
+	int fd[2], ret = KSFT_SKIP, added = 0, made = 0, w, at, err;
+	pid_t pid = -1;
+
+	if (!root[0] || fallback_cpus(!no_offline)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs%s\n",
+			       no_offline ? "" : ", CPU hotplug");
+		return KSFT_SKIP;
+	}
+	off_cpu = mode == FB_STAY_K ? fb_h : fb_i1;
+	if ((mode == FB_LAST_H || mode == FB_STAY_K) && !cpu_hotpluggable(fb_h)) {
+		ksft_print_msg("CPU %d cannot go offline\n", fb_h);
+		return KSFT_SKIP;
+	}

[ ... ]

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +4 -0
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	def = total_bw_of(fb_i2);

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

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c new file +10 -0
+	hk = total_bw_of(fb_k);
+	if (def != def_ref || hk != hk_ref) {
+		ksft_print_msg("task gone: total_bw %lld, %lld, not %lld, %lld\n",
+			       def, hk, def_ref, hk_ref);
+		ret = KSFT_FAIL;
+	}
+out_up:
+	reap(pid);
+	cpu_up(off_cpu);
+	pid = -1;

[Severity: Low]
Should cpu_up(off_cpu) at out_up be guarded by !no_offline?

For FB_MASK_H, FB_LAST_H, and FB_PART_H, off_cpu is never taken offline (and mask_out_refused and partition_takes_refused have no_hp = 1), so falling through to out_up attempts to write to the sysfs online file of fb_i1 and logs an error when fb_i1 is not hotpluggable.

Also, for FB_STAY_K, off_cpu is fb_h rather than fb_i1, but passing !no_offline to fallback_cpus() requires an isolated CPU to be hotpluggable and skips hotplug_keeps_root_domain if neither isolated CPU supports hotplug.

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