Linux kernel -stable discussions
 help / color / mirror / Atom feed
* [PATCH v12 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 02/43] sched/deadline: Rebuild the root domains' accounting from the task list Mathieu Desnoyers
                   ` (33 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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, added to
deadline_bw_test later in this series, tests this.

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

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

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

Fixes: 387e31300b57 ("sched/deadline: Fix the update of the total -deadline utilization")
Fixes: f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 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(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 88cda9c10cb8..b6d4e365afee 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -739,6 +739,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().
diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index 273538200a44..bdf39ac1d43d 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -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;
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 3219f927c35e..4159abfbbbb5 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -985,22 +985,15 @@ 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);
 
+	dl_clear_root_domains();
+
 	rcu_read_lock();
 
-	for_each_possible_cpu(cpu) {
-		if (dl_bw_visited(cpu, cookie))
-			continue;
-
-		dl_clear_root_domain_cpu(cpu);
-	}
-
 	cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
 
 		if (cpumask_empty(cs->effective_cpus)) {
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index fe6b12500b54..c2b5b5fdf1b9 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -163,7 +163,13 @@ static inline unsigned long dl_bw_capacity(int i)
 	}
 }
 
-bool dl_bw_visited(int cpu, u64 cookie)
+/*
+ * Used for dl_bw check and update, used under sched_rt_handler()::mutex and
+ * sched_domains_mutex.
+ */
+static u64 dl_cookie;
+
+static bool dl_bw_visited(int cpu, u64 cookie)
 {
 	struct root_domain *rd = cpu_rq(cpu)->rd;
 
@@ -217,6 +223,112 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
 	       cap_scale(dl_b->bw, cap) < dl_b->total_bw - old_bw + new_bw;
 }
 
+/*
+ * A task that leaves SCHED_DEADLINE, or dies, before its 0-lag time keeps
+ * its bandwidth in total_bw until that time. Then the inactive timer
+ * removes it. Meanwhile the task may run anywhere, under another policy.
+ * The timer holds a reference to it.
+ *
+ * A rebuild of the root domains' accounting (dl_clear_root_domains() and
+ * dl_add_task_root_domain()) does not find such a task among the deadline
+ * tasks of the cpusets. So dl_departed_list holds these tasks, from their
+ * departure to their timer. The rebuild puts their bandwidth back in the
+ * root domain of the CPU each one was on when it left.
+ *
+ * dl_bw_gen numbers the rebuilds of the accounting: how many times the
+ * root domains were wiped and reconstructed (dl_clear_root_domains()
+ * increments it). A task records the number of its last definite
+ * state, counted or settled. That number dates the state:
+ *
+ *  - Current: the bandwidth is counted, or a release settled it since
+ *    the rebuild began. A release subtracts; the walk of the cpusets
+ *    skips.
+ *  - One behind: the clear that just ran wiped it. The rebuild puts
+ *    it back.
+ *  - Older: an earlier rebuild dropped it. A task on the departed list
+ *    stays out, and its release removes nothing. A task that is in the
+ *    class is counted again.
+ *
+ * Only equalities are compared, so the wrap of the counter is
+ * harmless.
+ *
+ * A rebuild drops the bandwidth when the CPU recorded is no longer
+ * active. It also drops the bandwidth of a task that dies while the
+ * rebuild runs. The cpuset walk skips that task, and it was not dead yet
+ * when the list was put back.
+ *
+ * dl_departed_lock protects the list and both counts. Take it with
+ * interrupts disabled, under the task's rq lock or pi_lock or in the
+ * rebuild, and before any dl_bw lock.
+ */
+static LIST_HEAD(dl_departed_list);
+static DEFINE_RAW_SPINLOCK(dl_departed_lock);
+static unsigned int dl_bw_gen;
+
+/*
+ * Put @p on dl_departed_list with @cpu, a CPU of the root domain that
+ * keeps its bandwidth. @p leaves SCHED_DEADLINE, or dies, before its
+ * 0-lag time. Do nothing if @p is on the list already. Keep the CPU
+ * recorded if @p has one: priority inheritance boosted @p back into the
+ * class and its boost ends. The caller holds the rq lock of @p.
+ */
+static void dl_task_depart(struct task_struct *p, int cpu)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+
+	lockdep_assert_irqs_disabled();
+	guard(raw_spinlock)(&dl_departed_lock);
+	if (!list_empty(&dl_se->dl_departed_node))
+		return;
+	if (dl_se->dl_departed_cpu < 0)
+		dl_se->dl_departed_cpu = cpu;
+	list_add(&dl_se->dl_departed_node, &dl_departed_list);
+}
+
+/*
+ * Take @p off dl_departed_list. Priority inheritance boosts @p back into
+ * the deadline class. Keep the CPU recorded: its root domain still counts
+ * the bandwidth, wherever @p runs now. The caller holds the rq lock of
+ * @p.
+ */
+static void dl_task_undepart(struct task_struct *p)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+
+	lockdep_assert_irqs_disabled();
+	guard(raw_spinlock)(&dl_departed_lock);
+	list_del_init(&dl_se->dl_departed_node);
+}
+
+/*
+ * Remove the bandwidth of @p from the root domain that counts it. That is
+ * the root domain of the CPU recorded when @p departed, or else of @cpu.
+ * Clear the record. Take @p off dl_departed_list. Remove nothing if a
+ * rebuild dropped the bandwidth since it was counted. Then record the
+ * current dl_bw_gen in @p, so that a rebuild in progress does not count it
+ * again. The caller holds the rq lock of @p.
+ */
+static void dl_task_release_bw(struct task_struct *p, int cpu)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+	struct dl_bw *dl_b;
+
+	lockdep_assert_irqs_disabled();
+	guard(raw_spinlock)(&dl_departed_lock);
+	if (dl_se->dl_departed_cpu >= 0) {
+		cpu = dl_se->dl_departed_cpu;
+		dl_se->dl_departed_cpu = -1;
+		list_del_init(&dl_se->dl_departed_node);
+	}
+	if (dl_se->dl_bw_gen == dl_bw_gen) {
+		dl_b = dl_bw_of(cpu);
+		raw_spin_lock(&dl_b->lock);
+		__dl_sub(dl_b, dl_se->dl_bw, dl_bw_cpus(cpu));
+		raw_spin_unlock(&dl_b->lock);
+	}
+	dl_se->dl_bw_gen = dl_bw_gen;
+}
+
 static inline
 void __add_running_bw(u64 dl_bw, struct dl_rq *dl_rq)
 {
@@ -536,13 +648,9 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 				sub_running_bw(dl_se, dl_rq);
 
 			if (!dl_task || READ_ONCE(p->__state) == TASK_DEAD) {
-				struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
-
 				if (dl_task && READ_ONCE(p->__state) == TASK_DEAD)
 					sub_rq_bw(dl_se, &rq->dl);
-				raw_spin_lock(&dl_b->lock);
-				__dl_sub(dl_b, dl_se->dl_bw, dl_bw_cpus(task_cpu(p)));
-				raw_spin_unlock(&dl_b->lock);
+				dl_task_release_bw(p, task_cpu(p));
 				__dl_clear_params(dl_se);
 			}
 		}
@@ -551,8 +659,18 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 	}
 
 	dl_se->dl_non_contending = 1;
-	if (!dl_server(dl_se))
-		get_task_struct(dl_task_of(dl_se));
+	if (!dl_server(dl_se)) {
+		struct task_struct *p = dl_task_of(dl_se);
+
+		get_task_struct(p);
+		/*
+		 * A dying task keeps its bandwidth in the root domain of the
+		 * CPU it runs on. Record that CPU. switched_from_dl() records
+		 * a task that leaves SCHED_DEADLINE.
+		 */
+		if (READ_ONCE(p->__state) == TASK_DEAD)
+			dl_task_depart(p, task_cpu(p));
+	}
 
 	hrtimer_start(timer, ns_to_ktime(zerolag_time), HRTIMER_MODE_REL_HARD);
 }
@@ -2304,17 +2422,13 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 		goto no_task;
 
 	if (!dl_task(p) || READ_ONCE(p->__state) == TASK_DEAD) {
-		struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
-
 		if (READ_ONCE(p->__state) == TASK_DEAD && dl_se->dl_non_contending) {
 			sub_running_bw(&p->dl, dl_rq_of_se(&p->dl));
 			sub_rq_bw(&p->dl, dl_rq_of_se(&p->dl));
 			dl_se->dl_non_contending = 0;
 		}
 
-		raw_spin_lock(&dl_b->lock);
-		__dl_sub(dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
-		raw_spin_unlock(&dl_b->lock);
+		dl_task_release_bw(p, task_cpu(p));
 		__dl_clear_params(dl_se);
 
 		goto unlock;
@@ -3580,12 +3694,33 @@ void dl_add_task_root_domain(struct task_struct *p)
 	dl_get_task_effective_cpus(p, msk);
 	cpu = cpumask_first_and(cpu_active_mask, msk);
 	BUG_ON(cpu >= nr_cpu_ids);
+
+	raw_spin_lock(&dl_departed_lock);
+	/*
+	 * Skip a task whose dl_bw_gen is current. Either
+	 * dl_clear_root_domains() put it back as a departed task, and
+	 * priority inheritance boosted it into the class since. Or it died
+	 * since the rebuild started, and dl_task_release_bw() released its
+	 * bandwidth. A task that died since with its 0-lag time ahead is on
+	 * the departed list. Count it in the root domain of the CPU
+	 * recorded, if that CPU is active.
+	 */
+	if (p->dl.dl_bw_gen == dl_bw_gen)
+		goto unlock;
+	if (p->dl.dl_departed_cpu >= 0) {
+		cpu = p->dl.dl_departed_cpu;
+		if (!cpu_active(cpu))
+			goto unlock;
+	}
 	rq = cpu_rq(cpu);
 	dl_b = &rq->rd->dl_bw;
 
 	raw_spin_lock(&dl_b->lock);
 	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
 	raw_spin_unlock(&dl_b->lock);
+	p->dl.dl_bw_gen = dl_bw_gen;
+unlock:
+	raw_spin_unlock(&dl_departed_lock);
 	raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
 }
 
@@ -3643,9 +3778,51 @@ void dl_clear_root_domain(struct root_domain *rd)
 		dl_server_add_bw(rd, i);
 }
 
-void dl_clear_root_domain_cpu(int cpu)
+/*
+ * Clear every root domain before a rebuild of their accounting, and count
+ * the rebuild in dl_bw_gen. Put back the bandwidth of their servers. Put
+ * back the bandwidth of the tasks on dl_departed_list, which no cpuset
+ * holds as deadline tasks. Put each in the root domain of the CPU
+ * recorded for it, or drop it if that CPU is not active.
+ * dl_add_task_root_domain() then adds the deadline tasks of the cpusets.
+ */
+void dl_clear_root_domains(void)
 {
-	dl_clear_root_domain(cpu_rq(cpu)->rd);
+	struct sched_dl_entity *dl_se;
+	u64 cookie = ++dl_cookie;
+	struct dl_bw *dl_b;
+	int cpu;
+
+	guard(raw_spinlock_irqsave)(&dl_departed_lock);
+	dl_bw_gen++;
+	for_each_possible_cpu(cpu) {
+		if (!dl_bw_visited(cpu, cookie))
+			dl_clear_root_domain(cpu_rq(cpu)->rd);
+	}
+	list_for_each_entry(dl_se, &dl_departed_list, dl_departed_node) {
+		cpu = dl_se->dl_departed_cpu;
+		/*
+		 * Skip bandwidth that an earlier rebuild dropped. It is not
+		 * counted now, and its release removes nothing
+		 * (dl_task_release_bw()).
+		 */
+		if (dl_se->dl_bw_gen != dl_bw_gen - 1)
+			continue;
+		/*
+		 * Drop the bandwidth of a task whose CPU is inactive. A CPU
+		 * that goes offline is in the default root domain by then.
+		 * The root domain that counted the task cannot be found
+		 * from the recorded number. The release then removes
+		 * nothing, and no later rebuild restores it.
+		 */
+		if (!cpu_active(cpu))
+			continue;
+		dl_b = dl_bw_of(cpu);
+		raw_spin_lock(&dl_b->lock);
+		__dl_add(dl_b, dl_se->dl_bw, dl_bw_cpus(cpu));
+		raw_spin_unlock(&dl_b->lock);
+		dl_se->dl_bw_gen = dl_bw_gen;
+	}
 }
 
 static void switched_from_dl(struct rq *rq, struct task_struct *p)
@@ -3701,9 +3878,20 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 	 * We cannot use inactive_task_timer() to invoke sub_running_bw()
 	 * at the 0-lag time, because the task could have been migrated
 	 * while SCHED_OTHER in the meanwhile.
+	 *
+	 * For the same reason, the timer cannot take the task's bandwidth
+	 * from the root domain of the CPU the task is on by then. And a
+	 * rebuild of the root domains meanwhile would not find the task
+	 * among the deadline tasks. So record a CPU of the root domain that
+	 * keeps the bandwidth until the timer removes it (dl_task_depart()).
+	 * Test dl_non_contending: it tells that the timer is armed and its
+	 * handler has not run. hrtimer_active() stays true for a while after
+	 * the handler returns.
 	 */
-	if (p->dl.dl_non_contending)
+	if (p->dl.dl_non_contending) {
 		p->dl.dl_non_contending = 0;
+		dl_task_depart(p, task_cpu(p));
+	}
 
 	/*
 	 * Since this might be the only -deadline task on the rq,
@@ -3723,6 +3911,17 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 static void switched_to_dl(struct rq *rq, struct task_struct *p)
 {
 	cancel_inactive_timer(&p->dl);
+	/*
+	 * A task on the departed list gets here when priority inheritance
+	 * boosts it back into the class before its 0-lag time. (A policy change
+	 * took it off the list in sched_dl_overflow().) The inactive timer no
+	 * longer removes its bandwidth: the task does when it leaves the class
+	 * again. So take it off the list. The task keeps the CPU recorded. It
+	 * takes the bandwidth from the root domain of that CPU, even if it
+	 * moved to another root domain meanwhile.
+	 */
+	if (!list_empty(&p->dl.dl_departed_node))
+		dl_task_undepart(p);
 
 	/*
 	 * In case a task is setscheduled to SCHED_DEADLINE we need to keep
@@ -3837,12 +4036,6 @@ DEFINE_SCHED_CLASS(dl) = {
 #endif
 };
 
-/*
- * Used for dl_bw check and update, used under sched_rt_handler()::mutex and
- * sched_domains_mutex.
- */
-u64 dl_cookie;
-
 int sched_dl_global_validate(void)
 {
 	u64 runtime = global_rt_runtime();
@@ -3963,8 +4156,6 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 
 	if (dl_policy(policy) && !task_has_dl_policy(p) &&
 	    !__dl_overflow(dl_b, cap, 0, new_bw)) {
-		if (hrtimer_active(&p->dl.inactive_timer))
-			__dl_sub(dl_b, p->dl.dl_bw, cpus);
 		__dl_add(dl_b, new_bw, cpus);
 		err = 0;
 	} else if (dl_policy(policy) && task_has_dl_policy(p) &&
@@ -3990,6 +4181,19 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	}
 	raw_spin_unlock(&dl_b->lock);
 
+	/*
+	 * A task that comes back before its 0-lag time still has the
+	 * bandwidth it left with. The new bandwidth replaces it, so remove the
+	 * old one from the root domain that keeps it (dl_task_release_bw()).
+	 * No rebuild can run meanwhile: the caller holds cpuset_mutex.
+	 */
+	if (!err && dl_policy(policy) && !task_has_dl_policy(p)) {
+		lockdep_assert_cpuset_lock_held();
+		if (p->dl.dl_departed_cpu >= 0)
+			dl_task_release_bw(p, -1);
+		p->dl.dl_bw_gen = dl_bw_gen;
+	}
+
 	return err;
 }
 
@@ -4130,6 +4334,8 @@ void init_dl_entity(struct sched_dl_entity *dl_se)
 	init_dl_task_timer(dl_se);
 	init_dl_inactive_task_timer(dl_se);
 	__dl_clear_params(dl_se);
+	INIT_LIST_HEAD(&dl_se->dl_departed_node);
+	dl_se->dl_departed_cpu = -1;
 }
 
 bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 02/43] sched/deadline: Rebuild the root domains' accounting from the task list
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
  2026-11-27 14:35 ` [PATCH v12 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 03/43] sched/deadline: Record the root domain holding a task's bandwidth Mathieu Desnoyers
                   ` (32 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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, added to deadline_bw_test 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 this series found the wrong count, the exited tasks and the
zombie.

Fixes: f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 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(-)

diff --git a/include/linux/cpuset.h b/include/linux/cpuset.h
index 914983387e95..db1cc2fc0324 100644
--- a/include/linux/cpuset.h
+++ b/include/linux/cpuset.h
@@ -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)();
diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index bdf39ac1d43d..60be226699bb 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -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
diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index a284225f8dc9..2cfa770c2dcb 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -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)))
diff --git a/kernel/cgroup/cpuset-internal.h b/kernel/cgroup/cpuset-internal.h
index 1ba94ffaff9d..bf847953c78d 100644
--- a/kernel/cgroup/cpuset-internal.h
+++ b/kernel/cgroup/cpuset-internal.h
@@ -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;
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 4159abfbbbb5..7628cf77bdfd 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -225,20 +225,6 @@ struct tmpmasks {
 	cpumask_var_t new_cpus;		/* For update_cpumasks_hier() */
 };
 
-void inc_dl_tasks_cs(struct task_struct *p)
-{
-	struct cpuset *cs = task_cs(p);
-
-	atomic_inc(&cs->nr_deadline_tasks);
-}
-
-void dec_dl_tasks_cs(struct task_struct *p)
-{
-	struct cpuset *cs = task_cs(p);
-
-	atomic_dec(&cs->nr_deadline_tasks);
-}
-
 static inline bool is_partition_valid(const struct cpuset *cs)
 {
 	return cs->partition_root_state > 0;
@@ -965,54 +951,6 @@ static int generate_sched_domains(cpumask_var_t **domains,
 	return ndoms;
 }
 
-static void dl_update_tasks_root_domain(struct cpuset *cs)
-{
-	struct css_task_iter it;
-	struct task_struct *task;
-
-	if (atomic_read(&cs->nr_deadline_tasks) == 0)
-		return;
-
-	css_task_iter_start(&cs->css, 0, &it);
-
-	while ((task = css_task_iter_next(&it)))
-		dl_add_task_root_domain(task);
-
-	css_task_iter_end(&it);
-}
-
-void dl_rebuild_rd_accounting(void)
-{
-	struct cpuset *cs = NULL;
-	struct cgroup_subsys_state *pos_css;
-
-	lockdep_assert_cpuset_lock_held();
-	lockdep_assert_cpus_held();
-	lockdep_assert_held(&sched_domains_mutex);
-
-	dl_clear_root_domains();
-
-	rcu_read_lock();
-
-	cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
-
-		if (cpumask_empty(cs->effective_cpus)) {
-			pos_css = css_rightmost_descendant(pos_css);
-			continue;
-		}
-
-		css_get(&cs->css);
-
-		rcu_read_unlock();
-
-		dl_update_tasks_root_domain(cs);
-
-		rcu_read_lock();
-		css_put(&cs->css);
-	}
-	rcu_read_unlock();
-}
-
 /*
  * Rebuild scheduler domains.
  *
@@ -3181,9 +3119,7 @@ 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)
-				atomic_add(cs->nr_migrate_dl_tasks, &cs->nr_deadline_tasks);
-			else if (cs->dl_bw_cpu >= 0) /* && cancel */
+			if (cancel && cs->dl_bw_cpu >= 0)
 				dl_bw_free(cs->dl_bw_cpu, cs->sum_migrate_dl_bw);
 			cs->nr_migrate_dl_tasks = 0;
 			cs->sum_migrate_dl_bw = 0;
@@ -3272,7 +3208,6 @@ static int cpuset_can_attach(struct cgroup_taskset *tset)
 			 * contribute to sum_migrate_dl_bw.
 			 */
 			cs->nr_migrate_dl_tasks++;
-			oldcs->nr_migrate_dl_tasks--;
 			if (dl_task_needs_bw_move(task, cs->effective_cpus))
 				cs->sum_migrate_dl_bw += task->dl.dl_bw;
 		}
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index c2b5b5fdf1b9..d1a2ae9ab75f 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -230,10 +230,10 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
  * The timer holds a reference to it.
  *
  * A rebuild of the root domains' accounting (dl_clear_root_domains() and
- * dl_add_task_root_domain()) does not find such a task among the deadline
- * tasks of the cpusets. So dl_departed_list holds these tasks, from their
- * departure to their timer. The rebuild puts their bandwidth back in the
- * root domain of the CPU each one was on when it left.
+ * dl_add_task_root_domain()) does not count such a task as a deadline
+ * task. So dl_departed_list holds these tasks, from their departure to
+ * their timer. The rebuild puts their bandwidth back in the root domain
+ * of the CPU each one was on when it left.
  *
  * dl_bw_gen numbers the rebuilds of the accounting: how many times the
  * root domains were wiped and reconstructed (dl_clear_root_domains()
@@ -241,7 +241,7 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
  * state, counted or settled. That number dates the state:
  *
  *  - Current: the bandwidth is counted, or a release settled it since
- *    the rebuild began. A release subtracts; the walk of the cpusets
+ *    the rebuild began. A release subtracts; the walk of the task list
  *    skips.
  *  - One behind: the clear that just ran wiped it. The rebuild puts
  *    it back.
@@ -254,8 +254,8 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
  *
  * A rebuild drops the bandwidth when the CPU recorded is no longer
  * active. It also drops the bandwidth of a task that dies while the
- * rebuild runs. The cpuset walk skips that task, and it was not dead yet
- * when the list was put back.
+ * rebuild runs. The walk of the task list does not find that task, and
+ * it was not dead yet when the list was put back.
  *
  * dl_departed_lock protects the list and both counts. Take it with
  * interrupts disabled, under the task's rq lock or pi_lock or in the
@@ -265,6 +265,22 @@ static LIST_HEAD(dl_departed_list);
 static DEFINE_RAW_SPINLOCK(dl_departed_lock);
 static unsigned int dl_bw_gen;
 
+/*
+ * The number of tasks with a bandwidth: those whose dl_bw is not 0. A
+ * special entity and a server are not counted. __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, a rebuild of the
+ * accounting has no task to count, and does not walk the task list.
+ */
+static atomic_t dl_nr_bw_tasks;
+
+/* Return true if @dl_se is a task that holds a bandwidth. */
+static inline bool dl_se_holds_bw(struct sched_dl_entity *dl_se)
+{
+	return dl_se->dl_bw && !dl_se->dl_server &&
+	       !(dl_se->flags & SCHED_FLAG_SUGOV);
+}
+
 /*
  * Put @p on dl_departed_list with @cpu, a CPU of the root domain that
  * keeps its bandwidth. @p leaves SCHED_DEADLINE, or dies, before its
@@ -3675,7 +3691,7 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
 	cpuset_cpus_allowed_locked(p, cpus);
 }
 
-/* The caller should hold cpuset_mutex */
+/* From dl_rebuild_rd_accounting(), under the locks it asserts. */
 void dl_add_task_root_domain(struct task_struct *p)
 {
 	struct rq_flags rf;
@@ -3685,7 +3701,13 @@ void dl_add_task_root_domain(struct task_struct *p)
 	struct cpumask *msk;
 
 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
-	if (!dl_task(p) || dl_entity_is_special(&p->dl)) {
+	/*
+	 * Count nothing for a special entity, or for a task with no
+	 * bandwidth. The walk of the task list also finds exited tasks. An
+	 * exited task whose bandwidth went with its parameters has a dl_bw
+	 * of 0.
+	 */
+	if (!dl_task(p) || dl_entity_is_special(&p->dl) || !p->dl.dl_bw) {
 		raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
 		return;
 	}
@@ -3708,6 +3730,14 @@ void dl_add_task_root_domain(struct task_struct *p)
 	if (p->dl.dl_bw_gen == dl_bw_gen)
 		goto unlock;
 	if (p->dl.dl_departed_cpu >= 0) {
+		/*
+		 * The walk also finds a dead task that departed before an
+		 * earlier rebuild, if it is not reaped yet. If that rebuild
+		 * dropped its bandwidth, dl_clear_root_domains() skipped it,
+		 * and its release removes nothing. Skip it here too.
+		 */
+		if (p->dl.dl_bw_gen != dl_bw_gen - 1)
+			goto unlock;
 		cpu = p->dl.dl_departed_cpu;
 		if (!cpu_active(cpu))
 			goto unlock;
@@ -3778,13 +3808,80 @@ void dl_clear_root_domain(struct root_domain *rd)
 		dl_server_add_bw(rd, i);
 }
 
+#ifndef CONFIG_CPUSETS
+/*
+ * With cpusets, cpuset_mutex keeps an admission of bandwidth from running
+ * against a rebuild of the accounting. __sched_setscheduler() takes it for
+ * every change of or into SCHED_DEADLINE. The callers of
+ * partition_sched_domains() hold it from the attachment of the new root
+ * domains to the rebuild. Without cpusets, cpuset_lock() is a stub, and
+ * this mutex takes its place in both.
+ */
+static DEFINE_MUTEX(dl_accounting_mutex);
+
+void dl_accounting_lock(void)
+{
+	mutex_lock(&dl_accounting_mutex);
+}
+
+void dl_accounting_unlock(void)
+{
+	mutex_unlock(&dl_accounting_mutex);
+}
+
+void lockdep_assert_dl_accounting_held(void)
+{
+	lockdep_assert_held(&dl_accounting_mutex);
+}
+#endif /* !CONFIG_CPUSETS */
+
+/*
+ * Rebuild the root domains' accounting. Clear it, then walk all tasks and
+ * count each deadline task again. The caller holds the locks that this
+ * function asserts.
+ */
+void dl_rebuild_rd_accounting(void)
+{
+	struct task_struct *g, *p;
+
+	lockdep_assert_cpus_held();
+	lockdep_assert_held(&sched_domains_mutex);
+	lockdep_assert_cpuset_lock_held();
+	lockdep_assert_dl_accounting_held();
+
+	dl_clear_root_domains();
+
+	/*
+	 * Without a task that holds a bandwidth, there is nothing to count.
+	 * The walk would still visit every thread of the system. A CPU
+	 * that goes offline or comes back runs a rebuild, so a suspend and
+	 * a resume run one for each CPU. A task gets a bandwidth under the
+	 * locks this rebuild holds, so the count cannot leave 0 meanwhile.
+	 */
+	if (!atomic_read(&dl_nr_bw_tasks))
+		return;
+
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, p) {
+		/*
+		 * Test the class without the task's locks, and take them only
+		 * for a deadline task. A task enters the class under the locks
+		 * this rebuild holds, or by a boost. A boost brings no
+		 * bandwidth of its own to count.
+		 */
+		if (dl_task(p))
+			dl_add_task_root_domain(p);
+	}
+	read_unlock(&tasklist_lock);
+}
+
 /*
  * Clear every root domain before a rebuild of their accounting, and count
  * the rebuild in dl_bw_gen. Put back the bandwidth of their servers. Put
- * back the bandwidth of the tasks on dl_departed_list, which no cpuset
- * holds as deadline tasks. Put each in the root domain of the CPU
- * recorded for it, or drop it if that CPU is not active.
- * dl_add_task_root_domain() then adds the deadline tasks of the cpusets.
+ * back the bandwidth of the tasks on dl_departed_list, which the walk of
+ * the deadline tasks does not count. Put each in the root domain of the
+ * CPU recorded for it, or drop it if that CPU is not active.
+ * dl_add_task_root_domain() then adds the deadline tasks.
  */
 void dl_clear_root_domains(void)
 {
@@ -3848,12 +3945,6 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 		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).
-	 */
-	dec_dl_tasks_cs(p);
-
 	if (!task_on_rq_queued(p)) {
 		/*
 		 * Inactive timer is armed. However, p is leaving DEADLINE and
@@ -3923,12 +4014,6 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 	if (!list_empty(&p->dl.dl_departed_node))
 		dl_task_undepart(p);
 
-	/*
-	 * In case a task is setscheduled to SCHED_DEADLINE we need to keep
-	 * track of that on its cpuset (for correct bandwidth tracking).
-	 */
-	inc_dl_tasks_cs(p);
-
 	/* If p is not queued we will update its parameters at next wakeup. */
 	if (!task_on_rq_queued(p)) {
 		add_rq_bw(&p->dl, &rq->dl);
@@ -4185,10 +4270,12 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	 * A task that comes back before its 0-lag time still has the
 	 * bandwidth it left with. The new bandwidth replaces it, so remove the
 	 * old one from the root domain that keeps it (dl_task_release_bw()).
-	 * No rebuild can run meanwhile: the caller holds cpuset_mutex.
+	 * No rebuild can run meanwhile: the caller holds cpuset_mutex, or
+	 * dl_accounting_mutex without cpusets.
 	 */
 	if (!err && dl_policy(policy) && !task_has_dl_policy(p)) {
 		lockdep_assert_cpuset_lock_held();
+		lockdep_assert_dl_accounting_held();
 		if (p->dl.dl_departed_cpu >= 0)
 			dl_task_release_bw(p, -1);
 		p->dl.dl_bw_gen = dl_bw_gen;
@@ -4208,12 +4295,18 @@ 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;
+	bool held;
 
+	held = dl_se_holds_bw(dl_se);
 	dl_se->dl_runtime = attr->sched_runtime;
 	dl_se->dl_deadline = attr->sched_deadline;
 	dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
 	dl_se->flags = attr->sched_flags & SCHED_DL_FLAGS;
 	dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
+	if (dl_se_holds_bw(dl_se) && !held)
+		atomic_inc(&dl_nr_bw_tasks);
+	else if (!dl_se_holds_bw(dl_se) && held)
+		atomic_dec(&dl_nr_bw_tasks);
 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
 }
 
@@ -4303,6 +4396,9 @@ bool __checkparam_dl(const struct sched_attr *attr)
  */
 static void __dl_clear_params(struct sched_dl_entity *dl_se)
 {
+	if (dl_se_holds_bw(dl_se))
+		WARN_ON_ONCE(atomic_dec_return(&dl_nr_bw_tasks) < 0);
+
 	dl_se->dl_runtime		= 0;
 	dl_se->dl_deadline		= 0;
 	dl_se->dl_period		= 0;
@@ -4333,6 +4429,12 @@ void init_dl_entity(struct sched_dl_entity *dl_se)
 	RB_CLEAR_NODE(&dl_se->rb_node);
 	init_dl_task_timer(dl_se);
 	init_dl_inactive_task_timer(dl_se);
+	/*
+	 * A new task has a copy of the entity of its parent. That copy
+	 * holds no bandwidth, and dl_nr_bw_tasks does not count it. Clear
+	 * dl_bw first, so that __dl_clear_params() leaves the count alone.
+	 */
+	dl_se->dl_bw = 0;
 	__dl_clear_params(dl_se);
 	INIT_LIST_HEAD(&dl_se->dl_departed_node);
 	dl_se->dl_departed_cpu = -1;
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 5983232476a9..96a5f0a7adbc 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -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;
 }
 
diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c
index 9d3a1b8dd393..35e56a45c238 100644
--- a/kernel/sched/topology.c
+++ b/kernel/sched/topology.c
@@ -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();
 }
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 03/43] sched/deadline: Record the root domain holding a task's bandwidth
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
  2026-11-27 14:35 ` [PATCH v12 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 02/43] sched/deadline: Rebuild the root domains' accounting from the task list Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting Mathieu Desnoyers
                   ` (31 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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

First case: a sleeping task moved to a partition and back.
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:

  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.

Second case: a sleeping task whose CPU goes offline. It 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.

Fix this by recording with the bandwidth a CPU of the root domain that
counts it, in the new field dl_bw_cpu. It replaces dl_departed_cpu.
Each site that counts the bandwidth sets the record. Each release or
move reads it, and the release clears it.

These rules keep the record right:
- If dl_bw_gen shows that a rebuild dropped the bandwidth, nothing is
  taken back.
- A move skips a bandwidth of 0, and does not update its record. The
  admission tests treat such a task like one that enters the class
  (move_zero_bw).
- 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.

A move now also leaves out a sugov kthread, and a task boosted into the
class with no bandwidth of its own. The rebuild leaves them out
already. Before, a move would take their bandwidth from a root domain
that never held it.

The admission tests of sched_setattr() and sched_setaffinity() now use
the record. This changes their result in these cases:
- sched_setattr() on a deadline task moved asleep into a partition
  failed with EPERM until the task woke up (move_asleep_setattr).
- sched_setattr() that makes a sleeping task a deadline task tested the
  CPU the task is on. It now tests an active CPU of the task's mask, if
  that CPU is not one. Before, it failed with EPERM after a move into a
  partition (move_asleep_fair_setattr). It also failed with EBUSY on a
  CPU that went offline, when the default root domain had no active CPU
  (hotplug_asleep_setattr).
- sched_setaffinity() tested the root domain of the CPU the task is on.
  A new mask could then take a task moved asleep out of the root domain
  that counts it (affinity_moved_asleep).

The first case was reproduced on v7.4-rc2. The second case also needs
"sched/deadline: Release the bandwidth of a task that leaves the class
asleep", of the first series. Before it, nothing released 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, A then admitted 63 tasks of 10% where it had room for 66. This
held in each of 3 guests, with the CPU still offline.

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")
Reported-by: Weiheng Qiu <weihengqiuu@gmail.com>
Closes: https://lore.kernel.org/all/14508cb2-805f-41ac-9f6b-bfd7c3d7cb1c@gmail.com/
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
Link: https://lore.kernel.org/all/20261103-b4-sched-dl-bw-fixes-v1-1-dd761fe005b4@redhat.com/
---
 include/linux/sched.h   |  10 +-
 kernel/sched/deadline.c | 275 +++++++++++++++++++++++++++++-----------
 kernel/sched/syscalls.c |  23 +++-
 3 files changed, 226 insertions(+), 82 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index b6d4e365afee..4098b4e0f67e 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -744,15 +744,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;
 
 	/*
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index d1a2ae9ab75f..28fa8f0bc81b 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -233,7 +233,7 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
  * dl_add_task_root_domain()) does not count such a task as a deadline
  * task. So dl_departed_list holds these tasks, from their departure to
  * their timer. The rebuild puts their bandwidth back in the root domain
- * of the CPU each one was on when it left.
+ * of the CPU recorded with each task's bandwidth.
  *
  * dl_bw_gen numbers the rebuilds of the accounting: how many times the
  * root domains were wiped and reconstructed (dl_clear_root_domains()
@@ -255,7 +255,10 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
  * A rebuild drops the bandwidth when the CPU recorded is no longer
  * active. It also drops the bandwidth of a task that dies while the
  * rebuild runs. The walk of the task list does not find that task, and
- * it was not dead yet when the list was put back.
+ * it was not dead yet when the list was put back. The same happens to a
+ * task that priority inheritance deboosts while the rebuild runs. It was
+ * in the class when the list was put back, and out of it when the walk
+ * reaches it.
  *
  * dl_departed_lock protects the list and both counts. Take it with
  * interrupts disabled, under the task's rq lock or pi_lock or in the
@@ -282,66 +285,75 @@ static inline bool dl_se_holds_bw(struct sched_dl_entity *dl_se)
 }
 
 /*
- * Put @p on dl_departed_list with @cpu, a CPU of the root domain that
+ * Put @p on dl_departed_list. The root domain of the CPU recorded with it
  * keeps its bandwidth. @p leaves SCHED_DEADLINE, or dies, before its
- * 0-lag time. Do nothing if @p is on the list already. Keep the CPU
- * recorded if @p has one: priority inheritance boosted @p back into the
- * class and its boost ends. The caller holds the rq lock of @p.
+ * 0-lag time. Do nothing if @p is on the list already. The caller holds
+ * the rq lock of @p.
  */
-static void dl_task_depart(struct task_struct *p, int cpu)
+static void dl_task_depart(struct task_struct *p)
 {
 	struct sched_dl_entity *dl_se = &p->dl;
+	int cpu = task_cpu(p);
 
 	lockdep_assert_irqs_disabled();
 	guard(raw_spinlock)(&dl_departed_lock);
-	if (!list_empty(&dl_se->dl_departed_node))
+	if (!list_empty(&dl_se->dl_departed_node) || dl_se->dl_bw_cpu < 0)
 		return;
-	if (dl_se->dl_departed_cpu < 0)
-		dl_se->dl_departed_cpu = cpu;
+	/*
+	 * A rebuild drops the bandwidth if the CPU recorded is not active.
+	 * That CPU can be one that @p left long ago. Record the CPU @p
+	 * departs from instead, if it is active and the same root domain
+	 * counts the bandwidth.
+	 */
+	if (dl_se->dl_bw_gen == dl_bw_gen && cpu_active(cpu) &&
+	    cpu_rq(cpu)->rd == cpu_rq(dl_se->dl_bw_cpu)->rd)
+		dl_se->dl_bw_cpu = cpu;
 	list_add(&dl_se->dl_departed_node, &dl_departed_list);
 }
 
 /*
- * Take @p off dl_departed_list. Priority inheritance boosts @p back into
- * the deadline class. Keep the CPU recorded: its root domain still counts
- * the bandwidth, wherever @p runs now. The caller holds the rq lock of
- * @p.
+ * Take @p off dl_departed_list. @p comes back to the deadline class, and
+ * its bandwidth is that of a deadline task again. The caller holds the rq
+ * lock of @p.
  */
 static void dl_task_undepart(struct task_struct *p)
 {
 	struct sched_dl_entity *dl_se = &p->dl;
 
 	lockdep_assert_irqs_disabled();
+	if (list_empty(&dl_se->dl_departed_node))
+		return;
 	guard(raw_spinlock)(&dl_departed_lock);
 	list_del_init(&dl_se->dl_departed_node);
 }
 
 /*
  * Remove the bandwidth of @p from the root domain that counts it. That is
- * the root domain of the CPU recorded when @p departed, or else of @cpu.
- * Clear the record. Take @p off dl_departed_list. Remove nothing if a
- * rebuild dropped the bandwidth since it was counted. Then record the
- * current dl_bw_gen in @p, so that a rebuild in progress does not count it
- * again. The caller holds the rq lock of @p.
+ * the root domain of the CPU recorded with @p. Clear the record.
+ * Take @p off dl_departed_list. Remove nothing if a rebuild dropped the
+ * bandwidth since it was counted. Then record the current dl_bw_gen in
+ * @p, so that a rebuild in progress does not count it again. The caller
+ * holds the rq lock of @p.
  */
-static void dl_task_release_bw(struct task_struct *p, int cpu)
+static void dl_task_release_bw(struct task_struct *p)
 {
 	struct sched_dl_entity *dl_se = &p->dl;
 	struct dl_bw *dl_b;
+	int cpu;
 
 	lockdep_assert_irqs_disabled();
 	guard(raw_spinlock)(&dl_departed_lock);
-	if (dl_se->dl_departed_cpu >= 0) {
-		cpu = dl_se->dl_departed_cpu;
-		dl_se->dl_departed_cpu = -1;
+	if (!list_empty(&dl_se->dl_departed_node))
 		list_del_init(&dl_se->dl_departed_node);
-	}
-	if (dl_se->dl_bw_gen == dl_bw_gen) {
+	cpu = dl_se->dl_bw_cpu;
+	WARN_ON_ONCE(dl_se->dl_bw && cpu < 0);
+	if (cpu >= 0 && dl_se->dl_bw_gen == dl_bw_gen) {
 		dl_b = dl_bw_of(cpu);
 		raw_spin_lock(&dl_b->lock);
 		__dl_sub(dl_b, dl_se->dl_bw, dl_bw_cpus(cpu));
 		raw_spin_unlock(&dl_b->lock);
 	}
+	dl_se->dl_bw_cpu = -1;
 	dl_se->dl_bw_gen = dl_bw_gen;
 }
 
@@ -504,6 +516,7 @@ static void dl_change_utilization(struct task_struct *p, u64 new_bw)
 }
 
 static void __dl_clear_params(struct sched_dl_entity *dl_se);
+static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
 
 /*
  * Return the time from now to the 0-lag time of @dl_se, or a negative
@@ -666,7 +679,7 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 			if (!dl_task || READ_ONCE(p->__state) == TASK_DEAD) {
 				if (dl_task && READ_ONCE(p->__state) == TASK_DEAD)
 					sub_rq_bw(dl_se, &rq->dl);
-				dl_task_release_bw(p, task_cpu(p));
+				dl_task_release_bw(p);
 				__dl_clear_params(dl_se);
 			}
 		}
@@ -680,12 +693,13 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 
 		get_task_struct(p);
 		/*
-		 * A dying task keeps its bandwidth in the root domain of the
-		 * CPU it runs on. Record that CPU. switched_from_dl() records
-		 * a task that leaves SCHED_DEADLINE.
+		 * A dying task keeps its bandwidth until its 0-lag time. Put
+		 * it on the departed list. The CPU recorded with its bandwidth
+		 * tells the root domain that counts it. switched_from_dl() does
+		 * the same for a task that leaves SCHED_DEADLINE.
 		 */
 		if (READ_ONCE(p->__state) == TASK_DEAD)
-			dl_task_depart(p, task_cpu(p));
+			dl_task_depart(p);
 	}
 
 	hrtimer_start(timer, ns_to_ktime(zerolag_time), HRTIMER_MODE_REL_HARD);
@@ -923,19 +937,31 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 	}
 
 	/*
-	 * And we finally need to fix up root_domain(s) bandwidth accounting,
-	 * since p is still hanging out in the old (now moved to default) root
-	 * domain.
+	 * And we finally need to fix up root_domain(s) bandwidth accounting.
+	 * The bandwidth of @p is counted in the root domain of the CPU
+	 * recorded with it. That is not the root domain of @rq if @p was
+	 * moved to another cpuset while it was not running. If a rebuild
+	 * dropped the bandwidth, there is nothing to move: the next rebuild
+	 * counts it.
 	 */
-	dl_b = &rq->rd->dl_bw;
-	raw_spin_lock(&dl_b->lock);
-	__dl_sub(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
-	raw_spin_unlock(&dl_b->lock);
+	scoped_guard (raw_spinlock, &dl_departed_lock) {
+		if (p->dl.dl_bw_gen == dl_bw_gen) {
+			struct rq *src_rq = cpu_rq(dl_task_root_domain_cpu(p));
 
-	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);
+			dl_b = &src_rq->rd->dl_bw;
+			raw_spin_lock(&dl_b->lock);
+			__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);
+		}
+		p->dl.dl_bw_cpu = later_rq->cpu;
+	}
 
 	set_task_cpu(p, later_rq->cpu);
 	double_unlock_balance(later_rq, rq);
@@ -2444,7 +2470,7 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 			dl_se->dl_non_contending = 0;
 		}
 
-		dl_task_release_bw(p, task_cpu(p));
+		dl_task_release_bw(p);
 		__dl_clear_params(dl_se);
 
 		goto unlock;
@@ -3592,14 +3618,56 @@ static void task_woken_dl(struct rq *rq, struct task_struct *p)
 	}
 }
 
+/*
+ * Return a CPU of the root domain that counts the bandwidth of @p: the
+ * CPU recorded with it. Without a record, no root domain counts that
+ * bandwidth. Return the CPU @p is on then. Read the record once:
+ * cpuset_can_attach() calls this through dl_task_needs_bw_move() without
+ * the rq lock of @p.
+ */
+static unsigned int dl_task_root_domain_cpu(struct task_struct *p)
+{
+	int cpu = READ_ONCE(p->dl.dl_bw_cpu);
+
+	if (cpu < 0)
+		return task_cpu(p);
+	return cpu;
+}
+
+/*
+ * Return a CPU of the root domain that admits new parameters for @p.
+ * sched_dl_overflow() picks the same one. It is the CPU recorded with
+ * the bandwidth of a deadline task, if that bandwidth is counted. Else it
+ * is the CPU @p is on. A task moved asleep to another cpuset is still on
+ * a CPU it can no longer use. A task asleep on a CPU that went offline
+ * is still on that CPU, now in the default root domain. In both cases,
+ * take an active CPU of the mask of @p. The task runs in that root
+ * domain once it wakes. The caller holds the rq lock of @p. To read the
+ * record, it also holds cpuset_mutex, or dl_accounting_mutex without
+ * cpusets.
+ */
+static unsigned int dl_task_admit_cpu(struct task_struct *p)
+{
+	unsigned int cpu;
+
+	if (task_has_dl_policy(p) && p->dl.dl_bw && p->dl.dl_bw_cpu >= 0 &&
+	    p->dl.dl_bw_gen == dl_bw_gen)
+		return p->dl.dl_bw_cpu;
+	cpu = task_cpu(p);
+	if (!cpumask_test_cpu(cpu, &p->cpus_mask) || !cpu_active(cpu)) {
+		unsigned int other = cpumask_first_and(cpu_active_mask, &p->cpus_mask);
+
+		if (other < nr_cpu_ids)
+			cpu = other;
+	}
+	return cpu;
+}
+
 static void set_cpus_allowed_dl(struct task_struct *p,
 				struct affinity_context *ctx)
 {
-	struct rq *rq;
-
 	WARN_ON_ONCE(!dl_task(p));
 
-	rq = task_rq(p);
 	/*
 	 * Migrating a SCHED_DEADLINE task between exclusive
 	 * cpusets (different root_domains) entails a bandwidth
@@ -3607,17 +3675,31 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 	 * domain (see cpuset_can_attach()).
 	 */
 	if (dl_task_needs_bw_move(p, ctx->new_mask)) {
-		struct dl_bw *src_dl_b;
+		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;
 
-		src_dl_b = dl_bw_of(cpu_of(rq));
 		/*
 		 * We now free resources of the root_domain we are migrating
 		 * off. In the worst case, sched_setattr() may temporary fail
-		 * until we complete the update.
+		 * until we complete the update. A rebuild that dropped the
+		 * bandwidth of @p leaves nothing to free. dl_departed_lock
+		 * keeps a rebuild from changing dl_bw_gen meanwhile.
 		 */
-		raw_spin_lock(&src_dl_b->lock);
-		__dl_sub(src_dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
-		raw_spin_unlock(&src_dl_b->lock);
+		guard(raw_spinlock)(&dl_departed_lock);
+		if (p->dl.dl_bw_gen == dl_bw_gen) {
+			raw_spin_lock(&src_dl_b->lock);
+			__dl_sub(src_dl_b, p->dl.dl_bw, dl_bw_cpus(src_cpu));
+			raw_spin_unlock(&src_dl_b->lock);
+		}
+
+		/*
+		 * cpuset_can_attach() made room in the root domain of the new
+		 * mask. That root domain counts the bandwidth from now on.
+		 */
+		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;
 	}
 
 	set_cpus_allowed_common(p, ctx);
@@ -3626,10 +3708,18 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 bool dl_task_needs_bw_move(struct task_struct *p,
 			   const struct cpumask *new_mask)
 {
-	if (!dl_task(p))
+	unsigned int cpu;
+
+	/*
+	 * Nothing to move for a special entity, or for a task boosted into
+	 * the class with no bandwidth of its own. No root domain counts
+	 * 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 !cpumask_intersects(task_rq(p)->rd->span, new_mask);
+	cpu = dl_task_root_domain_cpu(p);
+	return !cpumask_intersects(cpu_rq(cpu)->rd->span, new_mask);
 }
 
 /* Assumes rq->lock is held */
@@ -3705,7 +3795,8 @@ void dl_add_task_root_domain(struct task_struct *p)
 	 * Count nothing for a special entity, or for a task with no
 	 * bandwidth. The walk of the task list also finds exited tasks. An
 	 * exited task whose bandwidth went with its parameters has a dl_bw
-	 * of 0.
+	 * of 0. So has a task boosted into the class with no bandwidth of
+	 * its own, which gets no record.
 	 */
 	if (!dl_task(p) || dl_entity_is_special(&p->dl) || !p->dl.dl_bw) {
 		raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
@@ -3729,7 +3820,9 @@ void dl_add_task_root_domain(struct task_struct *p)
 	 */
 	if (p->dl.dl_bw_gen == dl_bw_gen)
 		goto unlock;
-	if (p->dl.dl_departed_cpu >= 0) {
+	if (!list_empty(&p->dl.dl_departed_node)) {
+		int recorded = p->dl.dl_bw_cpu;
+
 		/*
 		 * The walk also finds a dead task that departed before an
 		 * earlier rebuild, if it is not reaped yet. If that rebuild
@@ -3738,9 +3831,9 @@ void dl_add_task_root_domain(struct task_struct *p)
 		 */
 		if (p->dl.dl_bw_gen != dl_bw_gen - 1)
 			goto unlock;
-		cpu = p->dl.dl_departed_cpu;
-		if (!cpu_active(cpu))
+		if (recorded < 0 || !cpu_active(recorded))
 			goto unlock;
+		cpu = recorded;
 	}
 	rq = cpu_rq(cpu);
 	dl_b = &rq->rd->dl_bw;
@@ -3748,6 +3841,7 @@ void dl_add_task_root_domain(struct task_struct *p)
 	raw_spin_lock(&dl_b->lock);
 	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
 	raw_spin_unlock(&dl_b->lock);
+	p->dl.dl_bw_cpu = cpu;
 	p->dl.dl_bw_gen = dl_bw_gen;
 unlock:
 	raw_spin_unlock(&dl_departed_lock);
@@ -3897,7 +3991,7 @@ void dl_clear_root_domains(void)
 			dl_clear_root_domain(cpu_rq(cpu)->rd);
 	}
 	list_for_each_entry(dl_se, &dl_departed_list, dl_departed_node) {
-		cpu = dl_se->dl_departed_cpu;
+		cpu = dl_se->dl_bw_cpu;
 		/*
 		 * Skip bandwidth that an earlier rebuild dropped. It is not
 		 * counted now, and its release removes nothing
@@ -3912,7 +4006,7 @@ void dl_clear_root_domains(void)
 		 * from the recorded number. The release then removes
 		 * nothing, and no later rebuild restores it.
 		 */
-		if (!cpu_active(cpu))
+		if (cpu < 0 || !cpu_active(cpu))
 			continue;
 		dl_b = dl_bw_of(cpu);
 		raw_spin_lock(&dl_b->lock);
@@ -3973,15 +4067,16 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 	 * For the same reason, the timer cannot take the task's bandwidth
 	 * from the root domain of the CPU the task is on by then. And a
 	 * rebuild of the root domains meanwhile would not find the task
-	 * among the deadline tasks. So record a CPU of the root domain that
-	 * keeps the bandwidth until the timer removes it (dl_task_depart()).
+	 * among the deadline tasks. So put the task on the departed list
+	 * until the timer removes the bandwidth (dl_task_depart()). The CPU
+	 * recorded with the bandwidth tells the root domain that keeps it.
 	 * Test dl_non_contending: it tells that the timer is armed and its
 	 * handler has not run. hrtimer_active() stays true for a while after
 	 * the handler returns.
 	 */
 	if (p->dl.dl_non_contending) {
 		p->dl.dl_non_contending = 0;
-		dl_task_depart(p, task_cpu(p));
+		dl_task_depart(p);
 	}
 
 	/*
@@ -4009,10 +4104,11 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 	 * longer removes its bandwidth: the task does when it leaves the class
 	 * again. So take it off the list. The task keeps the CPU recorded. It
 	 * takes the bandwidth from the root domain of that CPU, even if it
-	 * moved to another root domain meanwhile.
+	 * moved to another root domain meanwhile. A rebuild while it is
+	 * boosted counts it like any deadline task, and records the CPU it
+	 * picks.
 	 */
-	if (!list_empty(&p->dl.dl_departed_node))
-		dl_task_undepart(p);
+	dl_task_undepart(p);
 
 	/* If p is not queued we will update its parameters at next wakeup. */
 	if (!task_on_rq_queued(p)) {
@@ -4219,9 +4315,10 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	u64 period = attr->sched_period ?: attr->sched_deadline;
 	u64 runtime = attr->sched_runtime;
 	u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
-	int cpus, err = -1, cpu = task_cpu(p);
-	struct dl_bw *dl_b = dl_bw_of(cpu);
+	int cpus, err = -1, cpu;
+	struct dl_bw *dl_b;
 	unsigned long cap;
+	bool counted;
 
 	if (attr->sched_flags & SCHED_FLAG_SUGOV)
 		return 0;
@@ -4230,6 +4327,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 = dl_task_admit_cpu(p);
+	dl_b = dl_bw_of(cpu);
+
 	/*
 	 * Either if a task, enters, leave, or stays -deadline but changes
 	 * its parameters, we may need to update accordingly the total
@@ -4244,7 +4358,8 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 		__dl_add(dl_b, new_bw, cpus);
 		err = 0;
 	} else if (dl_policy(policy) && task_has_dl_policy(p) &&
-		   !__dl_overflow(dl_b, cap, p->dl.dl_bw, new_bw)) {
+		   !__dl_overflow(dl_b, cap, counted ? p->dl.dl_bw : 0,
+				  new_bw)) {
 		/*
 		 * XXX this is slightly incorrect: when the task
 		 * utilization decreases, we should delay the total
@@ -4252,7 +4367,8 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 		 * But this would require to set the task's "inactive
 		 * timer" when the task is not inactive.
 		 */
-		__dl_sub(dl_b, p->dl.dl_bw, cpus);
+		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;
@@ -4273,11 +4389,20 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	 * No rebuild can run meanwhile: the caller holds cpuset_mutex, or
 	 * dl_accounting_mutex without cpusets.
 	 */
-	if (!err && dl_policy(policy) && !task_has_dl_policy(p)) {
-		lockdep_assert_cpuset_lock_held();
-		lockdep_assert_dl_accounting_held();
-		if (p->dl.dl_departed_cpu >= 0)
-			dl_task_release_bw(p, -1);
+	if (!err && dl_policy(policy)) {
+		if (!task_has_dl_policy(p)) {
+			lockdep_assert_cpuset_lock_held();
+			lockdep_assert_dl_accounting_held();
+			/*
+			 * The new bandwidth replaces any the task still has
+			 * counted. That one may be on the departed list, or
+			 * taken off it by a boost into the class
+			 * (switched_to_dl()). The record says where it is.
+			 */
+			if (p->dl.dl_bw_cpu >= 0)
+				dl_task_release_bw(p);
+		}
+		p->dl.dl_bw_cpu = cpu;
 		p->dl.dl_bw_gen = dl_bw_gen;
 	}
 
@@ -4436,8 +4561,8 @@ void init_dl_entity(struct sched_dl_entity *dl_se)
 	 */
 	dl_se->dl_bw = 0;
 	__dl_clear_params(dl_se);
+	dl_se->dl_bw_cpu = -1;
 	INIT_LIST_HEAD(&dl_se->dl_departed_node);
-	dl_se->dl_departed_cpu = -1;
 }
 
 bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr)
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 96a5f0a7adbc..41c568fc514e 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -642,7 +642,14 @@ int __sched_setscheduler(struct task_struct *p,
 #endif /* CONFIG_RT_GROUP_SCHED */
 		if (dl_bandwidth_enabled() && dl_policy(policy) &&
 				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
-			cpumask_t *span = rq->rd->span;
+			/*
+			 * The root domain that admits the change: that of the
+			 * CPU recorded with the bandwidth of a deadline task.
+			 * A task moved asleep to another cpuset is still on a
+			 * CPU of the root domain it left.
+			 */
+			struct root_domain *rd = cpu_rq(dl_task_admit_cpu(p))->rd;
+			cpumask_t *span = rd->span;
 
 			/*
 			 * Don't allow tasks with an affinity mask smaller than
@@ -650,7 +657,7 @@ int __sched_setscheduler(struct task_struct *p,
 			 * will also fail if there's no bandwidth available.
 			 */
 			if (!cpumask_subset(span, &p->cpus_mask) ||
-			    rq->rd->dl_bw.bw == 0) {
+			    rd->dl_bw.bw == 0) {
 				retval = -EPERM;
 				goto unlock;
 			}
@@ -1185,6 +1192,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 +1213,17 @@ 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. Pick the CPU for it as sched_setattr() does.
 	 */
+	cpu = READ_ONCE(p->dl.dl_bw) ? dl_task_root_domain_cpu(p) :
+				       dl_task_admit_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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (2 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 03/43] sched/deadline: Record the root domain holding a task's bandwidth Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 07/43] sched/deadline: Move a task's bandwidth only where room was made Mathieu Desnoyers
                   ` (30 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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.

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.

The Sashiko AI review of this series found this window. It also 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.

Fixes: f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Reviewed-by: Juri Lelli <juri.lelli@redhat.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 28fa8f0bc81b..5d065ad27cc2 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3834,6 +3834,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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 07/43] sched/deadline: Move a task's bandwidth only where room was made
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (3 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains Mathieu Desnoyers
                   ` (29 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 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(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 4098b4e0f67e..e88616448b85 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -1966,6 +1966,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);
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 7628cf77bdfd..194a438e25c3 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -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;
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 32fe889e02fb..bd5f3dfa50ac 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -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.
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 5d065ad27cc2..67f7180559d5 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3669,12 +3669,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;
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 20ad13f388cb..61c73c7d3f27 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -2973,6 +2973,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);
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (4 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 07/43] sched/deadline: Move a task's bandwidth only where room was made Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach Mathieu Desnoyers
                   ` (28 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

Since commit 2ef269ef1ac0 ("cgroup/cpuset: Free DL BW in case
can_attach() fails"), 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. A
rebuild of the sched domains in between counts the deadline bandwidth
again from the task list. That count drops the reservation, since the
tasks have not moved yet.

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. Two kinds of callers
rebuild them:
- the callers of rebuild_sched_domains(), for example a write of
  sched_rt_runtime_us or the energy model;
- the callers of cpuset_full_lock(): the cgroup v1 writes of
  sched_load_balance and sched_relax_domain_level, and hk_sd_workfn().

In this example, 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. Two kinds of callers never wait:
- a rebuild from CPU hotplug finds no attach in progress;
- the online, offline and kill of a cpuset hold cgroup_mutex, which the
  attach holds throughout.

The move_vs_rebuild case, added to deadline_bw_test later in this
series, tests this race. It fails in 5 of 8 VMs with 8 CPUs without
this patch, and passes in all 8 with it.

A later patch of this series needs this wait too. It is
"cgroup/cpuset: Give back the bandwidth an attach did not move".
Without the wait, it would give back a reservation that a rebuild
dropped already.

The Sashiko AI reviews of this series found the race and the cgroup v1
writes.

Fixes: 2ef269ef1ac0 ("cgroup/cpuset: Free DL BW in case can_attach() fails")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Reviewed-by: Juri Lelli <juri.lelli@redhat.com>
Cc: stable@vger.kernel.org
---
 kernel/cgroup/cpuset.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 194a438e25c3..51b6be460794 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -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);
 }
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (5 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move Mathieu Desnoyers
                   ` (27 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

__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%. With two
deadline 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 making these calls wait until no cpuset attach is in
progress:
 - sched_setattr() and sched_setscheduler() on a deadline task
 - sched_setattr() that makes a task a deadline task
 - sched_setaffinity() on a deadline task

They take cpuset_mutex only when no attach is in progress, as
cpuset_partition_write() and cpuset_hotplug_update_tasks() already do.
A policy change then comes before the attach and is part of its
reservation, or comes after it.

sched_setaffinity() needs the wait for a later patch of this series,
"cgroup/cpuset: Reserve the bandwidth in the root domain a task moves
to". That patch reserves the bandwidth of the task on one CPU of its
new affinity, and records that CPU with the task. 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.

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. The new SCA_DL_NOWAIT flag tells __set_cpus_allowed_ptr()
that the caller did not wait. It then tests the policy again under the
runqueue lock, where the mask changes. For a deadline task, it returns
-EAGAIN, and sched_setaffinity() starts over and waits.

After a race with a cpuset update, __sched_setaffinity() sets the mask a
second time, within the cpuset. That second change cannot start over.
So it clears SCA_DL_NOWAIT and waits for an attach itself. It reads the
cpuset mask again after the wait, since the attach can move the task.

For user-space, the calls listed above can now wait for 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. When P
has no room for the three threads, the move and the sched_setattr() no
longer both succeed:
 - If the sched_setattr() comes first, the move fails with EBUSY.
 - If it comes after, sched_setattr() asks P for room, and fails with
   EBUSY.

Four cases, added to deadline_bw_test later in this series, test this:
 - move_became_deadline: the case above, with room in P. It fails
   without this patch.
 - move_became_deadline_no_room: two threads of 30% and a T of 40%.
   Without this patch, the move and the sched_setattr() both succeeded.
 - move_affinity_changed fails once the bandwidth is reserved on one
   CPU, if sched_setaffinity() does not wait.
 - 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()")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/cpuset.h  |  2 ++
 kernel/cgroup/cpuset.c  | 11 ++++++++
 kernel/sched/core.c     | 10 +++++++
 kernel/sched/sched.h    |  2 ++
 kernel/sched/syscalls.c | 59 +++++++++++++++++++++++++++++++++++------
 5 files changed, 76 insertions(+), 8 deletions(-)

diff --git a/include/linux/cpuset.h b/include/linux/cpuset.h
index db1cc2fc0324..5d0c01a25354 100644
--- a/include/linux/cpuset.h
+++ b/include/linux/cpuset.h
@@ -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) { }
 
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 51b6be460794..ce9c57617f49 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -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() &&
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index bd5f3dfa50ac..c0a714dde425 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -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
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 61c73c7d3f27..f4cd35811b96 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -2975,6 +2975,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);
 
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 41c568fc514e..4e0e6a326e5b 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -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();
 	}
 
@@ -1254,6 +1259,23 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)
 
 	cpuset_cpus_allowed(p, cpus_allowed);
 	if (!cpumask_subset(new_mask, cpus_allowed)) {
+		bool locked = false;
+
+		/*
+		 * A sched_setattr() may have made @p a deadline task since
+		 * the first call. SCA_DL_NOWAIT would then skip the second
+		 * call. Wait for a cpuset attach in progress instead, as
+		 * sched_setaffinity() does for a deadline task. That attach
+		 * can move @p to another cpuset: read its mask again after
+		 * the wait.
+		 */
+		if (ctx->flags & SCA_DL_NOWAIT) {
+			ctx->flags &= ~SCA_DL_NOWAIT;
+			cpuset_lock_no_attach();
+			locked = true;
+			cpuset_cpus_allowed(p, cpus_allowed);
+		}
+
 		/*
 		 * We must have raced with a concurrent cpuset update.
 		 * Just reset the cpumask to the cpuset's cpus_allowed.
@@ -1282,6 +1304,8 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)
 		 */
 		ctx->flags &= ~SCA_DL_CHECK;
 		__set_cpus_allowed_ptr(p, ctx);
+		if (locked)
+			cpuset_unlock();
 		retval = -EINVAL;
 	}
 
@@ -1297,6 +1321,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)
@@ -1326,13 +1351,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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (6 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to Mathieu Desnoyers
                   ` (26 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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, added to deadline_bw_test 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")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 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(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index e88616448b85..81a8d80a1aee 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -1967,7 +1967,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);
diff --git a/kernel/cgroup/cpuset-internal.h b/kernel/cgroup/cpuset-internal.h
index bf847953c78d..93aa46d76b04 100644
--- a/kernel/cgroup/cpuset-internal.h
+++ b/kernel/cgroup/cpuset-internal.h
@@ -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.
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index ce9c57617f49..2f39c3d12550 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -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;
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index c0a714dde425..fff2725a4cd5 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -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;
 }
 
 /*
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 67f7180559d5..e2ffdb23ba3e 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3676,6 +3676,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)) {
@@ -3704,6 +3707,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);
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index f4cd35811b96..65fc17909d56 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -2678,6 +2678,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;
 };
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (7 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in Mathieu Desnoyers
                   ` (25 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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 move also keeps the task within the affinity set by
sched_setaffinity(). The task's 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. set_cpus_allowed_dl() records with
the bandwidth a CPU of the root domain that counts it:

                                       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 choosing in cpuset_can_attach() the CPU that the move
records. The new dl_task_bw_reserve_cpu() works it out from the task's
new mask, and saves it in the new task field dl_bw_resv_cpu. The attach
then uses that CPU:
 - cpuset_can_attach() sums the bandwidth per such CPU, not per cpuset:
   one cpuset can need room in two root domains. It reserves each sum,
   and refuses with EBUSY as before.
 - cpuset_attach_task() moves the bandwidth to that CPU, and
   set_cpus_allowed_dl() records it. The CPU is not worked out again:
   the task may have run on another CPU since. No bandwidth moves for
   a task without dl_bw_resv_cpu. Juri Lelli suggested this: a task
   that cpuset_can_attach() did not count cannot use the room made for
   another task.
 - cpuset_attach() gives back the rest.

The CPU is the one 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.
Only active CPUs count. The rebuild of the accounting makes the same
choice, later in this series.

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
instead, if cpumask_any_and_distribute() picked a CPU of the other root
domain. A sleeping task gets the chosen CPU as its wakeup CPU.

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

cpuset_can_attach() works out the CPUs of the destination before the
task is in it. So 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, they fail with these boot options:
 - isolcpus=domain,1,2: all four fail.
 - isolcpus=domain,0,1: move_isolated and move_spanning fail, and six
   other move cases too.
The case move_back_cpu_offline tests a mask that holds an offline CPU.

Fixes: 7f51412a415d ("sched/deadline: Fix bandwidth check/update when migrating tasks between exclusive cpusets")
Suggested-by: Juri Lelli <juri.lelli@redhat.com>
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched.h           |   8 +-
 include/linux/sched/deadline.h  |  15 ++-
 kernel/cgroup/cpuset-internal.h |  12 --
 kernel/cgroup/cpuset.c          | 216 +++++++++++++++++++-------------
 kernel/sched/core.c             |  27 +++-
 kernel/sched/deadline.c         | 133 ++++++++++++++++----
 kernel/sched/sched.h            |   2 +
 kernel/sched/syscalls.c         |   5 +-
 8 files changed, 282 insertions(+), 136 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 81a8d80a1aee..8e7aa758d863 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -752,10 +752,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
@@ -1968,7 +1974,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);
diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index 60be226699bb..cbb7cd71db58 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -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)
 {
diff --git a/kernel/cgroup/cpuset-internal.h b/kernel/cgroup/cpuset-internal.h
index 93aa46d76b04..a83443dfb788 100644
--- a/kernel/cgroup/cpuset-internal.h
+++ b/kernel/cgroup/cpuset-internal.h
@@ -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;
 
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 2f39c3d12550..7bdb9e21a7ed 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -272,7 +272,6 @@ struct cpuset top_cpuset = {
 	.flags = BIT(CS_CPU_EXCLUSIVE) |
 		 BIT(CS_MEM_EXCLUSIVE) | BIT(CS_SCHED_LOAD_BALANCE),
 	.partition_root_state = PRS_ROOT,
-	.dl_bw_cpu = -1,
 };
 
 /**
@@ -487,28 +486,24 @@ static inline bool partition_is_populated(struct cpuset *cs,
 }
 
 /*
- * Return in pmask the portion of a task's cpusets's cpus_allowed that
- * are online and are capable of running the task.  If none are found,
- * walk up the cpuset hierarchy until we find one that does have some
- * appropriate cpus.
+ * Return in pmask the portion of the cpus_allowed of @cs that are online
+ * and are capable of running @tsk.  If none are found, walk up the cpuset
+ * hierarchy until we find one that does have some appropriate cpus.
  *
  * One way or another, we guarantee to return some non-empty subset
  * of cpu_active_mask.
  *
  * Call with callback_lock or cpuset_mutex held.
  */
-static void guarantee_active_cpus(struct task_struct *tsk,
+static void guarantee_active_cpus(struct cpuset *cs, struct task_struct *tsk,
 				  struct cpumask *pmask)
 {
 	const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
-	struct cpuset *cs;
 
 	if (WARN_ON(!cpumask_and(pmask, possible_mask, cpu_active_mask)))
 		cpumask_copy(pmask, cpu_active_mask);
 
 	rcu_read_lock();
-	cs = task_cs(tsk);
-
 	while (!cpumask_intersects(cs->effective_cpus, pmask)) {
 		cs = parent_cs(cs);
 		if (unlikely(!cs)) {
@@ -630,7 +625,6 @@ struct cpuset *dup_or_alloc_cpuset(struct cpuset *cs)
 	if (!trial)
 		return NULL;
 
-	trial->dl_bw_cpu = -1;
 	init_llist_node(&trial->attach_node);
 
 	/* Setup cpumask pointer array */
@@ -3106,61 +3100,89 @@ static int cpuset_can_attach_check(struct cpuset *cs, struct cpuset *oldcs,
 	return 0;
 }
 
+/*
+ * The deadline bandwidth of the attach in progress, per CPU. When the
+ * bandwidth of a deadline task moves to another root domain,
+ * dl_task_bw_reserve_cpu() returns the CPU that the move records with it.
+ * It also records that CPU with the task. cpuset_can_attach() sums the
+ * bandwidth of these tasks per such CPU. It reserves each sum in the root
+ * domain of its CPU. cpuset_attach_task() moves the bandwidth of each task
+ * to the CPU recorded with it. It counts what it moves, and cpuset_attach()
+ * gives back the rest.
+ * dl_attach_cpus holds the CPUs with a sum. cgroup_mutex lets one attach
+ * run at a time, and cpuset_mutex protects these.
+ */
+struct cpuset_dl_bw {
+	u64	sum;
+	u64	moved;		/* the part of sum moved */
+	bool	reserved;	/* dl_bw_alloc() took sum */
+};
+
+static DEFINE_PER_CPU(struct cpuset_dl_bw, cpuset_dl_bw);
+static cpumask_var_t dl_attach_cpus;
+
 static int cpuset_reserve_dl_bw(void)
 {
-	struct cpuset *cs;
 	int cpu, ret;
 
-	llist_for_each_entry(cs, dst_cs_head.first, attach_node) {
-		if (!cs->sum_migrate_dl_bw)
-			continue;
+	for_each_cpu(cpu, dl_attach_cpus) {
+		struct cpuset_dl_bw *b = per_cpu_ptr(&cpuset_dl_bw, cpu);
 
-		cpu = cpumask_any_and(cpu_active_mask, cs->effective_cpus);
-		if (unlikely(cpu >= nr_cpu_ids))
-			return -EINVAL;
-
-		ret = dl_bw_alloc(cpu, cs->sum_migrate_dl_bw);
+		ret = dl_bw_alloc(cpu, b->sum);
 		if (ret)
 			return ret;
-
-		cs->dl_bw_cpu = cpu;
+		b->reserved = true;
 	}
 	return 0;
 }
 
 /*
- * Clear and optionally apply (@cancel is false) the attach related data in the
- * source or destination cpuset.
+ * Give back the bandwidth the attach reserved and 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.
  */
-static void clear_attach_data(struct llist_head *head, bool cancel)
+static void cpuset_free_dl_bw(void)
+{
+	int cpu;
+
+	for_each_cpu(cpu, dl_attach_cpus) {
+		struct cpuset_dl_bw *b = per_cpu_ptr(&cpuset_dl_bw, cpu);
+
+		if (b->reserved && b->sum != b->moved)
+			dl_bw_free(cpu, b->sum - b->moved);
+		*b = (struct cpuset_dl_bw){ };
+	}
+	cpumask_clear(dl_attach_cpus);
+}
+
+/* Empty @head, the list of the source or destination cpusets. */
+static void clear_attach_data(struct llist_head *head)
 {
 	struct cpuset *cs, *next;
 	struct llist_node *lnode = __llist_del_all(head);
 
-	llist_for_each_entry_safe(cs, next, lnode, attach_node) {
+	llist_for_each_entry_safe(cs, next, lnode, attach_node)
 		init_llist_node(&cs->attach_node);
-		if (cs->nr_migrate_dl_tasks) {
-			/*
-			 * 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;
-		}
-	}
+/*
+ * Protected by cpuset_mutex. cpus_attach is used by cpuset_can_attach() and
+ * cpuset_attach_task(), but we can't allocate it dynamically there. Define
+ * it global and allocate from cpuset_init().
+ */
+static cpumask_var_t cpus_attach;
+
+/* Set @mask to the CPUs that an attach to @cs gives @task. */
+static void cpuset_attach_cpus(struct cpuset *cs, struct task_struct *task,
+			       struct cpumask *mask)
+{
+	if (cs != &top_cpuset)
+		guarantee_active_cpus(cs, task, mask);
+	else
+		cpumask_andnot(mask, task_cpu_possible_mask(task),
+			       subpartitions_cpus);
 }
 
 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
@@ -3170,7 +3192,7 @@ static int cpuset_can_attach(struct cgroup_taskset *tset)
 	struct cpuset *cs, *oldcs;
 	struct task_struct *task;
 	bool setsched_check;
-	int ret;
+	int cpu, ret;
 
 	cs = oldcs = NULL;
 	mutex_lock(&cpuset_mutex);
@@ -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);
 		}
 	}
 
@@ -3268,8 +3295,11 @@ static int cpuset_can_attach(struct cgroup_taskset *tset)
 
 out_unlock:
 	if (ret) {
-		clear_attach_data(&src_cs_head, true);
-		clear_attach_data(&dst_cs_head, true);
+		clear_attach_data(&src_cs_head);
+		clear_attach_data(&dst_cs_head);
+		cpuset_free_dl_bw();
+		cgroup_taskset_for_each(task, css, tset)
+			dl_task_bw_unreserve(task);
 	} else {
 		attach_ctx.in_progress++;
 	}
@@ -3280,50 +3310,59 @@ static int cpuset_can_attach(struct cgroup_taskset *tset)
 
 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
 {
+	struct cgroup_subsys_state *css;
+	struct task_struct *task;
+
 	mutex_lock(&cpuset_mutex);
 	dec_attach_in_progress_locked();
-	clear_attach_data(&src_cs_head, true);
-	clear_attach_data(&dst_cs_head, true);
+	clear_attach_data(&src_cs_head);
+	clear_attach_data(&dst_cs_head);
+	cpuset_free_dl_bw();
+	cgroup_taskset_for_each(task, css, tset)
+		dl_task_bw_unreserve(task);
 	mutex_unlock(&cpuset_mutex);
 }
 
-/*
- * Protected by cpuset_mutex. cpus_attach is used only by cpuset_attach_task()
- * but we can't allocate it dynamically there.  Define it global and
- * allocate from cpuset_init().
- */
-static cpumask_var_t cpus_attach;
-
 static void cpuset_attach_task(struct cpuset *cs, struct task_struct *task)
 {
-	bool reserved = false;
+	struct cpuset_dl_bw *b = NULL;
 	struct mm_struct *mm;
+	int cpu = -1;
 
 	lockdep_assert_cpuset_lock_held();
 
-	if (cs != &top_cpuset)
-		guarantee_active_cpus(task, cpus_attach);
-	else
-		cpumask_andnot(cpus_attach, task_cpu_possible_mask(task),
-			       subpartitions_cpus);
+	cpuset_attach_cpus(cs, task, cpus_attach);
 	/*
-	 * 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.
+	 * cpuset_can_attach() made room for the bandwidth of each deadline
+	 * task it moves, in the root domain of the CPU it recorded with the
+	 * task. Flag the move with that CPU, so that the bandwidth goes
+	 * there. The task may have run on another CPU since: the CPU is not
+	 * worked out again.
+	 *
+	 * A task with no CPU recorded needs no move, or was not a deadline
+	 * task in cpuset_can_attach(). Its move is not flagged, so that it
+	 * cannot use the room made for another task. Its bandwidth stays
+	 * where it is counted.
 	 */
-	if (dl_task(task) && dl_task_needs_bw_move(task, cs->effective_cpus))
-		reserved = true;
+	cpu = dl_task_bw_reserved_cpu(task);
+	if (cpu >= 0)
+		b = per_cpu_ptr(&cpuset_dl_bw, cpu);
 	/*
 	 * can_attach beforehand should guarantee that this doesn't
 	 * fail.  TODO: have a better way to handle failure here
 	 */
-	if (reserved) {
+	if (b) {
 		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;
+							  cpu, &moved));
+		b->moved += moved;
+		/*
+		 * set_cpus_allowed_dl() cleared the record, unless the task
+		 * left SCHED_DEADLINE. Clear it then too.
+		 */
+		dl_task_bw_unreserve(task);
 	} else {
 		WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
 	}
@@ -3397,6 +3436,13 @@ static void cpuset_attach(struct cgroup_taskset *tset)
 	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;
+		/*
+		 * No mask changes, so no bandwidth moves. Forget the CPU
+		 * that cpuset_can_attach() recorded with a deadline task, as
+		 * cpuset_attach_task() does. A later attach must not find it.
+		 */
+		cgroup_taskset_for_each(task, css, tset)
+			dl_task_bw_unreserve(task);
 		goto out;
 	}
 
@@ -3407,8 +3453,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);
@@ -3913,6 +3960,7 @@ int __init cpuset_init(void)
 	cpuset1_init(&top_cpuset);
 
 	BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
+	BUG_ON(!zalloc_cpumask_var(&dl_attach_cpus, GFP_KERNEL));
 
 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT))
 		cpumask_andnot(isolated_cpus, cpu_possible_mask,
@@ -4211,7 +4259,7 @@ static void __cpuset_cpus_allowed_locked(struct task_struct *tsk, struct cpumask
 
 	cs = task_cs(tsk);
 	if (cs != &top_cpuset)
-		guarantee_active_cpus(tsk, pmask);
+		guarantee_active_cpus(cs, tsk, pmask);
 	/*
 	 * Tasks in the top cpuset won't get update to their cpumasks
 	 * when a hotplug online/offline event happens. So we include all
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index fff2725a4cd5..7615ba02d52b 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -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;
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index e2ffdb23ba3e..c047169ccdd8 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3677,44 +3677,63 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 	 * 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.
+	 * 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
+	 * there. Do not work out the CPU again: @p may have run on another
+	 * CPU since. __set_cpus_allowed_ptr_locked() keeps @p in that root
+	 * domain.
+	 *
+	 * Report in @ctx the bandwidth moved. The caller gives back the room
+	 * that no move used.
 	 */
 	if ((ctx->flags & SCA_DL_BW_RESERVED) &&
-	    dl_task_needs_bw_move(p, ctx->new_mask)) {
+	    p->dl.dl_bw_resv_cpu == ctx->dl_bw_cpu) {
 		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;
 
+		p->dl.dl_bw_resv_cpu = -1;
 		/*
-		 * We now free resources of the root_domain we are migrating
-		 * off. In the worst case, sched_setattr() may temporary fail
-		 * until we complete the update. A rebuild that dropped the
-		 * bandwidth of @p leaves nothing to free. dl_departed_lock
-		 * keeps a rebuild from changing dl_bw_gen meanwhile.
+		 * Nothing moves if @p left the CPUs it was to move to, or if
+		 * its root domain already counts it: @p ran there since.
 		 */
-		guard(raw_spinlock)(&dl_departed_lock);
-		if (p->dl.dl_bw_gen == dl_bw_gen) {
-			raw_spin_lock(&src_dl_b->lock);
-			__dl_sub(src_dl_b, p->dl.dl_bw, dl_bw_cpus(src_cpu));
-			raw_spin_unlock(&src_dl_b->lock);
+		if (p->dl.dl_bw && !dl_entity_is_special(&p->dl) &&
+		    cpu_active(ctx->dl_bw_cpu) &&
+		    cpumask_test_cpu(ctx->dl_bw_cpu, ctx->new_mask) &&
+		    cpu_rq(src_cpu)->rd != cpu_rq(ctx->dl_bw_cpu)->rd) {
+			/*
+			 * We now free resources of the root_domain we are
+			 * migrating off. In the worst case, sched_setattr()
+			 * may temporary fail until we complete the update. A
+			 * rebuild that dropped the bandwidth of @p leaves
+			 * nothing to free. dl_departed_lock keeps a rebuild
+			 * from changing dl_bw_gen meanwhile.
+			 */
+			guard(raw_spinlock)(&dl_departed_lock);
+			if (p->dl.dl_bw_gen == dl_bw_gen) {
+				raw_spin_lock(&src_dl_b->lock);
+				__dl_sub(src_dl_b, p->dl.dl_bw, dl_bw_cpus(src_cpu));
+				raw_spin_unlock(&src_dl_b->lock);
+			}
+
+			/* Record the CPU the caller made room on. */
+			p->dl.dl_bw_cpu = ctx->dl_bw_cpu;
+			p->dl.dl_bw_gen = dl_bw_gen;
+			ctx->dl_bw_moved = p->dl.dl_bw;
 		}
-
-		/*
-		 * cpuset_can_attach() made room in the root domain of the new
-		 * mask. That root domain counts the bandwidth from now on.
-		 */
-		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);
 }
 
-bool dl_task_needs_bw_move(struct task_struct *p,
-			   const struct cpumask *new_mask)
+/*
+ * Return the CPU that a move of @p to the CPUs of @new_mask records with
+ * its bandwidth. That is the CPU @p is on, if @p can stay there. Else it
+ * is the first active CPU of @new_mask, a housekeeping one if there is
+ * one. Return -1 if the bandwidth stays in the root domain that counts
+ * it. The caller holds the rq lock of @p.
+ */
+static int __dl_task_bw_move_cpu(struct task_struct *p,
+				 const struct cpumask *new_mask)
 {
 	unsigned int cpu;
 
@@ -3724,10 +3743,69 @@ 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;
 
+	/*
+	 * Test the active CPUs only. The default root domain also holds the
+	 * offline CPUs, and the mask of the top cpuset holds them too.
+	 */
 	cpu = dl_task_root_domain_cpu(p);
-	return !cpumask_intersects(cpu_rq(cpu)->rd->span, new_mask);
+	if (cpumask_intersects_and(cpu_rq(cpu)->rd->span, new_mask,
+				   cpu_active_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.
+	 */
+	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;
+}
+
+/*
+ * Work out the CPU that a move of @p to the CPUs of @new_mask records
+ * with its bandwidth. Record it with @p: a cpuset attach reserves room
+ * on it. Return it, or -1 if the bandwidth stays where it is.
+ */
+int dl_task_bw_reserve_cpu(struct task_struct *p, const struct cpumask *new_mask)
+{
+	struct rq_flags rf;
+	struct rq *rq;
+	int cpu;
+
+	/* Like __set_cpus_allowed_ptr(), keep within the user affinity. */
+	rq = task_rq_lock(p, &rf);
+	if (p->user_cpus_ptr &&
+	    cpumask_and(rq->scratch_mask, new_mask, p->user_cpus_ptr))
+		new_mask = rq->scratch_mask;
+	cpu = __dl_task_bw_move_cpu(p, new_mask);
+	p->dl.dl_bw_resv_cpu = cpu;
+	task_rq_unlock(rq, p, &rf);
+	return cpu;
+}
+
+/* Return the CPU that dl_task_bw_reserve_cpu() recorded with @p, or -1. */
+int dl_task_bw_reserved_cpu(struct task_struct *p)
+{
+	return READ_ONCE(p->dl.dl_bw_resv_cpu);
+}
+
+/* Forget the CPU that dl_task_bw_reserve_cpu() recorded with @p. */
+void dl_task_bw_unreserve(struct task_struct *p)
+{
+	struct rq_flags rf;
+	struct rq *rq;
+
+	if (READ_ONCE(p->dl.dl_bw_resv_cpu) < 0)
+		return;
+	rq = task_rq_lock(p, &rf);
+	p->dl.dl_bw_resv_cpu = -1;
+	task_rq_unlock(rq, p, &rf);
 }
 
 /* Assumes rq->lock is held */
@@ -4581,6 +4659,7 @@ void init_dl_entity(struct sched_dl_entity *dl_se)
 	dl_se->dl_bw = 0;
 	__dl_clear_params(dl_se);
 	dl_se->dl_bw_cpu = -1;
+	dl_se->dl_bw_resv_cpu = -1;
 	INIT_LIST_HEAD(&dl_se->dl_departed_node);
 }
 
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 65fc17909d56..a719b62dc114 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -2680,6 +2680,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;
 };
 
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 4e0e6a326e5b..16fd65825367 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -1354,8 +1354,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,
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (8 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 14/43] sched/deadline: Move a task's bandwidth to " Mathieu Desnoyers
                   ` (24 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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.
 - 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 with dl_task_rebuild_cpu(). It counts the task where it runs
or will wake up. It takes the first active CPU in this list:

 1. The CPU the task is on, if it is in the task's mask. Also the CPU
    the task is queued on out of its mask, if the bandwidth is recorded
    there. Without admission control, dl_task_offline_migration() can
    put the task there (third case).
 2. dl_bw_cpu, the CPU recorded with the bandwidth, if it is in the
    mask. A task moved asleep is not on its new CPUs yet.
 3. A CPU of the mask, a housekeeping one first (first case).
 4. With no active CPU in the mask: steps 2 and 3 on the CPUs of the
    cpuset, from dl_get_task_effective_cpus(). A partition change sets
    the task masks before its rebuild, so the mask is up to date.

For the second case, 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() now counts the task when it moves it. A
departed task is not left out: it is still counted on the CPU recorded
with it, if that CPU is active.

Also make dl_get_task_effective_cpus() read the CPUs isolated at boot,
HK_TYPE_DOMAIN_BOOT. HK_TYPE_DOMAIN also leaves out the CPUs of
isolated partitions, and is updated after the rebuild. A CPU that just
left such a partition would still look isolated.

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 this series found these cases. The case
rebuild_record_taken, added to deadline_bw_test later in this series,
tests the rule for a task with no active CPU in its mask.

Fixes: f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
Fixes: 318e18ed22e8 ("sched/deadline: Walk up cpuset hierarchy to decide root domain when hot-unplug")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 107 ++++++++++++++++++++++++++++++++++------
 1 file changed, 91 insertions(+), 16 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index c047169ccdd8..510b0b243257 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -941,8 +941,8 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 	 * The bandwidth of @p is counted in the root domain of the CPU
 	 * recorded with it. That is not the root domain of @rq if @p was
 	 * moved to another cpuset while it was not running. If a rebuild
-	 * dropped the bandwidth, there is nothing to move: the next rebuild
-	 * counts it.
+	 * dropped the bandwidth, the source root domain has nothing to give
+	 * back.
 	 */
 	scoped_guard (raw_spinlock, &dl_departed_lock) {
 		if (p->dl.dl_bw_gen == dl_bw_gen) {
@@ -953,14 +953,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);
@@ -3847,8 +3853,14 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
 {
 	const struct cpumask *hk_msk;
 
-	hk_msk = housekeeping_cpumask(HK_TYPE_DOMAIN);
-	if (housekeeping_enabled(HK_TYPE_DOMAIN)) {
+	/*
+	 * Use the CPUs isolated at boot. HK_TYPE_DOMAIN also leaves out the
+	 * CPUs of isolated partitions, and is updated after the rebuild. A
+	 * CPU that just left such a partition is then in a new root domain,
+	 * but HK_TYPE_DOMAIN still says it is isolated.
+	 */
+	hk_msk = housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT);
+	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) {
 		if (!cpumask_intersects(p->cpus_ptr, hk_msk)) {
 			/*
 			 * CPUs isolated by isolcpu="domain" always belong to
@@ -3867,6 +3879,62 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
 	cpuset_cpus_allowed_locked(p, cpus);
 }
 
+/*
+ * Return a CPU of the root domain where a rebuild of the accounting should
+ * count the bandwidth of @p, or nr_cpu_ids if there is none.
+ *
+ * Prefer the CPU @p is on, if it is active and in the mask of @p. The
+ * task runs, or wakes up, in the root domain of that CPU. A mask can hold
+ * CPUs of two root domains: housekeeping CPUs and CPUs isolated by
+ * isolcpus="domain". When every CPU of a mask goes offline,
+ * select_fallback_rq() can widen it to both. It moves no bandwidth.
+ * Prefer that CPU also if @p is queued there, out of its mask, and the
+ * CPU is the one recorded. Without admission control,
+ * dl_task_offline_migration() can put a throttled task and its bandwidth
+ * on any active CPU. The task runs there until it blocks.
+ *
+ * Else prefer the CPU recorded with the bandwidth, if it is active and in
+ * the mask. It is in the root domain that admitted the bandwidth, or that
+ * its last move put it in. A task moved asleep is still on a CPU of the
+ * root domain it left, out of its mask. Else take the first active CPU of
+ * the mask, a housekeeping one if there is one. If no CPU of the mask is
+ * active, use the CPUs of the cpuset instead of the mask. 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);
+	/*
+	 * Read the record once. The last schedule of a dead task clears it
+	 * under its rq lock, and the caller holds only the pi_lock.
+	 */
+	int recorded = READ_ONCE(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. If no CPU of the mask
+	 * is active, ask the cpuset. The task wakes up on one of its CPUs.
+	 * Take the CPU recorded only if it is one of them: a partition root
+	 * can have taken it since it was recorded.
+	 */
+	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
+	cpu = task_cpu(p);
+	if (cpumask_test_cpu(cpu, msk) ||
+	    (cpu == recorded && cpu_active(cpu) && task_on_rq_queued(p)))
+		return cpu;
+	if (cpumask_empty(msk)) {
+		dl_get_task_effective_cpus(p, msk);
+		cpumask_and(msk, msk, cpu_active_mask);
+	}
+	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)
 {
@@ -3874,7 +3942,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);
 	/*
@@ -3889,12 +3956,20 @@ 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);
 	raw_spin_lock(&dl_departed_lock);
+	if (cpu >= nr_cpu_ids && list_empty(&p->dl.dl_departed_node)) {
+		/*
+		 * 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. Do not leave
+		 * out a departed task: the code below counts it on the CPU
+		 * recorded, if that CPU is active.
+		 */
+		goto unlock;
+	}
+
 	/*
 	 * Skip a task whose dl_bw_gen is current. Either
 	 * dl_clear_root_domains() put it back as a departed task, and
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 14/43] sched/deadline: Move a task's bandwidth to the root domain it runs in
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (9 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth Mathieu Desnoyers
                   ` (23 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A deadline task can run in a root domain that does not count its
bandwidth. Two moves cause this:
- 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. 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.
- Without admission control, sched_setaffinity() can give a task CPUs
  of another root domain. set_cpus_allowed_dl() then moves no
  bandwidth, since no one made room for it.

The root domain the task runs in can then admit deadline tasks beyond
its capacity, until the next rebuild.

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. Other moves
still move no bandwidth.

Fix this by moving the bandwidth when the task arrives in a root domain
that does not count it. Check this in two places:
- migrate_task_rq_dl(), when the task moves to another CPU;
- task_woken_dl(), when the task wakes up on its old CPU. 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.

dl_task_move_bw() moves the bandwidth and records the new CPU. As
dl_task_offline_migration() does, it adds the bandwidth even without
room, since the task runs there.

No bandwidth moves in these cases:
- The new CPU is not active. A migration-disabled task can wake up on a
  CPU that goes offline, which is in the default root domain by then.
  The task leaves that CPU later, and that move takes the bandwidth.
- The new CPU is not in the mask. A task that slept in a
  migrate_disable() section wakes up on its old CPU. A cpuset attach
  can have moved its mask and its bandwidth meanwhile.
- The sched domains are being rebuilt. The CPUs then change root
  domains one by one, so two CPUs can be in different root domains for
  a moment. dl_bw_rebuild_begin() and dl_clear_root_domains() mark this
  window.
- The walk of the task list that follows has not reached the task. The
  walk counts it where it is. A task that the walk left out, with no
  active CPU, is marked in dl_bw_skip_gen. It moves at once.

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

These cases, added to deadline_bw_test 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 this series.

Fixes: 59d06cea1198 ("sched/deadline: Fix bandwidth accounting at all levels after offline migration")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched.h          |   6 +
 include/linux/sched/deadline.h |   1 +
 kernel/sched/deadline.c        | 209 ++++++++++++++++++++++++++++++---
 kernel/sched/topology.c        |   3 +
 4 files changed, 200 insertions(+), 19 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 8e7aa758d863..e934e2225986 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -753,6 +753,11 @@ 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_skip_gen is the value of dl_bw_gen when the walk of the
+	 * task list after a rebuild left the task out: no CPU of it was
+	 * active. A move of the task then counts the bandwidth, even before
+	 * the walk ends.
+	 *
 	 * @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
@@ -761,6 +766,7 @@ struct sched_dl_entity {
 	struct list_head		dl_departed_node;
 	int				dl_bw_cpu;
 	unsigned int			dl_bw_gen;
+	unsigned int			dl_bw_skip_gen;
 	int				dl_bw_resv_cpu;
 
 	/*
diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index cbb7cd71db58..bdabd54af729 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -33,6 +33,7 @@ struct root_domain;
 extern void dl_add_task_root_domain(struct task_struct *p);
 extern void dl_clear_root_domain(struct root_domain *rd);
 extern void dl_clear_root_domains(void);
+extern void dl_bw_rebuild_begin(void);
 extern void dl_rebuild_rd_accounting(void);
 /*
  * Keep a rebuild of the root domains' accounting and an admission of
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 510b0b243257..cd5e3c355829 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -268,6 +268,73 @@ static LIST_HEAD(dl_departed_list);
 static DEFINE_RAW_SPINLOCK(dl_departed_lock);
 static unsigned int dl_bw_gen;
 
+/*
+ * Odd while the sched domains are rebuilt: from before the first CPU
+ * leaves its root domain until dl_clear_root_domains(). Meanwhile the
+ * CPUs change root domains one by one. Housekeeping CPUs pass through
+ * def_root_domain, next to the CPUs that isolcpus="domain" isolates. So
+ * the root domain of the CPU recorded with a task says nothing about
+ * where its bandwidth is counted. The new root domains count no task
+ * yet.
+ *
+ * Changed under dl_departed_lock. dl_task_bw_elsewhere() reads it
+ * without the lock.
+ */
+static unsigned int dl_bw_rebuild_seq;
+
+/*
+ * True while dl_rebuild_rd_accounting() walks the task list: from
+ * dl_clear_root_domains() until the walk ends. The root domains are final
+ * by then. A task the walk has not reached yet has a dl_bw_gen that is
+ * not current. Changed under dl_departed_lock. dl_task_bw_elsewhere()
+ * reads it without the lock.
+ */
+static bool dl_bw_walking;
+
+/* Return true while the sched domains are rebuilt. */
+static inline bool dl_bw_rebuilding(void)
+{
+	return READ_ONCE(dl_bw_rebuild_seq) & 1;
+}
+
+/*
+ * Return true if the bandwidth of @p must not move now. Either the sched
+ * domains are rebuilt, or the walk of the task list that follows has not
+ * reached @p yet. The walk then counts @p. A move must not count it
+ * first. A task the walk left out, with no active CPU, can move: no one
+ * else counts it.
+ *
+ * The answer is exact under dl_departed_lock. Without it, the answer is a
+ * hint: dl_task_move_bw() tests again under the lock.
+ */
+static inline bool dl_bw_move_blocked(struct task_struct *p)
+{
+	if (dl_bw_rebuilding())
+		return true;
+	return READ_ONCE(dl_bw_walking) &&
+	       READ_ONCE(p->dl.dl_bw_gen) != READ_ONCE(dl_bw_gen) &&
+	       READ_ONCE(p->dl.dl_bw_skip_gen) != READ_ONCE(dl_bw_gen);
+}
+
+/*
+ * Start a rebuild of the sched domains. Call it before the first CPU
+ * leaves its root domain. dl_clear_root_domains() ends the rebuild.
+ */
+void dl_bw_rebuild_begin(void)
+{
+	lockdep_assert_held(&sched_domains_mutex);
+	guard(raw_spinlock_irqsave)(&dl_departed_lock);
+	WRITE_ONCE(dl_bw_rebuild_seq, dl_bw_rebuild_seq + 1);
+}
+
+/* End the walk of the task list that dl_clear_root_domains() started. */
+static void dl_bw_walk_end(void)
+{
+	guard(raw_spinlock_irqsave)(&dl_departed_lock);
+	WARN_ON_ONCE(!dl_bw_walking);
+	WRITE_ONCE(dl_bw_walking, false);
+}
+
 /*
  * The number of tasks with a bandwidth: those whose dl_bw is not 0. A
  * special entity and a server are not counted. __setparam_dl() and
@@ -2947,11 +3014,87 @@ select_task_rq_dl(struct task_struct *p, int cpu, int flags)
 	return cpu;
 }
 
-static void migrate_task_rq_dl(struct task_struct *p, int new_cpu __maybe_unused)
+/*
+ * Return true if the root domain of @cpu may not count the bandwidth of
+ * @p. Either another root domain counts it, or a rebuild left @p out.
+ * Test without dl_departed_lock, so that a move inside a root domain
+ * takes no lock. dl_task_move_bw() tests again under it.
+ *
+ * Return false if @cpu is not active. A migration-disabled task can wake
+ * up on a CPU that goes offline, after it joined the default root domain.
+ * Keep the bandwidth where it is counted. balance_push() moves the task
+ * off that CPU once it enables migration, or its next wakeup does once
+ * the CPU is offline. That migration moves the bandwidth if needed.
+ *
+ * Return false also if @cpu is not in the mask of @p. A task that sleeps
+ * in a migrate_disable() section wakes up on the CPU it slept on. A
+ * cpuset attach can have moved its mask and its bandwidth elsewhere
+ * meanwhile. migrate_enable() then takes the task to its new mask.
+ *
+ * Return false while the sched domains are rebuilt. The CPUs then move
+ * to their new root domains one by one. That alone can make the two root
+ * domains differ. The rebuild of the accounting that follows counts @p.
+ * Return false also while that rebuild has not reached @p. Once it has
+ * counted @p, the root domains are final, and a move is right again.
+ */
+static bool dl_task_bw_elsewhere(struct task_struct *p, int cpu)
+{
+	int bw_cpu = READ_ONCE(p->dl.dl_bw_cpu);
+
+	if (bw_cpu < 0 || !p->dl.dl_bw || !cpu_active(cpu) ||
+	    !cpumask_test_cpu(cpu, &p->cpus_mask) || dl_bw_move_blocked(p))
+		return false;
+	return READ_ONCE(p->dl.dl_bw_gen) != READ_ONCE(dl_bw_gen) ||
+	       cpu_rq(bw_cpu)->rd != cpu_rq(cpu)->rd;
+}
+
+/*
+ * Move the bandwidth of @p to the root domain of @new_cpu. Count it there
+ * also if a rebuild left @p out. Add it even without room, since @p runs
+ * there. The caller holds the rq lock of @p, or its pi_lock for a wakeup.
+ */
+static void dl_task_move_bw(struct task_struct *p, int new_cpu)
+{
+	struct dl_bw *dl_b;
+	int cpu;
+
+	if (dl_entity_is_special(&p->dl) || !p->dl.dl_bw)
+		return;
+
+	guard(raw_spinlock)(&dl_departed_lock);
+	cpu = p->dl.dl_bw_cpu;
+	if (cpu < 0 || dl_bw_move_blocked(p))
+		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;
 
@@ -3614,6 +3757,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 &&
@@ -3679,9 +3831,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
@@ -3884,10 +4037,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.
  * Prefer that CPU also if @p is queued there, out of its mask, and the
  * CPU is the one recorded. Without admission control,
  * dl_task_offline_migration() can put a throttled task and its bandwidth
@@ -3962,11 +4116,13 @@ 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. Do not leave
-		 * out a departed task: the code below counts it on the CPU
-		 * recorded, if that CPU is active.
+		 * removing anything. A later rebuild counts it again. So does
+		 * the move of the task to an active CPU. Mark the task, so
+		 * that the move does not wait for the end of the walk. Do not
+		 * leave out a departed task: the code below counts it on the
+		 * CPU recorded, if that CPU is active.
 		 */
+		WRITE_ONCE(p->dl.dl_bw_skip_gen, dl_bw_gen);
 		goto unlock;
 	}
 
@@ -4124,8 +4280,10 @@ void dl_rebuild_rd_accounting(void)
 	 * a resume run one for each CPU. A task gets a bandwidth under the
 	 * locks this rebuild holds, so the count cannot leave 0 meanwhile.
 	 */
-	if (!atomic_read(&dl_nr_bw_tasks))
+	if (!atomic_read(&dl_nr_bw_tasks)) {
+		dl_bw_walk_end();
 		return;
+	}
 
 	read_lock(&tasklist_lock);
 	for_each_process_thread(g, p) {
@@ -4139,6 +4297,7 @@ void dl_rebuild_rd_accounting(void)
 			dl_add_task_root_domain(p);
 	}
 	read_unlock(&tasklist_lock);
+	dl_bw_walk_end();
 }
 
 /*
@@ -4157,7 +4316,17 @@ 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);
+	/*
+	 * The root domains are final. End the rebuild of the sched domains,
+	 * and start the walk of the task list. From now on, a task that the
+	 * walk has counted moves its bandwidth again. A task that the walk
+	 * has not reached still waits for it: see dl_bw_move_blocked().
+	 */
+	WARN_ON_ONCE(!(dl_bw_rebuild_seq & 1));
+	WRITE_ONCE(dl_bw_rebuild_seq, dl_bw_rebuild_seq + 1);
+	WRITE_ONCE(dl_bw_walking, true);
 	for_each_possible_cpu(cpu) {
 		if (!dl_bw_visited(cpu, cookie))
 			dl_clear_root_domain(cpu_rq(cpu)->rd);
@@ -4274,11 +4443,13 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 	 * boosts it back into the class before its 0-lag time. (A policy change
 	 * took it off the list in sched_dl_overflow().) The inactive timer no
 	 * longer removes its bandwidth: the task does when it leaves the class
-	 * again. So take it off the list. The task keeps the CPU recorded. It
-	 * takes the bandwidth from the root domain of that CPU, even if it
-	 * moved to another root domain meanwhile. A rebuild while it is
-	 * boosted counts it like any deadline task, and records the CPU it
-	 * picks.
+	 * again. So take it off the list. The task keeps the CPU recorded.
+	 * When it leaves the class, it takes the bandwidth from the root
+	 * domain of that CPU. If the task moved to another root domain
+	 * meanwhile, its next wakeup or migration there first moves the
+	 * bandwidth and the record, as for any deadline task. A rebuild while
+	 * it is boosted counts it like any deadline task, and records the CPU
+	 * it picks.
 	 */
 	dl_task_undepart(p);
 
diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c
index 35e56a45c238..754756d2db00 100644
--- a/kernel/sched/topology.c
+++ b/kernel/sched/topology.c
@@ -3430,6 +3430,9 @@ static void partition_sched_domains_locked(int ndoms_new, cpumask_var_t doms_new
 		n = ndoms_new;
 	}
 
+	/* dl_clear_root_domains() ends it, in dl_rebuild_rd_accounting(). */
+	dl_bw_rebuild_begin();
+
 	/* Destroy deleted domains: */
 	for (i = 0; i < ndoms_cur; i++) {
 		for (j = 0; j < n && !new_topology; j++) {
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (10 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 14/43] sched/deadline: Move a task's bandwidth to " Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 16/43] sched/deadline: Keep the last CPU a task has in its root domain Mathieu Desnoyers
                   ` (22 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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.

Fix this with 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.

A CPU offline and the rebuild of the sched domains need more than this,
at five points:

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

 - At an offline, select_fallback_rq() can widen the mask of the task
   before the cpuset update. It first gives the task the CPUs of its
   cpuset, then the housekeeping CPUs. The wider mask can hold no
   active CPU of the root domain that counts the task. The task then
   leaves that root domain, and stays out after the cpuset update. So
   in that case, allow the CPUs of that root domain instead. The cpuset
   update that comes next sets the real mask. If no CPU of that root
   domain is allowed, select_fallback_rq() still tries its fallback
   mask. Without this, in testing, a deadline task that spun on the CPU
   going offline left its root domain in every run.

 - dl_task_offline_migration() has the same window, for a throttled
   task whose timer fires on the CPU going offline. When no CPU of its
   mask was active, it warned and took any active CPU. It now takes an
   active CPU of the root domain that counts the task first. It warns
   only if that root domain has none either.

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

 - After a rebuild, a walk of the task list counts each deadline task
   on the CPU that dl_task_rebuild_cpu() picks. Until the walk reaches
   a task, dl_task_bw_span() returns NULL for it, and
   dl_task_offline_migration() moves none of its bandwidth. The root
   domains are new, and the CPU recorded can be offline. So
   dl_task_rebuild_cpu() cannot use the root domain of that CPU. Record
   in dl_bw_def whether the default root domain counted the task.
   dl_task_rebuild_cpu() then prefers a CPU of the mask on the same
   side: in the default root domain or not. The side cannot come from
   the CPUs isolated at boot: a CPU of an isolated partition is in the
   default root domain too.

A known limit remains. A wakeup can pick its CPU inside a rebuild. If
the walk counts the task before it is queued, its bandwidth can still
move to the other root domain, with no admission test. This was found
by reading, not reproduced.

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

The case hotplug_keeps_root_domain, added to deadline_bw_test 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, with
isolcpus=domain,0,1.

These cases test the other paths:
 - hotplug_spinner_keeps: a running task whose CPU goes offline.
 - hotplug_fallback_running: the same, when the cpuset of the task has
   no CPU left.
 - hotplug_waking_keeps: a task that wakes up often, at the offline.
 - hotplug_isolated_keeps: the same, for a task counted on the isolated
   side.
 - rebuild_waking_keeps: a wakeup inside a rebuild. It fails in most
   runs if dl_task_bw_span() does not return NULL there. That needs
   isolcpus=domain,0,1.
 - hotplug_isolated_partition_falls_back: a task counted on the CPU of
   an isolated partition, which goes offline. When the side came from
   the CPUs isolated at boot, the rebuild moved the bandwidth to the
   housekeeping root domain. This failed in testing with
   isolcpus=domain.

Fixes: 332ac17ef5bf ("sched/deadline: Add bandwidth management for SCHED_DEADLINE tasks")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched.h   |   7 ++
 kernel/sched/core.c     |  81 ++++++++++++
 kernel/sched/deadline.c | 271 ++++++++++++++++++++++++++++++++++------
 kernel/sched/sched.h    |   3 +
 4 files changed, 325 insertions(+), 37 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index e934e2225986..0c89263b1db9 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -762,6 +762,12 @@ struct sched_dl_entity {
 	 * in progress reserved room for the bandwidth, or -1.
 	 * cpuset_can_attach() sets it, and cpuset_attach() moves the
 	 * bandwidth there.
+	 *
+	 * @dl_bw_def is true if def_root_domain counted the bandwidth when
+	 * @dl_bw_cpu was recorded. A rebuild changes the root domains, and
+	 * the CPU recorded can go offline. A rebuild then keeps the
+	 * bandwidth on that side: in def_root_domain or not. It is the last
+	 * member, so that no hole is left.
 	 */
 	struct list_head		dl_departed_node;
 	int				dl_bw_cpu;
@@ -786,6 +792,7 @@ struct sched_dl_entity {
 	 */
 	struct sched_dl_entity *pi_se;
 #endif
+	bool				dl_bw_def;
 };
 
 #ifdef CONFIG_UCLAMP_TASK
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 7615ba02d52b..45e794bd39a3 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -3264,6 +3264,31 @@ 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. Also wake a sleeping @p up
+		 * there, unless its wakeup CPU is still allowed in it. A
+		 * wakeup during a rebuild of the sched domains has no span to
+		 * prefer.
+		 */
+		if (span && cpumask_test_cpu(dest_cpu, span))
+			cpu = dest_cpu;
+		else if (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) &&
+			    !(cpumask_test_cpu(p->wake_cpu, cpu_valid_mask) &&
+			      cpumask_test_cpu(p->wake_cpu, ctx->new_mask) &&
+			      cpumask_test_cpu(p->wake_cpu, span)))
+				p->wake_cpu = dest_cpu;
+		}
 	}
 
 	do_set_cpus_allowed(p, ctx);
@@ -3668,8 +3693,29 @@ 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;
+	bool span_forced = false;
 	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) {
+		/* Prefer the node of @cpu, as below. */
+		if (nid != -1) {
+			for_each_cpu_and(dest_cpu, span, cpumask_of_node(nid)) {
+				if (is_cpu_allowed(p, dest_cpu))
+					return dest_cpu;
+			}
+		}
+		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 +3732,32 @@ 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;
+			}
+			/*
+			 * The wider mask has no active CPU in that root
+			 * domain. Allow the CPUs of the root domain instead.
+			 * At an offline, the cpuset update comes next and sets
+			 * the real mask. Give @p a copy of the span: a rebuild
+			 * can change the span itself.
+			 */
+			if (!span_forced) {
+				struct cpumask *msk = dl_fallback_mask();
+
+				span_forced = true;
+				if (dl_task_bw_span_copy(p, msk) &&
+				    cpumask_intersects(msk, cpu_active_mask) &&
+				    cpumask_subset(msk, task_cpu_possible_mask(p))) {
+					set_cpus_allowed_force(p, msk);
+					continue;
+				}
+			}
+		}
+
 		/* Any allowed, online CPU? */
 		for_each_cpu(dest_cpu, p->cpus_ptr) {
 			if (!is_cpu_allowed(p, dest_cpu))
@@ -3707,6 +3779,15 @@ static int select_fallback_rq(int cpu, struct task_struct *p)
 			state = fail;
 			break;
 		case fail:
+			/*
+			 * The span replaced the fallback mask, and has no
+			 * allowed CPU. Try the fallback mask before giving up.
+			 */
+			if (span_forced && span) {
+				span = NULL;
+				set_cpus_allowed_force(p, task_cpu_fallback_mask(p));
+				break;
+			}
 			BUG();
 			break;
 		}
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index cd5e3c355829..dbf709fd0fd4 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -277,8 +277,8 @@ static unsigned int dl_bw_gen;
  * where its bandwidth is counted. The new root domains count no task
  * yet.
  *
- * Changed under dl_departed_lock. dl_task_bw_elsewhere() reads it
- * without the lock.
+ * Changed under dl_departed_lock. dl_task_bw_span() and
+ * dl_task_bw_elsewhere() read it without the lock.
  */
 static unsigned int dl_bw_rebuild_seq;
 
@@ -316,6 +316,23 @@ static inline bool dl_bw_move_blocked(struct task_struct *p)
 	       READ_ONCE(p->dl.dl_bw_skip_gen) != READ_ONCE(dl_bw_gen);
 }
 
+/* Return true if @cpu is in def_root_domain. */
+static inline bool dl_cpu_in_def(int cpu)
+{
+	return cpu_rq(cpu)->rd == &def_root_domain;
+}
+
+/*
+ * Record @cpu with @dl_se: the root domain of @cpu counts its bandwidth.
+ * Call it outside a rebuild of the sched domains, when that root domain
+ * is final.
+ */
+static inline void dl_record_bw_cpu(struct sched_dl_entity *dl_se, int cpu)
+{
+	WRITE_ONCE(dl_se->dl_bw_cpu, cpu);
+	WRITE_ONCE(dl_se->dl_bw_def, dl_cpu_in_def(cpu));
+}
+
 /*
  * Start a rebuild of the sched domains. Call it before the first CPU
  * leaves its root domain. dl_clear_root_domains() ends the rebuild.
@@ -325,6 +342,8 @@ void dl_bw_rebuild_begin(void)
 	lockdep_assert_held(&sched_domains_mutex);
 	guard(raw_spinlock_irqsave)(&dl_departed_lock);
 	WRITE_ONCE(dl_bw_rebuild_seq, dl_bw_rebuild_seq + 1);
+	/* Before the first write of rq->rd: see dl_task_bw_span(). */
+	smp_wmb();
 }
 
 /* End the walk of the task list that dl_clear_root_domains() started. */
@@ -372,9 +391,9 @@ static void dl_task_depart(struct task_struct *p)
 	 * departs from instead, if it is active and the same root domain
 	 * counts the bandwidth.
 	 */
-	if (dl_se->dl_bw_gen == dl_bw_gen && cpu_active(cpu) &&
+	if (dl_se->dl_bw_gen == dl_bw_gen && !dl_bw_rebuilding() && cpu_active(cpu) &&
 	    cpu_rq(cpu)->rd == cpu_rq(dl_se->dl_bw_cpu)->rd)
-		dl_se->dl_bw_cpu = cpu;
+		dl_record_bw_cpu(dl_se, cpu);
 	list_add(&dl_se->dl_departed_node, &dl_departed_list);
 }
 
@@ -956,18 +975,44 @@ static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq);
 
 static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p)
 {
+	const struct cpumask *span;
 	struct rq *later_rq = NULL;
 	struct dl_bw *dl_b;
 
 	later_rq = find_lock_later_rq(p, rq);
+	/*
+	 * find_lock_later_rq() looks in the root domain of @rq. Once @rq is
+	 * offline, a rebuild attaches it to def_root_domain. That root domain
+	 * may not count @p. Do not take @p out of the root domain that counts
+	 * it while @p has an active CPU there.
+	 */
+	span = dl_task_bw_span(p);
+	if (later_rq && span && !cpumask_test_cpu(later_rq->cpu, span) &&
+	    cpumask_first_and_and(cpu_active_mask, p->cpus_ptr, span) < nr_cpu_ids) {
+		double_unlock_balance(rq, later_rq);
+		later_rq = NULL;
+	}
 	if (!later_rq) {
 		int cpu;
 
 		/*
 		 * If we cannot preempt any rq, fall back to pick any
-		 * 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);
+		/*
+		 * No CPU of its mask is active: the CPU goes offline before
+		 * cpuset updates the mask. Keep the task in the root domain
+		 * that counts it, if a CPU of it is active. The task runs
+		 * there until cpuset gives it a new mask.
+		 */
+		if (cpu >= nr_cpu_ids && span)
+			cpu = cpumask_first_and(cpu_active_mask, span);
 		if (cpu >= nr_cpu_ids) {
 			/*
 			 * Failed to find any suitable CPU.
@@ -1010,8 +1055,15 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 	 * moved to another cpuset while it was not running. If a rebuild
 	 * dropped the bandwidth, the source root domain has nothing to give
 	 * back.
+	 *
+	 * Move nothing while the sched domains are rebuilt, or before the
+	 * walk that follows has counted @p, as dl_task_move_bw() does. The
+	 * CPU picked above then had no span to prefer. The walk counts @p
+	 * on the side of the CPU recorded.
 	 */
 	scoped_guard (raw_spinlock, &dl_departed_lock) {
+		if (dl_bw_move_blocked(p))
+			break;
 		if (p->dl.dl_bw_gen == dl_bw_gen) {
 			struct rq *src_rq = cpu_rq(dl_task_root_domain_cpu(p));
 
@@ -1032,7 +1084,7 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 		__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;
+		dl_record_bw_cpu(&p->dl, later_rq->cpu);
 		p->dl.dl_bw_gen = dl_bw_gen;
 	}
 
@@ -2969,6 +3021,7 @@ static int
 select_task_rq_dl(struct task_struct *p, int cpu, int flags)
 {
 	struct task_struct *curr, *donor;
+	const struct cpumask *span;
 	bool select_rq;
 	struct rq *rq;
 
@@ -3009,6 +3062,20 @@ select_task_rq_dl(struct task_struct *p, int cpu, int flags)
 		    dl_task_is_earliest_deadline(p, cpu_rq(target)))
 			cpu = target;
 	}
+
+	/*
+	 * Keep @p in the root domain that counts its bandwidth. Its mask
+	 * can hold CPUs of another root domain, with isolcpus="domain",
+	 * and @p can sleep on one of them.
+	 */
+	span = dl_task_bw_span(p);
+	if (span && !cpumask_test_cpu(cpu, span)) {
+		unsigned int in_span;
+
+		in_span = cpumask_first_and_and(span, p->cpus_ptr, cpu_active_mask);
+		if (in_span < nr_cpu_ids)
+			cpu = in_span;
+	}
 	rcu_read_unlock();
 
 	return cpu;
@@ -3077,7 +3144,7 @@ static void dl_task_move_bw(struct task_struct *p, int 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;
+	dl_record_bw_cpu(&p->dl, new_cpu);
 	p->dl.dl_bw_gen = dl_bw_gen;
 }
 
@@ -3375,6 +3442,13 @@ static struct task_struct *pick_earliest_pushable_dl_task(struct rq *rq, int cpu
 
 /* Access rule: must be called on local CPU with preemption disabled */
 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl);
+static DEFINE_PER_CPU(cpumask_var_t, dl_fallback_mask_pcpu);
+
+/* Return a mask for select_fallback_rq() alone. Interrupts are off. */
+struct cpumask *dl_fallback_mask(void)
+{
+	return this_cpu_cpumask_var_ptr(dl_fallback_mask_pcpu);
+}
 
 static int find_later_rq(struct task_struct *task)
 {
@@ -3821,6 +3895,100 @@ static unsigned int dl_task_admit_cpu(struct task_struct *p)
 	return cpu;
 }
 
+/*
+ * Return the root domain that counts the bandwidth of @p, or NULL if none
+ * does. Set *@seq to the value of dl_bw_rebuild_seq it was found under.
+ * 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.
+ *
+ * Return NULL while the sched domains are rebuilt. The CPU recorded can
+ * then sit in def_root_domain on its way to a new root domain. The span
+ * of def_root_domain holds the isolated CPUs, and no longer the
+ * housekeeping CPUs that already left it. A caller would send a
+ * housekeeping task to an isolated CPU.
+ *
+ * Return NULL also for a task that the walk of the task list after the
+ * rebuild has not reached yet. Its dl_bw_gen is not current.
+ *
+ * The caller holds the pi_lock or the rq lock of @p. With interrupts
+ * off, the root domain is not freed.
+ */
+static struct root_domain *dl_task_bw_rd(struct task_struct *p, unsigned int *seq)
+{
+	struct root_domain *rd;
+	int cpu;
+
+	/* Pairs with the release in dl_clear_root_domains(). */
+	*seq = smp_load_acquire(&dl_bw_rebuild_seq);
+	if (!task_has_dl_policy(p) || dl_entity_is_special(&p->dl) ||
+	    !p->dl.dl_bw || (*seq & 1))
+		return NULL;
+	cpu = READ_ONCE(p->dl.dl_bw_cpu);
+	if (cpu < 0 || READ_ONCE(p->dl.dl_bw_gen) != READ_ONCE(dl_bw_gen))
+		return NULL;
+	/*
+	 * The CPU recorded can be going offline. It keeps its root domain
+	 * until the rebuild attaches it to def_root_domain. The rebuild then
+	 * records an active CPU with @p, or leaves @p out. Until then, the
+	 * root domain of the CPU recorded still counts @p.
+	 *
+	 * The CPUs that isolcpus="domain" isolates are in def_root_domain.
+	 * So are the CPUs of an isolated partition. def_root_domain then
+	 * counts @p. A CPU that is not active, and in def_root_domain while
+	 * @p was counted elsewhere, was attached there by the rebuild.
+	 * def_root_domain does not count @p then.
+	 */
+	rd = READ_ONCE(cpu_rq(cpu)->rd);
+	if (!cpu_active(cpu) && rd == &def_root_domain && !READ_ONCE(p->dl.dl_bw_def))
+		return NULL;
+	return rd;
+}
+
+/*
+ * Return true if a rebuild of the sched domains started since @seq was
+ * read. A rebuild writes rq->rd, and the spans, after it makes
+ * dl_bw_rebuild_seq odd.
+ */
+static inline bool dl_bw_rebuild_since(unsigned int seq)
+{
+	/* Pairs with the smp_wmb() in dl_bw_rebuild_begin(). */
+	smp_rmb();
+	return READ_ONCE(dl_bw_rebuild_seq) != seq;
+}
+
+/*
+ * Return the CPUs of the root domain that counts the bandwidth of @p, or
+ * NULL: see dl_task_bw_rd(). The mask is that of the root domain. A
+ * rebuild that starts after the return can change it. Test bits of it
+ * only. To give the mask to @p, use dl_task_bw_span_copy().
+ */
+const struct cpumask *dl_task_bw_span(struct task_struct *p)
+{
+	unsigned int seq;
+	struct root_domain *rd = dl_task_bw_rd(p, &seq);
+
+	if (!rd || dl_bw_rebuild_since(seq))
+		return NULL;
+	return rd->span;
+}
+
+/*
+ * Copy into @dst the CPUs of the root domain that counts the bandwidth of
+ * @p: see dl_task_bw_rd(). Return false if none does, or if a rebuild of
+ * the sched domains changed the span during the copy.
+ */
+bool dl_task_bw_span_copy(struct task_struct *p, struct cpumask *dst)
+{
+	unsigned int seq;
+	struct root_domain *rd = dl_task_bw_rd(p, &seq);
+
+	if (!rd)
+		return false;
+	cpumask_copy(dst, rd->span);
+	return !dl_bw_rebuild_since(seq);
+}
+
 static void set_cpus_allowed_dl(struct task_struct *p,
 				struct affinity_context *ctx)
 {
@@ -3875,7 +4043,7 @@ static void set_cpus_allowed_dl(struct task_struct *p,
 			}
 
 			/* Record the CPU the caller made room on. */
-			p->dl.dl_bw_cpu = ctx->dl_bw_cpu;
+			dl_record_bw_cpu(&p->dl, ctx->dl_bw_cpu);
 			p->dl.dl_bw_gen = dl_bw_gen;
 			ctx->dl_bw_moved = p->dl.dl_bw;
 		}
@@ -3992,9 +4160,12 @@ void __init init_sched_dl_class(void)
 {
 	unsigned int i;
 
-	for_each_possible_cpu(i)
+	for_each_possible_cpu(i) {
 		zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i),
 					GFP_KERNEL, cpu_to_node(i));
+		zalloc_cpumask_var_node(&per_cpu(dl_fallback_mask_pcpu, i),
+					GFP_KERNEL, cpu_to_node(i));
+	}
 }
 
 /*
@@ -4036,24 +4207,25 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
  * 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 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.
- * Prefer that CPU also if @p is queued there, out of its mask, and the
- * CPU is the one recorded. Without admission control,
- * dl_task_offline_migration() can put a throttled task and its bandwidth
- * on any active CPU. The task runs there until it blocks.
+ * A mask can hold CPUs of two root domains: housekeeping CPUs and CPUs
+ * isolated by isolcpus="domain". Keep the bandwidth on the side of the
+ * CPU recorded with it. That CPU is in the root domain that admitted the
+ * bandwidth, or that its last move put it in. Take the CPU @p is on if it
+ * is active, in the mask of @p and on that side. Else take the CPU
+ * recorded, if it is active and in the mask. Else take a CPU of the mask
+ * on that side.
  *
- * 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. If no CPU of the mask is
- * active, use the CPUs of the cpuset instead of the mask. A task on
- * isolated CPUs that all went offline can have no active CPU at all.
+ * With no CPU on that side, or no CPU recorded, prefer the CPU @p is on.
+ * 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.
+ *
+ * One case comes before all of these. Take the CPU @p is on if @p is
+ * queued there, and the CPU is the one recorded or out of the mask of @p.
+ * Without admission control, dl_task_offline_migration() can put a
+ * throttled task and its bandwidth on any active CPU. The task runs there
+ * until it blocks. Inside a rebuild, that move leaves the record on the
+ * CPU that went offline.
  */
 static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
 {
@@ -4068,21 +4240,42 @@ static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
 	/*
 	 * Look at the mask of the task first. A change of the cpusets sets
 	 * the mask of each task before its rebuild. If no CPU of the mask
-	 * is active, ask the cpuset. The task wakes up on one of its CPUs.
-	 * Take the CPU recorded only if it is one of them: a partition root
-	 * can have taken it since it was recorded.
+	 * is active, ask the cpuset. The CPU recorded is taken below only if
+	 * the cpuset holds it: a partition root can have taken it since it
+	 * was recorded.
 	 */
 	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
 	cpu = task_cpu(p);
-	if (cpumask_test_cpu(cpu, msk) ||
-	    (cpu == recorded && cpu_active(cpu) && task_on_rq_queued(p)))
+	if (cpu_active(cpu) && task_on_rq_queued(p) &&
+	    (cpu == recorded || !cpumask_test_cpu(cpu, &p->cpus_mask)))
 		return cpu;
 	if (cpumask_empty(msk)) {
 		dl_get_task_effective_cpus(p, msk);
 		cpumask_and(msk, msk, cpu_active_mask);
 	}
-	if (recorded >= 0 && cpumask_test_cpu(recorded, msk))
-		return recorded;
+	/*
+	 * Keep the bandwidth where it was counted: in def_root_domain or
+	 * not. The root domains are new, and the CPU recorded can be offline
+	 * or in another root domain now. So prefer a CPU of the mask on the
+	 * side recorded with @p. Do not use the CPUs that isolcpus="domain"
+	 * isolates for this: a CPU of an isolated partition is in
+	 * def_root_domain too.
+	 */
+	if (recorded >= 0) {
+		bool def = READ_ONCE(p->dl.dl_bw_def);
+		unsigned int same;
+
+		if (cpumask_test_cpu(cpu, msk) && dl_cpu_in_def(cpu) == def)
+			return cpu;
+		if (cpumask_test_cpu(recorded, msk) && dl_cpu_in_def(recorded) == def)
+			return recorded;
+		for_each_cpu(same, msk) {
+			if (dl_cpu_in_def(same) == def)
+				return same;
+		}
+	}
+	if (cpumask_test_cpu(cpu, msk))
+		return cpu;
 	cpu = cpumask_first_and(msk, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
 	if (cpu < nr_cpu_ids)
 		return cpu;
@@ -4169,7 +4362,7 @@ void dl_add_task_root_domain(struct task_struct *p)
 	raw_spin_lock(&dl_b->lock);
 	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
 	raw_spin_unlock(&dl_b->lock);
-	p->dl.dl_bw_cpu = cpu;
+	dl_record_bw_cpu(&p->dl, cpu);
 	p->dl.dl_bw_gen = dl_bw_gen;
 unlock:
 	raw_spin_unlock(&dl_departed_lock);
@@ -4325,7 +4518,11 @@ void dl_clear_root_domains(void)
 	 * has not reached still waits for it: see dl_bw_move_blocked().
 	 */
 	WARN_ON_ONCE(!(dl_bw_rebuild_seq & 1));
-	WRITE_ONCE(dl_bw_rebuild_seq, dl_bw_rebuild_seq + 1);
+	/*
+	 * After the writes of rq->rd and of dl_bw_gen: pairs with the
+	 * acquire in dl_task_bw_rd().
+	 */
+	smp_store_release(&dl_bw_rebuild_seq, dl_bw_rebuild_seq + 1);
 	WRITE_ONCE(dl_bw_walking, true);
 	for_each_possible_cpu(cpu) {
 		if (!dl_bw_visited(cpu, cookie))
@@ -4745,7 +4942,7 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 			if (p->dl.dl_bw_cpu >= 0)
 				dl_task_release_bw(p);
 		}
-		p->dl.dl_bw_cpu = cpu;
+		dl_record_bw_cpu(&p->dl, cpu);
 		p->dl.dl_bw_gen = dl_bw_gen;
 	}
 
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index a719b62dc114..e2bb192f1ee6 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -361,6 +361,9 @@ 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 bool dl_task_bw_span_copy(struct task_struct *p, struct cpumask *dst);
+extern struct cpumask *dl_fallback_mask(void);
 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
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 16/43] sched/deadline: Keep the last CPU a task has in its root domain
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (11 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 17/43] cgroup/cpuset: Refuse to take a deadline task out of " Mathieu Desnoyers
                   ` (21 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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 only at the root domain of the CPU going offline, not
at the mask of each task. It misses two ways in which an offline takes
a deadline task out of the root domain that admitted it:

 - The task loses the last CPU of its mask in that root domain. 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.
 - The offline makes a cpuset partition invalid. Its CPUs then join the
   root domain of its parent, with its tasks. These tasks can be counted
   in another root domain than that of the CPU going offline. A test of
   that root domain does not see them. In testing, an offline put three
   deadline tasks of 40% in a root domain of one CPU this way.

Either way, the bandwidth of the task follows it with no admission
test, and the root domain it arrives in can exceed its limit.

Fix this by refusing such an offline with EBUSY. dl_bw_deactivate()
gets one check for each way.

The first check walks the deadline tasks counted in the root domain of
the CPU. It refuses if one of them has CPUs left to run on, but none in
that root domain. A task whose mask holds no other active CPU gets the
CPUs that its cpuset gives it after the offline. Add
cpuset_cpus_allowed_without(), which works them out as cpuset does, on
cgroup v1 and v2. Like __set_cpus_allowed_ptr(), it keeps them within
the affinity set by the user, if they intersect. If the cpuset gives no
CPU the task can run on, select_fallback_rq() picks one. The previous
patch makes it keep a deadline task in its root domain when it can.

The second check is cpuset_offline_moves_dl(). It refuses the offline
in these cases:

 - The partition root of the CPU has tasks and no CPU of its own left.
   It takes the CPUs of a child partition. cpuset makes that child
   invalid, with its own child partitions. Refuse if one of these
   cpusets holds a deadline task. Accept the two cases where the CPUs
   keep their root domain. Either the parent and the child are both
   isolated: the CPUs stay in the default root domain. Or neither is
   isolated. The parent takes all the CPUs of the child, so its root
   domain spans the root domain of the child. It counts the bandwidth
   admitted there. A child partition of that child had a root domain
   of its own, so this exception does not cover its tasks.
 - The partition root of the CPU has tasks and no CPU of its own left,
   and takes none from a child partition. cpuset makes it invalid, and
   its tasks count in its parent. If the parent keeps a CPU of its own,
   the first check sees these tasks. Otherwise, the order of the cpuset
   updates decides where the tasks end. cpuset updates a parent before
   its children, so the parent stays valid with no CPU. It takes the
   CPUs of the next child partition that cpuset updates, if there is
   one. Else a later hotplug event decides. The check does not model
   this. It goes up from the parent while each partition has no CPU of
   its own. It refuses if a deadline task is under the last of these
   partitions. This can refuse an offline that keeps each task in its
   root domain. That needs nested partitions, whose parents gave all
   their CPUs to their children or have them offline. The offline must
   also take the last CPU of a child that holds tasks.
 - The CPU is the last one left to the top cpuset, and partitions exist.
   cpuset then makes every partition invalid, and every deadline task
   changes root domain. Refuse if any cpuset holds a deadline task.

Both checks skip a dead task: it runs no more. They also skip a task
whose bandwidth no root domain counts, such as a sugov kthread. Add
dl_task_holds_bw() for that test.

Neither check runs during a suspend: a suspend takes the CPUs offline
with the tasks frozen, and the resume puts them back. Neither runs
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 first check cannot miss a task. Only a cpuset change or a cpuset
move gives a deadline task a mask that misses part of its root domain.
sched_setattr() refuses the deadline policy to a task with such a mask.
sched_setaffinity() refuses such a mask to a deadline task. A cpuset
change and a cpuset move both exclude CPU hotplug.

This holds for the tasks that are deadline tasks when the walk runs.
The walk runs before set_cpu_active(false), and sched_setattr() does
not exclude CPU hotplug. So sched_setattr() can admit a new deadline
task in between. The task is on the last CPU of a root domain, and has
an isolated CPU in its mask. After the offline, it would run on the
isolated CPU. That CPU is in the default root domain, which did not
admit it. The bandwidth test of dl_bw_deactivate() has the same
window, from before this series.

An accepted offline can still leave a parent partition valid, with
tasks and no CPU of its own. This happens when no deadline task is
under it. A deadline task can later join one of its child partitions.
The next hotplug event, an online too, can then give the CPUs of that
child to the parent. The task then changes root domain with no
admission test. cpuset could reach that state before this series.

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, added to deadline_bw_test later in this
series, tests this. Without this patch the offline is accepted. These
cases test the other paths:
- hotplug_user_mask_refused: the affinity set by the user.
- hotplug_nested_refused: nested cpusets.
- hotplug_dead_accepted: a dead task.
- hotplug_child_partition_kept and hotplug_partition_invalid_refused: a
  child partition made invalid.
- hotplug_sibling_partition_refused: a sibling partition that the
  offline makes invalid.
- hotplug_first_sibling_refused, hotplug_nested_partition_refused and
  hotplug_isolated_child_refused: a parent partition left with no CPU
  of its own.
- hotplug_top_last_refused: the last CPU of the top cpuset.

Fixes: d4742f6ed7ea ("sched/deadline: Correctly account for allocated bandwidth during hotplug")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/cpuset.h         |  17 ++
 include/linux/sched/deadline.h |   1 +
 kernel/cgroup/cpuset.c         | 308 +++++++++++++++++++++++++++++++++
 kernel/sched/deadline.c        |  78 ++++++++-
 4 files changed, 403 insertions(+), 1 deletion(-)

diff --git a/include/linux/cpuset.h b/include/linux/cpuset.h
index 5d0c01a25354..d3fceb919c46 100644
--- a/include/linux/cpuset.h
+++ b/include/linux/cpuset.h
@@ -16,6 +16,7 @@
 #include <linux/nodemask.h>
 #include <linux/mm.h>
 #include <linux/mmu_context.h>
+#include <linux/sched/isolation.h>
 #include <linux/jump_label.h>
 
 extern bool lockdep_is_cpuset_held(void);
@@ -79,6 +80,9 @@ 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 bool cpuset_cpus_allowed_without(struct task_struct *p, int cpu,
+					struct cpumask *mask);
+extern bool cpuset_offline_moves_dl(int cpu);
 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 +218,19 @@ static inline bool cpuset_cpus_allowed_fallback(struct task_struct *p)
 	return false;
 }
 
+static inline bool cpuset_cpus_allowed_without(struct task_struct *p, int cpu,
+					       struct cpumask *mask)
+{
+	cpumask_and(mask, task_cpu_fallback_mask(p), cpu_active_mask);
+	cpumask_clear_cpu(cpu, mask);
+	return false;
+}
+
+static inline bool cpuset_offline_moves_dl(int cpu)
+{
+	return false;
+}
+
 static inline int cpuset_num_cpus(struct cgroup *cgroup)
 {
 	return num_online_cpus();
diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index bdabd54af729..8eb5cd13b9dd 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -35,6 +35,7 @@ extern void dl_clear_root_domain(struct root_domain *rd);
 extern void dl_clear_root_domains(void);
 extern void dl_bw_rebuild_begin(void);
 extern void dl_rebuild_rd_accounting(void);
+extern bool dl_task_holds_bw(struct task_struct *p);
 /*
  * Keep a rebuild of the root domains' accounting and an admission of
  * bandwidth from running at the same time. With cpusets, cpuset_mutex
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 7bdb9e21a7ed..9461277ed0fa 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -1126,6 +1126,28 @@ static void update_partition_sd_lb(struct cpuset *cs, int old_prs)
 		cpuset_force_rebuild();
 }
 
+/*
+ * Set @new_cpus to the effective CPUs that @cp gets. On entry, @new_cpus
+ * holds those that @from gets. @from is @cp or one of its ancestors. Work
+ * down from the child of @from to @cp, as compute_effective_cpumask() does
+ * for a cpuset that is not a valid partition root.
+ */
+static void effective_cpus_below(struct cpuset *cp, struct cpuset *from,
+				 struct cpumask *new_cpus)
+{
+	struct cpuset *a;
+	int depth = 0, i;
+
+	for (a = cp; a != from; a = parent_cs(a))
+		depth++;
+	while (depth--) {
+		for (a = cp, i = 0; i < depth; i++)
+			a = parent_cs(a);
+		if (cpumask_intersects(new_cpus, a->cpus_allowed) || !is_in_v2_mode())
+			cpumask_and(new_cpus, new_cpus, a->cpus_allowed);
+	}
+}
+
 /*
  * tasks_nocpu_error - Return true if tasks will have no effective_cpus
  */
@@ -4312,6 +4334,292 @@ void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
 	spin_unlock_irqrestore(&callback_lock, flags);
 }
 
+/*
+ * Return true if @cs holds a task, or one of its cpusets that is not a
+ * valid partition root does. This is partition_is_populated() for the
+ * offline path, which holds the CPU hotplug lock for writing instead of
+ * cpuset_mutex. That lock keeps tasks from moving to another cgroup:
+ * cgroup_attach_lock() takes it. The caller holds rcu_read_lock().
+ */
+static bool partition_populated_offline(struct cpuset *cs)
+{
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp;
+
+	if (cgroup_has_tasks(cs->css.cgroup))
+		return true;
+	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
+		if (cp == cs)
+			continue;
+		if (is_partition_valid(cp)) {
+			pos_css = css_rightmost_descendant(pos_css);
+			continue;
+		}
+		if (cgroup_is_populated(cp->css.cgroup))
+			return true;
+	}
+	return false;
+}
+
+/*
+ * Return the child partition of the valid partition root @p that the
+ * offline of @cpu makes invalid, or NULL. Set @new_cpus to the active CPUs
+ * that @p then has. This follows compute_partition_effective_cpumask().
+ * The offline can leave a populated @p no CPU of its own. The child
+ * partition that holds the last CPUs left then becomes invalid, and @p
+ * takes its CPUs. The caller holds rcu_read_lock().
+ */
+static struct cpuset *partition_child_lost(struct cpuset *p, int cpu,
+					   struct cpumask *new_cpus)
+{
+	bool populated = partition_populated_offline(p);
+	struct cgroup_subsys_state *css;
+	struct cpuset *child, *lost = NULL;
+
+	cpumask_and(new_cpus, p->effective_xcpus, cpu_active_mask);
+	cpumask_clear_cpu(cpu, new_cpus);
+	if (cpumask_empty(new_cpus))
+		return NULL;
+	cpuset_for_each_child(child, css, p) {
+		if (!is_partition_valid(child))
+			continue;
+		if (populated && cpumask_subset(new_cpus, child->effective_xcpus)) {
+			lost = child;
+			continue;
+		}
+		cpumask_andnot(new_cpus, new_cpus, child->effective_xcpus);
+	}
+	return lost;
+}
+
+/*
+ * Set @pmask to the active CPUs that the cpuset of @tsk gives it once @cpu
+ * is offline. Keep the CPUs possible for @tsk, as
+ * cpuset_update_tasks_cpumask() does. As __set_cpus_allowed_ptr() does,
+ * keep those of the affinity the user set, if one is left. Return true.
+ *
+ * If no CPU possible for @tsk is left, the cpuset cannot set the mask of
+ * @tsk. select_fallback_rq() then picks the CPU. It widens the mask to
+ * cpuset.cpus first, on cgroup v2, then to task_cpu_fallback_mask(): the
+ * housekeeping CPUs. It drops the affinity the user set. Give the active
+ * CPUs of that wider mask, and return false. For a deadline task,
+ * select_fallback_rq() may then pick a CPU of its root domain instead.
+ * The caller checks for that.
+ *
+ * The caller holds the CPU hotplug lock for writing, which keeps the
+ * cpusets and their tasks as they are. It does not keep the housekeeping
+ * CPUs: housekeeping_update() does not take that lock. The caller holds
+ * the pi_lock of @tsk, which keeps its user affinity.
+ */
+bool cpuset_cpus_allowed_without(struct task_struct *tsk, int cpu,
+				 struct cpumask *pmask)
+{
+	const struct cpumask *possible = task_cpu_possible_mask(tsk);
+	struct cpuset *cs = task_cs(tsk), *from, *gone = NULL;
+
+	guard(rcu)();
+	if (!is_in_v2_mode()) {
+		/*
+		 * cgroup v1 moves the tasks of a cpuset left with no CPU to
+		 * the nearest ancestor that keeps one.
+		 */
+		for (from = cs; from; from = parent_cs(from)) {
+			cpumask_and(pmask, from->effective_cpus, cpu_active_mask);
+			cpumask_clear_cpu(cpu, pmask);
+			if (!cpumask_empty(pmask))
+				break;
+		}
+	} else {
+		/*
+		 * cgroup v2 works out the CPUs of each cpuset from the top
+		 * down. A cpuset keeps those of its parent that cpuset.cpus
+		 * holds, or takes all of them if there are none. Start from
+		 * the nearest partition root that keeps an active CPU, or from
+		 * the top cpuset. A partition root left with no CPU of its own
+		 * can take those of a child partition. One left with tasks and
+		 * no CPU becomes invalid, and its tasks count in its parent. If
+		 * that parent has no CPU of its own either, where the tasks end
+		 * depends on the order of the hotplug walk. Stop there, with no
+		 * CPU from the cpuset: cpuset_offline_moves_dl() refuses that
+		 * offline if a deadline task is under that parent.
+		 */
+		for (from = cs; ; from = parent_cs(from)) {
+			if (from != &top_cpuset && !is_partition_valid(from))
+				continue;
+			cpumask_and(pmask, from->effective_cpus, cpu_active_mask);
+			cpumask_clear_cpu(cpu, pmask);
+			if (cpumask_empty(pmask) && from != &top_cpuset && !gone &&
+			    !partition_child_lost(from, cpu, pmask))
+				cpumask_clear(pmask);
+			if (!cpumask_empty(pmask) || from == &top_cpuset || gone)
+				break;
+			if (partition_populated_offline(from))
+				gone = from;
+		}
+		effective_cpus_below(cs, from, pmask);
+	}
+	if (!cpumask_and(pmask, pmask, possible)) {
+		if (is_in_v2_mode() && cpumask_subset(cs->cpus_allowed, possible)) {
+			cpumask_and(pmask, cs->cpus_allowed, cpu_active_mask);
+			cpumask_clear_cpu(cpu, pmask);
+			if (!cpumask_empty(pmask))
+				return false;
+		}
+		cpumask_and(pmask, task_cpu_fallback_mask(tsk), cpu_active_mask);
+		cpumask_clear_cpu(cpu, pmask);
+		return false;
+	}
+	if (tsk->user_cpus_ptr && cpumask_intersects(pmask, tsk->user_cpus_ptr))
+		cpumask_and(pmask, pmask, tsk->user_cpus_ptr);
+	return true;
+}
+
+/*
+ * Scratch mask of cpuset_offline_moves_dl(). The CPU hotplug lock
+ * protects it.
+ */
+static cpumask_t dl_offline_cpus;
+
+/*
+ * Return true if a task of @cs has the deadline policy and holds a
+ * bandwidth. A dead task does not count: it runs no more.
+ */
+static bool dl_task_in_cpuset(struct cpuset *cs)
+{
+	struct css_task_iter it;
+	struct task_struct *task;
+	bool found = false;
+
+	css_task_iter_start(&cs->css, 0, &it);
+	while (!found && (task = css_task_iter_next(&it)))
+		found = task->policy == SCHED_DEADLINE && dl_task_holds_bw(task) &&
+			READ_ONCE(task->__state) != TASK_DEAD;
+	css_task_iter_end(&it);
+	return found;
+}
+
+/*
+ * A child partition of @pp is left with tasks and no CPU by the offline of
+ * @cpu. It becomes invalid, and its tasks count in @pp. Return true if a
+ * deadline task can then change root domain, as far as this can be told
+ * before the offline.
+ *
+ * If @pp keeps a CPU of its own, return false: the walk of the deadline
+ * tasks in dl_cpu_last_of_task() checks the tasks of that child.
+ * Otherwise, where they end depends on the order of the cpuset hotplug
+ * walk, and on later hotplug events. Do not predict it. Go up from @pp
+ * while each partition has no CPU of its own. Return true if a deadline
+ * task is in the last of them, or in a cpuset under it. The caller holds
+ * rcu_read_lock().
+ */
+static bool dl_offline_order_dependent(struct cpuset *pp, int cpu)
+{
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp, *top = NULL;
+	bool found = false;
+
+	for (cp = pp; cp != &top_cpuset && is_partition_valid(cp);
+	     cp = parent_cs(cp)) {
+		cpumask_and(&dl_offline_cpus, cp->effective_cpus, cpu_active_mask);
+		cpumask_clear_cpu(cpu, &dl_offline_cpus);
+		if (!cpumask_empty(&dl_offline_cpus))
+			break;
+		top = cp;
+	}
+	if (!top)
+		return false;
+	cpuset_for_each_descendant_pre(cp, pos_css, top) {
+		if (!css_tryget_online(&cp->css))
+			continue;
+		rcu_read_unlock();
+		found = dl_task_in_cpuset(cp);
+		rcu_read_lock();
+		css_put(&cp->css);
+		if (found)
+			break;
+	}
+	return found;
+}
+
+/*
+ * Return true if the offline of @cpu makes a partition invalid, and a
+ * deadline task of its cpusets then runs in another root domain. That root
+ * domain did not admit the task.
+ *
+ * The partition root @p that holds @cpu can be left with no CPU of its
+ * own. It then takes the CPUs of a child partition, which becomes invalid
+ * with its own child partitions. A task of these cpusets keeps its root
+ * domain in two cases only. Its partition is isolated, and so is @p: the
+ * CPUs stay in the default root domain. Or its partition is the child
+ * whose CPUs @p takes, and neither is isolated. The root domain of @p
+ * then spans all the CPUs of the root domain of that child, and counts
+ * the bandwidth admitted there. A child partition of that child had a
+ * root domain of its own: this case does not cover its tasks.
+ * If @cpu is the last CPU left to the top cpuset, every partition becomes
+ * invalid. The top cpuset takes their CPUs, and every deadline task
+ * changes root domain, those of the top cpuset too.
+ *
+ * The caller holds the CPU hotplug lock for writing, which keeps the
+ * cpusets and their tasks as they are.
+ */
+bool cpuset_offline_moves_dl(int cpu)
+{
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp, *a, *p = &top_cpuset, *lost = NULL;
+	bool found = false;
+
+	if (!is_in_v2_mode())
+		return false;
+	rcu_read_lock();
+	cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
+		if (cp != &top_cpuset && is_partition_valid(cp) &&
+		    cpumask_test_cpu(cpu, cp->effective_cpus)) {
+			p = cp;
+			break;
+		}
+	}
+	if (p != &top_cpuset) {
+		lost = partition_child_lost(p, cpu, &dl_offline_cpus);
+		if (!lost && cpumask_empty(&dl_offline_cpus) &&
+		    partition_populated_offline(p) &&
+		    parent_cs(p) != &top_cpuset && is_partition_valid(parent_cs(p))) {
+			found = dl_offline_order_dependent(parent_cs(p), cpu);
+			rcu_read_unlock();
+			return found;
+		}
+	} else {
+		cpumask_and(&dl_offline_cpus, top_cpuset.effective_cpus, cpu_active_mask);
+		cpumask_clear_cpu(cpu, &dl_offline_cpus);
+		if (cpumask_empty(&dl_offline_cpus) && !cpumask_empty(subpartitions_cpus))
+			lost = &top_cpuset;
+	}
+	if (!lost) {
+		rcu_read_unlock();
+		return false;
+	}
+	cpuset_for_each_descendant_pre(cp, pos_css, lost) {
+		/* The partition that gives @cp its CPUs. */
+		for (a = cp; a != lost && !is_partition_valid(a); a = parent_cs(a))
+			;
+		if (lost != &top_cpuset &&
+		    ((a->partition_root_state == PRS_ISOLATED &&
+		      p->partition_root_state == PRS_ISOLATED) ||
+		     (a == lost && a->partition_root_state != PRS_ISOLATED &&
+		      p->partition_root_state != PRS_ISOLATED)))
+			continue;
+		if (!css_tryget_online(&cp->css))
+			continue;
+		rcu_read_unlock();
+		found = dl_task_in_cpuset(cp);
+		rcu_read_lock();
+		css_put(&cp->css);
+		if (found)
+			break;
+	}
+	rcu_read_unlock();
+	return found;
+}
+
 /**
  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
  * @tsk: pointer to task_struct with which the scheduler is struggling
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index dbf709fd0fd4..cb738ad23b12 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -370,6 +370,12 @@ static inline bool dl_se_holds_bw(struct sched_dl_entity *dl_se)
 	       !(dl_se->flags & SCHED_FLAG_SUGOV);
 }
 
+/* Return true if a root domain counts the bandwidth of @p. */
+bool dl_task_holds_bw(struct task_struct *p)
+{
+	return dl_se_holds_bw(&p->dl);
+}
+
 /*
  * Put @p on dl_departed_list. The root domain of the CPU recorded with it
  * keeps its bandwidth. @p leaves SCHED_DEADLINE, or dies, before its
@@ -5215,9 +5221,79 @@ 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. A dead task runs no
+ * more. It can wait for its 0-lag time, or for its parent to reap it.
+ * Return false for it.
+ */
+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);
+	if (READ_ONCE(p->__state) == TASK_DEAD || dl_task_bw_span(p) != span)
+		return false;
+	msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
+	/* A task in a migrate_disable() section has a cpus_ptr of one CPU. */
+	cpumask_and(msk, &p->cpus_mask, cpu_active_mask);
+	cpumask_clear_cpu(cpu, msk);
+	/* With no CPU left, ask which CPUs the cpuset gives @p. */
+	if (cpumask_empty(msk) && !cpuset_cpus_allowed_without(p, cpu, msk)) {
+		/*
+		 * select_fallback_rq() picks the CPU. It gives @p the CPUs of
+		 * @span if one of them is active and @p can run on all of them.
+		 */
+		if (cpumask_any_and_but(span, cpu_active_mask, cpu) < nr_cpu_ids &&
+		    cpumask_subset(span, task_cpu_possible_mask(p)))
+			return false;
+	}
+	return !cpumask_empty(msk) && !cpumask_intersects(msk, span);
+}
+
+/*
+ * 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 can hold CPUs of two root domains: with isolcpus="domain", or on
+ * cgroup v1 with sched_load_balance off.
+ *
+ * Also return true if the offline makes a cpuset partition invalid, and a
+ * deadline task then runs in another root 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())
+		return false;
+	/* No task holds a bandwidth: do not walk the task list. */
+	if (!atomic_read(&dl_nr_bw_tasks))
+		return false;
+	if (cpuset_offline_moves_dl(cpu))
+		return true;
+	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;
+	}
+	return false;
+}
+
 int dl_bw_deactivate(int cpu)
 {
-	return dl_bw_manage(dl_bw_req_deactivate, cpu, 0);
+	int ret = dl_bw_manage(dl_bw_req_deactivate, cpu, 0);
+
+	if (!ret && dl_cpu_last_of_task(cpu))
+		ret = -EBUSY;
+	return ret;
 }
 
 int dl_bw_alloc(int cpu, u64 dl_bw)
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 17/43] cgroup/cpuset: Refuse to take a deadline task out of its root domain
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (12 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 16/43] sched/deadline: Keep the last CPU a task has in its root domain Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 19/43] sched/deadline: Count only active CPUs when spreading extra_bw Mathieu Desnoyers
                   ` (20 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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

A cpuset that is not a partition root can hold CPUs of two root
domains. This happens with isolcpus="domain", or on cgroup v1 with
sched_load_balance off. 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.

A task goes to another root domain by a move to another cpuset, which
asks for room. So refuse both changes:

 - 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 change that leaves each deadline task a CPU in its root domain is
accepted as before.

Like __set_cpus_allowed_ptr(), the check keeps the new mask within the
affinity set by the user, if they intersect. So a mask that grows can
also take a task out of its root domain, and it is checked too.

cpuset cannot refuse these changes, so they are not checked:
 - disabling a partition;
 - a partition that cpuset makes invalid;
 - a CPU that comes online.

dl_task_keeps_root_domain() tells whether a new mask keeps a task in the
root domain that counts it. It accepts any mask for a dead task, which
does not run again. 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.

cpuset calls it on each task of a cpuset whose CPUs change. cpuset skips
this walk when no task holds a deadline bandwidth, or without admission
control.

The check runs before the rebuild of the sched domains, which ends the
change. A partition root whose CPUs grew can then have tasks counted in
a root domain that does not span the new CPUs yet. A child partition
can take the old CPUs, and leave these tasks only the new ones. A check
of that span alone would refuse the child. The child would then stay
invalid until the next change. So for a root or an isolated partition,
the check also accepts the CPUs that the partition has after the
change. The rebuild gives those of a root partition to its root
domain, and those of an isolated one to the default root domain.

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

Fixes: f82f80426f7a ("sched/deadline: Ensure that updates to exclusive cpusets don't break AC")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched/deadline.h  |   4 +
 kernel/cgroup/cpuset-internal.h |   1 +
 kernel/cgroup/cpuset.c          | 218 +++++++++++++++++++++++++++++++-
 kernel/sched/deadline.c         |  50 ++++++++
 4 files changed, 270 insertions(+), 3 deletions(-)

diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index 8eb5cd13b9dd..26cda4460604 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -63,6 +63,10 @@ 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,
+				      const struct cpumask *pending);
+extern bool dl_tasks_hold_bw(void);
 
 static inline bool dl_server(struct sched_dl_entity *dl_se)
 {
diff --git a/kernel/cgroup/cpuset-internal.h b/kernel/cgroup/cpuset-internal.h
index a83443dfb788..8fe0225704eb 100644
--- a/kernel/cgroup/cpuset-internal.h
+++ b/kernel/cgroup/cpuset-internal.h
@@ -36,6 +36,7 @@ enum prs_errcode {
 	PERR_ACCESS,
 	PERR_REMOTE,
 	PERR_ISOPARENT,
+	PERR_DLTASK,
 };
 
 /* bits in struct cpuset flags field */
diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
index 9461277ed0fa..62f0c7e6a97b 100644
--- a/kernel/cgroup/cpuset.c
+++ b/kernel/cgroup/cpuset.c
@@ -61,6 +61,7 @@ static const char * const perr_strings[] = {
 	[PERR_ACCESS]    = "Enable partition not permitted",
 	[PERR_REMOTE]    = "Have remote partition underneath",
 	[PERR_ISOPARENT] = "Root partition is not allowed with isolated parent",
+	[PERR_DLTASK]    = "Deadline task would leave its root domain",
 };
 
 /*
@@ -1126,6 +1127,38 @@ static void update_partition_sd_lb(struct cpuset *cs, int old_prs)
 		cpuset_force_rebuild();
 }
 
+/*
+ * Return false if the CPUs of @new_cpus make a deadline task of @cp leave
+ * the root domain that counts its bandwidth. @pending, if not NULL, holds
+ * the CPUs that the rebuild at the end of the change gives to that root
+ * domain. Called under rcu_read_lock(), which it drops and takes again.
+ */
+static bool dl_tasks_keep_cpus(struct cpuset *cp, const struct cpumask *new_cpus,
+			       const struct cpumask *pending)
+{
+	struct css_task_iter it;
+	struct task_struct *task;
+	bool keep = true;
+
+	if (!dl_tasks_hold_bw() || !css_tryget_online(&cp->css))
+		return true;
+	rcu_read_unlock();
+
+	css_task_iter_start(&cp->css, 0, &it);
+	while (keep && (task = css_task_iter_next(&it))) {
+		/* The top cpuset leaves the mask of these tasks alone. */
+		if (cp == &top_cpuset &&
+		    (task->flags & (PF_KTHREAD | PF_NO_SETAFFINITY)))
+			continue;
+		keep = dl_task_keeps_root_domain(task, new_cpus, pending);
+	}
+	css_task_iter_end(&it);
+
+	rcu_read_lock();
+	css_put(&cp->css);
+	return keep;
+}
+
 /*
  * Set @new_cpus to the effective CPUs that @cp gets. On entry, @new_cpus
  * holds those that @from gets. @from is @cp or one of its ancestors. Work
@@ -1148,6 +1181,96 @@ static void effective_cpus_below(struct cpuset *cp, struct cpuset *from,
 	}
 }
 
+/*
+ * A scratch mask for dl_tasks_keep_without(). Its callers still need each
+ * mask of their struct tmpmasks after the call. Protected by
+ * cpuset_mutex.
+ */
+static cpumask_var_t dl_keep_cpus, dl_pending_cpus;
+
+/*
+ * Return false if a partition that takes the CPUs of @xcpus makes a
+ * deadline task leave the root domain that counts its bandwidth. A cpuset
+ * can hold CPUs of two root domains: with isolcpus="domain", or on cgroup
+ * v1 with sched_load_balance off. Such a task would run in a root domain
+ * that did not admit it.
+ *
+ * @root is the partition root that gives the CPUs. @part is the cpuset
+ * that takes them. In the same change, @part can give the CPUs of @gives
+ * back to @root. @gives is NULL if it gives none back.
+ *
+ * Work out the new CPUs of each cpuset of @root from the top down, as
+ * update_cpumasks_hier() does, down to the next partition roots. If
+ * @enable, @part becomes a partition root. Then do the same for its own
+ * cpusets, starting from the active CPUs of @xcpus.
+ */
+static bool dl_tasks_keep_without(struct cpuset *root, struct cpuset *part,
+				  const struct cpumask *xcpus,
+				  const struct cpumask *gives, bool enable)
+{
+	struct cpumask *new_cpus = dl_keep_cpus, *pending = NULL;
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp;
+	bool keep = true;
+
+	lockdep_assert_cpuset_lock_held();
+	/*
+	 * The CPUs of @root can have changed before the rebuild of the
+	 * sched domains, which ends the change. Then the root domain of a
+	 * task of @root does not span them yet. The rebuild gives the CPUs
+	 * of a root partition to one root domain. It gives those of an
+	 * isolated partition, and of its valid children, to the default
+	 * root domain.
+	 */
+	if (root->partition_root_state == PRS_ROOT ||
+	    root->partition_root_state == PRS_ISOLATED) {
+		pending = dl_pending_cpus;
+		cpumask_copy(pending, root->effective_cpus);
+		if (root == &top_cpuset)
+			cpumask_and(pending, pending,
+				    housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
+	}
+	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;
+		}
+		/* The CPUs that @root has after the change. */
+		cpumask_copy(new_cpus, root->effective_cpus);
+		if (gives) {
+			cpumask_or(new_cpus, new_cpus, gives);
+			cpumask_and(new_cpus, new_cpus, cpu_active_mask);
+		}
+		cpumask_andnot(new_cpus, new_cpus, xcpus);
+		effective_cpus_below(cp, root, new_cpus);
+		if (cpumask_equal(cp->effective_cpus, new_cpus))
+			continue;
+		keep = dl_tasks_keep_cpus(cp, new_cpus, pending);
+		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;
+			}
+			cpumask_and(new_cpus, xcpus, cpu_active_mask);
+			effective_cpus_below(cp, part, new_cpus);
+			if (cpumask_equal(cp->effective_cpus, new_cpus))
+				continue;
+			keep = dl_tasks_keep_cpus(cp, new_cpus,
+				root->partition_root_state == PRS_ISOLATED ?
+				pending : NULL);
+			if (!keep)
+				break;
+		}
+	}
+	rcu_read_unlock();
+	return keep;
+}
+
 /*
  * tasks_nocpu_error - Return true if tasks will have no effective_cpus
  */
@@ -1698,6 +1821,8 @@ static int remote_partition_enable(struct cpuset *cs, int new_prs,
 		return PERR_NOCPUS;
 	if (prstate_housekeeping_conflict(new_prs, PRS_ROOT, tmp->new_cpus, NULL))
 		return PERR_HKEEPING;
+	if (!dl_tasks_keep_without(&top_cpuset, cs, tmp->new_cpus, NULL, true))
+		return PERR_DLTASK;
 
 	spin_lock_irq(&callback_lock);
 	partition_xcpus_add(new_prs, NULL, tmp->new_cpus);
@@ -1801,6 +1926,10 @@ 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,
+						deleting ? tmp->delmask : NULL,
+						false))
+			WRITE_ONCE(cs->prs_err, PERR_DLTASK);
 		if (cs->prs_err)
 			goto invalidate;
 	}
@@ -1948,6 +2077,9 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		if (nocpu)
 			return PERR_NOCPUS;
 
+		if (!dl_tasks_keep_without(parent, cs, tmp->delmask, NULL, true))
+			return PERR_DLTASK;
+
 		/*
 		 * This function will only be called when all the preliminary
 		 * checks have passed. At this point, the following condition
@@ -2035,6 +2167,20 @@ 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 &&
+			   !dl_tasks_keep_without(parent, cs, tmp->delmask,
+						  adding ? tmp->addmask : NULL,
+						  is_partition_invalid(cs))) {
+			/*
+			 * As above: the partition is or becomes invalid. Only
+			 * a valid one holds CPUs of its parent to give back.
+			 */
+			part_error = PERR_DLTASK;
+			deleting = false;
+			if (is_partition_valid(cs))
+				adding = cpumask_and(tmp->addmask,
+						     cs->effective_xcpus,
+						     parent->effective_xcpus);
 		}
 	} else {
 		/*
@@ -2106,10 +2252,13 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 				}
 				rcu_read_unlock();
 			}
-			if (exclusive)
-				deleting = !cpumask_empty(tmp->delmask);
-			else
+			if (!exclusive)
 				part_error = PERR_NOTEXCL;
+			else if (!dl_tasks_keep_without(parent, cs, tmp->delmask,
+							NULL, true))
+				part_error = PERR_DLTASK;
+			else
+				deleting = !cpumask_empty(tmp->delmask);
 		}
 		/*
 		 * When both cs and parent remain valid, parent's
@@ -2518,6 +2667,62 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
 	}
 }
 
+/*
+ * Set @new_cpus to the effective CPUs that @cp gets if @cs takes the CPUs
+ * of @trialcs. @cp is @cs or one of its descendants.
+ */
+static void trial_effective_cpus(struct cpuset *cp, struct cpuset *cs,
+				 struct cpuset *trialcs, struct cpumask *new_cpus)
+{
+	struct cpuset *parent = parent_cs(cs);
+
+	if (!cpumask_and(new_cpus, trialcs->cpus_allowed, parent->effective_cpus) &&
+	    is_in_v2_mode())
+		cpumask_copy(new_cpus, parent->effective_cpus);
+	effective_cpus_below(cp, cs, new_cpus);
+}
+
+/*
+ * Return false if the CPUs of @trialcs make a deadline task of @cs, or of
+ * a descendant, leave the root domain that counts its bandwidth. A cpuset
+ * can hold CPUs of two root domains: with isolcpus="domain", or on cgroup
+ * v1 with sched_load_balance off. The task would run in a root domain that
+ * did not admit it. Only a move to another cpuset can take the task
+ * there. The move asks the other root domain for room.
+ *
+ * A partition root takes its CPUs from its parent, which checks the same
+ * for its own tasks: see dl_tasks_keep_without().
+ */
+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);
+		/*
+		 * Test a mask that grows too. A task whose user affinity
+		 * holds none of the old CPUs gets only the new ones.
+		 */
+		if (cpumask_equal(cp->effective_cpus, new_cpus))
+			continue;
+		keep = dl_tasks_keep_cpus(cp, new_cpus, NULL);
+		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
@@ -2550,6 +2755,11 @@ static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
 	if (alloc_tmpmasks(&tmp))
 		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.
@@ -3983,6 +4193,8 @@ int __init cpuset_init(void)
 
 	BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
 	BUG_ON(!zalloc_cpumask_var(&dl_attach_cpus, GFP_KERNEL));
+	BUG_ON(!alloc_cpumask_var(&dl_keep_cpus, GFP_KERNEL));
+	BUG_ON(!alloc_cpumask_var(&dl_pending_cpus, GFP_KERNEL));
 
 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT))
 		cpumask_andnot(isolated_cpus, cpu_possible_mask,
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index cb738ad23b12..882e7bc5a934 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -5296,6 +5296,56 @@ int dl_bw_deactivate(int cpu)
 	return ret;
 }
 
+/*
+ * Return false if @p has CPUs in the root domain that counts its
+ * bandwidth and @new_mask holds none of them. A cpuset refuses such a
+ * mask: only a move to another cpuset makes room in another root domain.
+ * Like __set_cpus_allowed_ptr(), keep @new_mask within the affinity set by
+ * the user, if they intersect. @pending is NULL, or holds the CPUs that
+ * the rebuild at the end of the change gives to the root domain of a
+ * partition root.
+ */
+bool dl_task_keeps_root_domain(struct task_struct *p,
+			       const struct cpumask *new_mask,
+			       const struct cpumask *pending)
+{
+	const struct cpumask *span, *user = cpu_possible_mask;
+
+	if (!dl_bandwidth_enabled() || !task_has_dl_policy(p))
+		return true;
+	/* A dead task does not run again, so its mask does not matter. */
+	if (READ_ONCE(p->__state) == TASK_DEAD)
+		return true;
+	/* pi_lock also protects p->user_cpus_ptr. */
+	guard(raw_spinlock_irqsave)(&p->pi_lock);
+	guard(rcu)();
+	span = dl_task_bw_span(p);
+	/* A task in a migrate_disable() section has a cpus_ptr of one CPU. */
+	if (!span || !cpumask_intersects(span, &p->cpus_mask))
+		return true;
+	if (p->user_cpus_ptr && cpumask_intersects(new_mask, p->user_cpus_ptr))
+		user = p->user_cpus_ptr;
+	if (cpumask_intersects_and(span, new_mask, user))
+		return true;
+	/*
+	 * The rebuild at the end of the change can give the root domain
+	 * of @p the CPUs of @pending. Test those too.
+	 */
+	return pending && cpumask_intersects(span, pending) &&
+	       cpumask_intersects_and(pending, new_mask, user);
+}
+
+/*
+ * Return true if admission control is on and a task holds a bandwidth.
+ * Otherwise dl_task_keeps_root_domain() accepts any mask. The caller must
+ * hold cpuset_mutex. A task gets a bandwidth only under it, in
+ * __sched_setscheduler(), so none gets one while the caller holds it.
+ */
+bool dl_tasks_hold_bw(void)
+{
+	return dl_bandwidth_enabled() && atomic_read(&dl_nr_bw_tasks);
+}
+
 int dl_bw_alloc(int cpu, u64 dl_bw)
 {
 	return dl_bw_manage(dl_bw_req_alloc, cpu, dl_bw);
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 19/43] sched/deadline: Count only active CPUs when spreading extra_bw
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (13 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 17/43] cgroup/cpuset: Refuse to take a deadline task out of " Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
                   ` (19 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

__dl_add() and __dl_sub() change the total_bw of a root domain. They
also spread the change over the extra_bw of its CPUs, which GRUB uses
for SCHED_FLAG_RECLAIM tasks. __dl_update() changes only the active
CPUs, so the cpus argument must count those. Most callers pass
dl_bw_cpus(), which does.

dl_task_offline_migration() and dl_add_task_root_domain() pass
cpumask_weight(rd->span) instead. That also counts the inactive CPUs of
the span. A span holds one while that CPU goes offline, which is when
dl_task_offline_migration() runs. Each active CPU then gets a smaller
share of the change than it should. A later change made with
dl_bw_cpus() does not undo it exactly. extra_bw stays off until the
next rebuild of the root domains resets it. SCHED_FLAG_RECLAIM tasks
would reclaim a little more or less than their share meanwhile. This
was found by reading.

Fix this by passing dl_bw_cpus() of the CPU whose root domain changes.

Fixes: 59d06cea1198 ("sched/deadline: Fix bandwidth accounting at all levels after offline migration")
Fixes: f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 882e7bc5a934..3f02d150e15d 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1076,7 +1076,7 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 			dl_b = &src_rq->rd->dl_bw;
 			raw_spin_lock(&dl_b->lock);
 			__dl_sub(dl_b, p->dl.dl_bw,
-				 cpumask_weight(src_rq->rd->span));
+				 dl_bw_cpus(cpu_of(src_rq)));
 			raw_spin_unlock(&dl_b->lock);
 		}
 		/*
@@ -1088,7 +1088,7 @@ static struct rq *dl_task_offline_migration(struct rq *rq, struct task_struct *p
 		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));
+			 dl_bw_cpus(cpu_of(later_rq)));
 		raw_spin_unlock(&dl_b->lock);
 		dl_record_bw_cpu(&p->dl, later_rq->cpu);
 		p->dl.dl_bw_gen = dl_bw_gen;
@@ -4366,7 +4366,7 @@ void dl_add_task_root_domain(struct task_struct *p)
 	dl_b = &rq->rd->dl_bw;
 
 	raw_spin_lock(&dl_b->lock);
-	__dl_add(dl_b, p->dl.dl_bw, cpumask_weight(rq->rd->span));
+	__dl_add(dl_b, p->dl.dl_bw, dl_bw_cpus(cpu));
 	raw_spin_unlock(&dl_b->lock);
 	dl_record_bw_cpu(&p->dl, cpu);
 	p->dl.dl_bw_gen = dl_bw_gen;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub()
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (14 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 19/43] sched/deadline: Count only active CPUs when spreading extra_bw Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-30 12:56   ` Juri Lelli
  2026-11-30 14:12   ` David Laight
  2026-11-27 14:35 ` [PATCH v12 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes Mathieu Desnoyers
                   ` (18 subsequent siblings)
  34 siblings, 2 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

__dl_add() and __dl_sub() spread a change of total_bw over the extra_bw
of the active CPUs of the root domain. Commit daec57983670
("sched/deadline: Reclaim bandwidth not used by dl tasks") added this,
for the bandwidth of one task. That is at most 1 << 20, the bandwidth
of one CPU.

But cpuset_can_attach() reserves the sum of the bandwidths of all the
deadline tasks it moves, with dl_bw_alloc(). __dl_add() and __dl_sub()
cast the bandwidth to s32 before the division. Past S32_MAX, more than
2048 CPUs of deadline bandwidth, the cast flips its sign. The extra_bw
of each CPU then moves the wrong way. GRUB lets reclaiming tasks run
more than the free bandwidth, or less. This was found by reading. It
needs a machine with more than 2048 CPUs, so no case tests it.

Fix this by dividing on 64 bits, with div_u64().

The Sashiko AI review of the first series found this.

Fixes: daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 3f02d150e15d..7a6057326611 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -205,7 +205,7 @@ void __dl_sub(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
 {
 	dl_b->total_bw -= tsk_bw;
 	if (cpus)
-		__dl_update(dl_b, (s32)tsk_bw / cpus);
+		__dl_update(dl_b, div_u64(tsk_bw, cpus));
 }
 
 static inline
@@ -213,7 +213,7 @@ void __dl_add(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
 {
 	dl_b->total_bw += tsk_bw;
 	if (cpus)
-		__dl_update(dl_b, -((s32)tsk_bw / cpus));
+		__dl_update(dl_b, -(s64)div_u64(tsk_bw, cpus));
 }
 
 static inline bool
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (15 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed Mathieu Desnoyers
                   ` (17 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A task boosted by a SCHED_DEADLINE waiter runs on the parameters of a
donor, dl.pi_se. The top waiter can itself be a boosted task without
deadline parameters of its own. So the donor follows the chain since
commit 2279f540ea7d ("sched/deadline: Fix priority inheritance with
multiple scheduling classes"). rt_mutex_setprio() copies the donor of
the top waiter to the owner. The owner at the end of a chain then
points at the deadline task at its head. That task waits on no lock the
owner holds.

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

But the donor of a blocked task can change while its keys stay the
same. The task keeps a deadline priority. It sleeps, so no refill
moves its deadline. The walk then stops one lock too early, and the
next owner keeps the old donor. Three changes do this:
- A boost by a waiter with an earlier deadline than the current
  donor. The diagram below shows it.
- A deboost. A deadline task, boosted by a waiter with an earlier
  deadline, blocks on a second lock. When that waiter leaves,
  rt_mutex_setprio() makes the task its own donor again.
- A policy change in __setscheduler_dl_pi(). rt_mutex_adjust_pi() then
  skips the walk.

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

  O            M                       W                       Z

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

O runs on W's parameters, with a later deadline than Z's, while Z waits
for it. After W exits, O's next refill would read W's freed task_struct.
Setting up the deadline tasks needs CAP_SYS_NICE. The timeout of a
FUTEX_LOCK_PI needs no privilege.

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

A known limit remains. A walk records the donor of a blocked task in
its waiter, then drops the pi_lock of that task. At the owner of the
next lock, rt_mutex_setprio() reads that donor again, without that
pi_lock. A new waiter of the task can change the donor in between. A
sched_setattr() can then change it back, before the walk of the new
waiter passes. Both walks then find the waiter up to date, and stop
requeueing there. The owner would keep the donor of the new waiter
until a later change of the chain. This can happen on a chain of two
locks. "sched/deadline: Hold a reference on the deadline donor of a
boosted task", later in this series, keeps the task_struct of that
donor alive. This was found by reading.

The case pi_chain_top_moves of deadline_bw_test, added later in this
series, needs this patch and the next one. If one of the two is
missing, another deadline task gets 30ms of 200ms in every run, in
place of 60ms. With both, it passes. The older case
pi_chain_donor_leaves has W leave SCHED_DEADLINE in place of exiting.
It passes on v7.4-rc2, and without this patch.

The Sashiko AI review of this series found the deboost case.

Fixes: 2279f540ea7d ("sched/deadline: Fix priority inheritance with multiple scheduling classes")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org # v5.15+
---
 kernel/locking/rtmutex.c        | 22 ++++++++++++++++++++--
 kernel/locking/rtmutex_api.c    |  2 +-
 kernel/locking/rtmutex_common.h |  3 +++
 3 files changed, 24 insertions(+), 3 deletions(-)

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


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (16 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task Mathieu Desnoyers
                   ` (16 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

rt_mutex_adjust_prio_chain() stops the walk early at an owner in two
cases. Each case misses a change of the owner's priority:
- The owner's top pi waiter is not the top waiter of the lock just
  walked. That lock then does not set the owner's priority, so there is
  nothing to pass on. But the step before can requeue a waiter whose
  priority dropped. The top pi waiter of the owner can then be a waiter
  on another lock. The owner's priority, or its deadline donor, changed.
  With deadlock detection on, the walk went on, but without requeueing.
  It now requeues there too.
- The owner has no pi waiters left. A waiter that left caused this, and
  remove_waiter() walks on from the owner itself. But that walk can be
  preempted and come late.

The walk then stops at the owner, and the next owner keeps the old
priority or the old donor. With deadline tasks, the old donor can exit.
The refill of the next owner would then read its freed task_struct.
When the waiters are SCHED_FIFO tasks, the first case leaves the next
owner boosted to the old priority until it releases its lock.

Fix this by removing both checks. The next check already stops the walk
when the owner's waiter is up to date. An out of date waiter is now
requeued, and the walk goes on to the next owner. A late walk can still
leave an owner on an exited donor for a while. The next patch keeps the
donor's task_struct alive as long as a boost points at it.

The first case, with deadline tasks. O and M are SCHED_OTHER tasks. W
and Z are SCHED_DEADLINE tasks. W has the earlier deadline. X is a
SCHED_FIFO task. It takes the top of L1' from W:

   O         M                 W                                  Z             X

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

The second case. O, M and X are SCHED_OTHER tasks. W is a
SCHED_DEADLINE task. Another task, S, changes the policy of W:

  O         M            S                          W                          X

  locks L2  locks L1
            blocks on L2
                                                    blocks on L1
                                                      M, O get W's parameters
                                                                               blocks on L1
                         sched_setscheduler(W)
                           walk at L1: W behind X,
                             M deboosted
                                                    times out on L1
                                                      not top waiter: no walk
                                                                               times out on L1
                                                                                 M: no pi waiters
                                                                                 walk from M:
                                                                                   preempted
                           walk at M:
                             no pi waiters, stops
                                                    exits
  runs out of runtime
    refill reads O->dl.pi_se:
      W's freed task_struct

The cases pi_chain_top_moves and pi_chain_top_moves_rt, added to
deadline_bw_test later in this series, test the first case.
pi_chain_top_moves_rt fails without this patch and passes with it.
pi_chain_top_moves also needs the previous patch. No case tests the
second one: it needs a walk preempted at the right step.

The Sashiko AI review of this series found both cases.

Fixes: 23f78d4a03c5 ("[PATCH] pi-futex: rt mutex core")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/locking/rtmutex.c | 27 +++++++--------------------
 1 file changed, 7 insertions(+), 20 deletions(-)

diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c
index c78dfe9c93fc..b09816977d4e 100644
--- a/kernel/locking/rtmutex.c
+++ b/kernel/locking/rtmutex.c
@@ -818,27 +818,14 @@ static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
 		detect_deadlock = false;
 
 	/*
-	 * Drop out, when the task has no waiters. Note,
-	 * top_waiter can be NULL, when we are in the deboosting
-	 * mode!
+	 * Do not stop at a task that has no pi waiters, or whose top pi
+	 * waiter is not top_waiter. The previous step can have made a
+	 * waiter on another lock the top pi waiter of the task. A waiter
+	 * can also have left meanwhile, and its own walk can be late. The
+	 * priority of the task changed then, and the next owner must
+	 * follow. The test below tells whether there is something to pass
+	 * on.
 	 */
-	if (top_waiter) {
-		if (!task_has_pi_waiters(task))
-			goto out_unlock_pi;
-		/*
-		 * If deadlock detection is off, we stop here if we
-		 * are not the top pi waiter of the task. If deadlock
-		 * detection is enabled we continue, but stop the
-		 * requeueing in the chain walk.
-		 */
-		if (top_waiter != task_top_pi_waiter(task)) {
-			if (!detect_deadlock)
-				goto out_unlock_pi;
-			else
-				requeue = false;
-		}
-	}
-
 	/*
 	 * If the waiter priority is the same as the task priority
 	 * then there is no further priority adjustment necessary. The
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (17 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-30 14:25   ` Juri Lelli
  2026-11-27 14:35 ` [PATCH v12 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
                   ` (15 subsequent siblings)
  34 siblings, 1 reply; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A task boosted by a SCHED_DEADLINE waiter runs on the parameters of a
donor, dl.pi_se. Since commit 2279f540ea7d ("sched/deadline: Fix
priority inheritance with multiple scheduling classes"),
rt_mutex_setprio() copies the donor of the top waiter to the owner. So
each owner along a chain points at the deadline task at its head.

rt_mutex_setprio() keeps the top waiter, pi_top_task, as a plain
pointer. The top waiter is blocked, so it cannot exit. The donor further
up the chain has no such guarantee. When it stops waiting, the owners
below it are fixed by chain walks. A walk can be preempted, and it runs
in the context of the task that started it, not the donor's. So the
donor can exit before the walk reaches the last owner.

M, O and P are SCHED_OTHER tasks. W is a SCHED_DEADLINE task:

  P         O              M                          W

  locks L3  locks L2       locks L1
            blocks on L3
                           blocks on L2
                                                      blocks on L1
                                                        M, O, P get W's parameters
                           times out on L2
                             O deboosted
                             walk from O: preempted
                                                      times out on L1
                                                        M not blocked: no walk
                                                      exits
  runs out of runtime
    refill reads P->dl.pi_se:
      W's freed task_struct

P would run on parameters read from freed memory, until M's walk
reaches it. Setting up the deadline task needs CAP_SYS_NICE. The
timeout of a FUTEX_LOCK_PI needs no privilege. This was found by
reading.

Fix this by holding a reference on the donor's task, for each task whose
donor is another task. dl_set_donor() gives a task the donor of its top
waiter. dl_clear_donor() ends the boost. Both move the reference. A
late walk can still leave P on the parameters of an exited donor for a
while. P now reads them from valid memory.

Three details of the fix:
- dl_set_donor() reads the donor of the top waiter without the waiter's
  locks. Another CPU can change that donor at the same time, and put
  the last reference on the old one. So dl_set_donor() takes its
  reference with tryget_task_struct(). If that fails, it reads the new
  donor again.
- put_task_struct() can run under the rq lock, because it frees the
  task through call_rcu(). This holds for every task since v6.17:
  commit 8671bad873eb ("sched: Do not call __put_task_struct() on rt if
  pi_blocked_on is set"). Before it, put_task_struct() frees the task
  at once without PREEMPT_RT. So stable trees older than v6.17 need
  that commit first.
- __dl_clear_params() no longer resets the donor. switched_from_dl()
  can call it on a boosted task, before the deboost drops the
  reference. init_dl_entity() resets it for a new task, whose copy of
  the pointer holds no reference.

No case tests the use after free: it needs a walk preempted at the right
step.

Fixes: 2279f540ea7d ("sched/deadline: Fix priority inheritance with multiple scheduling classes")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org # 6.16.x and older: 8671bad873eb: sched: Do not call __put_task_struct() on rt if pi_blocked_on is set
Cc: stable@vger.kernel.org
---
 kernel/sched/core.c     |  8 +++---
 kernel/sched/deadline.c | 12 ++++++---
 kernel/sched/sched.h    | 56 +++++++++++++++++++++++++++++++++++++++++
 kernel/sched/syscalls.c |  4 +--
 4 files changed, 70 insertions(+), 10 deletions(-)

diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 45e794bd39a3..2700c8e98b0e 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7980,19 +7980,19 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 			if (!dl_prio(p->normal_prio) ||
 			    (pi_task && dl_prio(pi_task->prio) &&
 			     dl_entity_preempt(&pi_task->dl, &p->dl))) {
-				p->dl.pi_se = pi_task->dl.pi_se;
+				dl_set_donor(&p->dl, pi_task);
 				scope->flags |= ENQUEUE_REPLENISH;
 			} else {
-				p->dl.pi_se = &p->dl;
+				dl_clear_donor(&p->dl);
 			}
 		} else if (rt_prio(prio)) {
 			if (dl_prio(oldprio))
-				p->dl.pi_se = &p->dl;
+				dl_clear_donor(&p->dl);
 			if (oldprio < prio)
 				scope->flags |= ENQUEUE_HEAD;
 		} else {
 			if (dl_prio(oldprio))
-				p->dl.pi_se = &p->dl;
+				dl_clear_donor(&p->dl);
 			if (rt_prio(oldprio))
 				p->rt.timeout = 0;
 		}
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 7a6057326611..d481bf5a68c7 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -5089,10 +5089,6 @@ 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;
-
-#ifdef CONFIG_RT_MUTEXES
-	dl_se->pi_se			= dl_se;
-#endif
 }
 
 void init_dl_entity(struct sched_dl_entity *dl_se)
@@ -5107,6 +5103,14 @@ void init_dl_entity(struct sched_dl_entity *dl_se)
 	 */
 	dl_se->dl_bw = 0;
 	__dl_clear_params(dl_se);
+#ifdef CONFIG_RT_MUTEXES
+	/*
+	 * The copy points at the donor of the parent, without a reference.
+	 * Reset it here only: __dl_clear_params() can run on a boosted entity,
+	 * from switched_from_dl() before the deboost drops its reference.
+	 */
+	dl_se->pi_se = dl_se;
+#endif
 	dl_se->dl_bw_cpu = -1;
 	dl_se->dl_bw_resv_cpu = -1;
 	INIT_LIST_HEAD(&dl_se->dl_departed_node);
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index e2bb192f1ee6..859d782cc899 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -356,6 +356,62 @@ 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
+/*
+ * Make @pi_se the deadline donor of @dl_se. The caller holds a reference
+ * on the task of @pi_se, unless @pi_se is @dl_se. Put the reference on
+ * the old donor.
+ */
+static inline void dl_replace_donor(struct sched_dl_entity *dl_se,
+				    struct sched_dl_entity *pi_se)
+{
+	struct sched_dl_entity *old = dl_se->pi_se;
+
+	WRITE_ONCE(dl_se->pi_se, pi_se);
+	if (old != dl_se)
+		put_task_struct(container_of(old, struct task_struct, dl));
+}
+
+/*
+ * Make the deadline donor of the waiter @pi_task the donor of @dl_se. A
+ * boosted entity holds a reference on the task of its donor. The donor
+ * is the deadline task at the head of the chain. It can stop waiting
+ * and exit before the chain walk reaches @dl_se: that walk can be
+ * preempted.
+ *
+ * The donor of @pi_task is read without the locks of @pi_task. Another
+ * CPU can change it meanwhile, and put the last reference on the old
+ * donor. That CPU stores the new donor first: read it again then. The
+ * old task_struct stays readable while the rq lock is held:
+ * put_task_struct() frees it through call_rcu(), and the rq lock holds
+ * off the grace period.
+ *
+ * The caller holds the rq lock and the pi_lock of the task of @dl_se.
+ */
+static inline void dl_set_donor(struct sched_dl_entity *dl_se,
+				struct task_struct *pi_task)
+{
+	struct sched_dl_entity *pi_se;
+
+	for (;;) {
+		pi_se = READ_ONCE(pi_task->dl.pi_se);
+		if (pi_se == dl_se->pi_se)
+			return;
+		if (pi_se == dl_se ||
+		    tryget_task_struct(container_of(pi_se, struct task_struct, dl)))
+			break;
+		/* Pairs with the ordering of refcount_dec_and_test(). */
+		smp_rmb();
+	}
+	dl_replace_donor(dl_se, pi_se);
+}
+
+/* Make @dl_se its own donor. The caller holds the rq lock of its task. */
+static inline void dl_clear_donor(struct sched_dl_entity *dl_se)
+{
+	dl_replace_donor(dl_se, dl_se);
+}
+#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);
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 16fd65825367..79285e66e051 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -300,7 +300,7 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
 		struct task_struct *pi_task = rt_mutex_get_top_task(p);
 
 		if (pi_task) {
-			p->dl.pi_se = pi_task->dl.pi_se;
+			dl_set_donor(&p->dl, pi_task);
 			scope->flags |= ENQUEUE_REPLENISH;
 		}
 	}
@@ -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_clear_donor(&p->dl);
 }
 #else /* !CONFIG_RT_MUTEXES */
 static inline void __setscheduler_dl_pi(int newprio, int policy,
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 25/43] sched/deadline: Count the 0-lag time from the next period
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (18 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-30 16:47   ` Juri Lelli
  2026-11-27 14:35 ` [PATCH v12 26/43] sched/deadline: Keep a departing constrained task until its " Mathieu Desnoyers
                   ` (14 subsequent siblings)
  34 siblings, 1 reply; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A deadline task that blocks keeps counting in running_bw until its
0-lag time. Commit 209a0cbda7a0 ("sched/deadline: Improve the tracking
of active utilization") added this for GRUB. A task that leaves the
class or exits also keeps its bandwidth in total_bw until then.
Commit 387e31300b57 ("sched/deadline: Fix the update of the
total -deadline utilization") added that.

The 0-lag time is when the task, served at its bandwidth since the
start of its period, has received the runtime it used. That is:

  next period - runtime * dl_period / dl_runtime

Here runtime is the runtime left. GRUB [1] has the same formula (rule 5
of section 4.1), with the deadline in place of the next period. In
GRUB, the deadline is always the end of the period (rules 1 and 3). For
a constrained deadline, rule R6 of [2] puts the end of the period at
deadline - dl_deadline + dl_period. This is what dl_next_period()
returns.

dl_time_to_zerolag() uses the deadline in place of the next period. The
two are the same only for an implicit deadline. A constrained deadline
comes dl_period - dl_deadline before the next period. So the 0-lag time
comes that much too early.

For example, take a task with a runtime of 10ms, a deadline of 20ms and
a period of 500ms. It runs 2ms into its period, then sleeps with 8ms
left. dl_time_to_zerolag() puts its 0-lag time at
20 - 8 * 500 / 10 = -380ms, before the task even blocked. Counted from
the next period, it is 500 - 400 = 100ms.

On v7.4-rc2, this would affect a constrained task:
- When it blocks, GRUB reclaiming would give its bandwidth to
  SCHED_FLAG_RECLAIM tasks too early. Schedutil could lower the CPU
  frequency too early. Deadline tasks could then miss their deadlines.
- When it exits or leaves the class, admission control could admit
  other tasks into a temporary overload.
This was found by reading.

Fix this by counting the 0-lag time from the next period, with
dl_next_period(). Update the formula in
Documentation/scheduler/sched-deadline.rst too.

This needs "sched/deadline: Fix an overflow of the 0-lag time with long
periods", which adds dl_time_to_zerolag().

A task that leaves the class and comes back after its 0-lag time
starts a new period. "sched/deadline: Reset the deadline and the
runtime with the parameters" does this. So a constrained task can come
back after the early 0-lag time, before its next period. It then runs
again before that next period. Three cases of deadline_bw_test check
this: reenter_runnable_in_gap, reenter_asleep_in_gap and
reenter_pi_blocked_in_gap. "selftests/sched: Test parameter changes in
deadline_bw_test", later in this series, adds them. They fail without
this patch and pass from it on.

[1] L. Abeni, G. Lipari, A. Parri, Y. Sun, "Parallel and sequential
    reclaiming in multicore real-time global scheduling", arXiv
    1512.01984, 2016, https://arxiv.org/abs/1512.01984
[2] D. Casini, L. Abeni, A. Biondi, T. Cucinotta, G. Buttazzo,
    "Constant Bandwidth Servers with Constrained Deadlines", RTNS 2017,
    https://retis.santannapisa.it/~a.biondi/papers/CBS_CD_RTNS17.pdf

Fixes: 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 Documentation/scheduler/sched-deadline.rst | 12 ++++----
 kernel/sched/deadline.c                    | 32 ++++++++++++++--------
 2 files changed, 27 insertions(+), 17 deletions(-)

diff --git a/Documentation/scheduler/sched-deadline.rst b/Documentation/scheduler/sched-deadline.rst
index 9019b66f6a5b..3529b667c07f 100644
--- a/Documentation/scheduler/sched-deadline.rst
+++ b/Documentation/scheduler/sched-deadline.rst
@@ -171,12 +171,14 @@ Deadline Task Scheduling
       The 0-lag time for a task entering the ActiveNonContending state is
       computed as::
 
-                        (runtime * dl_period)
-             deadline - ---------------------
-                             dl_runtime
+                           (runtime * dl_period)
+             next period - ---------------------
+                                dl_runtime
 
-      where runtime is the remaining runtime, while dl_runtime and dl_period
-      are the reservation parameters.
+      where runtime is the remaining runtime, next period is the start of
+      the task's next period, and dl_runtime and dl_period are the
+      reservation parameters. When dl_deadline equals dl_period, the next
+      period starts at the deadline.
 
   (b) If the task wakes up before the inactive timer fires, the task re-enters
       the ActiveContending state and the "inactive timer" is canceled.
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index d481bf5a68c7..7dc0b71e7cce 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -607,6 +607,7 @@ static void dl_change_utilization(struct task_struct *p, u64 new_bw)
 	dl_rq_change_utilization(task_rq(p), &p->dl, new_bw);
 }
 
+static inline u64 dl_next_period(struct sched_dl_entity *dl_se);
 static void __dl_clear_params(struct sched_dl_entity *dl_se);
 static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
 
@@ -614,14 +615,17 @@ static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
  * Return the time from now to the 0-lag time of @dl_se, or a negative
  * value if the 0-lag time has passed.
  *
- * The 0-lag time is when a task running at its reserved bandwidth would
- * use up the runtime it has left:
+ * The 0-lag time is when the task, served at its reserved bandwidth
+ * since the start of its period, has received the runtime it used. From
+ * there to the next period, the bandwidth gives exactly the runtime left:
  *
- *   0-lag = deadline - runtime * dl_period / dl_runtime
+ *   0-lag = next period - runtime * dl_period / dl_runtime
  *
  * Example: 30ms every 100ms, blocking 10ms into its period with 20ms
- * left. 0-lag = 100 - 20 * 100 / 30 = 33ms. From there to the deadline,
- * 30% of the CPU is exactly the 20ms left.
+ * left. 0-lag = 100 - 20 * 100 / 30 = 33ms.
+ *
+ * Do not count from the deadline. A constrained deadline comes before
+ * the next period, so the 0-lag time would come too early.
  *
  * The product can overflow 64 bits, so mul_u64_u64_div_u64() multiplies
  * on 128 bits. Its quotient must still fit: on x86-64 it traps
@@ -633,12 +637,16 @@ static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
  */
 static s64 dl_time_to_zerolag(struct sched_dl_entity *dl_se, struct rq *rq)
 {
-	/* Time to the deadline. Negative if the deadline has passed. */
-	s64 left = dl_se->deadline - rq_clock(rq);
+	/* Time to the next period. Negative if it has started. */
+	s64 left = dl_next_period(dl_se) - rq_clock(rq);
+
+	/* A task with no period yet has received nothing: no 0-lag time. */
+	if (!dl_se->deadline)
+		return -1;
 
 	if (dl_se->runtime < 0) {
 		/*
-		 * Overrun: the 0-lag time is after the deadline, by the time
+		 * Overrun: the 0-lag time is after the next period, by the time
 		 * needed to pay the overrun back at the reserved bandwidth.
 		 */
 		u64 overrun = -dl_se->runtime;
@@ -659,8 +667,8 @@ static s64 dl_time_to_zerolag(struct sched_dl_entity *dl_se, struct rq *rq)
 	}
 
 	/*
-	 * Runtime left: the 0-lag time is before the deadline. It has
-	 * passed if the deadline has.
+	 * Runtime left: the 0-lag time is before the next period. It has
+	 * passed if the next period has started.
 	 */
 	if (left < 0)
 		return -1;
@@ -668,7 +676,7 @@ static s64 dl_time_to_zerolag(struct sched_dl_entity *dl_se, struct rq *rq)
 	/*
 	 * runtime * dl_period / dl_runtime > left: the 0-lag time has
 	 * passed. The runtime left is more than the bandwidth gives until
-	 * the deadline, as a wakeup would find with dl_entity_overflow().
+	 * the next period.
 	 */
 	if (dl_se->runtime > mul_u64_u64_div_u64(left, dl_se->dl_runtime,
 						 dl_se->dl_period)) {
@@ -1756,7 +1764,7 @@ static inline void dl_check_constrained_dl(struct sched_dl_entity *dl_se)
 {
 	struct rq *rq = rq_of_dl_se(dl_se);
 
-	if (dl_time_before(dl_se->deadline, rq_clock(rq)) &&
+	if (dl_se->deadline && dl_time_before(dl_se->deadline, rq_clock(rq)) &&
 	    dl_time_before(rq_clock(rq), dl_next_period(dl_se))) {
 		if (unlikely(is_dl_boosted(dl_se) || !start_dl_timer(dl_se)))
 			return;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 26/43] sched/deadline: Keep a departing constrained task until its next period
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (19 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep Mathieu Desnoyers
                   ` (13 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A task that leaves SCHED_DEADLINE keeps its bandwidth until its 0-lag
time, so that leaving and coming back gains nothing. Until the series
this one builds on, it also kept its deadline. For an implicit
deadline, losing it after the 0-lag time changes nothing: a wakeup in
the class then starts a new period anyway. A constrained task in the
class keeps its deadline until its next period. Past its deadline, its
wakeup throttles it until then.

That series clears the deadline of a task when it releases its
bandwidth:
- "sched/deadline: Reset the deadline and the runtime with the
  parameters" resets the deadline in __dl_clear_params().
- "sched/deadline: Release the bandwidth of a task that leaves the class
  asleep" adds this release for a task that leaves the class asleep
  with no timer pending.

So a constrained task that leaves the class between its 0-lag time and
its next period now loses its deadline. If it comes back before its
next period, it gets a new period at once. Repeated, this gives the
task more than its bandwidth. Other deadline tasks could then miss
their deadlines.

For example, take a task with a runtime of 10ms, a deadline of 20ms and
a period of 500ms. Its period starts at 0ms.
 1. It runs 2ms, then sleeps with 8ms left. Its 0-lag time is
    500 - 8 * 500 / 10 = 100ms.
 2. At 200ms, it is past its 0-lag time and before its next period.
    Another thread calls sched_setattr() to make it SCHED_OTHER, then
    SCHED_DEADLINE again. Leaving the class releases its bandwidth and
    clears its deadline.
 3. At 205ms, it wakes up. Its wakeup starts a new period at once, not
    at 500ms. Between 0ms and 500ms, it can run 12ms, not 10ms.

Fix this by keeping the bandwidth and the deadline of a constrained
task that leaves the class until its next period. task_non_contending()
and inactive_task_timer() wait for the later of the 0-lag time and the
next period. In the example, the task keeps its deadline at 200ms. Its
wakeup throttles it until 500ms.

inactive_task_timer() restarts itself until the next period.
switched_to_dl() cannot cancel it while its handler runs. So the timer
can stay queued after the task comes back to the class. The next
task_non_contending() would then take the 0-lag time as passed. It now
cancels such a timer first.

The proof of Lemma 5.1 in [1] uses the same rule for its H-CBSD-W
server. A server that used up its budget while idle stays throttled
until the end of its period, as a sporadic task would.

The cost: a constrained task that leaves the class keeps its bandwidth
in total_bw up to one period longer. Until then, sched_setattr() can
fail with EBUSY for a new deadline task.

A backport of the two patches above needs this one, and
"sched/deadline: Count the 0-lag time from the next period" before it.

"selftests/sched: Test parameter changes in deadline_bw_test", later in
this series, adds the reenter_asleep_late_in_gap case. It runs the
example above, with the round trip at 150ms. The case fails without
this patch, and passes with it.

[1] D. Casini, L. Abeni, A. Biondi, T. Cucinotta, G. Buttazzo,
    "Constant Bandwidth Servers with Constrained Deadlines", RTNS 2017,
    https://retis.santannapisa.it/~a.biondi/papers/CBS_CD_RTNS17.pdf

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 49 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 48 insertions(+), 1 deletion(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 7dc0b71e7cce..adcd9c9f8a9d 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -761,8 +761,35 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 
 	WARN_ON(dl_se->dl_non_contending);
 
+	/*
+	 * inactive_task_timer() restarts itself for a constrained task that
+	 * has left the class. If the task came back while the handler ran,
+	 * switched_to_dl() could not cancel the timer, and it is still
+	 * queued. Cancel it here, so that the test below sees only a handler
+	 * that is running.
+	 */
+	if (!dl_server(dl_se) && hrtimer_try_to_cancel(timer) == 1)
+		put_task_struct(dl_task_of(dl_se));
+
 	zerolag_time = dl_time_to_zerolag(dl_se, rq);
 
+	/*
+	 * A constrained task that leaves the class keeps its bandwidth and its
+	 * deadline until its next period, if that comes after its 0-lag time.
+	 * Back in the class before then, it goes on with its current period,
+	 * as if it had stayed. A new period at once would give it more than
+	 * its runtime in this period. A dying task does not come back, so it
+	 * releases its bandwidth at its 0-lag time.
+	 */
+	if (!dl_task && !dl_server(dl_se) && !dl_is_implicit(dl_se) &&
+	    dl_se->deadline &&
+	    READ_ONCE(dl_task_of(dl_se)->__state) != TASK_DEAD) {
+		s64 next = dl_next_period(dl_se) - rq_clock(rq);
+
+		if (next > zerolag_time)
+			zerolag_time = next;
+	}
+
 	/*
 	 * If the "0-lag time" already passed, decrease the active
 	 * utilization now, instead of starting a timer
@@ -2602,6 +2629,25 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 	if (dl_server(dl_se))
 		goto no_task;
 
+	/*
+	 * A constrained task which has left the class keeps its bandwidth
+	 * and its deadline until its next period, as in
+	 * task_non_contending(). This timer may have been armed for the
+	 * 0-lag time while the task was still in the class.
+	 */
+	if (!dl_task(p) && READ_ONCE(p->__state) != TASK_DEAD &&
+	    !dl_is_implicit(dl_se)) {
+		s64 left = dl_next_period(dl_se) - rq_clock(rq);
+
+		if (left > 0) {
+			ktime_t at = ktime_add_ns(hrtimer_cb_get_time(timer), left);
+
+			hrtimer_set_expires(timer, at);
+			task_rq_unlock(rq, p, &rf);
+			return HRTIMER_RESTART;
+		}
+	}
+
 	if (!dl_task(p) || READ_ONCE(p->__state) == TASK_DEAD) {
 		if (READ_ONCE(p->__state) == TASK_DEAD && dl_se->dl_non_contending) {
 			sub_running_bw(&p->dl, dl_rq_of_se(&p->dl));
@@ -4576,7 +4622,8 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 	 * the "inactive timer" fires, it can continue to consume its current
 	 * runtime using its current deadline. If it stays outside of
 	 * SCHED_DEADLINE until the 0-lag time passes, inactive_task_timer()
-	 * will reset the task parameters.
+	 * will reset the task parameters. For a constrained task, the reset
+	 * waits for its next period, if that is later.
 	 */
 	if (task_on_rq_queued(p) && p->dl.dl_runtime)
 		task_non_contending(&p->dl, false);
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (20 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 26/43] sched/deadline: Keep a departing constrained task until its " Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-30 14:48   ` Juri Lelli
  2026-11-27 14:35 ` [PATCH v12 28/43] sched/deadline: Restore the owner's period at a deboost in the class Mathieu Desnoyers
                   ` (12 subsequent siblings)
  34 siblings, 1 reply; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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

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

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

  T                                  W                              T's timer

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

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

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

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

The Sashiko AI review of this series found this.

Fixes: feff2e65efd8 ("sched/deadline: Unthrottle PI boosted threads while enqueuing")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index adcd9c9f8a9d..a6ca7870416e 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1690,10 +1690,13 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
 	}
 
 	/*
-	 * The task might have been boosted by someone else and might be in the
-	 * boosting/deboosting path, its not throttled.
+	 * A boost overrides the throttle. enqueue_task_dl() lifts it when the
+	 * boost enqueues the task, or when the task wakes up boosted. So a
+	 * queued task needs nothing here. A boost of a sleeping task does not
+	 * enqueue it, and it can end before the wakeup. Nothing would lift the
+	 * throttle then. So let a sleeping task reach the !queued case below.
 	 */
-	if (is_dl_boosted(dl_se))
+	if (is_dl_boosted(dl_se) && task_on_rq_queued(p))
 		goto unlock;
 
 	/*
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 28/43] sched/deadline: Restore the owner's period at a deboost in the class
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (21 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 29/43] sched/deadline: Count the bandwidth a boosted task is given Mathieu Desnoyers
                   ` (11 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A task that holds an rt_mutex wanted by a deadline task is boosted. That
deadline task is its donor. Commit 2d3d891d3344 ("sched/deadline: Add
SCHED_DEADLINE inheritance logic") gives the boosted task the donor's
parameters "during the whole period it holds the pi-lock". When its
runtime runs out, replenish_dl_entity() refills it from the donor: it
adds the donor's runtime, and moves the deadline by the donor's period.

A task that stays in the class at its deboost keeps these values.
rt_mutex_setprio() only resets dl.pi_se. So after the unlock, the task
can run the rest of the donor's refill on top of its own runtime, in
one of its own periods. Other deadline tasks would then miss their
deadlines.

In M-BWI [1], the owner goes back to its own server at the unlock. Do
the same here:
- At the first refill from the donor, the new dl_hold_refilled_boost()
  saves the task's own deadline and runtime, and sets dl_boost_held.
  A negative runtime is saved as 0: that overrun comes from the boost.
- At the deboost, the new dl_deboost() puts them back. A task whose own
  runtime is used up, or whose own deadline has passed, is throttled
  until its own next period. If that period has started, the task
  starts it. The runtime put back is capped at what the task's own
  density allows, as update_dl_revised_wakeup() does.
- A task asleep on anything but an rt_mutex, and not throttled before
  the boost, is not throttled and starts no period. A period started
  while it sleeps could end before it wakes. Its wakeup throttles it,
  or starts its next period.
- A task with no parameters of its own at the first refill has nothing
  saved. If sched_setattr() gives it parameters during the boost, its
  deboost starts a new period from them. A new flag, dl_donor_refill,
  records the refill.

dl_deboost() runs at the deboost, not at the next enqueue. A task
blocked on another rt_mutex is not enqueued, and the chain walk copies
its deadline into its waiter node first. dl_deboost() also cancels an
inactive timer armed from the donor's values, and computes the 0-lag
time again. Right after a deboost starts a period, that time is exactly
now. task_non_contending() now takes it as passed. The deadline put
back can be later than the top waiter's: rt_mutex_setprio() then boosts
the task again.

"sched/deadline: Restore the owner's period at a deboost out of the
class", later in this series, does the same for a task that leaves the
class at its deboost.

The Sashiko AI review of this series found the sched_setattr() case and
the inactive timer. deboost_in_class_resets_period and
deboost_after_donor_refill, added to deadline_bw_test later in this
series, fail without this patch, in every run.

[1] D. Faggioli, G. Lipari, T. Cucinotta, "Analysis and Implementation
    of the Multiprocessor BandWidth Inheritance Protocol", Real-Time
    Systems, 2012, section 5.1

Fixes: 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched.h   |  16 ++++
 kernel/sched/core.c     |  16 +++-
 kernel/sched/deadline.c | 205 +++++++++++++++++++++++++++++++++++++++-
 kernel/sched/sched.h    |  14 +++
 kernel/sched/syscalls.c |   2 +-
 5 files changed, 245 insertions(+), 8 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 0c89263b1db9..5a056a2914d0 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -661,6 +661,9 @@ struct sched_dl_entity {
 	 */
 	s64				runtime;	/* Remaining runtime for this instance	*/
 	u64				deadline;	/* Absolute deadline for this instance	*/
+	/* Saved when a boost is held: see dl_boost_held */
+	u64				own_deadline;
+	s64				own_runtime;
 	unsigned int			flags;		/* Specifying the scheduler behaviour	*/
 
 	/*
@@ -683,6 +686,17 @@ struct sched_dl_entity {
 	 * @dl_overrun tells if the task asked to be informed about runtime
 	 * overruns.
 	 *
+	 * @dl_donor_refill tells if a replenishment changed the runtime of
+	 * a boosted task. The replenishment used the parameters of its
+	 * donor, or set the runtime to 0 when those were cleared. The
+	 * runtime and deadline are then not those of the task's own
+	 * reservation. The end of the boost clears the flag.
+	 *
+	 * @dl_boost_held tells that own_deadline and own_runtime hold the
+	 * task's own deadline and runtime. The first refill of a boost saves
+	 * them, for a task with parameters of its own. The deboost puts them
+	 * back.
+	 *
 	 * @dl_server tells if this is a server entity.
 	 *
 	 * @dl_server_active tells if the dlserver is active(started).
@@ -715,6 +729,8 @@ 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_boost_held     : 1;
 	unsigned int			dl_server         : 1;
 	unsigned int			dl_server_active  : 1;
 	unsigned int			dl_defer	  : 1;
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 2700c8e98b0e..7a3a7e755d20 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7983,16 +7983,26 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 				dl_set_donor(&p->dl, pi_task);
 				scope->flags |= ENQUEUE_REPLENISH;
 			} else {
-				dl_clear_donor(&p->dl);
+				dl_deboost(&p->dl);
+				/*
+				 * The deadline that dl_deboost() gives back
+				 * can 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)) {
+					dl_set_donor(&p->dl, pi_task);
+					scope->flags |= ENQUEUE_REPLENISH;
+				}
 			}
 		} else if (rt_prio(prio)) {
 			if (dl_prio(oldprio))
-				dl_clear_donor(&p->dl);
+				dl_drop_boost(&p->dl);
 			if (oldprio < prio)
 				scope->flags |= ENQUEUE_HEAD;
 		} else {
 			if (dl_prio(oldprio))
-				dl_clear_donor(&p->dl);
+				dl_drop_boost(&p->dl);
 			if (rt_prio(oldprio))
 				p->rt.timeout = 0;
 		}
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index a6ca7870416e..c7f6b45d2a3a 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -83,6 +83,60 @@ static inline int on_dl_rq(struct sched_dl_entity *dl_se)
 	return !RB_EMPTY_NODE(&dl_se->rb_node);
 }
 
+/*
+ * Start a period of the reservation of @dl_se now. The caller holds the rq
+ * lock and has updated the rq clock.
+ */
+static inline void dl_start_own_period(struct sched_dl_entity *dl_se)
+{
+	dl_se->deadline = rq_clock(rq_of_dl_se(dl_se)) + dl_se->dl_deadline;
+	dl_se->runtime = dl_se->dl_runtime;
+}
+
+/*
+ * Put back the deadline and runtime saved when the boost was held, by
+ * dl_hold_refilled_boost(). If the task's own next period has started
+ * since, start a period of its own instead. Return true if the boost was
+ * held. The caller holds the rq lock and has updated the rq clock.
+ *
+ * A task @asleep on anything but an rt_mutex gets that period at its
+ * wakeup instead: a period started now would run while it sleeps.
+ */
+static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se,
+				     bool asleep)
+{
+	u64 now = rq_clock(rq_of_dl_se(dl_se));
+	u64 next = dl_se->own_deadline - dl_se->dl_deadline + dl_se->dl_period;
+
+	if (!dl_se->dl_boost_held)
+		return false;
+	if (dl_time_before(now, next)) {
+		dl_se->deadline = dl_se->own_deadline;
+		dl_se->runtime = dl_se->own_runtime;
+		/*
+		 * Past its own deadline, the task is in its constrained gap:
+		 * it waits for its own next period. Give back no runtime, so
+		 * that dl_deboost() throttles it. Before its deadline,
+		 * dl_hold_refilled_boost() can keep runtime left, from a
+		 * wakeup refill. Cap it at what the task's own density allows
+		 * until its deadline, as update_dl_revised_wakeup() does.
+		 */
+		if (!dl_time_before(now, dl_se->deadline))
+			dl_se->runtime = 0;
+		else if (dl_se->runtime > 0)
+			dl_se->runtime = min_t(s64, dl_se->runtime,
+					       (dl_se->dl_density *
+						(dl_se->deadline - now)) >> BW_SHIFT);
+	} else if (asleep) {
+		dl_se->deadline = dl_se->own_deadline;
+		dl_se->runtime = 0;
+	} else {
+		dl_start_own_period(dl_se);
+	}
+	dl_se->dl_donor_refill = 0;
+	return true;
+}
+
 #ifdef CONFIG_RT_MUTEXES
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -93,12 +147,116 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return pi_of(dl_se) != dl_se;
 }
+
+static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se);
+
+/*
+ * Record that a replenishment changes the runtime of @dl_se while it is
+ * boosted. At the first refill, dl_hold_refilled_boost() saves the
+ * task's own deadline and runtime. Call this before the replenishment
+ * adds runtime or moves the deadline. A task with no parameters of its
+ * own at the first refill, or no period yet, has no period to save. The
+ * deboost then starts a period of its own. Later refills of the
+ * same boost save nothing, even if the task gets parameters meanwhile.
+ */
+static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
+{
+	bool first;
+
+	if (!is_dl_boosted(dl_se))
+		return;
+	first = !dl_se->dl_donor_refill;
+	dl_se->dl_donor_refill = 1;
+	if (first && dl_se->dl_runtime && dl_se->deadline &&
+	    !dl_se->dl_boost_held)
+		dl_hold_refilled_boost(dl_se);
+}
+
+static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task);
+static int start_dl_timer(struct sched_dl_entity *dl_se);
+
+/*
+ * End the boost of @dl_se, whose task stays in the class. Then bring the
+ * runtime and the deadline of the task back to its own parameters:
+ *  - After a held boost, dl_end_held_boost() puts back the values that
+ *    dl_hold_refilled_boost() saved. The time the task ran on the
+ *    donor's refills is not charged to its own runtime. If that runtime
+ *    is used up, throttle the task again until its own next period, or
+ *    start that period if it has started.
+ *  - After a refill of a task that had no parameters of its own at the
+ *    refill, start a new period now, or at the wakeup of a task asleep.
+ *  - Without a refill, the task keeps the runtime and the deadline of its
+ *    own reservation.
+ * Do it 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.
+ *
+ * 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 task_struct *p = dl_task_of(dl_se);
+	bool asleep = !task_on_rq_queued(p) && !p->pi_blocked_on;
+	bool held = dl_end_held_boost(dl_se, asleep);
+	bool own = held;
+
+	if (dl_se->dl_donor_refill) {
+		/* A task asleep gets its first own period at its wakeup. */
+		if (asleep) {
+			dl_se->deadline = 0;
+			dl_se->runtime = 0;
+		} else {
+			dl_start_own_period(dl_se);
+		}
+		own = true;
+	}
+	/*
+	 * If the task blocked while boosted, its inactive timer can be armed
+	 * from the runtime and deadline of the donor's refills. Cancel it, and
+	 * work out the 0-lag time again from the runtime and deadline the task
+	 * gets back.
+	 * If the timer handler is already running, it releases the
+	 * bandwidth.
+	 */
+	if (own && dl_se->dl_non_contending &&
+	    hrtimer_try_to_cancel(&dl_se->inactive_timer) == 1) {
+		dl_se->dl_non_contending = 0;
+		put_task_struct(p);
+		task_non_contending(dl_se, true);
+	}
+	dl_drop_boost(dl_se);
+
+	/*
+	 * A held boost can end before the task's own next period, with its
+	 * own runtime used up. Throttle the task until that period. If
+	 * start_dl_timer() finds that the period has already started, start
+	 * it now. Leave a task asleep to its wakeup, unless it was throttled
+	 * before the boost: its wakeup throttles it, or starts its next
+	 * period.
+	 */
+	if (held && dl_se->runtime <= 0 && (!asleep || dl_se->dl_throttled)) {
+		struct rq *rq = task_rq(p);
+
+		dl_se->dl_throttled = 1;
+		if (!start_dl_timer(dl_se)) {
+			dl_se->dl_throttled = 0;
+			if (!asleep)
+				dl_start_own_period(dl_se);
+		} else if (task_current_donor(rq, p)) {
+			resched_curr(rq);
+		}
+	}
+}
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
 	return dl_se;
 }
 
+static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
+{
+}
+
 static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return false;
@@ -791,10 +949,12 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 	}
 
 	/*
-	 * If the "0-lag time" already passed, decrease the active
-	 * utilization now, instead of starting a timer
+	 * If the "0-lag time" is now or already passed, decrease the active
+	 * utilization now, instead of starting a timer. A deboost can call
+	 * this right after it starts a period. The 0-lag time is then
+	 * exactly now.
 	 */
-	if ((zerolag_time < 0) || hrtimer_active(&dl_se->inactive_timer)) {
+	if ((zerolag_time <= 0) || hrtimer_active(&dl_se->inactive_timer)) {
 		if (dl_server(dl_se)) {
 			sub_running_bw(dl_se, dl_rq);
 		} else {
@@ -1144,6 +1304,7 @@ static void wakeup_preempt_dl(struct rq *rq, struct task_struct *p, int flags);
 static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 					    struct rq *rq)
 {
+	dl_note_donor_refill(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;
@@ -1243,11 +1404,14 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 	if (unlikely(!runtime || !deadline || !period)) {
 		WARN_ON_ONCE(!is_dl_boosted(dl_se));
 		if (!dl_se->dl_deadline) {
+			dl_note_donor_refill(dl_se);
 			dl_se->deadline = rq_clock(rq);
 			dl_se->runtime = 0;
 		}
-		if (dl_se->runtime < 0 || dl_se->dl_yielded)
+		if (dl_se->runtime < 0 || dl_se->dl_yielded) {
 			dl_se->runtime = 0;
+			dl_note_donor_refill(dl_se);
+		}
 		dl_se->dl_yielded = 0;
 		dl_se->dl_throttled = 0;
 		return;
@@ -1265,6 +1429,7 @@ 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_note_donor_refill(dl_se);
 		dl_se->deadline = rq_clock(rq) + deadline;
 		dl_se->runtime = runtime;
 	}
@@ -1272,6 +1437,9 @@ static void replenish_dl_entity(struct sched_dl_entity *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
@@ -5013,6 +5181,33 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	return err;
 }
 
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * A boosted task is refilled from its donor when its runtime is used up,
+ * or when its deadline has passed. A wakeup also refills it when the
+ * donor's density does not allow the runtime left. After the first
+ * refill, the runtime and the deadline of the task are no longer those
+ * of its own reservation. So save them in own_* at that refill: this
+ * holds the boost. dl_deboost() puts them back.
+ *
+ * Keep the runtime left if the task's own deadline is still ahead.
+ * Otherwise save no runtime. A negative runtime is an overrun that comes
+ * from the boost, so the task's own reservation does not pay for it (see
+ * replenish_dl_entity()).
+ *
+ * The caller holds the rq lock of the task, and has updated the rq clock.
+ */
+static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
+{
+	u64 now = rq_clock(rq_of_dl_se(dl_se));
+
+	dl_se->own_deadline = dl_se->deadline;
+	dl_se->own_runtime = dl_time_before(now, dl_se->deadline) ?
+			     max_t(s64, dl_se->runtime, 0) : 0;
+	dl_se->dl_boost_held = 1;
+}
+#endif /* CONFIG_RT_MUTEXES */
+
 /*
  * This function initializes the sched_dl_entity of a newly becoming
  * SCHED_DEADLINE task.
@@ -5142,6 +5337,8 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se)
 	dl_se->dl_yielded		= 0;
 	dl_se->dl_non_contending	= 0;
 	dl_se->dl_overrun		= 0;
+	dl_se->dl_donor_refill		= 0;
+	dl_se->dl_boost_held		= 0;
 	dl_se->dl_server		= 0;
 	dl_se->dl_defer			= 0;
 	dl_se->dl_defer_running		= 0;
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 859d782cc899..b53885c624fd 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -411,6 +411,20 @@ static inline void dl_clear_donor(struct sched_dl_entity *dl_se)
 {
 	dl_replace_donor(dl_se, dl_se);
 }
+
+extern void dl_deboost(struct sched_dl_entity *dl_se);
+
+/*
+ * End the boost of @dl_se, and forget the deadline and runtime saved for
+ * it. dl_deboost() puts them back first, for a task that stays in the
+ * class. The caller holds the rq lock of its task.
+ */
+static inline void dl_drop_boost(struct sched_dl_entity *dl_se)
+{
+	dl_clear_donor(dl_se);
+	dl_se->dl_donor_refill = 0;
+	dl_se->dl_boost_held = 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);
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 79285e66e051..9778663fe370 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -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))
-		dl_clear_donor(&p->dl);
+		dl_drop_boost(&p->dl);
 }
 #else /* !CONFIG_RT_MUTEXES */
 static inline void __setscheduler_dl_pi(int newprio, int policy,
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 29/43] sched/deadline: Count the bandwidth a boosted task is given
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (22 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 28/43] sched/deadline: Restore the owner's period at a deboost in the class Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 30/43] sched/deadline: Start a period for a task that enters the class blocked Mathieu Desnoyers
                   ` (10 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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 this patch
removes the WARN_ON_ONCE() for SCHED_FLAG_SUGOV there.
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. sched_dl_overflow() now admits such a
bandwidth as new. Without room, that fails with EBUSY. The Sashiko AI
review of this series 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")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Reviewed-by: Juri Lelli <juri.lelli@redhat.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 54 ++++++++++++++++++++++++++++++++---------
 1 file changed, 43 insertions(+), 11 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index c7f6b45d2a3a..26cab0470cb7 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -747,22 +747,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. This holds
+	 * for a task that enters the class asleep, for a special entity given
+	 * a reservation of its own, and for 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 inline u64 dl_next_period(struct sched_dl_entity *dl_se);
@@ -5095,10 +5110,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
@@ -5113,6 +5124,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 = dl_task_admit_cpu(p);
 	dl_b = dl_bw_of(cpu);
 
@@ -5142,7 +5163,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)) {
 		/*
@@ -5219,8 +5239,20 @@ static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 30/43] sched/deadline: Start a period for a task that enters the class blocked
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (23 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 29/43] sched/deadline: Count the bandwidth a boosted task is given Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 31/43] sched/deadline: Restore the owner's period at a deboost out of the class Mathieu Desnoyers
                   ` (9 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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 that blocks by itself is running, so its deadline is a
current one.

A task can also enter the class while it waits on an rt_mutex. Another
task can make it SCHED_DEADLINE with sched_setattr(). A priority
inheritance boost can also put it in the class, if it owns another
rt_mutex. switched_to_dl() does not set up a task that is not queued.
Its wakeup does. But the chain walk that follows the change reads the
deadline before that wakeup, 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 while the task waits, as
setup_new_dl_entity() does at an enqueue. The period uses the
parameters the task runs on: its own, or its donor's when it is
boosted. At the wakeup, update_dl_entity() then checks that period as
for any wakeup. Two places start the period:
 - switched_to_dl(), for a task that waits on an rt_mutex, if its
   deadline has passed.
 - rt_mutex_setprio(), with the new dl_boost_blocked(), when a blocked
   task with no parameters of its own gets a new donor. This includes
   the boost that puts it in the class. For a queued task, the enqueue
   of the boost already does this.

switched_to_dl() leaves one case alone. A task that comes back to the
class can keep its deadline. v7.4-rc2 always keeps it. With the first
series, it keeps it only if it comes back before its 0-lag time. So a
constrained task can come back past its deadline and before its next
period. A new period would let it run before its next period. So, as
dl_check_constrained_dl() does, leave it alone unless it is boosted. Its
wakeup throttles it until its next period.

Its waiter then keeps the passed deadline, and sorts before the other
deadline waiters. At an unlock, it is woken and throttled. The lock then
stays free until its next period.

The setattr_blocked_keeps_order and boost_blocked_keeps_order cases,
added to deadline_bw_test later in this series, test this. Both fail on
v7.4-rc2 and on the series without this patch. The case
reenter_pi_blocked_in_gap tests the constrained task left alone. The
triage of the Sashiko AI review of this series found the bug.

Fixes: fb00aca47440 ("rtmutex: Turn the plist into an rb-tree")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/core.c     |  4 +++
 kernel/sched/deadline.c | 55 +++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h    |  1 +
 3 files changed, 60 insertions(+)

diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 7a3a7e755d20..edd26b321fee 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7980,8 +7980,12 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 			if (!dl_prio(p->normal_prio) ||
 			    (pi_task && dl_prio(pi_task->prio) &&
 			     dl_entity_preempt(&pi_task->dl, &p->dl))) {
+				struct sched_dl_entity *old_donor = p->dl.pi_se;
+
 				dl_set_donor(&p->dl, pi_task);
 				scope->flags |= ENQUEUE_REPLENISH;
+				if (!scope->queued && p->dl.pi_se != old_donor)
+					dl_boost_blocked(p);
 			} else {
 				dl_deboost(&p->dl);
 				/*
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 26cab0470cb7..9c707512d93d 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -247,6 +247,12 @@ void dl_deboost(struct sched_dl_entity *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)
 {
@@ -261,6 +267,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)
@@ -1335,6 +1346,30 @@ static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 	trace_sched_dl_replenish_tp(dl_se, cpu_of(rq), dl_get_type(dl_se, rq));
 }
 
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * Start a period from the new donor of @p, if @p has no reservation of its
+ * own and waits on an rt_mutex. The enqueue does this for a queued task, in
+ * replenish_dl_entity(). A blocked task is not enqueued, but the chain walk
+ * copies its deadline into its waiter.
+ *
+ * Call it only when the donor changes. A new period changes the deadline,
+ * so the chain walk finds the waiter out of date and goes on. In a ww_mutex
+ * cycle, a new period at each step would never let the walk stop.
+ *
+ * The caller holds the rq lock and the pi_lock of @p, and has updated the
+ * rq clock.
+ */
+void dl_boost_blocked(struct task_struct *p)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+
+	if (!dl_se->dl_deadline && !dl_se->dl_throttled &&
+	    dl_task_pi_blocked(p))
+		replenish_dl_new_period(dl_se, task_rq(p));
+}
+#endif
+
 /*
  * We are being explicitly informed that a new instance is starting,
  * and this means that:
@@ -4901,6 +4936,26 @@ 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);
 
+		/*
+		 * The chain walk sorts the waiter of a task by its deadline,
+		 * before the wakeup sets the task up. A task new to the class
+		 * has a deadline of 0, which goes before every real one. So
+		 * start a new period now for a task that waits on an
+		 * rt_mutex, as setup_new_dl_entity() does at an enqueue.
+		 *
+		 * A task that comes back to the class before its 0-lag time
+		 * keeps its deadline. For a constrained task, that deadline
+		 * can have passed before its next period. As
+		 * dl_check_constrained_dl() does, leave such a task alone
+		 * unless it is boosted. Its wakeup throttles it until its
+		 * next period.
+		 */
+		if (dl_task_pi_blocked(p) && !p->dl.dl_throttled &&
+		    dl_time_before(p->dl.deadline, rq_clock(rq)) &&
+		    (is_dl_boosted(&p->dl) ||
+		     !dl_time_before(rq_clock(rq), dl_next_period(&p->dl))))
+			replenish_dl_new_period(&p->dl, rq);
+
 		return;
 	}
 
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index b53885c624fd..32560b08808e 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -413,6 +413,7 @@ static inline void dl_clear_donor(struct sched_dl_entity *dl_se)
 }
 
 extern void dl_deboost(struct sched_dl_entity *dl_se);
+extern void dl_boost_blocked(struct task_struct *p);
 
 /*
  * End the boost of @dl_se, and forget the deadline and runtime saved for
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 31/43] sched/deadline: Restore the owner's period at a deboost out of the class
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (24 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 30/43] sched/deadline: Start a period for a task that enters the class blocked Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:35 ` [PATCH v12 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex Mathieu Desnoyers
                   ` (8 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A task that leaves SCHED_DEADLINE keeps its runtime and deadline, so
that leaving the class and coming back gains nothing. Commit
a649f237db18 ("sched,dl: Fix sched class hopping CBS hole") did this.
Its bandwidth also stays in total_bw until its 0-lag time.

Such a task can hold an rt_mutex. A deadline task that blocks on the
lock before the 0-lag time boosts it back into the class. A task that
switches to SCHED_OTHER while boosted also stays in the class. Either
way, it leaves the class at the deboost, with parameters of its own.

A boosted task is not throttled. When it runs out of runtime,
replenish_dl_entity() refills it from the donor's parameters. Its
runtime and deadline are then the donor's. For a task that stays in
the class, "sched/deadline: Restore the owner's period at a deboost in
the class" saves the task's own values at the first refill. This holds
the boost. At the deboost, dl_deboost() puts the values back.

A deboost out of the class is missed. task_non_contending(), called
from switched_from_dl(), mixes the donor's runtime and deadline with
the task's own dl_runtime and dl_period. The bandwidth then stays in
total_bw too long, or would leave it too early. Until it leaves,
sched_setattr() refuses new deadline tasks that would fit, with EBUSY.

Fix this in switched_from_dl(), as dl_deboost() does:
- After a held boost, dl_end_held_boost() puts back the saved deadline
  and runtime. If the task's own period has ended, it starts the next
  one instead. The 0-lag time is then that of the task's own period.
- A task with no parameters at the first refill has nothing saved. If
  it got parameters later in the boost, start a period of its own. Its
  0-lag time is then now.

The task can leave the class this way with no runtime left, before its
own deadline. Its first refill came when its runtime ran out, so the
saved runtime is often used up. In the class, dl_deboost() throttles
such a task. Out of the class, nothing does. If it comes back to the
class before that deadline, it would run until the next tick. Fix this
too: its enqueue now throttles it until its next period. A task can
then reach the cancel of the replenishment timer at the end of
enqueue_dl_entity(), which only servers reached before. It now drops
the reference that a queued timer holds on the task.

A task can also sleep while boosted, after a refill. Its dequeue then
arms the inactive timer from the mixed values. If the boost ends while
it sleeps, switched_from_dl() keeps that timer. Fix this too: cancel
the timer, and compute the 0-lag time from the task's own values.

The Sashiko AI review found this, on "sched/deadline: Reset the
deadline and the runtime with the parameters" of the first series.
These cases of deadline_bw_test, added later in this series, test it:
- deboost_out_asleep_after_refill: the owner sleeps when the boost
  ends, and its own period has ended. Without this patch, its bandwidth
  was still in total_bw after the boost ended, in every run.
- deboost_out_after_donor_refill: the owner runs when the boost ends.
  Its bandwidth must still be in total_bw right after the unlock. It
  passes without this patch too.

Fixes: 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 45 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 44 insertions(+), 1 deletion(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 9c707512d93d..6e20efb86359 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3132,6 +3132,21 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 		setup_new_dl_entity(dl_se);
 	}
 
+	/*
+	 * A task can come back to the class with no runtime left, before its
+	 * deadline. It would run until the next tick. Throttle it now, until
+	 * its next period, as update_curr_dl_se() would.
+	 */
+	if (!dl_server(dl_se) && !is_dl_boosted(dl_se) &&
+	    !dl_entity_is_special(dl_se) && dl_se->dl_runtime &&
+	    !dl_se->dl_throttled && dl_se->runtime <= 0) {
+		struct rq *rq = rq_of_dl_se(dl_se);
+
+		dl_se->dl_throttled = 1;
+		if (task_current_donor(rq, dl_task_of(dl_se)))
+			resched_curr(rq);
+	}
+
 	/*
 	 * If the reservation is still throttled, e.g., it got replenished but is a
 	 * deferred task and still got to wait, don't enqueue.
@@ -3146,7 +3161,7 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 	 * Also cancel earlier timers, since letting those run is pointless.
 	 */
 	if (dl_se->dl_throttled) {
-		hrtimer_try_to_cancel(&dl_se->dl_timer);
+		cancel_replenish_timer(dl_se);
 		dl_se->dl_defer_armed = 0;
 		dl_se->dl_throttled = 0;
 	}
@@ -4837,6 +4852,22 @@ void dl_clear_root_domains(void)
 
 static void switched_from_dl(struct rq *rq, struct task_struct *p)
 {
+	bool held = dl_end_held_boost(&p->dl, false);
+	bool own_period = held || (p->dl.dl_runtime && p->dl.dl_donor_refill);
+
+	/*
+	 * After a refill from the donor, the runtime and deadline are the
+	 * donor's. task_non_contending() would mix them with the task's own
+	 * dl_runtime and dl_period. So give the task values of its own first,
+	 * as dl_deboost() does. After a held boost, dl_end_held_boost() above
+	 * has put back the saved ones. A task with nothing saved starts a
+	 * period of its own. Its 0-lag time is then now. A constrained task
+	 * still keeps its bandwidth until its next period: see
+	 * task_non_contending().
+	 */
+	if (own_period && !held)
+		dl_start_own_period(&p->dl);
+
 	/*
 	 * task_non_contending() can start the "inactive timer" (if the 0-lag
 	 * time is in the future). If the task switches back to dl before
@@ -4869,6 +4900,18 @@ 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);
+		/*
+		 * If the task blocked while boosted, its inactive timer can be
+		 * armed from the donor's runtime and deadline. Cancel it, so
+		 * that the code below computes the 0-lag time again from the
+		 * values set above. If the timer handler is already running,
+		 * it releases the bandwidth.
+		 */
+		if (own_period && p->dl.dl_non_contending &&
+		    hrtimer_try_to_cancel(&p->dl.inactive_timer) == 1) {
+			p->dl.dl_non_contending = 0;
+			put_task_struct(p);
+		}
 		/*
 		 * 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
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (25 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 31/43] sched/deadline: Restore the owner's period at a deboost out of the class Mathieu Desnoyers
@ 2026-11-27 14:35 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 34/43] sched/deadline: Cancel the replenishment timer with the parameters Mathieu Desnoyers
                   ` (7 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:35 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

The waiter node of an rt_mutex holds the deadline of its task, as a sort
key. task_blocks_on_rt_mutex() copies it when the task blocks. A task
that blocks by itself is running, so its deadline is a current one.

FUTEX_CMP_REQUEUE_PI is different. It makes a task that sleeps in
FUTEX_WAIT_REQUEUE_PI wait on the rt_mutex of a PI futex, with
rt_mutex_start_proxy_lock(). That task is not running. Its deadline can
be one that it would never run with:
- 0, if sched_setattr() made it SCHED_DEADLINE while it slept.
  switched_to_dl() leaves its deadline to its next wakeup.
- one that has passed, if it slept past it.
- one with more runtime left than its bandwidth allows until then. Its
  wakeup would give it a new period.

The waiter then sorts before the waiters with a real deadline. At the
unlock, it gets the lock before waiters with earlier deadlines. Its
deadline also decides the boost of the owner.

Fix this in __rt_mutex_start_proxy_lock(), before its trylock: the
trylock reads the deadline too. Add dl_proxy_block(), which applies the
wakeup rule of update_dl_entity() to the requeued task:
- A deadline of 0 gets a new period. So does a deadline that has
  passed, or a runtime that overflows it. For a boosted task, it is a
  period of its donor.
- A task past its deadline and before its next period keeps its
  deadline: its wakeup throttles it until that period. A period started
  now would come before that next period, which the constrained gap
  forbids. So its waiter still sorts first.

__rt_mutex_start_proxy_lock() drops the pi_lock of the task after
dl_proxy_block(). sched_setattr() can then make the task a deadline
task, before task_blocks_on_rt_mutex() sets its waiter node. So
task_blocks_on_rt_mutex() calls dl_proxy_block() again, under that
pi_lock.

futex_lock_pi() also calls __rt_mutex_start_proxy_lock(), with the
current task. That task is running, so its deadline is up to date.
dl_proxy_block() is not called for it.

The Sashiko AI review of this series found this. The case
requeue_pi_new_period of deadline_bw_test, added later in this series,
tests the deadline of 0. It fails without this patch.

Fixes: 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched/deadline.h |  1 +
 kernel/locking/rtmutex.c       |  8 +++++
 kernel/locking/rtmutex_api.c   | 12 +++++++
 kernel/sched/deadline.c        | 61 ++++++++++++++++++++++++++++++++--
 4 files changed, 79 insertions(+), 3 deletions(-)

diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index 26cda4460604..438a54aa95b1 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -63,6 +63,7 @@ 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 void dl_proxy_block(struct task_struct *p);
 extern bool dl_task_keeps_root_domain(struct task_struct *p,
 				      const struct cpumask *new_mask,
 				      const struct cpumask *pending);
diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c
index b09816977d4e..49caf38759f3 100644
--- a/kernel/locking/rtmutex.c
+++ b/kernel/locking/rtmutex.c
@@ -1245,6 +1245,14 @@ static int __sched task_blocks_on_rt_mutex(struct rt_mutex_base *lock,
 		return -EDEADLK;
 
 	raw_spin_lock(&task->pi_lock);
+	/*
+	 * A proxy lock blocks a task that is not current: see
+	 * __rt_mutex_start_proxy_lock(). sched_setattr() can have made it a
+	 * deadline task since its call of dl_proxy_block(). Update its
+	 * deadline again, before the waiter node takes it.
+	 */
+	if (task != current)
+		dl_proxy_block(task);
 	waiter->task = task;
 	waiter->lock = lock;
 	waiter_update_prio(waiter, task);
diff --git a/kernel/locking/rtmutex_api.c b/kernel/locking/rtmutex_api.c
index 6bdbd36bac94..f1246efc62d3 100644
--- a/kernel/locking/rtmutex_api.c
+++ b/kernel/locking/rtmutex_api.c
@@ -342,6 +342,18 @@ int __sched __rt_mutex_start_proxy_lock(struct rt_mutex_base *lock,
 
 	lockdep_assert_held(&lock->wait_lock);
 
+	/*
+	 * A requeued @task sleeps, so its deadline can be stale. The trylock
+	 * below and the waiter node both read it: update it first.
+	 * futex_lock_pi() passes current, which is running. Its deadline is
+	 * up to date.
+	 */
+	if (task != current) {
+		raw_spin_lock(&task->pi_lock);
+		dl_proxy_block(task);
+		raw_spin_unlock(&task->pi_lock);
+	}
+
 	if (try_to_take_rt_mutex(lock, task, NULL))
 		return 1;
 
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 6e20efb86359..3eeb4c5cd924 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1717,6 +1717,61 @@ static inline u64 dl_next_period(struct sched_dl_entity *dl_se)
 	return dl_se->deadline - dl_se->dl_deadline + dl_se->dl_period;
 }
 
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * FUTEX_CMP_REQUEUE_PI makes @p wait on an rt_mutex while @p sleeps.
+ * The waiter node of @p takes its deadline before any wakeup. So apply
+ * the wakeup rule of update_dl_entity() to @p now:
+ * - A deadline of 0, which a task that entered the class asleep has,
+ *   gets a new period.
+ * - A constrained task past its deadline and before its next period
+ *   keeps its deadline. Its wakeup throttles it until that period. Its
+ *   waiter node keeps that passed deadline, and sorts first.
+ * - Any other task gets the check of update_dl_entity(). A deadline
+ *   that has passed gets a new period.
+ *
+ * The caller holds the pi_lock of @p.
+ */
+void dl_proxy_block(struct task_struct *p)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+	struct rq_flags rf;
+	struct rq *rq;
+
+	if (!dl_task(p))
+		return;
+	rq = __task_rq_lock(p, &rf);
+	update_rq_clock(rq);
+	if (task_on_rq_queued(p) || dl_se->dl_throttled)
+		goto unlock;
+	/*
+	 * A boosted task runs on the parameters of its donor. Start a period
+	 * from them if its deadline is 0 or has passed, or if its runtime
+	 * overflows it, as at a wakeup. A task in the class
+	 * with no runtime of its own is always boosted: the test of
+	 * dl_runtime is only a guard.
+	 */
+	if (is_dl_boosted(dl_se) || !dl_se->dl_runtime) {
+		if (!dl_se->deadline ||
+		    dl_time_before(dl_se->deadline, rq_clock(rq)) ||
+		    dl_entity_overflow(dl_se, rq_clock(rq)))
+			replenish_dl_new_period(dl_se, rq);
+		goto unlock;
+	}
+	if (!dl_se->deadline) {
+		replenish_dl_new_period(dl_se, rq);
+		goto unlock;
+	}
+	if (!dl_is_implicit(dl_se) &&
+	    dl_time_before(dl_se->deadline, rq_clock(rq)) &&
+	    dl_time_before(rq_clock(rq), dl_next_period(dl_se)))
+		goto unlock;
+	update_dl_entity(dl_se);
+unlock:
+	__task_rq_unlock(rq, p, &rf);
+}
+#endif
+
 /*
  * If the entity depleted all its runtime, and if we want it to sleep
  * while waiting for some new execution time to become available, we
@@ -4989,9 +5044,9 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 		 * A task that comes back to the class before its 0-lag time
 		 * keeps its deadline. For a constrained task, that deadline
 		 * can have passed before its next period. As
-		 * dl_check_constrained_dl() does, leave such a task alone
-		 * unless it is boosted. Its wakeup throttles it until its
-		 * next period.
+		 * dl_check_constrained_dl() and dl_proxy_block() do, leave
+		 * such a task alone unless it is boosted. Its wakeup
+		 * throttles it until its next period.
 		 */
 		if (dl_task_pi_blocked(p) && !p->dl.dl_throttled &&
 		    dl_time_before(p->dl.deadline, rq_clock(rq)) &&
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 34/43] sched/deadline: Cancel the replenishment timer with the parameters
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (26 preceding siblings ...)
  2026-11-27 14:35 ` [PATCH v12 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime Mathieu Desnoyers
                   ` (6 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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 this series found this. It has no reproducer.

Fixes: 209a0cbda7a0 ("sched/deadline: Improve the tracking of active utilization")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Reviewed-by: Juri Lelli <juri.lelli@redhat.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 3eeb4c5cd924..94d2b962208e 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -993,6 +993,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);
 			}
 		}
@@ -2932,6 +2933,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;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (27 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 34/43] sched/deadline: Cancel the replenishment timer with the parameters Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 36/43] sched/deadline: Check the runtime of a task that comes back runnable Mathieu Desnoyers
                   ` (5 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

After sched_setattr() shortens the dl_deadline of a constrained
SCHED_DEADLINE task, its next wakeup can leave it more runtime than its
new dl_runtime.

sched_setattr() keeps the runtime and the absolute deadline of the
task: the new parameters take effect at the next period. At the next
wakeup, update_dl_entity() checks the runtime left against the new
parameters. For a constrained task, that check uses the density,
dl_runtime / dl_deadline:
- Commit 2317d5f1c349 ("sched/deadline: Use deadline instead of period
  when calculating overflow") made dl_entity_overflow() compare with
  it: "We care about if the runtime can make its deadline, not its
  period."
- Commit 3effcb4247e7 ("sched/deadline: Use the revised wakeup rule for
  suspending constrained dl tasks") cut the runtime of a constrained
  task that overflows to density * laxity.

Both bound the runtime by dl_runtime only while the deadline is at
most dl_deadline ahead. After a change to a shorter dl_deadline, the
old deadline can be farther ahead. The check then keeps more runtime
than the new dl_runtime, or computes more.

For example, take a task of 50ms every 100ms, with 49ms left and its
deadline 99ms ahead. Changed to 8ms in 20ms every 100ms, it would wake
with 0.4 * 99ms = 39.6ms. Admission control already counts the new,
smaller bandwidth. So other deadline tasks could miss their deadlines.

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

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

The cases change_constrained_new_params and wake_constrained_new_params,
added to deadline_bw_test later in this series, test this. The first
changes a running task, the second a sleeping one.
wake_constrained_new_params fails without this patch, and passes with
it. change_constrained_new_params also needs "sched/deadline: Keep the
debt of a task across a change of parameters".

The Sashiko AI review of this series found this.

Fixes: 2317d5f1c349 ("sched/deadline: Use deadline instead of period when calculating overflow")
Fixes: 3effcb4247e7 ("sched/deadline: Use the revised wakeup rule for suspending constrained dl tasks")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 94d2b962208e..8babc3e2ac51 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1683,6 +1683,19 @@ static void update_dl_entity(struct sched_dl_entity *dl_se)
 {
 	struct rq *rq = rq_of_dl_se(dl_se);
 
+	/*
+	 * The checks below let a constrained task keep up to its density
+	 * times the time left to its deadline. After a change to a shorter
+	 * dl_deadline, the deadline can be more than dl_deadline ahead, and
+	 * that allows more than dl_runtime. So cap the runtime at dl_runtime
+	 * first. An implicit task is checked against its bandwidth, which
+	 * keeps it within its reservation for any deadline. A boosted task
+	 * runs on the parameters of its donor.
+	 */
+	if (!dl_is_implicit(dl_se) && !is_dl_boosted(dl_se) &&
+	    dl_se->runtime > (s64)dl_se->dl_runtime)
+		dl_se->runtime = dl_se->dl_runtime;
+
 	if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
 	    dl_entity_overflow(dl_se, rq_clock(rq))) {
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 36/43] sched/deadline: Check the runtime of a task that comes back runnable
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (28 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 37/43] sched/deadline: Keep the debt of a task across a change of parameters Mathieu Desnoyers
                   ` (4 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

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

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

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

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

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

Fixes: a649f237db18 ("sched,dl: Fix sched class hopping CBS hole")
Reported-by: Juri Lelli <juri.lelli@redhat.com>
Closes: https://lore.kernel.org/all/avHvPjz4dL0zNyGb@jlelli-thinkpadt14gen4.remote.csb/
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 8babc3e2ac51..884fe83538ab 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3196,6 +3196,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)))) {
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 37/43] sched/deadline: Keep the debt of a task across a change of parameters
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (29 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 36/43] sched/deadline: Check the runtime of a task that comes back runnable Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 38/43] sched/deadline: Boost an owner that cannot run on its own reservation Mathieu Desnoyers
                   ` (3 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

sched_setattr() changes the parameters of a deadline task, and leaves
the period in progress as it is. Commit 40767b0dc768 ("sched/deadline:
Fix deadline parameter modification handling") chose this: a change
that takes effect at once "would allow one to circumvent the CBS
guarantees". It also knew the cost: admission control counts the new
bandwidth at once, which is "not on the safe side".

The period in progress does not match the new parameters:
- A task that shrinks its reservation runs on with its old runtime,
  while other tasks can be admitted into the bandwidth it gave back.
- The replenishment timer of a throttled task stays armed for the old
  dl_period.
- dl_next_period(), from commit 5ac69d37784b ("sched/deadline: Make
  sure the replenishment timer fires in the next period"), gives a
  wrong next period after a change of dl_deadline.

A task can then get more than its bandwidth, and other deadline tasks
can miss their deadlines. Tang, Anderson and Abeni build such an
overload with two tasks that pass a large runtime back and forth [1].
In the test case params_swap_overload, with 70ms and 1ms every 100ms,
the two tasks take 99% of the CPU on v7.4-rc2, where admission control
counts 71%. With this series, they get 64%. The paper refuses changes
of parameters, but sched_setattr() allows them: that is user-space ABI.

Fix this by fitting the period in progress to the new parameters, at
the change. A task served at its old bandwidth since the start of its
period would have received some runtime by now. If it used more, the
difference is its debt. The new dl_setattr_period(), called from
__setparam_dl(), keeps that debt:
- An awake task goes on with its job, with the runtime left, up to the
  new dl_runtime.
- Its next period starts when the new bandwidth has repaid the debt and
  supplied that runtime. A task that must wait is throttled until then.
- With a constrained deadline, a job that ran counts as a whole job of
  the new parameters. dl_setattr_place() lists the rules.

The rules need the start of the period, in a new field period_start.
dl_next_period() and the replenishment use it. dl_task_timer() no
longer refills a task before its next period: its handler can run just
after a change moved that period.

Some tasks are not fitted at the change. The new flag dl_new_params
marks them:
- A task with no period under the old parameters: its next enqueue
  checks it, as a wakeup does. If it is blocked on an rt_mutex,
  dl_check_blocked_params() checks it at once, so that its waiter node
  is right.
- A boosted task: the boost would override a throttle, and lose the
  debt. Its period is fitted at the first refill that holds the boost,
  or at the deboost. Its 0-lag time meanwhile counts from a fitted copy,
  in dl_zerolag_period().
- A task that comes back to the class with the same parameters, before
  its 0-lag time. It still has its old runtime and deadline, and
  __setparam_dl() fits nothing. __setscheduler_params() marks it.

User-space sees two changes:
- New parameters apply to the period in progress. A task in debt waits
  until the debt is repaid.
- A task in debt that leaves the class stays counted by admission
  control until then. Meanwhile, sched_setattr() can refuse another
  task with -EBUSY.
sched_getattr() returns what it returned before.

What remains: admission control still releases the old bandwidth at
the change. Right after a cut, a task admitted into it can rarely miss
a deadline near the change. With a constrained deadline, a job that
used the new dl_runtime ends at the change. A task that changes its
constrained dl_deadline back and forth while it waits moves its next
period later.

The Sashiko AI review of this series found the dl_next_period()
problem. "selftests/sched: Test parameter changes in deadline_bw_test",
later in this series, lists the cases that fail without this patch.
This patch also updates the expectation of params_switched_asleep,
from "selftests/sched: Add a test of SCHED_DEADLINE bandwidth
accounting": the bandwidth now stays counted until the debt is repaid.

[1] S. Tang, J. H. Anderson, L. Abeni, "On the Defectiveness of
    SCHED_DEADLINE w.r.t. Tardiness and Affinities, and a Partial Fix",
    RTNS 2021, section 3.1, Example 1,
    https://doi.org/10.1145/3453417.3453440

Fixes: 40767b0dc768 ("sched/deadline: Fix deadline parameter modification handling")
Fixes: 5ac69d37784b ("sched/deadline: Make sure the replenishment timer fires in the next period")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched.h                         |  46 +-
 kernel/sched/core.c                           |  11 +-
 kernel/sched/deadline.c                       | 616 ++++++++++++++++--
 kernel/sched/sched.h                          |   3 +
 kernel/sched/syscalls.c                       |  25 +-
 .../sched/deadline/deadline_bw_test.c         |  28 +-
 6 files changed, 646 insertions(+), 83 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 5a056a2914d0..148e2939e6cb 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -661,9 +661,26 @@ struct sched_dl_entity {
 	 */
 	s64				runtime;	/* Remaining runtime for this instance	*/
 	u64				deadline;	/* Absolute deadline for this instance	*/
-	/* Saved when a boost is held: see dl_boost_held */
-	u64				own_deadline;
-	s64				own_runtime;
+	u64				period_start;	/* Absolute start of this instance	*/
+	/*
+	 * setattr_* are used before a boost is held, own_* while it is held.
+	 * dl_hold_refilled_boost() goes from one to the other: it reads
+	 * setattr_* before it writes own_*.
+	 */
+	union {
+		/* Saved when a boost is held: see dl_boost_held */
+		struct {
+			u64		own_deadline;
+			s64		own_runtime;
+			u64		own_period_start;
+		};
+		/* Saved by sched_setattr(): see dl_setattr_saved */
+		struct {
+			u64		setattr_deadline;
+			u64		setattr_runtime;
+			u64		setattr_period;
+		};
+	};
 	unsigned int			flags;		/* Specifying the scheduler behaviour	*/
 
 	/*
@@ -692,10 +709,10 @@ struct sched_dl_entity {
 	 * runtime and deadline are then not those of the task's own
 	 * reservation. The end of the boost clears the flag.
 	 *
-	 * @dl_boost_held tells that own_deadline and own_runtime hold the
-	 * task's own deadline and runtime. The first refill of a boost saves
-	 * them, for a task with parameters of its own. The deboost puts them
-	 * back.
+	 * @dl_boost_held tells that own_deadline, own_runtime and
+	 * own_period_start hold the task's own period. The first refill of a
+	 * boost saves them, for a task with parameters of its own. The deboost
+	 * puts them back.
 	 *
 	 * @dl_server tells if this is a server entity.
 	 *
@@ -724,6 +741,19 @@ 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 that the runtime left still needs a check
+	 * against new parameters, as a wakeup does. sched_setattr() sets it
+	 * when it changes the runtime, the deadline or the period, or brings
+	 * the task back into the class. It stays set when the change cannot
+	 * fit the period in progress, or when the task is boosted: see
+	 * dl_setattr_period().
+	 *
+	 * @dl_setattr_saved tells that sched_setattr() changed the parameters
+	 * of a boosted task before any refill from its donor.
+	 * setattr_runtime, setattr_deadline and setattr_period hold the old
+	 * parameters. The first refill or the deboost fits the period to the
+	 * new ones with them.
 	 */
 	unsigned int			dl_throttled      : 1;
 	unsigned int			dl_yielded        : 1;
@@ -739,6 +769,8 @@ 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;
+	unsigned int			dl_setattr_saved  : 1;
 
 	/*
 	 * Bandwidth enforcement timer. Each -deadline task has its
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index edd26b321fee..f374b8a0a38b 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7977,8 +7977,15 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 		 *          running task
 		 */
 		if (dl_prio(prio)) {
+			/*
+			 * A boosted task whose parameters changed gets back its
+			 * own period, fitted to them, only at the deboost.
+			 * Deboost it first, so that the top waiter is compared
+			 * with that deadline.
+			 */
 			if (!dl_prio(p->normal_prio) ||
 			    (pi_task && dl_prio(pi_task->prio) &&
+			     !(p->dl.dl_new_params && p->dl.pi_se != &p->dl) &&
 			     dl_entity_preempt(&pi_task->dl, &p->dl))) {
 				struct sched_dl_entity *old_donor = p->dl.pi_se;
 
@@ -8001,12 +8008,12 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 			}
 		} else if (rt_prio(prio)) {
 			if (dl_prio(oldprio))
-				dl_drop_boost(&p->dl);
+				dl_drop_boost_out(&p->dl);
 			if (oldprio < prio)
 				scope->flags |= ENQUEUE_HEAD;
 		} else {
 			if (dl_prio(oldprio))
-				dl_drop_boost(&p->dl);
+				dl_drop_boost_out(&p->dl);
 			if (rt_prio(oldprio))
 				p->rt.timeout = 0;
 		}
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 884fe83538ab..ae0940838ca5 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -89,15 +89,17 @@ static inline int on_dl_rq(struct sched_dl_entity *dl_se)
  */
 static inline void dl_start_own_period(struct sched_dl_entity *dl_se)
 {
-	dl_se->deadline = rq_clock(rq_of_dl_se(dl_se)) + dl_se->dl_deadline;
+	dl_se->period_start = rq_clock(rq_of_dl_se(dl_se));
+	dl_se->deadline = dl_se->period_start + dl_se->dl_deadline;
 	dl_se->runtime = dl_se->dl_runtime;
 }
 
 /*
- * Put back the deadline and runtime saved when the boost was held, by
- * dl_hold_refilled_boost(). If the task's own next period has started
- * since, start a period of its own instead. Return true if the boost was
- * held. The caller holds the rq lock and has updated the rq clock.
+ * Put back the deadline, runtime and period start saved when the boost
+ * was held, by dl_hold_refilled_boost(). If the task's own next period
+ * has started since, start a period of its own instead. Return true if
+ * the boost was held. The caller holds the rq lock and has updated the
+ * rq clock.
  *
  * A task @asleep on anything but an rt_mutex gets that period at its
  * wakeup instead: a period started now would run while it sleeps.
@@ -106,13 +108,13 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se,
 				     bool asleep)
 {
 	u64 now = rq_clock(rq_of_dl_se(dl_se));
-	u64 next = dl_se->own_deadline - dl_se->dl_deadline + dl_se->dl_period;
 
 	if (!dl_se->dl_boost_held)
 		return false;
-	if (dl_time_before(now, next)) {
+	if (dl_time_before(now, dl_se->own_period_start + dl_se->dl_period)) {
 		dl_se->deadline = dl_se->own_deadline;
 		dl_se->runtime = dl_se->own_runtime;
+		dl_se->period_start = dl_se->own_period_start;
 		/*
 		 * Past its own deadline, the task is in its constrained gap:
 		 * it waits for its own next period. Give back no runtime, so
@@ -129,6 +131,7 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se,
 						(dl_se->deadline - now)) >> BW_SHIFT);
 	} else if (asleep) {
 		dl_se->deadline = dl_se->own_deadline;
+		dl_se->period_start = dl_se->own_period_start;
 		dl_se->runtime = 0;
 	} else {
 		dl_start_own_period(dl_se);
@@ -137,6 +140,20 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se,
 	return true;
 }
 
+/*
+ * Return true if @dl_se has a constrained deadline and a period, and the
+ * rq clock is past its deadline and before its next period. An enqueue
+ * then throttles it until that period.
+ */
+static inline bool dl_in_constrained_gap(struct sched_dl_entity *dl_se)
+{
+	u64 now = rq_clock(rq_of_dl_se(dl_se));
+
+	return dl_se->deadline && !dl_is_implicit(dl_se) &&
+	       dl_time_before(dl_se->deadline, now) &&
+	       dl_time_before(now, dl_se->period_start + dl_se->dl_period);
+}
+
 #ifdef CONFIG_RT_MUTEXES
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -151,13 +168,13 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se);
 
 /*
- * Record that a replenishment changes the runtime of @dl_se while it is
- * boosted. At the first refill, dl_hold_refilled_boost() saves the
- * task's own deadline and runtime. Call this before the replenishment
- * adds runtime or moves the deadline. A task with no parameters of its
- * own at the first refill, or no period yet, has no period to save. The
- * deboost then starts a period of its own. Later refills of the
- * same boost save nothing, even if the task gets parameters meanwhile.
+ * Record that a replenishment changes the runtime of @dl_se while
+ * boosted. At the first refill, hold the boost: dl_hold_refilled_boost()
+ * saves the task's own period. Call this before the replenishment moves
+ * the deadline or adds runtime. A task with no parameters of its own at the
+ * first refill, or no period yet, has no period to save. Later refills of
+ * its boost leave it
+ * as it is, even if the task gets parameters meanwhile.
  */
 static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
 {
@@ -175,6 +192,17 @@ static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
 static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task);
 static int start_dl_timer(struct sched_dl_entity *dl_se);
 
+static void update_dl_entity(struct sched_dl_entity *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;
+}
+
+static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
+			      u64 old_deadline, u64 old_period);
+
 /*
  * End the boost of @dl_se, whose task stays in the class. Then bring the
  * runtime and the deadline of the task back to its own parameters:
@@ -185,10 +213,28 @@ static int start_dl_timer(struct sched_dl_entity *dl_se);
  *    start that period if it has started.
  *  - After a refill of a task that had no parameters of its own at the
  *    refill, start a new period now, or at the wakeup of a task asleep.
- *  - Without a refill, the task keeps the runtime and the deadline of its
- *    own reservation.
- * Do it 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.
+ *    dl_hold_refilled_boost() holds the boost of a task that had them.
+ *  - If sched_setattr() changed the parameters during the boost, before
+ *    any refill, fit the period to them with dl_setattr_period(). It
+ *    uses the old parameters saved at the change.
+ *  - If dl_new_params is still set, check the runtime left against the
+ *    parameters, as a wakeup does.
+ *  - Otherwise, keep the runtime and the deadline of the task's own
+ *    reservation.
+ *
+ * Do this 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. rt_mutex_setprio() then compares the result with the top waiter.
+ *
+ * Leave dl_new_params set, and the check to the next enqueue, in two
+ * cases:
+ *  - The task is asleep on anything but an rt_mutex. A period started now
+ *    would run while it sleeps.
+ *  - The task has a constrained deadline, and is past its deadline and
+ *    before its next period. The enqueue throttles it until that period:
+ *    see dl_check_constrained_dl().
+ * A throttled task needs no check: its replenishment uses the new
+ * parameters.
  *
  * The caller holds the rq lock and the pi_lock of the task, and has
  * updated the rq clock.
@@ -196,6 +242,7 @@ static int start_dl_timer(struct sched_dl_entity *dl_se);
 void dl_deboost(struct sched_dl_entity *dl_se)
 {
 	struct task_struct *p = dl_task_of(dl_se);
+	bool saved = dl_se->dl_setattr_saved;
 	bool asleep = !task_on_rq_queued(p) && !p->pi_blocked_on;
 	bool held = dl_end_held_boost(dl_se, asleep);
 	bool own = held;
@@ -204,6 +251,7 @@ void dl_deboost(struct sched_dl_entity *dl_se)
 		/* A task asleep gets its first own period at its wakeup. */
 		if (asleep) {
 			dl_se->deadline = 0;
+			dl_se->period_start = 0;
 			dl_se->runtime = 0;
 		} else {
 			dl_start_own_period(dl_se);
@@ -246,12 +294,90 @@ void dl_deboost(struct sched_dl_entity *dl_se)
 			resched_curr(rq);
 		}
 	}
+
+	/*
+	 * Without a held boost and without a refill, fit the period with the
+	 * saved parameters. After a refill, the period started above follows
+	 * the new parameters. A held boost had its own period fitted at the
+	 * change, or at the refill that held it. In all three cases, no check
+	 * is due.
+	 */
+	if (saved) {
+		if (!own)
+			dl_setattr_period(dl_se, dl_se->setattr_runtime,
+					  dl_se->setattr_deadline,
+					  dl_se->setattr_period);
+		dl_se->dl_new_params = 0;
+	} else if (held) {
+		dl_se->dl_new_params = 0;
+	}
+
+	if (!task_on_rq_queued(p) && !dl_task_pi_blocked(p))
+		return;
+	if (dl_se->dl_new_params && !dl_se->dl_throttled && dl_in_constrained_gap(dl_se))
+		return;
+	if (dl_se->dl_new_params) {
+		dl_se->dl_new_params = 0;
+		if (!dl_se->dl_throttled)
+			update_dl_entity(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)
+static bool dl_setattr_place(struct sched_dl_entity *dl_se, u64 now,
+			     u64 *start, u64 *deadline, s64 *runtime,
+			     u64 old_runtime, u64 old_deadline, u64 old_period,
+			     bool run, bool asleep);
+
+/*
+ * End the boost of @dl_se, whose task leaves the class. If sched_setattr()
+ * changed its parameters before any refill of the boost, fit its period
+ * to them. switched_from_dl() has already worked out the 0-lag time from
+ * a copy of the period fitted the same way: see dl_zerolag_period(). Out
+ * of the class, the task does not go on in its job, and is not throttled.
+ *
+ * The caller holds the rq lock and the pi_lock of the task, and has
+ * updated the rq clock. The task is not on its dl_rq.
+ */
+void dl_drop_boost_out(struct sched_dl_entity *dl_se)
 {
-	return p->pi_blocked_on;
+	bool saved = dl_se->dl_setattr_saved && !dl_se->dl_donor_refill;
+
+	dl_drop_boost(dl_se);
+	if (saved && dl_se->deadline && dl_se->dl_runtime &&
+	    dl_se->setattr_runtime && dl_se->setattr_period)
+		dl_setattr_place(dl_se, rq_clock(rq_of_dl_se(dl_se)),
+				 &dl_se->period_start, &dl_se->deadline,
+				 &dl_se->runtime, dl_se->setattr_runtime,
+				 dl_se->setattr_deadline, dl_se->setattr_period,
+				 false, false);
+}
+
+/*
+ * If sched_setattr() changed the parameters of @p while @p waits on an
+ * rt_mutex, check its runtime left against them now, as a wakeup does.
+ * Before any wakeup, the waiter node of @p holds its deadline.
+ * __sched_setscheduler() then calls rt_mutex_adjust_pi(), which requeues
+ * the waiter with the result. Other changes of @p, such as a cgroup move,
+ * do not requeue the waiter. So only __sched_setscheduler() calls this.
+ *
+ * Leave dl_new_params set for a task that is boosted, throttled, or past
+ * its constrained deadline and before its next period. Its deboost, its
+ * replenishment or its wakeup deals with the new parameters.
+ *
+ * The caller holds the rq lock and the pi_lock of @p, and has updated the
+ * rq clock.
+ */
+void dl_check_blocked_params(struct task_struct *p)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+
+	if (!dl_task(p) || task_on_rq_queued(p) || !dl_task_pi_blocked(p))
+		return;
+	if (dl_se->dl_new_params && !is_dl_boosted(dl_se) &&
+	    !dl_se->dl_throttled && !dl_in_constrained_gap(dl_se)) {
+		dl_se->dl_new_params = 0;
+		update_dl_entity(dl_se);
+	}
 }
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
@@ -792,6 +918,35 @@ static void dl_change_utilization(struct task_struct *p, u64 new_bw)
 }
 
 static inline u64 dl_next_period(struct sched_dl_entity *dl_se);
+static bool dl_setattr_place(struct sched_dl_entity *dl_se, u64 now,
+			     u64 *start, u64 *deadline, s64 *runtime,
+			     u64 old_runtime, u64 old_deadline, u64 old_period,
+			     bool run, bool asleep);
+
+/*
+ * Return the start of the next period that the 0-lag time of @dl_se
+ * counts from, and set *@runtime to the runtime left in the period.
+ * Before the first refill from its donor, a boosted task whose
+ * parameters changed keeps its old period until its deboost. Fit a
+ * copy of it to the new parameters, as the deboost does: see
+ * dl_setattr_period(). The task does not go on in its job here, so the
+ * copy keeps no runtime. Its next period is then the repayment of its
+ * debt, if it has one.
+ */
+static u64 dl_zerolag_period(struct sched_dl_entity *dl_se, struct rq *rq,
+			     s64 *runtime)
+{
+	u64 start = dl_se->period_start, deadline = dl_se->deadline;
+
+	*runtime = dl_se->runtime;
+	if (dl_se->dl_setattr_saved && !dl_se->dl_donor_refill &&
+	    deadline && dl_se->dl_runtime && dl_se->setattr_runtime &&
+	    dl_se->setattr_period)
+		dl_setattr_place(dl_se, rq_clock(rq), &start, &deadline, runtime,
+				 dl_se->setattr_runtime, dl_se->setattr_deadline,
+				 dl_se->setattr_period, false, false);
+	return start + dl_se->dl_period;
+}
 static void __dl_clear_params(struct sched_dl_entity *dl_se);
 static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
 
@@ -818,22 +973,31 @@ static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
  *
  * Each check compares against the bound scaled by dl_runtime / dl_period.
  * That quotient cannot overflow, as dl_runtime <= dl_period.
+ *
+ * After sched_setattr(), a boosted task with no refill from its donor yet
+ * keeps the runtime and the deadline of its old parameters until its
+ * deboost: see dl_setattr_period().
+ * dl_zerolag_period() counts from a copy of that period, fitted to the new
+ * parameters as the deboost fits it. This matters when the task blocks
+ * while boosted, or leaves the class at its deboost: switched_from_dl()
+ * runs before dl_drop_boost_out() fits the period.
  */
 static s64 dl_time_to_zerolag(struct sched_dl_entity *dl_se, struct rq *rq)
 {
+	s64 runtime;
 	/* Time to the next period. Negative if it has started. */
-	s64 left = dl_next_period(dl_se) - rq_clock(rq);
+	s64 left = dl_zerolag_period(dl_se, rq, &runtime) - rq_clock(rq);
 
 	/* A task with no period yet has received nothing: no 0-lag time. */
 	if (!dl_se->deadline)
 		return -1;
 
-	if (dl_se->runtime < 0) {
+	if (runtime < 0) {
 		/*
 		 * Overrun: the 0-lag time is after the next period, by the time
 		 * needed to pay the overrun back at the reserved bandwidth.
 		 */
-		u64 overrun = -dl_se->runtime;
+		u64 overrun = -runtime;
 		u64 room = S64_MAX - max(left, 0LL);
 
 		/*
@@ -862,13 +1026,13 @@ static s64 dl_time_to_zerolag(struct sched_dl_entity *dl_se, struct rq *rq)
 	 * passed. The runtime left is more than the bandwidth gives until
 	 * the next period.
 	 */
-	if (dl_se->runtime > mul_u64_u64_div_u64(left, dl_se->dl_runtime,
-						 dl_se->dl_period)) {
+	if (runtime > mul_u64_u64_div_u64(left, dl_se->dl_runtime,
+					  dl_se->dl_period)) {
 		return -1;
 	}
 
 	/* The quotient is at most @left here. */
-	return left - mul_u64_u64_div_u64(dl_se->runtime, dl_se->dl_period,
+	return left - mul_u64_u64_div_u64(runtime, dl_se->dl_period,
 					  dl_se->dl_runtime);
 }
 
@@ -968,7 +1132,8 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 	if (!dl_task && !dl_server(dl_se) && !dl_is_implicit(dl_se) &&
 	    dl_se->deadline &&
 	    READ_ONCE(dl_task_of(dl_se)->__state) != TASK_DEAD) {
-		s64 next = dl_next_period(dl_se) - rq_clock(rq);
+		s64 runtime;
+		s64 next = dl_zerolag_period(dl_se, rq, &runtime) - rq_clock(rq);
 
 		if (next > zerolag_time)
 			zerolag_time = next;
@@ -1333,7 +1498,8 @@ static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 {
 	dl_note_donor_refill(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->period_start = rq_clock(rq);
+	dl_se->deadline = dl_se->period_start + pi_of(dl_se)->dl_deadline;
 	dl_se->runtime = pi_of(dl_se)->dl_runtime;
 
 	/*
@@ -1436,6 +1602,7 @@ static void replenish_dl_entity(struct sched_dl_entity *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);
+	bool new_period = false;
 
 	/*
 	 * A boosted entity runs on the parameters of its donor, the top
@@ -1457,6 +1624,7 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 		if (!dl_se->dl_deadline) {
 			dl_note_donor_refill(dl_se);
 			dl_se->deadline = rq_clock(rq);
+			dl_se->period_start = dl_se->deadline;
 			dl_se->runtime = 0;
 		}
 		if (dl_se->runtime < 0 || dl_se->dl_yielded) {
@@ -1481,7 +1649,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_note_donor_refill(dl_se);
-		dl_se->deadline = rq_clock(rq) + deadline;
+		dl_se->period_start = rq_clock(rq);
+		dl_se->deadline = dl_se->period_start + deadline;
 		dl_se->runtime = runtime;
 	}
 
@@ -1499,8 +1668,19 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 	 */
 	while (dl_se->runtime <= 0) {
 		dl_se->deadline += period;
+		dl_se->period_start += period;
 		dl_se->runtime += runtime;
+		new_period = true;
 	}
+	/*
+	 * The loop moves the deadline and period_start together. After
+	 * sched_setattr(), deadline - period_start can differ from
+	 * dl_deadline. Set the deadline from period_start for the new
+	 * period. A boosted task keeps the relative deadline of its donor.
+	 * sched_setattr() does not change a dl_server.
+	 */
+	if (new_period && !is_dl_boosted(dl_se) && !dl_server(dl_se))
+		dl_se->deadline = dl_se->period_start + dl_se->dl_deadline;
 
 	/*
 	 * At this point, the deadline really should be "in
@@ -1690,7 +1870,8 @@ static void update_dl_entity(struct sched_dl_entity *dl_se)
 	 * that allows more than dl_runtime. So cap the runtime at dl_runtime
 	 * first. An implicit task is checked against its bandwidth, which
 	 * keeps it within its reservation for any deadline. A boosted task
-	 * runs on the parameters of its donor.
+	 * runs on the parameters of its donor. dl_setattr_period() keeps no
+	 * more than dl_runtime already, so this check is only a guard.
 	 */
 	if (!dl_is_implicit(dl_se) && !is_dl_boosted(dl_se) &&
 	    dl_se->runtime > (s64)dl_se->dl_runtime)
@@ -1726,9 +1907,14 @@ static void update_dl_entity(struct sched_dl_entity *dl_se)
 	}
 }
 
+/*
+ * Return the start of the next period of @dl_se. Do not work it out from
+ * the deadline and dl_deadline: sched_setattr() can change dl_deadline
+ * during the period.
+ */
 static inline u64 dl_next_period(struct sched_dl_entity *dl_se)
 {
-	return dl_se->deadline - dl_se->dl_deadline + dl_se->dl_period;
+	return dl_se->period_start + dl_se->dl_period;
 }
 
 #ifdef CONFIG_RT_MUTEXES
@@ -1780,6 +1966,7 @@ void dl_proxy_block(struct task_struct *p)
 	    dl_time_before(dl_se->deadline, rq_clock(rq)) &&
 	    dl_time_before(rq_clock(rq), dl_next_period(dl_se)))
 		goto unlock;
+	dl_se->dl_new_params = 0;
 	update_dl_entity(dl_se);
 unlock:
 	__task_rq_unlock(rq, p, &rf);
@@ -1821,7 +2008,7 @@ static int start_dl_timer(struct sched_dl_entity *dl_se)
 		WARN_ON_ONCE(!dl_se->dl_throttled);
 		act = ns_to_ktime(dl_se->deadline - dl_se->runtime);
 	} else {
-		/* act = deadline - rel-deadline + period */
+		/* act = the start of the next period */
 		act = ns_to_ktime(dl_next_period(dl_se));
 	}
 
@@ -1971,6 +2158,10 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
 		if (dl_se->dl_throttled && !is_dl_boosted(dl_se)) {
 			sched_clock_tick();
 			update_rq_clock(rq);
+			/* Not before the next period: see below. */
+			if (dl_time_before(rq_clock(rq), dl_next_period(dl_se)) &&
+			    start_dl_timer(dl_se))
+				goto unlock;
 			replenish_dl_entity(dl_se);
 		}
 		goto unlock;
@@ -1996,6 +2187,18 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
 	sched_clock_tick();
 	update_rq_clock(rq);
 
+	/*
+	 * sched_setattr() can move the next period while this handler waits
+	 * for the rq lock: see dl_setattr_period(). Do not refill before that
+	 * period starts. start_dl_timer() arms the timer there, or finds it
+	 * armed. If it finds the time passed, refill now. A boosted task
+	 * asleep is in a period of its donor: refill it as before.
+	 */
+	if (!is_dl_boosted(dl_se) &&
+	    dl_time_before(rq_clock(rq), dl_next_period(dl_se)) &&
+	    start_dl_timer(dl_se))
+		goto unlock;
+
 	/*
 	 * If the throttle happened during sched-out; like:
 	 *
@@ -2689,6 +2892,7 @@ int dl_server_apply_params(struct sched_dl_entity *dl_se, u64 runtime, u64 perio
 
 	dl_se->runtime = 0;
 	dl_se->deadline = 0;
+	dl_se->period_start = 0;
 
 	dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
@@ -3147,7 +3351,18 @@ 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));
+	/*
+	 * Clear dl_new_params unless the task is boosted. The code below
+	 * checks the runtime left as a wakeup does, or refills the task.
+	 * A throttled task waits for its replenishment instead. A boosted
+	 * task is refilled from its donor: dl_deboost() checks it at the
+	 * deboost.
+	 */
+	if (!is_dl_boosted(dl_se))
+		dl_se->dl_new_params = 0;
 
 	update_stats_enqueue_dl(dl_rq_of_se(dl_se), dl_se, flags);
 
@@ -3196,12 +3411,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) &&
@@ -3211,8 +3427,9 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 	}
 
 	/*
-	 * A task can come back to the class with no runtime left, before its
-	 * deadline. It would run until the next tick. Throttle it now, until
+	 * A task can be enqueued with no runtime left, before its deadline: a
+	 * return to the class, or a wakeup after sched_setattr() left it no
+	 * runtime. It would run until the next tick. Throttle it now, until
 	 * its next period, as update_curr_dl_se() would.
 	 */
 	if (!dl_server(dl_se) && !is_dl_boosted(dl_se) &&
@@ -4965,6 +5182,7 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 	 */
 	if (!p->dl.dl_runtime) {
 		p->dl.deadline = 0;
+		p->dl.period_start = 0;
 		p->dl.runtime = 0;
 	}
 
@@ -5064,8 +5282,9 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 		 * start a new period now for a task that waits on an
 		 * rt_mutex, as setup_new_dl_entity() does at an enqueue.
 		 *
-		 * A task that comes back to the class before its 0-lag time
-		 * keeps its deadline. For a constrained task, that deadline
+		 * A task that sched_setattr() brings back before its 0-lag
+		 * time keeps its deadline. dl_check_blocked_params() has
+		 * checked its runtime. For a constrained task, that deadline
 		 * can have passed before its next period. As
 		 * dl_check_constrained_dl() and dl_proxy_block() do, leave
 		 * such a task alone unless it is boosted. Its wakeup
@@ -5073,8 +5292,7 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 		 */
 		if (dl_task_pi_blocked(p) && !p->dl.dl_throttled &&
 		    dl_time_before(p->dl.deadline, rq_clock(rq)) &&
-		    (is_dl_boosted(&p->dl) ||
-		     !dl_time_before(rq_clock(rq), dl_next_period(&p->dl))))
+		    (is_dl_boosted(&p->dl) || !dl_in_constrained_gap(&p->dl)))
 			replenish_dl_new_period(&p->dl, rq);
 
 		return;
@@ -5377,47 +5595,304 @@ int sched_dl_overflow(struct task_struct *p, int policy,
 	return err;
 }
 
+/*
+ * Return @a * @b / @c rounded up, capped at @cap. With a raised
+ * sched_deadline_period_max_us, a runtime times a ratio of period to
+ * runtime can exceed 64 bits. mul_u64_u64_div_u64() then traps on
+ * x86-64, so compare with @cap first.
+ */
+static u64 dl_mul_div_cap(u64 a, u64 b, u64 c, u64 cap)
+{
+	if (b > c && a > mul_u64_u64_div_u64(cap, c, b))
+		return cap;
+	return min(mul_u64_u64_div_u64_roundup(a, b, c), cap);
+}
+
+/* The longest wait that sched_setattr() sets, far longer than any period. */
+#define DL_SETATTR_WAIT_MAX	(1ULL << 62)
+
+/*
+ * Fit a period of @dl_se to its new parameters. sched_setattr() changed
+ * them from @old_runtime, @old_deadline and @old_period. At @now,
+ * *@start, *@deadline and *@runtime describe the period in progress
+ * under the old parameters. On return, they describe a period under the
+ * new ones. Return true if the task must wait for that period, with no
+ * runtime.
+ *
+ * These terms are used below:
+ *  - The release of the job is *@deadline - @old_deadline.
+ *  - The 0-lag time is when the task, served at its old bandwidth since
+ *    *@start, would have received the runtime it used.
+ *  - The debt is the runtime that the old bandwidth gives from @now to
+ *    a 0-lag time ahead. A task with a debt ran ahead of its
+ *    reservation.
+ *  - The repayment is when the new bandwidth, from @now, has supplied
+ *    the debt and the runtime that the job keeps.
+ *
+ * Keep the debt across the change. Admission control already counts the
+ * new bandwidth, so repay the debt at that bandwidth. Otherwise, a change
+ * could give the task a new period at once, ahead of the tasks it was
+ * admitted with.
+ *
+ * If @run, the task goes on in its current job, with the runtime left
+ * capped at dl_runtime. The next period starts at the repayment. With a
+ * new implicit deadline, the job ends there too.
+ *
+ * A constrained deadline, old or new, adds these rules:
+ *  - A job past its old deadline, or past its release plus dl_deadline,
+ *    keeps no runtime.
+ *  - A job keeps no more than the runtime left of a job of the new
+ *    parameters.
+ *  - Two releases are at least dl_period apart.
+ *
+ * A new constrained deadline adds these rules:
+ *  - The job keeps no more runtime than the new density allows before
+ *    its release plus dl_deadline.
+ *  - The job ends at max(release + dl_deadline,
+ *                        min(repayment, old deadline)).
+ *  - A job that ran counts as a whole job of the new parameters. So the
+ *    next period starts no earlier than the end of the job - dl_deadline
+ *    + dl_period. Otherwise, an old job followed closely by new jobs
+ *    could put more demand in a window than either set of parameters
+ *    does.
+ *
+ * Without a job to go on with, the task waits for its next period with no
+ * runtime, or starts it now if it is due. A task @asleep with a new
+ * constrained deadline does not wait: its wakeup starts its next period,
+ * or throttles it until then. Throttling it while it sleeps could waste
+ * a period. Its timer could start a period that ends before the wakeup.
+ * The wakeup would then throttle it until the period after.
+ */
+static bool dl_setattr_place(struct sched_dl_entity *dl_se, u64 now,
+			     u64 *start, u64 *deadline, s64 *runtime,
+			     u64 old_runtime, u64 old_deadline, u64 old_period,
+			     bool run, bool asleep)
+{
+	u64 dl_runtime = dl_se->dl_runtime;
+	u64 dl_deadline = dl_se->dl_deadline;
+	u64 dl_period = dl_se->dl_period;
+	bool constrained = dl_deadline < dl_period || old_deadline < old_period;
+	u64 release = *deadline - old_deadline;
+	u64 zerolag = *start + old_period;
+	u64 debt = 0, keep = 0, used = 0, next = now, end = *deadline;
+
+	/* Round against the task, here and below. */
+	if (*runtime > 0)
+		zerolag -= mul_u64_u64_div_u64(*runtime, old_period, old_runtime);
+	else
+		zerolag += dl_mul_div_cap(-*runtime, old_period, old_runtime,
+					  DL_SETATTR_WAIT_MAX);
+	if (dl_time_before(now, zerolag))
+		debt = mul_u64_u64_div_u64_roundup(zerolag - now, old_runtime, old_period);
+
+	if (*runtime < (s64)old_runtime)
+		used = old_runtime - max_t(s64, *runtime, 0);
+
+	if (run && *runtime > 0) {
+		if (!constrained) {
+			keep = min_t(u64, *runtime, dl_runtime);
+		} else if (dl_time_before(now, *deadline) &&
+			   dl_time_before(now, release + dl_deadline)) {
+			if (used < dl_runtime)
+				keep = min_t(u64, *runtime, dl_runtime - used);
+			if (dl_deadline < dl_period)
+				keep = min(keep, mul_u64_u64_div_u64(release + dl_deadline - now,
+								     dl_runtime, dl_deadline));
+		}
+	}
+
+	next += dl_mul_div_cap(debt + keep, dl_period, dl_runtime, DL_SETATTR_WAIT_MAX);
+	if (dl_deadline < dl_period && keep) {
+		if (dl_time_before(next, end))
+			end = next;
+		if (dl_time_before(end, release + dl_deadline))
+			end = release + dl_deadline;
+	}
+	if (constrained && dl_time_before(next, release + dl_period))
+		next = release + dl_period;
+	/* A job that ran counts as a whole job: see above. */
+	if (dl_deadline < dl_period && (keep || used) &&
+	    dl_time_before(next, end - dl_deadline + dl_period))
+		next = end - dl_deadline + dl_period;
+
+	if (keep) {
+		*runtime = keep;
+		*start = next - dl_period;
+		*deadline = dl_deadline < dl_period ? end : next;
+		return false;
+	}
+	*runtime = 0;
+	if (asleep && dl_deadline < dl_period) {
+		if (dl_time_before(next, now))
+			next = now;
+		*start = next - dl_period;
+		*deadline = *start + dl_deadline;
+		return false;
+	}
+	if (!dl_time_before(now, next)) {
+		*start = now;
+		*deadline = now + dl_deadline;
+		*runtime = dl_runtime;
+		return false;
+	}
+	*start = next - dl_period;
+	*deadline = *start + dl_deadline;
+	return true;
+}
+
+/*
+ * Fit the period in progress of @dl_se to its new parameters, by the
+ * rules of dl_setattr_place(). @old_runtime, @old_deadline and
+ * @old_period are the parameters before sched_setattr() changed them. A
+ * task that must wait for its next period is throttled until then. A
+ * task blocked on an rt_mutex counts as awake: the chain walk copies its
+ * deadline into its waiter node before any wakeup.
+ *
+ * For a boosted task, it depends on the boost:
+ *  - A held boost keeps the task's own period aside, and the task does
+ *    not run in it. Fit that period. dl_end_held_boost() puts it back.
+ *  - Any other boost runs the task in its own period until the first
+ *    refill from its donor. Save the old parameters at the first change
+ *    before that refill. If the refill comes first, it holds the boost,
+ *    and dl_hold_refilled_boost() fits the period with them. If the
+ *    deboost comes first, dl_deboost() or dl_drop_boost_out() fits it.
+ *
+ * Return true if the runtime left or the period still needs work later.
+ * That is the case for a boosted task: its deboost does it. A task with
+ * no period under the old parameters needs it too: its next enqueue
+ * checks the runtime left as a wakeup does. Return false for any other
+ * task: it is now in a period of the new parameters. The wakeup check
+ * rounds to the microsecond. It could find an overflow there and start
+ * a new period, which the debt does not allow.
+ *
+ * The caller holds the rq lock and the pi_lock of the task, and has
+ * updated the rq clock. The task is not on its dl_rq: every caller runs
+ * inside a change of the task, which dequeues it first.
+ */
+static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
+			      u64 old_deadline, u64 old_period)
+{
+	struct task_struct *p = dl_task_of(dl_se);
+	struct rq *rq = task_rq(p);
+	u64 now = rq_clock(rq);
+	bool asleep = !task_on_rq_queued(p) && !dl_task_pi_blocked(p);
+
+	if (!dl_se->deadline || !dl_se->dl_runtime || !old_runtime || !old_period)
+		return true;
+
+	if (dl_se->dl_boost_held) {
+		dl_setattr_place(dl_se, now, &dl_se->own_period_start,
+				 &dl_se->own_deadline, &dl_se->own_runtime,
+				 old_runtime, old_deadline, old_period, false, false);
+		return true;
+	}
+
+	if (is_dl_boosted(dl_se)) {
+		if (!dl_se->dl_setattr_saved && !dl_se->dl_donor_refill) {
+			dl_se->setattr_runtime = old_runtime;
+			dl_se->setattr_deadline = old_deadline;
+			dl_se->setattr_period = old_period;
+			dl_se->dl_setattr_saved = 1;
+		}
+		return true;
+	}
+
+	/*
+	 * start_dl_timer() does not move a queued timer: cancel it first. If
+	 * its handler is already running, the cancel fails. The handler then
+	 * waits for the rq lock. It finds the task no longer throttled, or
+	 * arms the timer again at the next period set here.
+	 */
+	cancel_replenish_timer(dl_se);
+	/* A yield gave up the rest of the old period only. */
+	dl_se->dl_yielded = 0;
+	if (!dl_setattr_place(dl_se, now, &dl_se->period_start, &dl_se->deadline,
+			      &dl_se->runtime, old_runtime, old_deadline,
+			      old_period, !dl_se->dl_throttled && !asleep, asleep)) {
+		dl_se->dl_throttled = 0;
+		return false;
+	}
+
+	/*
+	 * The next period is ahead, so the timer can be armed. A running
+	 * task is now off the dl_rq: reschedule, as a throttle in
+	 * update_curr_dl_se() does.
+	 */
+	dl_se->dl_throttled = 1;
+	if (WARN_ON_ONCE(!start_dl_timer(dl_se)))
+		replenish_dl_entity(dl_se);
+	if (task_current_donor(rq, p))
+		resched_curr(rq);
+	return false;
+}
+
 #ifdef CONFIG_RT_MUTEXES
 /*
  * A boosted task is refilled from its donor when its runtime is used up,
  * or when its deadline has passed. A wakeup also refills it when the
- * donor's density does not allow the runtime left. After the first
- * refill, the runtime and the deadline of the task are no longer those
- * of its own reservation. So save them in own_* at that refill: this
- * holds the boost. dl_deboost() puts them back.
+ * donor's density does not allow the runtime left. From then on, the task
+ * runs on the donor's reservation. So save the task's own period in own_*
+ * at the first refill: this holds the boost. dl_deboost() puts it back.
  *
  * Keep the runtime left if the task's own deadline is still ahead.
  * Otherwise save no runtime. A negative runtime is an overrun that comes
  * from the boost, so the task's own reservation does not pay for it (see
  * replenish_dl_entity()).
  *
- * The caller holds the rq lock of the task, and has updated the rq clock.
+ * If sched_setattr() changed the parameters before this refill,
+ * dl_setattr_period() saved the old ones in setattr_*. Fit the period
+ * saved in own_* to the new parameters with them. setattr_* share
+ * storage with own_*: read them before writing own_*. The caller holds
+ * the rq lock of the task, and has updated the rq clock.
  */
 static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 {
+	u64 old_runtime = dl_se->setattr_runtime;
+	u64 old_deadline = dl_se->setattr_deadline;
+	u64 old_period = dl_se->setattr_period;
+	bool saved = dl_se->dl_setattr_saved;
 	u64 now = rq_clock(rq_of_dl_se(dl_se));
 
 	dl_se->own_deadline = dl_se->deadline;
-	dl_se->own_runtime = dl_time_before(now, dl_se->deadline) ?
-			     max_t(s64, dl_se->runtime, 0) : 0;
+	dl_se->own_runtime = max_t(s64, dl_se->runtime, 0);
+	dl_se->own_period_start = dl_se->period_start;
 	dl_se->dl_boost_held = 1;
+	dl_se->dl_setattr_saved = 0;
+	/*
+	 * An overrun is saved as 0: it comes from the boost. The fit counts
+	 * the runtime left as unused, even past the deadline. Without a fit,
+	 * keep no runtime past the deadline.
+	 */
+	if (saved && dl_se->own_deadline && old_runtime && old_period)
+		dl_setattr_place(dl_se, now, &dl_se->own_period_start,
+				 &dl_se->own_deadline, &dl_se->own_runtime,
+				 old_runtime, old_deadline, old_period, false, false);
+	else if (!dl_time_before(now, dl_se->own_deadline))
+		dl_se->own_runtime = 0;
 }
 #endif /* CONFIG_RT_MUTEXES */
 
 /*
- * This function initializes the sched_dl_entity of a newly becoming
- * SCHED_DEADLINE task.
- *
- * Only the static values are considered here, the actual runtime and the
- * absolute deadline will be properly calculated when the task is enqueued
- * for the first time with its new policy.
+ * Set the deadline parameters of @p from @attr. A task new to the class
+ * gets its runtime and its absolute deadline at its first enqueue with
+ * its new policy. For a task with a period in progress, fit that period
+ * to the new parameters with dl_setattr_period().
  */
 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;
+	u64 old_runtime = dl_se->dl_runtime;
+	u64 old_deadline = dl_se->dl_deadline;
+	u64 old_period = dl_se->dl_period;
+	bool pending = dl_se->dl_new_params;
 	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
@@ -5440,6 +5915,30 @@ void __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
 	else if (!dl_se_holds_bw(dl_se) && held)
 		atomic_dec(&dl_nr_bw_tasks);
 	dl_se->dl_density = to_ratio(dl_se->dl_deadline, dl_se->dl_runtime);
+	/*
+	 * Fit the period in progress to the new parameters. Then clear
+	 * dl_new_params if the runtime left needs no check. Keep it if it
+	 * was set before this change: that check is still due.
+	 */
+	if (dl_se->dl_new_params &&
+	    !dl_setattr_period(dl_se, old_runtime, old_deadline, old_period) &&
+	    !pending)
+		dl_se->dl_new_params = 0;
+
+	/*
+	 * The inactive timer of a task asleep in the class is armed for the
+	 * 0-lag time of its old period. A change that keeps dl_bw leaves it
+	 * armed: see dl_change_utilization(). Arm it again from the period
+	 * set above. If its handler is already running, it releases the
+	 * bandwidth.
+	 */
+	if (dl_prio(p->prio) && !is_dl_boosted(dl_se) &&
+	    dl_se->dl_non_contending &&
+	    hrtimer_try_to_cancel(&dl_se->inactive_timer) == 1) {
+		dl_se->dl_non_contending = 0;
+		put_task_struct(p);
+		task_non_contending(dl_se, true);
+	}
 }
 
 void __getparam_dl(struct task_struct *p, struct sched_attr *attr, unsigned int flags)
@@ -5539,6 +6038,7 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se)
 	dl_se->dl_density		= 0;
 
 	dl_se->deadline			= 0;
+	dl_se->period_start		= 0;
 	dl_se->runtime			= 0;
 
 	dl_se->dl_throttled		= 0;
@@ -5552,6 +6052,8 @@ 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;
+	dl_se->dl_setattr_saved		= 0;
 }
 
 void init_dl_entity(struct sched_dl_entity *dl_se)
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 32560b08808e..43aef9b61b67 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -413,7 +413,9 @@ static inline void dl_clear_donor(struct sched_dl_entity *dl_se)
 }
 
 extern void dl_deboost(struct sched_dl_entity *dl_se);
+extern void dl_drop_boost_out(struct sched_dl_entity *dl_se);
 extern void dl_boost_blocked(struct task_struct *p);
+extern void dl_check_blocked_params(struct task_struct *p);
 
 /*
  * End the boost of @dl_se, and forget the deadline and runtime saved for
@@ -425,6 +427,7 @@ static inline void dl_drop_boost(struct sched_dl_entity *dl_se)
 	dl_clear_donor(dl_se);
 	dl_se->dl_donor_refill = 0;
 	dl_se->dl_boost_held = 0;
+	dl_se->dl_setattr_saved = 0;
 }
 #endif
 extern void __getparam_dl(struct task_struct *p, struct sched_attr *attr, unsigned int flags);
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 9778663fe370..4f26601f0530 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -242,15 +242,31 @@ static void __setscheduler_params(struct task_struct *p,
 		const struct sched_attr *attr)
 {
 	int policy = attr->sched_policy;
+	bool enters_dl;
 
 	if (policy == SETPARAM_POLICY)
 		policy = p->policy;
 
+	enters_dl = dl_policy(policy) && !dl_policy(p->policy);
 	p->policy = policy;
 
-	if (dl_policy(policy))
+	if (dl_policy(policy)) {
+		u64 period = attr->sched_period ?: attr->sched_deadline;
+		bool same = attr->sched_runtime == p->dl.dl_runtime &&
+			    attr->sched_deadline == p->dl.dl_deadline &&
+			    period == p->dl.dl_period;
+
 		__setparam_dl(p, attr);
-	else if (fair_policy(policy))
+		/*
+		 * A task that comes back to the class before its 0-lag time
+		 * still has its old runtime and deadline. With new parameters,
+		 * __setparam_dl() has fitted its period to them. With the same
+		 * ones, set dl_new_params, so that the runtime left is checked
+		 * as at a wakeup.
+		 */
+		if (enters_dl && same)
+			p->dl.dl_new_params = 1;
+	} else if (fair_policy(policy))
 		__setparam_fair(p, attr);
 
 	/* rt-policy tasks do not have a timerslack */
@@ -310,7 +326,10 @@ 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))
-		dl_drop_boost(&p->dl);
+		dl_drop_boost_out(&p->dl);
+
+	/* A blocked task's waiter node holds its deadline: check it now. */
+	dl_check_blocked_params(p);
 }
 #else /* !CONFIG_RT_MUTEXES */
 static inline void __setscheduler_dl_pi(int newprio, int policy,
diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index 1e3881199e4c..83dd8b4e79a3 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -1246,17 +1246,17 @@ static long long bw_of(uint64_t runtime, uint64_t period)
 }
 
 /*
- * A deadline task of 20ms every 100ms runs 10ms of a new period, then
- * sleeps. The main thread changes its parameters, then switches it to
- * SCHED_OTHER. task_non_contending() computes its 0-lag time from the
- * 10ms left and the new parameters. The root domain keeps the new
- * bandwidth in its total_bw until then.
- *  - Changed to 5ms every 100ms, the 10ms left overflow the new
- *    parameters. The 0-lag time has passed. The bandwidth must be
- *    released at once. The old parameters would keep it about 40ms more.
- *  - Changed to 50ms every 100ms, the 10ms left fit. The 0-lag time is
- *    20ms before the deadline, about 70ms ahead. The bandwidth must still
- *    be counted right after the switch, and released after the deadline.
+ * A deadline task of 20ms every 100ms runs 10ms at the start of a new
+ * period, then sleeps. In those 10ms, its bandwidth gave it 2ms: it ran
+ * 8ms ahead. The main thread changes its parameters, then switches it
+ * to SCHED_OTHER. The change keeps the 8ms as a debt, repaid at the new
+ * bandwidth. task_non_contending() releases the bandwidth once the debt
+ * is repaid. Until then, the root domain counts the new bandwidth in its
+ * total_bw:
+ *  - changed to 5ms every 100ms, for about 160ms;
+ *  - changed to 50ms every 100ms, for about 16ms.
+ * The bandwidth must be counted right after the switch, and released
+ * within 300ms.
  */
 static int params_switched_asleep(void)
 {
@@ -1281,16 +1281,16 @@ static int params_switched_asleep(void)
 			ret = KSFT_FAIL;
 		} else {
 			bw = total_bw_of(cpu);
-			want = base + (i ? bw_of(rt[i] * NSEC_PER_MSEC, PERIOD) : 0);
+			want = base + bw_of(rt[i] * NSEC_PER_MSEC, PERIOD);
 			if (bw != want) {
 				ksft_print_msg("%llums every 100ms: total_bw %lld after the switch, %lld expected\n",
 					       (unsigned long long)rt[i], bw, want);
 				ret = KSFT_FAIL;
 			}
-			sleep_ns(PERIOD);	/* past the deadline */
+			sleep_ns(3 * PERIOD);	/* past the 0-lag time */
 			bw = total_bw_of(cpu);
 			if (ret == KSFT_PASS && bw != base) {
-				ksft_print_msg("%llums every 100ms: total_bw %lld after the deadline, %lld expected\n",
+				ksft_print_msg("%llums every 100ms: total_bw %lld after the 0-lag time, %lld expected\n",
 					       (unsigned long long)rt[i], bw, base);
 				ret = KSFT_FAIL;
 			}
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 38/43] sched/deadline: Boost an owner that cannot run on its own reservation
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (30 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 37/43] sched/deadline: Keep the debt of a task across a change of parameters Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 39/43] sched/deadline: Boost an owner throttled after its waiter blocked Mathieu Desnoyers
                   ` (2 subsequent siblings)
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

rt_mutex_setprio() lets a deadline waiter boost the owner of the lock
only if the waiter's deadline is earlier than the owner's. Commit
2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
added this test with the boost. The boost is there to "ensure a pi-lock
owner with waiters is never throttled down". The test assumes that the
owner runs on its current deadline. Two owners do not:
- An owner that ran out of runtime is throttled until its next period.
  Its deadline is often earlier than the waiter's.
- A constrained owner past its deadline and before its next period is
  in its constrained gap. Its deadline has passed. Its next enqueue
  throttles it, since commit df8eac8cafce ("sched/deadline: Throttle a
  constrained deadline task activated after the deadline").

The waiter does not boost these owners. It waits for the owner's next
period, and can miss its own deadline. This holds for a deadline task
that waits on a PI futex, or on an rt_mutex in the kernel.

Fix the test in a new dl_waiter_boosts(). It always boosts an owner
that is throttled or has no runtime left, and an owner in its
constrained gap. In M-BWI [1], an owner runs in the reservation of a
waiter when its own cannot run. Another owner past its deadline is
compared at now + dl_deadline, the deadline its next enqueue gives it.

Such a boost is held from its start, until the owner's own next period.
The new dl_boost_start() saves the owner's period, as a boost held at
its first refill does. The new dl_boost_donor_period() then runs the
owner on a period of the donor's parameters, starting now. A refill
from the owner's own deadline would often end after the waiter's.

Nothing charges the donor for this time. A waiter that times out again
and again would give the owner one donor runtime per boost. So the
deboost keeps the donor period, and the next held boost resumes it,
until a whole donor period has passed. The next boost can have another
donor. It keeps the start of the period and the runtime left, and takes
the deadline from the new donor. The resumed runtime is capped at the
donor's runtime, and at what the donor's density allows until the
deadline, as update_dl_revised_wakeup() does.

The patch also handles these cases:
- At the deboost, an owner throttled while asleep is throttled again
  until its own next period, with its timer moved there.
- A yield gave up the rest of the owner's own period: dl_boost_start()
  saves no runtime for it, and the donor period ignores the yield.
- sched_setattr() during a held boost fits the saved period to the new
  parameters, as for a boost held at its first refill.
- replenish_dl_entity() no longer warns that it "lagged too much" when
  it refills a boosted entity past its deadline.
- In a lock cycle, the top waiter's donor can be the owner itself.
  dl_set_donor() now reports it, and rt_mutex_setprio() ends the boost
  instead of leaving it held. A Spin model of the chain walk found this.
- An owner with no deadline policy is not boosted by such a waiter at
  all. In the class, it would have no parameters and no donor, and its
  enqueue would leave it off the runqueue. This happens on v7.4-rc2
  too, after a failed ABBA lock attempt and a sched_setscheduler(), or
  with a stale donor that a chain walk left in the waiter.
  __rt_effective_prio() now leaves the owner at its own priority. One
  read of the waiter's donor, in dl_top_donor(), chooses both the class
  and the donor. With two reads, a store in between would bring the bad
  state back. A Spin model finds this state in 8 steps with two reads,
  and none within its bounds with one. dl_top_donor() also takes the
  reference on the donor, so that nothing can fail once the class is
  chosen.

The limit is per owner: a waiter that boosts N owners in turn gives
them N donor runtimes per donor period. The limit also needs a donor
with an implicit deadline. An owner with no parameters of its own still
has no limit, as before this patch.

The Sashiko AI review of this series found the gap case.
"selftests/sched: Test parameter changes in deadline_bw_test", later in
this series, lists the cases that fail without this patch.

[1] D. Faggioli, G. Lipari, T. Cucinotta, "Analysis and Implementation
    of the Multiprocessor BandWidth Inheritance Protocol", Real-Time
    Systems, 2012, section 5.1

Fixes: 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
Fixes: df8eac8cafce ("sched/deadline: Throttle a constrained deadline task activated after the deadline")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 include/linux/sched.h   |  18 +++-
 kernel/sched/core.c     |  57 +++++++---
 kernel/sched/deadline.c | 230 +++++++++++++++++++++++++++++++++++-----
 kernel/sched/sched.h    | 125 +++++++++++++++++-----
 kernel/sched/syscalls.c |  22 ++--
 5 files changed, 373 insertions(+), 79 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 148e2939e6cb..cafa26c874b0 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -681,6 +681,10 @@ struct sched_dl_entity {
 			u64		setattr_period;
 		};
 	};
+	/* Saved by dl_end_held_boost(): see dl_boost_granted */
+	u64				boost_deadline;
+	s64				boost_runtime;
+	u64				boost_period_start;
 	unsigned int			flags;		/* Specifying the scheduler behaviour	*/
 
 	/*
@@ -710,9 +714,12 @@ struct sched_dl_entity {
 	 * reservation. The end of the boost clears the flag.
 	 *
 	 * @dl_boost_held tells that own_deadline, own_runtime and
-	 * own_period_start hold the task's own period. The first refill of a
-	 * boost saves them, for a task with parameters of its own. The deboost
-	 * puts them back.
+	 * own_period_start hold the task's own period. dl_boost_start() saves
+	 * them for a task that could not run on its own reservation: it was
+	 * throttled, or past its deadline and before its next period. While a
+	 * waiter waits, that boost lasts at least until the task's own next
+	 * period. The first refill of any other boost saves them too, for a
+	 * task with parameters of its own. The deboost puts them back.
 	 *
 	 * @dl_server tells if this is a server entity.
 	 *
@@ -754,6 +761,10 @@ struct sched_dl_entity {
 	 * setattr_runtime, setattr_deadline and setattr_period hold the old
 	 * parameters. The first refill or the deboost fits the period to the
 	 * new ones with them.
+	 *
+	 * @dl_boost_granted tells if boost_deadline, boost_runtime and
+	 * boost_period_start hold the donor period that the last held boost
+	 * ran on. dl_boost_donor_period() can resume it.
 	 */
 	unsigned int			dl_throttled      : 1;
 	unsigned int			dl_yielded        : 1;
@@ -770,6 +781,7 @@ struct sched_dl_entity {
 	unsigned int			dl_bw_attached    : 1;
 	unsigned int			dl_bw_oncpu       : 1;
 	unsigned int			dl_new_params     : 1;
+	unsigned int			dl_boost_granted  : 1;
 	unsigned int			dl_setattr_saved  : 1;
 
 	/*
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index f374b8a0a38b..9fda819aa4ef 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7904,17 +7904,23 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 	int prio, oldprio, queue_flag =
 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
 	const struct sched_class *prev_class, *next_class;
+	struct sched_dl_entity *donor;
 	struct rq_flags rf;
 	struct rq *rq;
+	int wprio;
 
+	/* One read decides the class and the donor: see dl_top_donor(). */
+	donor = dl_top_donor(&p->dl, pi_task, &wprio);
 	/* XXX used to be waiter->prio, not waiter->task->prio */
-	prio = __rt_effective_prio(pi_task, p->normal_prio);
+	prio = __rt_effective_prio(p, donor, wprio, p->normal_prio);
 
 	/*
 	 * If nothing changed; bail early.
 	 */
-	if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
+	if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio)) {
+		dl_put_donor(&p->dl, donor);
 		return;
+	}
 
 	rq = __task_rq_lock(p, &rf);
 	update_rq_clock(rq);
@@ -7972,9 +7978,9 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 		 * 1. -rt task is running and holds mutex A
 		 *      --> -dl task blocks on mutex A
 		 *
-		 * 2. -dl task is running and holds mutex A
-		 *      --> -dl task blocks on mutex A and could preempt the
-		 *          running task
+		 * 2. -dl task holds mutex A
+		 *      --> -dl task blocks on mutex A, and dl_waiter_boosts()
+		 *          returns true for it
 		 */
 		if (dl_prio(prio)) {
 			/*
@@ -7984,15 +7990,36 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 			 * with that deadline.
 			 */
 			if (!dl_prio(p->normal_prio) ||
-			    (pi_task && dl_prio(pi_task->prio) &&
+			    (donor &&
 			     !(p->dl.dl_new_params && p->dl.pi_se != &p->dl) &&
-			     dl_entity_preempt(&pi_task->dl, &p->dl))) {
+			     dl_waiter_boosts(p, pi_task))) {
 				struct sched_dl_entity *old_donor = p->dl.pi_se;
 
-				dl_set_donor(&p->dl, pi_task);
-				scope->flags |= ENQUEUE_REPLENISH;
-				if (!scope->queued && p->dl.pi_se != old_donor)
-					dl_boost_blocked(p);
+				/*
+				 * donor is not NULL here. A task with no
+				 * deadline policy has a deadline prio only from
+				 * a deadline waiter, whose donor is not @p: see
+				 * __rt_effective_prio().
+				 */
+				if (!dl_set_donor(&p->dl, &donor)) {
+					/*
+					 * The donor of the top waiter is @p: @p waits
+					 * on a lock that it owns, or the waiter has a
+					 * stale donor. End the boost of a deadline
+					 * task, as a deboost does. A task with no
+					 * deadline policy does not get here:
+					 * __rt_effective_prio() did not boost it.
+					 */
+					if (dl_prio(p->normal_prio) && old_donor != &p->dl)
+						dl_deboost(&p->dl);
+				} else {
+					if (dl_prio(p->normal_prio) &&
+					    old_donor == &p->dl && p->dl.pi_se != &p->dl)
+						dl_boost_start(&p->dl);
+					scope->flags |= ENQUEUE_REPLENISH;
+					if (!scope->queued && p->dl.pi_se != old_donor)
+						dl_boost_blocked(p);
+				}
 			} else {
 				dl_deboost(&p->dl);
 				/*
@@ -8000,9 +8027,10 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 				 * can 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)) {
-					dl_set_donor(&p->dl, pi_task);
+				if (donor && dl_waiter_boosts(p, pi_task) &&
+				    dl_set_donor(&p->dl, &donor)) {
+					if (p->dl.pi_se != &p->dl)
+						dl_boost_start(&p->dl);
 					scope->flags |= ENQUEUE_REPLENISH;
 				}
 			}
@@ -8022,6 +8050,7 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 		p->prio = prio;
 	}
 out_unlock:
+	dl_put_donor(&p->dl, donor);
 	/* Caller holds task_struct::pi_lock, IRQs are still disabled */
 
 	__balance_callbacks(rq, &rf);
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index ae0940838ca5..7f839185eb38 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -96,10 +96,10 @@ static inline void dl_start_own_period(struct sched_dl_entity *dl_se)
 
 /*
  * Put back the deadline, runtime and period start saved when the boost
- * was held, by dl_hold_refilled_boost(). If the task's own next period
- * has started since, start a period of its own instead. Return true if
- * the boost was held. The caller holds the rq lock and has updated the
- * rq clock.
+ * was held, by dl_boost_start() or dl_hold_refilled_boost(). If the
+ * task's own next period has started since, start a period of its own
+ * instead. Return true if the boost was held. The caller holds the rq
+ * lock and has updated the rq clock.
  *
  * A task @asleep on anything but an rt_mutex gets that period at its
  * wakeup instead: a period started now would run while it sleeps.
@@ -111,30 +111,61 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se,
 
 	if (!dl_se->dl_boost_held)
 		return false;
+	/*
+	 * Keep what is left of the donor period, for the next held boost to
+	 * resume: see dl_boost_donor_period().
+	 */
+	dl_se->boost_deadline = dl_se->deadline;
+	dl_se->boost_runtime = dl_se->runtime;
+	dl_se->boost_period_start = dl_se->period_start;
+	dl_se->dl_boost_granted = 1;
 	if (dl_time_before(now, dl_se->own_period_start + dl_se->dl_period)) {
 		dl_se->deadline = dl_se->own_deadline;
 		dl_se->runtime = dl_se->own_runtime;
 		dl_se->period_start = dl_se->own_period_start;
 		/*
 		 * Past its own deadline, the task is in its constrained gap:
-		 * it waits for its own next period. Give back no runtime, so
-		 * that dl_deboost() throttles it. Before its deadline,
+		 * it waits for its own next period. Give back no runtime left,
+		 * so that dl_deboost() throttles it. An overrun of its own
+		 * runtime stays, as a refill pays it back. Before its deadline,
 		 * dl_hold_refilled_boost() can keep runtime left, from a
 		 * wakeup refill. Cap it at what the task's own density allows
 		 * until its deadline, as update_dl_revised_wakeup() does.
 		 */
 		if (!dl_time_before(now, dl_se->deadline))
-			dl_se->runtime = 0;
+			dl_se->runtime = min_t(s64, dl_se->runtime, 0);
 		else if (dl_se->runtime > 0)
 			dl_se->runtime = min_t(s64, dl_se->runtime,
 					       (dl_se->dl_density *
 						(dl_se->deadline - now)) >> BW_SHIFT);
-	} else if (asleep) {
-		dl_se->deadline = dl_se->own_deadline;
-		dl_se->period_start = dl_se->own_period_start;
-		dl_se->runtime = 0;
+		/*
+		 * sched_setattr() during the boost can have started a new
+		 * period of the task's own, with runtime. A throttle from
+		 * before the boost does not apply to it: lift it.
+		 */
+		if (dl_se->runtime > 0 && dl_se->dl_throttled) {
+			dl_se->dl_throttled = 0;
+			if (hrtimer_try_to_cancel(&dl_se->dl_timer) == 1)
+				put_task_struct(dl_task_of(dl_se));
+		}
 	} else {
-		dl_start_own_period(dl_se);
+		/*
+		 * The own next period has started, which lifts the throttle.
+		 * A task asleep since before the boost still has its
+		 * replenishment timer armed for its old next period: cancel
+		 * it. A task asleep keeps the end of its own period: its
+		 * wakeup starts the next one.
+		 */
+		if (asleep) {
+			dl_se->deadline = dl_se->own_deadline;
+			dl_se->period_start = dl_se->own_period_start;
+			dl_se->runtime = 0;
+		} else {
+			dl_start_own_period(dl_se);
+		}
+		dl_se->dl_throttled = 0;
+		if (hrtimer_try_to_cancel(&dl_se->dl_timer) == 1)
+			put_task_struct(dl_task_of(dl_se));
 	}
 	dl_se->dl_donor_refill = 0;
 	return true;
@@ -190,9 +221,12 @@ static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
 }
 
 static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task);
-static int start_dl_timer(struct sched_dl_entity *dl_se);
 
 static void update_dl_entity(struct sched_dl_entity *dl_se);
+static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
+					   struct rq *rq);
+static int start_dl_timer(struct sched_dl_entity *dl_se);
+static void cancel_replenish_timer(struct sched_dl_entity *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)
@@ -207,10 +241,10 @@ static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
  * End the boost of @dl_se, whose task stays in the class. Then bring the
  * runtime and the deadline of the task back to its own parameters:
  *  - After a held boost, dl_end_held_boost() puts back the values that
- *    dl_hold_refilled_boost() saved. The time the task ran on the
- *    donor's refills is not charged to its own runtime. If that runtime
- *    is used up, throttle the task again until its own next period, or
- *    start that period if it has started.
+ *    dl_boost_start() or dl_hold_refilled_boost() saved. The time the
+ *    task ran on its donor's parameters is not charged to its own
+ *    runtime. If that runtime is used up, throttle the task again until
+ *    its own next period, or start that period if it has started.
  *  - After a refill of a task that had no parameters of its own at the
  *    refill, start a new period now, or at the wakeup of a task asleep.
  *    dl_hold_refilled_boost() holds the boost of a task that had them.
@@ -285,6 +319,13 @@ void dl_deboost(struct sched_dl_entity *dl_se)
 	if (held && dl_se->runtime <= 0 && (!asleep || dl_se->dl_throttled)) {
 		struct rq *rq = task_rq(p);
 
+		/*
+		 * The timer can still be armed. enqueue_task_dl() cancels it
+		 * when it boosts a runnable task, but a task that slept through
+		 * the boost kept it. sched_setattr() can have moved the task's
+		 * next period since. Cancel the timer before arming it again.
+		 */
+		cancel_replenish_timer(dl_se);
 		dl_se->dl_throttled = 1;
 		if (!start_dl_timer(dl_se)) {
 			dl_se->dl_throttled = 0;
@@ -379,6 +420,130 @@ void dl_check_blocked_params(struct task_struct *p)
 		update_dl_entity(dl_se);
 	}
 }
+
+/*
+ * Return true if the deadline waiter @pi_task must boost the owner @p,
+ * which has a deadline policy of its own. Compare @pi_task with the
+ * deadline that @p would run on:
+ * - The boost of @p is held: keep it until the next period of @p
+ *   starts. After that, compare with now + dl_deadline.
+ * - @p is not boosted, and cannot run on its own reservation. It is
+ *   throttled, or past its deadline and before its next period. Boost it.
+ * - @p is not boosted, and past its deadline otherwise: its next enqueue
+ *   starts a new period. Compare with now + dl_deadline.
+ * - Else, compare with the deadline of @p.
+ * A special entity (a sugov kthread) always boosts @p.
+ *
+ * The caller holds the rq lock of @p and has updated the rq clock.
+ */
+bool dl_waiter_boosts(struct task_struct *p, struct task_struct *pi_task)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+	u64 now = rq_clock(task_rq(p));
+
+	if (dl_entity_is_special(&pi_task->dl))
+		return true;
+	if (dl_se->dl_boost_held) {
+		/*
+		 * A boost held at a wakeup refill can keep runtime of the
+		 * task's own, before its own deadline. The task can run on
+		 * it: compare with that deadline.
+		 */
+		if (dl_se->own_runtime > 0 &&
+		    dl_time_before(now, dl_se->own_deadline))
+			return dl_time_before(pi_task->dl.deadline,
+					      dl_se->own_deadline);
+		if (dl_time_before(now, dl_se->own_period_start + dl_se->dl_period))
+			return true;
+		return dl_time_before(pi_task->dl.deadline, now + dl_se->dl_deadline);
+	}
+	if (!is_dl_boosted(dl_se)) {
+		if (dl_se->dl_throttled || dl_in_constrained_gap(dl_se) ||
+		    (dl_se->dl_runtime && dl_se->runtime <= 0))
+			return true;
+		if (dl_time_before(dl_se->deadline, now))
+			return dl_time_before(pi_task->dl.deadline,
+					      now + dl_se->dl_deadline);
+	}
+	return dl_entity_preempt(&pi_task->dl, dl_se);
+}
+
+static bool dl_entity_overflow(struct sched_dl_entity *dl_se, u64 t);
+
+/*
+ * Run @dl_se, whose boost is held, on a period of its donor. Resume the
+ * donor period that the last held boost ran on, unless a whole period of
+ * the current donor has passed since it started. A new period at each
+ * boost would give the task one donor runtime per boost. Nothing charges
+ * the donor for that runtime.
+ *
+ * If the deadline of the resumed period has passed, move to its next
+ * period here, with a full donor runtime. A later enqueue would
+ * otherwise start a period from now, which gives a second donor runtime
+ * too early. As in a refill by replenish_dl_entity(), the task can use
+ * that runtime at once, although its period starts in the future.
+ *
+ * Cap the runtime to the donor's density until the deadline, as
+ * update_dl_revised_wakeup() does at the wakeup of a constrained task.
+ */
+static void dl_boost_donor_period(struct sched_dl_entity *dl_se)
+{
+	struct sched_dl_entity *pi_se = pi_of(dl_se);
+	struct rq *rq = rq_of_dl_se(dl_se);
+	u64 runtime = READ_ONCE(pi_se->dl_runtime);
+	u64 period = READ_ONCE(pi_se->dl_period);
+	u64 now = rq_clock(rq);
+
+	/*
+	 * The donor can differ from the one of the last held boost. Keep the
+	 * start of the donor period and the runtime left, but take the
+	 * deadline and the cap of the runtime from this donor.
+	 */
+	if (dl_se->dl_boost_granted && runtime && period &&
+	    dl_time_before(now, dl_se->boost_period_start + period)) {
+		dl_se->period_start = dl_se->boost_period_start;
+		dl_se->deadline = dl_se->period_start +
+				  READ_ONCE(pi_se->dl_deadline);
+		dl_se->runtime = min_t(s64, dl_se->boost_runtime, runtime);
+		if (!dl_time_before(now, dl_se->deadline)) {
+			dl_se->period_start += period;
+			dl_se->deadline += period;
+			dl_se->runtime = runtime;
+		}
+		if (dl_entity_overflow(dl_se, now))
+			dl_se->runtime = (READ_ONCE(pi_se->dl_density) *
+					  (dl_se->deadline - now)) >> BW_SHIFT;
+		return;
+	}
+	replenish_dl_new_period(dl_se, rq);
+}
+
+/*
+ * Call this when @dl_se gets its first donor, after dl_set_donor(). If
+ * @dl_se cannot run on its own reservation, hold the boost from now. Save
+ * its deadline, runtime and period start in own_*, and set dl_boost_held.
+ * Then run it on a period of the donor. A refill would instead add donor
+ * periods to its own deadline. That is often later than the waiter's.
+ *
+ * A task with no parameters of its own has nothing to save. The caller
+ * holds the rq lock and has updated the rq clock.
+ */
+void dl_boost_start(struct sched_dl_entity *dl_se)
+{
+	if (!dl_se->dl_runtime ||
+	    (!dl_se->dl_throttled && !dl_in_constrained_gap(dl_se)))
+		return;
+	/*
+	 * A yield gave up the rest of the task's own period: save no runtime
+	 * for it. The yield does not apply to the donor period placed below.
+	 */
+	dl_se->own_deadline = dl_se->deadline;
+	dl_se->own_runtime = dl_se->dl_yielded ? 0 : dl_se->runtime;
+	dl_se->own_period_start = dl_se->period_start;
+	dl_se->dl_boost_held = 1;
+	dl_se->dl_yielded = 0;
+	dl_boost_donor_period(dl_se);
+}
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -1692,7 +1857,13 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 	 * entity.
 	 */
 	if (dl_time_before(dl_se->deadline, rq_clock(rq))) {
-		printk_deferred_once("sched: DL replenish lagged too much\n");
+		/*
+		 * dl_waiter_boosts() can boost an owner past its deadline: do
+		 * not warn for a boosted entity. The new period takes the
+		 * donor's parameters.
+		 */
+		if (!is_dl_boosted(dl_se))
+			printk_deferred_once("sched: DL replenish lagged too much\n");
 		replenish_dl_new_period(dl_se, rq);
 	}
 
@@ -5614,10 +5785,10 @@ static u64 dl_mul_div_cap(u64 a, u64 b, u64 c, u64 cap)
 /*
  * Fit a period of @dl_se to its new parameters. sched_setattr() changed
  * them from @old_runtime, @old_deadline and @old_period. At @now,
- * *@start, *@deadline and *@runtime describe the period in progress
- * under the old parameters. On return, they describe a period under the
- * new ones. Return true if the task must wait for that period, with no
- * runtime.
+ * *@start, *@deadline and *@runtime describe a period under the old
+ * parameters: the one in progress, or the one that a held boost keeps
+ * aside. On return, they describe a period under the new ones. Return
+ * true if the task must wait for that period, with no runtime.
  *
  * These terms are used below:
  *  - The release of the job is *@deadline - @old_deadline.
@@ -5758,12 +5929,14 @@ static bool dl_setattr_place(struct sched_dl_entity *dl_se, u64 now,
  *    deboost comes first, dl_deboost() or dl_drop_boost_out() fits it.
  *
  * Return true if the runtime left or the period still needs work later.
- * That is the case for a boosted task: its deboost does it. A task with
- * no period under the old parameters needs it too: its next enqueue
- * checks the runtime left as a wakeup does. Return false for any other
- * task: it is now in a period of the new parameters. The wakeup check
- * rounds to the microsecond. It could find an overflow there and start
- * a new period, which the debt does not allow.
+ * That is the case for a boosted task: its deboost does it. dl_new_params
+ * also makes rt_mutex_setprio() deboost it, and compare it again with
+ * its top waiter. A task with no period under the old parameters needs
+ * it too: its next enqueue checks the runtime left as a wakeup does.
+ * Return false for any other task: it is now in a period of the new
+ * parameters. The wakeup check rounds to the microsecond. It could find
+ * an overflow there and start a new period, which the debt does not
+ * allow.
  *
  * The caller holds the rq lock and the pi_lock of the task, and has
  * updated the rq clock. The task is not on its dl_rq: every caller runs
@@ -6053,6 +6226,7 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se)
 	dl_se->dl_defer_armed		= 0;
 	dl_se->dl_bw_oncpu		= 0;
 	dl_se->dl_new_params		= 0;
+	dl_se->dl_boost_granted		= 0;
 	dl_se->dl_setattr_saved		= 0;
 }
 
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 43aef9b61b67..efc16cc6fa95 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -373,37 +373,88 @@ static inline void dl_replace_donor(struct sched_dl_entity *dl_se,
 }
 
 /*
- * Make the deadline donor of the waiter @pi_task the donor of @dl_se. A
- * boosted entity holds a reference on the task of its donor. The donor
- * is the deadline task at the head of the chain. It can stop waiting
- * and exit before the chain walk reaches @dl_se: that walk can be
- * preempted.
+ * Return the deadline donor of the waiter @pi_task, for the boost of
+ * @dl_se, and set *@prio to the priority of @pi_task. Return NULL if
+ * @pi_task is NULL or has no deadline priority, and @dl_se itself if
+ * the donor of @pi_task is @dl_se: the task of @dl_se then waits on a
+ * lock that it owns, or a chain walk left a stale donor in @pi_task.
+ * Otherwise, the donor comes with a reference on its task. Pass it to
+ * dl_set_donor(), or drop it with dl_put_donor().
+ *
+ * Read the priority and the donor once per decision. The class of the
+ * boosted task and its donor must come from the same values. Take the
+ * reference here too: nothing may fail once the class is chosen.
+ *
+ * The two are separate loads. A change of @pi_task between them can give
+ * a deadline priority with the own entity of @pi_task as donor, while
+ * @pi_task has no deadline policy. The boosted task then runs on a donor
+ * with no parameters, as when a donor leaves the class:
+ * replenish_dl_entity() covers it. The chain walk of that change then
+ * corrects the boost.
  *
  * The donor of @pi_task is read without the locks of @pi_task. Another
  * CPU can change it meanwhile, and put the last reference on the old
  * donor. That CPU stores the new donor first: read it again then. The
- * old task_struct stays readable while the rq lock is held:
- * put_task_struct() frees it through call_rcu(), and the rq lock holds
- * off the grace period.
- *
- * The caller holds the rq lock and the pi_lock of the task of @dl_se.
+ * old task_struct stays readable: put_task_struct() frees it through
+ * call_rcu(). The caller holds the pi_lock of the task of @dl_se with
+ * interrupts off, on a CPU that RCU watches: a chain walk, the irq_work
+ * of rt_mutex_adjust_owner(), or a system call. That holds off the grace
+ * period.
  */
-static inline void dl_set_donor(struct sched_dl_entity *dl_se,
-				struct task_struct *pi_task)
+static inline struct sched_dl_entity *dl_top_donor(struct sched_dl_entity *dl_se,
+						   struct task_struct *pi_task,
+						   int *prio)
 {
 	struct sched_dl_entity *pi_se;
 
+	*prio = pi_task ? READ_ONCE(pi_task->prio) : MAX_PRIO;
+	if (!dl_prio(*prio))
+		return NULL;
 	for (;;) {
 		pi_se = READ_ONCE(pi_task->dl.pi_se);
-		if (pi_se == dl_se->pi_se)
-			return;
 		if (pi_se == dl_se ||
 		    tryget_task_struct(container_of(pi_se, struct task_struct, dl)))
-			break;
+			return pi_se;
 		/* Pairs with the ordering of refcount_dec_and_test(). */
 		smp_rmb();
 	}
-	dl_replace_donor(dl_se, pi_se);
+}
+
+/* Drop a donor that dl_top_donor() returned for @dl_se and that is unused. */
+static inline void dl_put_donor(struct sched_dl_entity *dl_se,
+				struct sched_dl_entity *pi_se)
+{
+	if (pi_se && pi_se != dl_se)
+		put_task_struct(container_of(pi_se, struct task_struct, dl));
+}
+
+/*
+ * Make *@pi_se, a donor that dl_top_donor() returned, the donor of
+ * @dl_se. A boosted entity holds a reference on the task of its donor.
+ * The donor is the deadline task at the head of the chain. It can stop
+ * waiting and exit before the chain walk reaches @dl_se: that walk can be
+ * preempted.
+ *
+ * Return false if *@pi_se is @dl_se itself, and leave the donor as it
+ * is. Otherwise use the reference of *@pi_se, set *@pi_se to NULL, and
+ * return true. *@pi_se must not be NULL: the caller tests it, or knows
+ * it from a deadline priority that the donor gave.
+ *
+ * The caller holds the rq lock and the pi_lock of the task of @dl_se.
+ */
+static inline bool dl_set_donor(struct sched_dl_entity *dl_se,
+				struct sched_dl_entity **pi_se)
+{
+	struct sched_dl_entity *donor = *pi_se;
+
+	if (donor == dl_se)
+		return false;
+	*pi_se = NULL;
+	if (donor == dl_se->pi_se)
+		dl_put_donor(dl_se, donor);
+	else
+		dl_replace_donor(dl_se, donor);
+	return true;
 }
 
 /* Make @dl_se its own donor. The caller holds the rq lock of its task. */
@@ -416,6 +467,8 @@ extern void dl_deboost(struct sched_dl_entity *dl_se);
 extern void dl_drop_boost_out(struct sched_dl_entity *dl_se);
 extern void dl_boost_blocked(struct task_struct *p);
 extern void dl_check_blocked_params(struct task_struct *p);
+extern bool dl_waiter_boosts(struct task_struct *p, struct task_struct *pi_task);
+extern void dl_boost_start(struct sched_dl_entity *dl_se);
 
 /*
  * End the boost of @dl_se, and forget the deadline and runtime saved for
@@ -429,6 +482,11 @@ static inline void dl_drop_boost(struct sched_dl_entity *dl_se)
 	dl_se->dl_boost_held = 0;
 	dl_se->dl_setattr_saved = 0;
 }
+#else /* !CONFIG_RT_MUTEXES: */
+static inline void dl_put_donor(struct sched_dl_entity *dl_se,
+				struct sched_dl_entity *pi_se)
+{
+}
 #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);
@@ -4349,25 +4407,44 @@ bool task_is_pushable(struct rq *rq, struct task_struct *p, int cpu)
 
 #ifdef CONFIG_RT_MUTEXES
 
-static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
+/*
+ * Return the priority of @p, of normal priority @prio, boosted by its top
+ * waiter of priority @wprio and deadline donor @donor, both read by
+ * dl_top_donor(). @donor can be @p itself: @p waits on a lock it owns,
+ * or a chain walk left a stale donor in the waiter. A boost would then
+ * leave a task with no deadline policy in the class, with no parameters
+ * and no donor: its enqueue would not put it on the runqueue. Do not
+ * boost it with that waiter.
+ */
+static inline int __rt_effective_prio(struct task_struct *p,
+				      struct sched_dl_entity *donor,
+				      int wprio, int prio)
 {
-	if (pi_task)
-		prio = min(prio, pi_task->prio);
-
-	return prio;
+	if (donor == &p->dl && !dl_prio(prio))
+		return prio;
+	return min(prio, wprio);
 }
 
-static inline int rt_effective_prio(struct task_struct *p, int prio)
+/*
+ * As __rt_effective_prio(), for the top waiter of @p. Also return in
+ * *@donor the donor it used, as dl_top_donor() returns it.
+ */
+static inline int rt_effective_prio(struct task_struct *p, int prio,
+				    struct sched_dl_entity **donor)
 {
 	struct task_struct *pi_task = rt_mutex_get_top_task(p);
+	int wprio;
 
-	return __rt_effective_prio(pi_task, prio);
+	*donor = dl_top_donor(&p->dl, pi_task, &wprio);
+	return __rt_effective_prio(p, *donor, wprio, prio);
 }
 
 #else /* !CONFIG_RT_MUTEXES: */
 
-static inline int rt_effective_prio(struct task_struct *p, int prio)
+static inline int rt_effective_prio(struct task_struct *p, int prio,
+				    struct sched_dl_entity **donor)
 {
+	*donor = NULL;
 	return prio;
 }
 
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 4f26601f0530..b71df4c2c13a 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -303,6 +303,7 @@ static bool check_same_owner(struct task_struct *p)
 #ifdef CONFIG_RT_MUTEXES
 static inline void __setscheduler_dl_pi(int newprio, int policy,
 			      struct task_struct *p,
+			      struct sched_dl_entity **donor,
 			      struct sched_change_ctx *scope)
 {
 	/*
@@ -312,14 +313,10 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
 	 * sure replenishment happens with the next enqueue.
 	 */
 
-	if (dl_prio(newprio) && !dl_policy(policy)) {
-		struct task_struct *pi_task = rt_mutex_get_top_task(p);
-
-		if (pi_task) {
-			dl_set_donor(&p->dl, pi_task);
-			scope->flags |= ENQUEUE_REPLENISH;
-		}
-	}
+	/* *@donor chose newprio: see rt_effective_prio(). */
+	if (dl_prio(newprio) && !dl_policy(policy) && *donor &&
+	    dl_set_donor(&p->dl, donor))
+		scope->flags |= ENQUEUE_REPLENISH;
 
 	/*
 	 * Without pi, as from normalize_rt_tasks(), a boosted task can leave
@@ -334,6 +331,7 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
 #else /* !CONFIG_RT_MUTEXES */
 static inline void __setscheduler_dl_pi(int newprio, int policy,
 			      struct task_struct *p,
+			      struct sched_dl_entity **donor,
 			      struct sched_change_ctx *scope)
 {
 }
@@ -523,6 +521,7 @@ int __sched_setscheduler(struct task_struct *p,
 	int oldpolicy = -1, policy = attr->sched_policy;
 	int retval, oldprio, newprio;
 	const struct sched_class *prev_class, *next_class;
+	struct sched_dl_entity *donor = NULL;
 	struct balance_callback *head;
 	struct rq_flags rf;
 	int reset_on_fork;
@@ -729,7 +728,7 @@ int __sched_setscheduler(struct task_struct *p,
 		 * the runqueue. This will be done when the task deboost
 		 * itself.
 		 */
-		newprio = rt_effective_prio(p, newprio);
+		newprio = rt_effective_prio(p, newprio, &donor);
 		if (newprio == oldprio && !dl_prio(newprio))
 			queue_flags &= ~DEQUEUE_MOVE;
 	}
@@ -790,7 +789,7 @@ int __sched_setscheduler(struct task_struct *p,
 			__setscheduler_params(p, attr);
 			p->sched_class = next_class;
 			p->prio = newprio;
-			__setscheduler_dl_pi(newprio, policy, p, scope);
+			__setscheduler_dl_pi(newprio, policy, p, &donor, scope);
 		}
 		__setscheduler_uclamp(p, attr);
 
@@ -807,6 +806,8 @@ int __sched_setscheduler(struct task_struct *p,
 	/* Avoid rq from going away on us: */
 	preempt_disable();
 	head = splice_balance_callbacks(rq);
+	/* A donor read for newprio and not used. */
+	dl_put_donor(&p->dl, donor);
 	task_rq_unlock(rq, p, &rf);
 
 	if (pi) {
@@ -824,6 +825,7 @@ int __sched_setscheduler(struct task_struct *p,
 	return 0;
 
 unlock:
+	dl_put_donor(&p->dl, donor);
 	task_rq_unlock(rq, p, &rf);
 	if (cpuset_locked) {
 		dl_accounting_unlock();
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 39/43] sched/deadline: Boost an owner throttled after its waiter blocked
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (31 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 38/43] sched/deadline: Boost an owner that cannot run on its own reservation Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 40/43] sched/deadline: Reschedule a running task throttled at its enqueue Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 41/43] sched/deadline: Run a boost held at its first refill on a donor period Mathieu Desnoyers
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

"sched/deadline: Boost an owner that cannot run on its own reservation"
boosts a throttled owner when a waiter blocks, leaves or changes. But
the owner can be throttled after its waiter blocked:
- its runtime runs out;
- an enqueue throttles it in its constrained gap;
- sched_setattr() throttles it until it repays its debt.
Nothing calls rt_mutex_setprio() then. The waiter waits for the owner's
next period, and can miss its own deadline.

Fix this by asking for a boost at these throttles, with the new
dl_request_owner_boost(). rt_mutex_setprio() needs the owner's
pi_lock, which nests outside the rq lock held there. So
dl_request_owner_boost() queues a hard irq_work. The work calls the new
rt_mutex_adjust_owner(), which boosts the owner from its top waiter
under the pi_lock, if dl_waiter_boosts() says so. A call to
rt_mutex_setprio() that boosts nothing would still dequeue and enqueue
the owner.

The rtmutex code also asks, without the rq lock:
- In try_to_take_rt_mutex(): the tick can throttle a task in the slow
  path of a lock, before it has waiters. It can still take the lock,
  and get waiters.
- Where a task stops waiting on a lock without taking it.
  rt_mutex_adjust_owner() skips an owner that waits on another lock,
  since a new donor would need a chain walk.
A throttle after a yield does not ask: the owner gave up its runtime.

One case stays open. An owner throttled while it waits on another lock
cannot run to take that lock. Its own waiters wait for its next period.

On a CPU going offline, the __balance_callbacks() at the end of
rt_mutex_setprio() runs balance_push(). Its per-CPU work buffer
expects one call per switch-in. The irq_work can interrupt the tail of
a switch-in, and would queue that buffer twice. balance_push() now
returns in hard interrupt context. The next __schedule() does the push.

dl_owner_boost_work() can drop the last reference on the task that
holds the irq_work, before irq_work_single() is done with it. This is
safe because put_task_struct() frees the task through call_rcu(), since
commit 8671bad873eb ("sched: Do not call __put_task_struct() on rt if
pi_blocked_on is set"), in v6.17. A backport needs that commit.
RT_MUTEXES now selects IRQ_WORK, which is only built by default on SMP.

"selftests/sched: Test parameter changes in deadline_bw_test", later in
this series, lists the cases that fail without this patch.

Fixes: 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org # 6.16.x and older: 8671bad873eb: sched: Do not call __put_task_struct() on rt if pi_blocked_on is set
Cc: stable@vger.kernel.org
---
 include/linux/sched.h        |  6 +++
 include/linux/sched/rt.h     |  4 ++
 init/Kconfig                 |  1 +
 kernel/locking/rtmutex.c     | 27 +++++++++++
 kernel/locking/rtmutex_api.c | 27 +++++++++++
 kernel/sched/core.c          |  9 ++++
 kernel/sched/deadline.c      | 94 ++++++++++++++++++++++++++++++++++++
 7 files changed, 168 insertions(+)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index cafa26c874b0..3e14987e0177 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -26,6 +26,7 @@
 #include <linux/mutex_types.h>
 #include <linux/plist_types.h>
 #include <linux/hrtimer_types.h>
+#include <linux/irq_work_types.h>
 #include <linux/timer_types.h>
 #include <linux/seccomp_types.h>
 #include <linux/nodemask_types.h>
@@ -851,6 +852,11 @@ struct sched_dl_entity {
 	 * to (the original one/itself).
 	 */
 	struct sched_dl_entity *pi_se;
+	/*
+	 * Queued when the task, an rt_mutex owner, can no longer run on its
+	 * own reservation: see dl_request_owner_boost().
+	 */
+	struct irq_work			boost_work;
 #endif
 	bool				dl_bw_def;
 };
diff --git a/include/linux/sched/rt.h b/include/linux/sched/rt.h
index 922935cc3383..7be8f196a2fb 100644
--- a/include/linux/sched/rt.h
+++ b/include/linux/sched/rt.h
@@ -66,6 +66,10 @@ static inline struct task_struct *rt_mutex_get_top_task(struct task_struct *p)
 }
 extern void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task);
 extern void rt_mutex_adjust_pi(struct task_struct *p);
+extern void rt_mutex_adjust_owner(struct task_struct *p);
+extern void dl_request_owner_boost(struct task_struct *p);
+extern bool dl_owner_needs_boost(struct task_struct *p,
+				 struct task_struct *pi_task);
 #else
 static inline struct task_struct *rt_mutex_get_top_task(struct task_struct *task)
 {
diff --git a/init/Kconfig b/init/Kconfig
index 4013781e0a02..f0a700046133 100644
--- a/init/Kconfig
+++ b/init/Kconfig
@@ -2115,6 +2115,7 @@ source "arch/Kconfig"
 config RT_MUTEXES
 	bool
 	default y if PREEMPT_RT
+	select IRQ_WORK
 
 config MODULE_SIG_FORMAT
 	def_bool n
diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c
index 49caf38759f3..1deed8937e41 100644
--- a/kernel/locking/rtmutex.c
+++ b/kernel/locking/rtmutex.c
@@ -1086,6 +1086,20 @@ static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
 	return ret;
 }
 
+/*
+ * Ask for a boost of @task, a deadline task with a deadline top waiter.
+ * @task can be throttled already. Its throttle is only read under the
+ * rq lock, so leave the check to the irq_work of
+ * dl_request_owner_boost(). The caller holds the pi_lock of @task.
+ */
+static __always_inline void rt_mutex_ask_dl_boost(struct task_struct *task)
+{
+	lockdep_assert_held(&task->pi_lock);
+	if (dl_prio(task->normal_prio) && task_has_pi_waiters(task) &&
+	    dl_prio(task_top_pi_waiter(task)->pi_tree.prio))
+		dl_request_owner_boost(task);
+}
+
 /*
  * Try to take an rt-mutex
  *
@@ -1195,6 +1209,13 @@ try_to_take_rt_mutex(struct rt_mutex_base *lock, struct task_struct *task,
 	 */
 	if (rt_mutex_has_waiters(lock))
 		rt_mutex_enqueue_pi(task, rt_mutex_top_waiter(lock));
+	/*
+	 * @task took the lock ahead of the remaining waiters, so none of
+	 * them has a higher priority. A deadline task can still need a
+	 * boost: it can be throttled already. Its throttle found no waiter,
+	 * or it waited on this lock then. Ask for the boost again.
+	 */
+	rt_mutex_ask_dl_boost(task);
 	raw_spin_unlock(&task->pi_lock);
 
 takeit:
@@ -1278,6 +1299,7 @@ static int __sched task_blocks_on_rt_mutex(struct rt_mutex_base *lock,
 			raw_spin_lock(&task->pi_lock);
 			rt_mutex_dequeue(lock, waiter);
 			task->pi_blocked_on = NULL;
+			rt_mutex_ask_dl_boost(task);
 			raw_spin_unlock(&task->pi_lock);
 			return res;
 		}
@@ -1582,6 +1604,11 @@ static void __sched remove_waiter(struct rt_mutex_base *lock,
 	scoped_guard(raw_spinlock, &waiter_task->pi_lock) {
 		rt_mutex_dequeue(lock, waiter);
 		waiter_task->pi_blocked_on = NULL;
+		/*
+		 * The task stops waiting. If it owns a lock with waiters and
+		 * was throttled meanwhile, no boost could reach it then.
+		 */
+		rt_mutex_ask_dl_boost(waiter_task);
 	}
 
 	/*
diff --git a/kernel/locking/rtmutex_api.c b/kernel/locking/rtmutex_api.c
index f1246efc62d3..384a6e951515 100644
--- a/kernel/locking/rtmutex_api.c
+++ b/kernel/locking/rtmutex_api.c
@@ -536,6 +536,33 @@ void __sched rt_mutex_adjust_pi(struct task_struct *task)
 				   next_lock, NULL, task);
 }
 
+/*
+ * Boost @task from its top waiter, as rt_mutex_adjust_prio() does when a
+ * waiter changes. dl_request_owner_boost() queues this call when @task, a
+ * deadline owner, can no longer run on its own reservation. The pi_lock
+ * of @task keeps its pi_waiters, and so its top waiter, in place.
+ *
+ * Leave @task alone if it waits on another lock, with pi_blocked_on set.
+ * A new donor would then need a chain walk from @task, and this runs in
+ * hard interrupt context. The rtmutex code asks again when @task takes
+ * that lock or stops waiting on it. If @task is throttled before then,
+ * it cannot run to take the lock, and its waiters wait for its next
+ * period.
+ */
+void rt_mutex_adjust_owner(struct task_struct *task)
+{
+	unsigned long flags;
+
+	raw_spin_lock_irqsave(&task->pi_lock, flags);
+	if (!task->pi_blocked_on && task_has_pi_waiters(task)) {
+		struct task_struct *pi_task = task_top_pi_waiter(task)->task;
+
+		if (dl_owner_needs_boost(task, pi_task))
+			rt_mutex_setprio(task, pi_task);
+	}
+	raw_spin_unlock_irqrestore(&task->pi_lock, flags);
+}
+
 /*
  * Performs the wakeup of the top-waiter and re-enables preemption.
  */
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 9fda819aa4ef..e993054b5b76 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -8650,6 +8650,15 @@ static void balance_push(struct rq *rq)
 	if (!cpu_dying(rq->cpu) || rq != this_rq())
 		return;
 
+	/*
+	 * push_work is per CPU: run once per switch-in, from __schedule().
+	 * A hard interrupt can call rt_mutex_setprio() in the tail of that
+	 * switch-in: see dl_request_owner_boost(). Leave the push to the
+	 * next __schedule(), which finds the callback installed above.
+	 */
+	if (in_hardirq())
+		return;
+
 	/*
 	 * Both the cpu-hotplug and stop task are in this case and are
 	 * required to complete the hotplug process.
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 7f839185eb38..6bb92dfecbb8 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -544,6 +544,82 @@ void dl_boost_start(struct sched_dl_entity *dl_se)
 	dl_se->dl_yielded = 0;
 	dl_boost_donor_period(dl_se);
 }
+
+/*
+ * Run as the irq_work that dl_request_owner_boost() queued, and drop the
+ * reference that it took. That can be the last one. irq_work_single()
+ * still writes the work, in the task_struct, after this returns. This is
+ * safe: put_task_struct() frees the task through call_rcu(). A hard
+ * irq_work runs with interrupts off, so no grace period can end before
+ * irq_work_single() returns.
+ */
+static void dl_owner_boost_work(struct irq_work *work)
+{
+	struct task_struct *p = container_of(work, struct task_struct,
+					     dl.boost_work);
+
+	rt_mutex_adjust_owner(p);
+	put_task_struct(p);
+}
+
+/*
+ * Ask for a boost of @p, an rt_mutex owner that was just throttled.
+ * rt_mutex_setprio() did not boost @p when its waiters blocked, because
+ * @p could still run on its own reservation then. It is called again
+ * only when a waiter changes. The rtmutex code also asks, when @p gets
+ * waiters, or stops waiting on another lock: @p can be throttled
+ * already. A throttle after a yield does not ask: the task gave up its
+ * runtime, and waits for its next period with its waiters.
+ *
+ * rt_mutex_setprio() needs the pi_lock of @p, which nests outside the rq
+ * lock that the caller holds. So queue an irq_work, which calls
+ * rt_mutex_adjust_owner() after the rq lock is released. The irq_work is
+ * hard: on PREEMPT_RT, other irq_work runs in a kthread, which the
+ * deadline tasks would delay.
+ */
+void dl_request_owner_boost(struct task_struct *p)
+{
+	if (is_dl_boosted(&p->dl) || !p->dl.dl_runtime)
+		return;
+	/*
+	 * From a throttle, the read of pi_waiters is racy: the work tests it
+	 * again under the pi_lock. A waiter that this test misses is added
+	 * under that pi_lock after it. Its path then asks for a boost, or
+	 * calls rt_mutex_setprio(), and either takes the rq lock that the
+	 * caller holds. Under that lock, the throttle is seen.
+	 */
+	if (data_race(RB_EMPTY_ROOT(&p->pi_waiters.rb_root)))
+		return;
+	get_task_struct(p);
+	if (!irq_work_queue(&p->dl.boost_work))
+		put_task_struct(p);
+}
+
+/*
+ * Return true if the waiter @pi_task must boost @p, an rt_mutex owner.
+ * Return false unless both are deadline tasks and @p is not boosted.
+ * The caller holds the pi_lock of @p, so that rt_mutex_setprio() can
+ * follow with the same top waiter. A call to rt_mutex_setprio() that
+ * boosts nothing would still dequeue and enqueue @p, and its enqueue can
+ * throttle @p. This only filters: rt_mutex_setprio() decides again, with
+ * a newer clock.
+ */
+bool dl_owner_needs_boost(struct task_struct *p, struct task_struct *pi_task)
+{
+	struct rq_flags rf;
+	struct rq *rq;
+	bool ret = false;
+
+	if (!dl_prio(p->normal_prio) || !dl_prio(pi_task->prio))
+		return false;
+	rq = __task_rq_lock(p, &rf);
+	if (!is_dl_boosted(&p->dl)) {
+		update_rq_clock(rq);
+		ret = dl_waiter_boosts(p, pi_task);
+	}
+	__task_rq_unlock(rq, p, &rf);
+	return ret;
+}
 #else /* !CONFIG_RT_MUTEXES: */
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -554,6 +630,10 @@ static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
 {
 }
 
+static inline void dl_request_owner_boost(struct task_struct *p)
+{
+}
+
 static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return false;
@@ -2463,6 +2543,9 @@ static inline void dl_check_constrained_dl(struct sched_dl_entity *dl_se)
 		dl_se->dl_throttled = 1;
 		if (dl_se->runtime > 0)
 			dl_se->runtime = 0;
+		/* A deadline waiter on an rt_mutex may boost it now. */
+		if (!dl_server(dl_se))
+			dl_request_owner_boost(dl_task_of(dl_se));
 	}
 }
 
@@ -2635,6 +2718,12 @@ static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64
 		if (!dl_server(dl_se)) {
 			update_stats_dequeue_dl(&rq->dl, dl_se, 0);
 			dequeue_pushable_dl_task(rq, dl_task_of(dl_se));
+			/*
+			 * A deadline waiter on an rt_mutex may boost it now.
+			 * Not after a yield: the task gave up its runtime.
+			 */
+			if (!dl_se->dl_yielded)
+				dl_request_owner_boost(dl_task_of(dl_se));
 		}
 
 		if (unlikely(is_dl_boosted(dl_se) || !start_dl_timer(dl_se))) {
@@ -3611,6 +3700,8 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 		dl_se->dl_throttled = 1;
 		if (task_current_donor(rq, dl_task_of(dl_se)))
 			resched_curr(rq);
+		/* A deadline waiter on an rt_mutex may boost it now. */
+		dl_request_owner_boost(dl_task_of(dl_se));
 	}
 
 	/*
@@ -5996,6 +6087,8 @@ static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
 		replenish_dl_entity(dl_se);
 	if (task_current_donor(rq, p))
 		resched_curr(rq);
+	/* A deadline waiter on an rt_mutex may boost it now. */
+	dl_request_owner_boost(p);
 	return false;
 }
 
@@ -6249,6 +6342,7 @@ void init_dl_entity(struct sched_dl_entity *dl_se)
 	 * from switched_from_dl() before the deboost drops its reference.
 	 */
 	dl_se->pi_se = dl_se;
+	dl_se->boost_work = IRQ_WORK_INIT_HARD(dl_owner_boost_work);
 #endif
 	dl_se->dl_bw_cpu = -1;
 	dl_se->dl_bw_resv_cpu = -1;
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 40/43] sched/deadline: Reschedule a running task throttled at its enqueue
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (32 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 39/43] sched/deadline: Boost an owner throttled after its waiter blocked Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  2026-11-27 14:36 ` [PATCH v12 41/43] sched/deadline: Run a boost held at its first refill on a donor period Mathieu Desnoyers
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

A task with a constrained deadline (dl_deadline < dl_period) can wake up
after its deadline but before its next period.
Commit df8eac8cafce ("sched/deadline: Throttle a constrained deadline
task activated after the deadline") throttles it then until that period.
A refill would let it run for dl_runtime every dl_deadline, more than
its reservation.

enqueue_dl_entity() makes this check at every enqueue, not only at a
wakeup. These changes to a running task also dequeue and enqueue it:
- sched_setattr() and sched_setaffinity();
- a cgroup move;
- a deboost in rt_mutex_setprio().

A task can run past its deadline with runtime left, for example after
tasks with earlier deadlines delayed it. The check then throttles it and
leaves it off the dl_rq. But nothing reschedules: prio_changed_dl() sees
the same deadline and returns.

The task keeps the CPU. update_curr_dl() skips a task that is off the
dl_rq, so the tick neither charges it nor preempts it. It runs until it
blocks, until a task with an earlier deadline wakes up, or until its
next period. That is up to dl_period - dl_deadline of CPU time outside
its reservation. The Sashiko AI review of this series found this.

Fix this by rescheduling when the check throttles the current task, as
a throttle in update_curr_dl_se() does.

The task stopped this way can own an rt_mutex. Its deadline waiters
then wait for its next period, unless they boost it. So this patch comes
after "sched/deadline: Boost an owner that cannot run on its own
reservation" and "sched/deadline: Boost an owner throttled after its
waiter blocked".

The constrained_gap_change_running case of deadline_bw_test changes a
running task with sched_setattr(). "sched/deadline: Keep the debt of a
task across a change of parameters", earlier in this series, already
reschedules a task that sched_setattr() throttles. So the case passes
without this patch too. sched_setaffinity(), a cgroup move and a
deboost have no test case. Their effect was found by reading.

Fixes: df8eac8cafce ("sched/deadline: Throttle a constrained deadline task activated after the deadline")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 6bb92dfecbb8..b9dd7ec10e7d 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -2546,6 +2546,13 @@ static inline void dl_check_constrained_dl(struct sched_dl_entity *dl_se)
 		/* A deadline waiter on an rt_mutex may boost it now. */
 		if (!dl_server(dl_se))
 			dl_request_owner_boost(dl_task_of(dl_se));
+		/*
+		 * A running task is now off the dl_rq: the tick no longer
+		 * charges it or preempts it. Reschedule, as a throttle in
+		 * update_curr_dl_se() does.
+		 */
+		if (!dl_server(dl_se) && task_current_donor(rq, dl_task_of(dl_se)))
+			resched_curr(rq);
 	}
 }
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* [PATCH v12 41/43] sched/deadline: Run a boost held at its first refill on a donor period
       [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
                   ` (33 preceding siblings ...)
  2026-11-27 14:36 ` [PATCH v12 40/43] sched/deadline: Reschedule a running task throttled at its enqueue Mathieu Desnoyers
@ 2026-11-27 14:36 ` Mathieu Desnoyers
  34 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-27 14:36 UTC (permalink / raw)
  To: juri.lelli, peterz, mingo, vincent.guittot
  Cc: Mathieu Desnoyers, tglx, will, boqun, dietmar.eggemann, rostedt,
	bsegall, mgorman, vschneid, kprateek.nayak, luca.abeni,
	tommaso.cucinotta, mathieu.poirier, longman, ridong.chen, tj,
	hannes, mkoutny, shuah, bigeasy, clrkwllms, parri.andrea,
	m.szyprowski, kayracizmeci, weihengqiuu, linux-kernel, cgroups,
	linux-kselftest, linux-rt-devel, stable

"sched/deadline: Restore the owner's period at a deboost in the class",
earlier in this series, holds a boost at its first refill from the
donor. It saves the owner's own period, and puts it back at the
deboost. But the refill itself is the one of replenish_dl_entity(): it
adds the donor's runtime, and moves the owner's own deadline by the
donor's period. That deadline is often later than the waiter's. The
donor's runtime also pays for the owner's overrun.

"sched/deadline: Boost an owner that cannot run on its own
reservation" runs a boost held from its start on a donor period
instead: a period with the donor's parameters, which starts at the
boost. It also limits the owner to one donor runtime per donor period:
the next held boost resumes the donor period of the last one. A boost
held at its first refill gets neither. A waiter that times out on the
lock again and again would then give the owner one donor runtime per
boost. Other deadline tasks would then miss their deadlines.

Fix this by running a boost held at its first refill on a donor period
too. dl_hold_refilled_boost() calls dl_boost_donor_period(), which
resumes the donor period of the last held boost, or starts a new one.
dl_note_donor_refill() returns true when a donor period was placed, and
replenish_dl_new_period() then keeps it. None is placed when the
donor's parameters were cleared: replenish_dl_entity() adds no runtime
then.

This was found in a user-space model of the CBS, not reproduced on a
kernel. No case of deadline_bw_test fails without this patch.

Fixes: 2d3d891d3344 ("sched/deadline: Add SCHED_DEADLINE inheritance logic")
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: stable@vger.kernel.org
---
 kernel/sched/deadline.c | 74 ++++++++++++++++++++++++++---------------
 1 file changed, 48 insertions(+), 26 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index b9dd7ec10e7d..f4e07aa47715 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -196,28 +196,32 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 	return pi_of(dl_se) != dl_se;
 }
 
-static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se);
+static bool dl_hold_refilled_boost(struct sched_dl_entity *dl_se);
 
 /*
  * Record that a replenishment changes the runtime of @dl_se while
- * boosted. At the first refill, hold the boost: dl_hold_refilled_boost()
- * saves the task's own period. Call this before the replenishment moves
- * the deadline or adds runtime. A task with no parameters of its own at the
- * first refill, or no period yet, has no period to save. Later refills of
- * its boost leave it
- * as it is, even if the task gets parameters meanwhile.
+ * boosted. At the first refill of a boost that is not held, hold it. Call
+ * this before the replenishment changes the deadline and the runtime:
+ * dl_hold_refilled_boost() saves them, and places a period of the donor.
+ * Return true if it placed one: the caller must keep that period. It
+ * places none if the donor's parameters were cleared. A task with no
+ * parameters of its own at the first refill, or no period yet, has no
+ * period to save. Later
+ * refills of its boost leave it as it is, even if the task gets
+ * parameters meanwhile.
  */
-static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
+static inline bool dl_note_donor_refill(struct sched_dl_entity *dl_se)
 {
 	bool first;
 
 	if (!is_dl_boosted(dl_se))
-		return;
+		return false;
 	first = !dl_se->dl_donor_refill;
 	dl_se->dl_donor_refill = 1;
-	if (first && dl_se->dl_runtime && dl_se->deadline &&
-	    !dl_se->dl_boost_held)
-		dl_hold_refilled_boost(dl_se);
+	if (!first || !dl_se->dl_runtime || !dl_se->deadline ||
+	    dl_se->dl_boost_held)
+		return false;
+	return dl_hold_refilled_boost(dl_se);
 }
 
 static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task);
@@ -626,8 +630,9 @@ static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 	return dl_se;
 }
 
-static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)
+static inline bool dl_note_donor_refill(struct sched_dl_entity *dl_se)
 {
+	return false;
 }
 
 static inline void dl_request_owner_boost(struct task_struct *p)
@@ -1741,11 +1746,13 @@ static void wakeup_preempt_dl(struct rq *rq, struct task_struct *p, int flags);
 static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 					    struct rq *rq)
 {
-	dl_note_donor_refill(dl_se);
-	/* for non-boosted task, pi_of(dl_se) == dl_se */
-	dl_se->period_start = rq_clock(rq);
-	dl_se->deadline = dl_se->period_start + pi_of(dl_se)->dl_deadline;
-	dl_se->runtime = pi_of(dl_se)->dl_runtime;
+	/* A boost held from this refill keeps the period it placed. */
+	if (!dl_note_donor_refill(dl_se)) {
+		/* for non-boosted task, pi_of(dl_se) == dl_se */
+		dl_se->period_start = rq_clock(rq);
+		dl_se->deadline = dl_se->period_start + pi_of(dl_se)->dl_deadline;
+		dl_se->runtime = pi_of(dl_se)->dl_runtime;
+	}
 
 	/*
 	 * If it is a deferred reservation, and the server
@@ -6101,11 +6108,14 @@ static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
 
 #ifdef CONFIG_RT_MUTEXES
 /*
- * A boosted task is refilled from its donor when its runtime is used up,
- * or when its deadline has passed. A wakeup also refills it when the
- * donor's density does not allow the runtime left. From then on, the task
- * runs on the donor's reservation. So save the task's own period in own_*
- * at the first refill: this holds the boost. dl_deboost() puts it back.
+ * A boost that is not held runs the task on its own reservation. The task
+ * is refilled from its donor when its runtime is used up, or when its
+ * deadline has passed. A wakeup also refills it when the donor's density
+ * does not allow the runtime left. From then on, the task runs on the
+ * donor's reservation. So hold the boost at the first refill. Save the
+ * task's own period in own_*, and run the task on a period of the donor,
+ * resumed or new: see dl_boost_donor_period(). dl_boost_start() does the
+ * same at the start of a boost.
  *
  * Keep the runtime left if the task's own deadline is still ahead.
  * Otherwise save no runtime. A negative runtime is an overrun that comes
@@ -6115,11 +6125,15 @@ static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
  * If sched_setattr() changed the parameters before this refill,
  * dl_setattr_period() saved the old ones in setattr_*. Fit the period
  * saved in own_* to the new parameters with them. setattr_* share
- * storage with own_*: read them before writing own_*. The caller holds
- * the rq lock of the task, and has updated the rq clock.
+ * storage with own_*: read them before writing own_*. Return true if a
+ * period of the donor was placed. The caller holds the rq lock of the
+ * task, and has updated the rq clock.
  */
-static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
+static bool dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 {
+	struct sched_dl_entity *pi_se = pi_of(dl_se);
+	u64 donor_runtime = READ_ONCE(pi_se->dl_runtime);
+	u64 donor_deadline = READ_ONCE(pi_se->dl_deadline);
 	u64 old_runtime = dl_se->setattr_runtime;
 	u64 old_deadline = dl_se->setattr_deadline;
 	u64 old_period = dl_se->setattr_period;
@@ -6142,6 +6156,14 @@ static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 				 old_runtime, old_deadline, old_period, false, false);
 	else if (!dl_time_before(now, dl_se->own_deadline))
 		dl_se->own_runtime = 0;
+	/*
+	 * replenish_dl_entity() checks the donor's parameters: it adds no
+	 * runtime if they were cleared. Start no period from them then.
+	 */
+	if (!donor_runtime || !donor_deadline)
+		return false;
+	dl_boost_donor_period(dl_se);
+	return true;
 }
 #endif /* CONFIG_RT_MUTEXES */
 
-- 
2.47.3


^ permalink raw reply related	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub()
  2026-11-27 14:35 ` [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
@ 2026-11-30 12:56   ` Juri Lelli
  2026-11-30 14:12   ` David Laight
  1 sibling, 0 replies; 44+ messages in thread
From: Juri Lelli @ 2026-11-30 12:56 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

Hello,

On 27/11/26 09:35, Mathieu Desnoyers wrote:
> __dl_add() and __dl_sub() spread a change of total_bw over the extra_bw
> of the active CPUs of the root domain. Commit daec57983670
> ("sched/deadline: Reclaim bandwidth not used by dl tasks") added this,
> for the bandwidth of one task. That is at most 1 << 20, the bandwidth
> of one CPU.
> 
> But cpuset_can_attach() reserves the sum of the bandwidths of all the
> deadline tasks it moves, with dl_bw_alloc(). __dl_add() and __dl_sub()
> cast the bandwidth to s32 before the division. Past S32_MAX, more than
> 2048 CPUs of deadline bandwidth, the cast flips its sign. The extra_bw
> of each CPU then moves the wrong way. GRUB lets reclaiming tasks run
> more than the free bandwidth, or less. This was found by reading. It
> needs a machine with more than 2048 CPUs, so no case tests it.
> 
> Fix this by dividing on 64 bits, with div_u64().
> 
> The Sashiko AI review of the first series found this.
> 
> Fixes: daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks")
> Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
> Cc: stable@vger.kernel.org
> ---

Reviewed-by: Juri Lelli <juri.lelli@redhat.com>

Thanks,
Juri

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub()
  2026-11-27 14:35 ` [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
  2026-11-30 12:56   ` Juri Lelli
@ 2026-11-30 14:12   ` David Laight
  2026-11-30 15:26     ` Mathieu Desnoyers
  1 sibling, 1 reply; 44+ messages in thread
From: David Laight @ 2026-11-30 14:12 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: juri.lelli, peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

On Fri, 27 Nov 2026 09:35:47 -0500
Mathieu Desnoyers <mathieu.desnoyers@efficios.com> wrote:

> __dl_add() and __dl_sub() spread a change of total_bw over the extra_bw
> of the active CPUs of the root domain. Commit daec57983670
> ("sched/deadline: Reclaim bandwidth not used by dl tasks") added this,
> for the bandwidth of one task. That is at most 1 << 20, the bandwidth
> of one CPU.
> 
> But cpuset_can_attach() reserves the sum of the bandwidths of all the
> deadline tasks it moves, with dl_bw_alloc(). __dl_add() and __dl_sub()
> cast the bandwidth to s32 before the division. Past S32_MAX, more than
> 2048 CPUs of deadline bandwidth, the cast flips its sign. The extra_bw
> of each CPU then moves the wrong way. GRUB lets reclaiming tasks run
> more than the free bandwidth, or less. This was found by reading. It
> needs a machine with more than 2048 CPUs, so no case tests it.
> 
> Fix this by dividing on 64 bits, with div_u64().
> 
> The Sashiko AI review of the first series found this.
> 
> Fixes: daec57983670 ("sched/deadline: Reclaim bandwidth not used by dl tasks")
> Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
> Cc: stable@vger.kernel.org
> ---
>  kernel/sched/deadline.c | 4 ++--
>  1 file changed, 2 insertions(+), 2 deletions(-)
> 
> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 3f02d150e15d..7a6057326611 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
> @@ -205,7 +205,7 @@ void __dl_sub(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
>  {
>  	dl_b->total_bw -= tsk_bw;
>  	if (cpus)
> -		__dl_update(dl_b, (s32)tsk_bw / cpus);
> +		__dl_update(dl_b, div_u64(tsk_bw, cpus));

It looks like the casts were added to avoid an expensive 64bit divide.
So I'm not at all sure it is sensible to remove them.
Changing to (u32) is enough to stop the sign being flipped and requires
4096 CPU before there is any overflow.

The code seems to have loops across all the cpu - so I'm not sure how
well it actually scales for large systems.

I'm also not sure of the locking for the 'rq->dl_extra_bw += bw' in
__dl_update().

If this code runs every time a deadline process suspends it could
get very expensive even without the divide.

David 

>  }
>  
>  static inline
> @@ -213,7 +213,7 @@ void __dl_add(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
>  {
>  	dl_b->total_bw += tsk_bw;
>  	if (cpus)
> -		__dl_update(dl_b, -((s32)tsk_bw / cpus));
> +		__dl_update(dl_b, -(s64)div_u64(tsk_bw, cpus));
>  }
>  
>  static inline bool


^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task
  2026-11-27 14:35 ` [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task Mathieu Desnoyers
@ 2026-11-30 14:25   ` Juri Lelli
  2026-11-30 15:27     ` Mathieu Desnoyers
  0 siblings, 1 reply; 44+ messages in thread
From: Juri Lelli @ 2026-11-30 14:25 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

Hello,

On 27/11/26 09:35, Mathieu Desnoyers wrote:

...

> Fix this by holding a reference on the donor's task, for each task whose
> donor is another task. dl_set_donor() gives a task the donor of its top
> waiter. dl_clear_donor() ends the boost. Both move the reference. A
> late walk can still leave P on the parameters of an exited donor for a
> while. P now reads them from valid memory.

Thanks for implementing this. As far as I can see it covers all the
writers of pi_se, and it closes the use after free without needing the
two rtmutex patches before it.

...

> Cc: stable@vger.kernel.org # 6.16.x and older: 8671bad873eb: sched: Do not call __put_task_struct() on rt if pi_blocked_on is set
> Cc: stable@vger.kernel.org

Nit: the second line looks redundant. Also, tryget_task_struct() is only
there since v6.12, so older trees need something else on top of
8671bad873eb.

...

> +static inline void dl_set_donor(struct sched_dl_entity *dl_se,
> +				struct task_struct *pi_task)
> +{
> +	struct sched_dl_entity *pi_se;
> +
> +	for (;;) {
> +		pi_se = READ_ONCE(pi_task->dl.pi_se);
> +		if (pi_se == dl_se->pi_se)
> +			return;
> +		if (pi_se == dl_se ||
> +		    tryget_task_struct(container_of(pi_se, struct task_struct, dl)))
> +			break;
> +		/* Pairs with the ordering of refcount_dec_and_test(). */
> +		smp_rmb();
> +	}
> +	dl_replace_donor(dl_se, pi_se);
> +}

I convinced myself that this terminates: tryget can only fail once the
last reference on the donor is gone, which means the waiter dropped its
own. The waiter does that only in dl_replace_donor(), after storing the
new donor in its pi_se, so the re-read after the smp_rmb() finds a
newer pointer. And the rq lock keeps the old task_struct from being
freed meanwhile.

Still, this is an open-ended loop with the rq lock and the pi_lock held
and interrupts disabled, and it ends only as long as every writer of
pi_se that points it at another task holds a reference on that task. We
have a few of them already and later patches rework this code. If one of
them ever gets it wrong we spin here forever, with nothing telling us
why.

Would it make sense to give up after a few tries, warn, and fall back to
the top waiter itself? It is blocked, so it cannot go away, and a waiter
with no parameters of its own is what "sched/deadline: Do not replenish
a boost from cleared parameters" already handles. The boost is then less
accurate in a case that should never happen, which looks better to me
than a silent lockup. Giving up also puts a hard limit on the time spent
here with interrupts off.

One more thing. Since this fixes a use after free and seems to stand on
its own, can we move it ahead of the rest of the series?

Thanks,
Juri

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep
  2026-11-27 14:35 ` [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep Mathieu Desnoyers
@ 2026-11-30 14:48   ` Juri Lelli
  2026-11-30 15:27     ` Mathieu Desnoyers
  0 siblings, 1 reply; 44+ messages in thread
From: Juri Lelli @ 2026-11-30 14:48 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

Hello,

On 27/11/26 09:35, Mathieu Desnoyers wrote:

...

> The refill reads the parameters of the donor, from the timer. So this
> relies on two earlier patches. "sched/deadline: Do not replenish a boost
> from cleared parameters" keeps the refill from looping on cleared
> parameters. "rtmutex: Continue the chain walk when a waiter's deadline
> donor changes" keeps the donor pointer from going stale.

I think the second one should rather be "sched/deadline: Hold a
reference on the deadline donor of a boosted task" (23/43)?

What the refill from the timer needs is a donor pointer that points to
valid memory. The chain walk patch keeps the donor up to date in more
cases, but cannot guarantee that (its changelog leaves a stale donor as
a known limit and points to 23 for it). With the reference, a stale
donor is still readable, and if it left the class its cleared
parameters are handled by the first one. A stale but still valid donor
only makes the refill less accurate, as for a boosted task that is
queued today.

The other way around, without 23 this patch adds a reader of a donor
that can be gone, from the timer.

So maybe 23 and this one can go together, ahead of the rest of the
series? If it makes sense, could you please fix the changelog
accordingly?

With that,

Reviewed-by: Juri Lelli <juri.lelli@redhat.com>

Thanks,
Juri

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub()
  2026-11-30 14:12   ` David Laight
@ 2026-11-30 15:26     ` Mathieu Desnoyers
  2026-11-30 18:16       ` David Laight
  0 siblings, 1 reply; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-30 15:26 UTC (permalink / raw)
  To: David Laight
  Cc: juri.lelli, peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

On 2026-11-30 09:12, David Laight wrote:
> It looks like the casts were added to avoid an expensive 64bit divide.
> So I'm not at all sure it is sensible to remove them.

The divide runs rarely, so I do not think its cost matters here.
__dl_add() and __dl_sub() run only when deadline bandwidth is
admitted, released, or moved to another root domain:
- sched_setattr() and sched_setaffinity();
- a cpuset attach, CPU hotplug and a rebuild of the root domains;
- a write to the parameters of a deadline server in debugfs;
- the load or the unload of a sched_ext scheduler;
- a task that leaves the deadline class or exits;
- a task that wakes up or migrates into a root domain that does not
  count its bandwidth. Patch 14 of this series adds this case.

Each caller first counts the active CPUs of the root domain, with
dl_bw_cpus(). __dl_update() then writes the extra_bw of each of them.
Next to these two loops, one divide costs little. div_u64() is one
divide instruction on 64-bit, and one or two divl on 32-bit x86.

> Changing to (u32) is enough to stop the sign being flipped and requires
> 4096 CPU before there is any overflow.

Two problems with (u32):
- In __dl_add(), -((u32)tsk_bw / cpus) is an unsigned int. The s64
  argument of __dl_update() then gets a large positive value. So
  extra_bw would grow instead of shrinking.
- x86 with MAXSMP allows 8192 CPUs. A sum of bandwidths can then still
  pass U32_MAX.

> If this code runs every time a deadline process suspends it could
> get very expensive even without the divide.

No. A deadline task that blocks or wakes up changes only running_bw
and this_bw of its runqueue. At a wakeup, only the last case of the
list above calls __dl_sub() and __dl_add(). It does so once, when the
task changes root domain.

> The code seems to have loops across all the cpu - so I'm not sure how
> well it actually scales for large systems.

Those loops are already in v7.4-rc2, and this patch does not change
them. They run only on the paths listed above.

> I'm also not sure of the locking for the 'rq->dl_extra_bw += bw' in
> __dl_update().

Good point. __dl_update() writes extra_bw under the dl_bw lock of the
root domain. grub_reclaim() reads it under the lock of its own
runqueue only, and reads it twice. A write between the two reads could
make u_act wrap around. A 32-bit kernel could also read a torn value.
init_dl_rq_bw_ratio() also writes extra_bw without the dl_bw lock, from
the handler of the sched_rt_runtime_us and sched_rt_period_us sysctls.
It sets extra_bw back to max_bw, which forgets the bandwidth already
admitted. All of this is already in v7.4-rc2. I have only checked it by
reading. I would rather fix it in a separate patch.

Thanks,

Mathieu


-- 
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task
  2026-11-30 14:25   ` Juri Lelli
@ 2026-11-30 15:27     ` Mathieu Desnoyers
  0 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-30 15:27 UTC (permalink / raw)
  To: Juri Lelli
  Cc: peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

On 2026-11-30 09:25, Juri Lelli wrote:
>> Cc: stable@vger.kernel.org # 6.16.x and older: 8671bad873eb: sched: Do not call __put_task_struct() on rt if pi_blocked_on is set
>> Cc: stable@vger.kernel.org
>
> Nit: the second line looks redundant. Also, tryget_task_struct() is only
> there since v6.12, so older trees need something else on top of
> 8671bad873eb.

Right on both counts. The next version drops the second Cc line. Its
changelog also says that trees older than v6.12 need
tryget_task_struct(). Commit a8532fac7b5d ("sched_ext: TASK_DEAD tasks
must be switched into SCX on ops_enable") added it. Those trees need
only the helper it adds to include/linux/sched/task.h.

> Would it make sense to give up after a few tries, warn, and fall back to
> the top waiter itself? It is blocked, so it cannot go away, and a waiter
> with no parameters of its own is what "sched/deadline: Do not replenish
> a boost from cleared parameters" already handles. The boost is then less
> accurate in a case that should never happen, which looks better to me
> than a silent lockup. Giving up also puts a hard limit on the time spent
> here with interrupts off.

Yes. In the next version, dl_set_donor() reads the donor of the top
waiter at most 8 times. If tryget_task_struct() fails each time, it
warns. It then makes the top waiter itself the donor, with a reference
on it. Later patches move the loop to dl_top_donor() and keep the
bound.

> One more thing. Since this fixes a use after free and seems to stand on
> its own, can we move it ahead of the rest of the series?

Yes. It applies and compiles on top of the first series, without the
rest of this one. In the next version, it is patch 1. Patch 27 follows
it as patch 2, as you asked in your reply to 27.

Thanks,

Mathieu


-- 
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep
  2026-11-30 14:48   ` Juri Lelli
@ 2026-11-30 15:27     ` Mathieu Desnoyers
  0 siblings, 0 replies; 44+ messages in thread
From: Mathieu Desnoyers @ 2026-11-30 15:27 UTC (permalink / raw)
  To: Juri Lelli
  Cc: peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

On 2026-11-30 09:48, Juri Lelli wrote:
> I think the second one should rather be "sched/deadline: Hold a
> reference on the deadline donor of a boosted task" (23/43)?

Yes. In the next version, the changelog cites 23 in place of the chain
walk patch. It also says that a stale donor only makes the refill less
accurate.

> So maybe 23 and this one can go together, ahead of the rest of the
> series? If it makes sense, could you please fix the changelog
> accordingly?

Yes. In the next version, 23 and this patch are patches 1 and 2. This
one needs only 23 and the first series. It carries your Reviewed-by.

Thanks for the review,

Mathieu


-- 
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 25/43] sched/deadline: Count the 0-lag time from the next period
  2026-11-27 14:35 ` [PATCH v12 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
@ 2026-11-30 16:47   ` Juri Lelli
  0 siblings, 0 replies; 44+ messages in thread
From: Juri Lelli @ 2026-11-30 16:47 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

Hello,

On 27/11/26 09:35, Mathieu Desnoyers wrote:

...

> Fix this by counting the 0-lag time from the next period, with
> dl_next_period(). Update the formula in
> Documentation/scheduler/sched-deadline.rst too.

...

> @@ -1756,7 +1764,7 @@ static inline void dl_check_constrained_dl(struct sched_dl_entity *dl_se)
>  {
>  	struct rq *rq = rq_of_dl_se(dl_se);
>  
> -	if (dl_time_before(dl_se->deadline, rq_clock(rq)) &&
> +	if (dl_se->deadline && dl_time_before(dl_se->deadline, rq_clock(rq)) &&
>  	    dl_time_before(rq_clock(rq), dl_next_period(dl_se))) {
>  		if (unlikely(is_dl_boosted(dl_se) || !start_dl_timer(dl_se)))
>  			return;

Nit: the patch also makes dl_check_constrained_dl() skip a task with no
period yet (deadline of 0), which could otherwise be taken for one in
its constrained gap right after boot. That isn't obvious from the code,
so maybe a comment before the check, something like

	/*
	 * A deadline of 0 means the task has no period yet: this enqueue
	 * starts one. Skip it, or the check below would see a deadline in
	 * the past and, while rq_clock is still below dl_period (right
	 * after boot), throttle the task until a next period computed
	 * from that 0.
	 */

and a sentence in the changelog?

Apart from that, this fix maybe should go at the top of the series so
that it can be picked up more easily?

Reviewed-by: Juri Lelli <juri.lelli@redhat.com>

Thanks,
Juri

^ permalink raw reply	[flat|nested] 44+ messages in thread

* Re: [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub()
  2026-11-30 15:26     ` Mathieu Desnoyers
@ 2026-11-30 18:16       ` David Laight
  0 siblings, 0 replies; 44+ messages in thread
From: David Laight @ 2026-11-30 18:16 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: juri.lelli, peterz, mingo, vincent.guittot, tglx, will, boqun,
	dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
	kprateek.nayak, luca.abeni, tommaso.cucinotta, mathieu.poirier,
	longman, ridong.chen, tj, hannes, mkoutny, shuah, bigeasy,
	clrkwllms, parri.andrea, m.szyprowski, kayracizmeci, weihengqiuu,
	linux-kernel, cgroups, linux-kselftest, linux-rt-devel, stable

On Mon, 30 Nov 2026 10:26:19 -0500
Mathieu Desnoyers <mathieu.desnoyers@efficios.com> wrote:

> On 2026-11-30 09:12, David Laight wrote:
> > It looks like the casts were added to avoid an expensive 64bit divide.
> > So I'm not at all sure it is sensible to remove them.  
> 
> The divide runs rarely, so I do not think its cost matters here.
> __dl_add() and __dl_sub() run only when deadline bandwidth is
> admitted, released, or moved to another root domain:
> - sched_setattr() and sched_setaffinity();
> - a cpuset attach, CPU hotplug and a rebuild of the root domains;
> - a write to the parameters of a deadline server in debugfs;
> - the load or the unload of a sched_ext scheduler;
> - a task that leaves the deadline class or exits;
> - a task that wakes up or migrates into a root domain that does not
>   count its bandwidth. Patch 14 of this series adds this case.
> 
> Each caller first counts the active CPUs of the root domain, with
> dl_bw_cpus().

From the above it seems like that is 'almost constant' so doesn't
need recalculating all the time.

> __dl_update() then writes the extra_bw of each of them.
> Next to these two loops, one divide costs little. div_u64() is one
> divide instruction on 64-bit, and one or two divl on 32-bit x86.
> 
> > Changing to (u32) is enough to stop the sign being flipped and requires
> > 4096 CPU before there is any overflow.  
> 
> Two problems with (u32):
> - In __dl_add(), -((u32)tsk_bw / cpus) is an unsigned int. The s64
>   argument of __dl_update() then gets a large positive value.

Nope, the unsigned int is converted to u64 before being converted to s64.
The existing code is doing a signed divide so can generate 'very large
positive values'; just changing 'int cpus' to 'unsigned int cpus'
would also have the same effect.

> So
>   extra_bw would grow instead of shrinking.
> - x86 with MAXSMP allows 8192 CPUs. A sum of bandwidths can then still
>   pass U32_MAX.

That probably means that a lot of the '<< 20' should be '<< 19'.

> 
> > If this code runs every time a deadline process suspends it could
> > get very expensive even without the divide.  
> 
> No. A deadline task that blocks or wakes up changes only running_bw
> and this_bw of its runqueue. At a wakeup, only the last case of the
> list above calls __dl_sub() and __dl_add(). It does so once, when the
> task changes root domain.
> 
> > The code seems to have loops across all the cpu - so I'm not sure how
> > well it actually scales for large systems.  
> 
> Those loops are already in v7.4-rc2, and this patch does not change
> them. They run only on the paths listed above.

Indeed - that doesn't mean it is a good idea...
There is nothing in the commit I read that added this code that mentioned
anything about performance.

> > I'm also not sure of the locking for the 'rq->dl_extra_bw += bw' in
> > __dl_update().  
> 
> Good point. __dl_update() writes extra_bw under the dl_bw lock of the
> root domain.

Are you saying that either there is only one rd->span, or that they are
all disjoint.
Otherwise there can be two updates of the field under different locks.

David

> grub_reclaim() reads it under the lock of its own
> runqueue only, and reads it twice. A write between the two reads could
> make u_act wrap around. A 32-bit kernel could also read a torn value.
> init_dl_rq_bw_ratio() also writes extra_bw without the dl_bw lock, from
> the handler of the sched_rt_runtime_us and sched_rt_period_us sysctls.
> It sets extra_bw back to max_bw, which forgets the bandwidth already
> admitted. All of this is already in v7.4-rc2. I have only checked it by
> reading. I would rather fix it in a separate patch.
> 
> Thanks,
> 
> Mathieu
> 
> 


^ permalink raw reply	[flat|nested] 44+ messages in thread

end of thread, other threads:[~2026-11-30 18:16 UTC | newest]

Thread overview: 44+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
     [not found] <cover.1795771147.git.mathieu.desnoyers@efficios.com>
2026-11-27 14:35 ` [PATCH v12 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 02/43] sched/deadline: Rebuild the root domains' accounting from the task list Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 03/43] sched/deadline: Record the root domain holding a task's bandwidth Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 07/43] sched/deadline: Move a task's bandwidth only where room was made Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 14/43] sched/deadline: Move a task's bandwidth to " Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 16/43] sched/deadline: Keep the last CPU a task has in its root domain Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 17/43] cgroup/cpuset: Refuse to take a deadline task out of " Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 19/43] sched/deadline: Count only active CPUs when spreading extra_bw Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
2026-11-30 12:56   ` Juri Lelli
2026-11-30 14:12   ` David Laight
2026-11-30 15:26     ` Mathieu Desnoyers
2026-11-30 18:16       ` David Laight
2026-11-27 14:35 ` [PATCH v12 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task Mathieu Desnoyers
2026-11-30 14:25   ` Juri Lelli
2026-11-30 15:27     ` Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
2026-11-30 16:47   ` Juri Lelli
2026-11-27 14:35 ` [PATCH v12 26/43] sched/deadline: Keep a departing constrained task until its " Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 27/43] sched/deadline: Replenish a throttled task boosted while asleep Mathieu Desnoyers
2026-11-30 14:48   ` Juri Lelli
2026-11-30 15:27     ` Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 28/43] sched/deadline: Restore the owner's period at a deboost in the class Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 29/43] sched/deadline: Count the bandwidth a boosted task is given Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 30/43] sched/deadline: Start a period for a task that enters the class blocked Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 31/43] sched/deadline: Restore the owner's period at a deboost out of the class Mathieu Desnoyers
2026-11-27 14:35 ` [PATCH v12 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 34/43] sched/deadline: Cancel the replenishment timer with the parameters Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 36/43] sched/deadline: Check the runtime of a task that comes back runnable Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 37/43] sched/deadline: Keep the debt of a task across a change of parameters Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 38/43] sched/deadline: Boost an owner that cannot run on its own reservation Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 39/43] sched/deadline: Boost an owner throttled after its waiter blocked Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 40/43] sched/deadline: Reschedule a running task throttled at its enqueue Mathieu Desnoyers
2026-11-27 14:36 ` [PATCH v12 41/43] sched/deadline: Run a boost held at its first refill on a donor period Mathieu Desnoyers

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox